index
int64
0
0
repo_id
stringclasses
829 values
file_path
stringlengths
34
254
content
stringlengths
6
5.38M
0
code_files/vets-api-private/app/controllers
code_files/vets-api-private/app/controllers/v0/efolder_controller.rb
# frozen_string_literal: true require 'efolder/service' module V0 class EfolderController < ApplicationController service_tag 'deprecated' def index render(json: service.list_documents) end def show send_data( service.get_document(params[:id]), type: 'application/pdf', filename: params[:filename] ) end private def service Efolder::Service.new(@current_user) end end end
0
code_files/vets-api-private/app/controllers
code_files/vets-api-private/app/controllers/v0/search_typeahead_controller.rb
# frozen_string_literal: true require 'search_typeahead/service' module V0 class SearchTypeaheadController < ApplicationController include ActionView::Helpers::SanitizeHelper service_tag 'search' skip_before_action :authenticate skip_before_action :verify_authenticity_token # gets suggestions list from search.gov after being passed a query, name, and API key # def index response = SearchTypeahead::Service.new(query).suggestions render json: response.body, status: response.status end private def typeahead_params params.permit(:query) end # Returns a sanitized, permitted version of the passed query params. # # @return [String] # @see https://api.rubyonrails.org/v4.2/classes/ActionView/Helpers/SanitizeHelper.html#method-i-sanitize # def query sanitize typeahead_params['query'] end end end
0
code_files/vets-api-private/app/controllers
code_files/vets-api-private/app/controllers/v0/backend_statuses_controller.rb
# frozen_string_literal: true require 'lighthouse/benefits_education/service' require 'backend_services' module V0 class BackendStatusesController < ApplicationController service_tag 'maintenance-windows' skip_before_action :authenticate def index options = { params: { maintenance_windows: } } render json: BackendStatusesSerializer.new(backend_statuses, options) end private # NOTE: Data is from PagerDuty def backend_statuses @backend_statuses ||= ExternalServicesRedis::Status.new.fetch_or_cache end def maintenance_windows @maintenance_windows ||= MaintenanceWindow.end_after(Time.zone.now) end end end
0
code_files/vets-api-private/app/controllers
code_files/vets-api-private/app/controllers/v0/in_progress_forms_controller.rb
# frozen_string_literal: true module V0 class InProgressFormsController < ApplicationController include IgnoreNotFound service_tag 'save-in-progress' def index # the keys of metadata shouldn't be deeply transformed, which might corrupt some keys # see https://github.com/department-of-veterans-affairs/va.gov-team/issues/17595 for more details pending_submissions = InProgressForm.submission_pending.for_user(@current_user) render json: InProgressFormSerializer.new(pending_submissions) end def show render json: form_for_user&.data_and_metadata || camelized_prefill_for_user end def update if Flipper.enabled?(:in_progress_form_atomicity, @current_user) atomic_update else original_update end end def destroy raise Common::Exceptions::RecordNotFound, form_id if form_for_user.blank? form_for_user.destroy render json: InProgressFormSerializer.new(form_for_user) end private def original_update form = InProgressForm.form_for_user(form_id, @current_user) || InProgressForm.new(form_id:, user_uuid: @current_user.uuid) form.user_account = @current_user.user_account form.real_user_uuid = @current_user.uuid if Flipper.enabled?(:disability_compensation_sync_modern0781_flow_metadata) && (form_id == FormProfiles::VA526ez::FORM_ID) && params[:metadata].present? && params[:form_data].present? form_hash = params[:form_data].is_a?(String) ? JSON.parse(params[:form_data]) : params[:form_data] params[:metadata][:sync_modern0781_flow] = form_hash[:sync_modern0781_flow] || false end ClaimFastTracking::MaxCfiMetrics.log_form_update(form, params) form.update!( form_data: params[:form_data] || params[:formData], metadata: params[:metadata], expires_at: form.next_expires_at ) render json: InProgressFormSerializer.new(form) end def atomic_update form_data = params[:form_data] || params[:formData] InProgressForm.transaction do # Lock the specific row to prevent concurrent updates, and use create_or_find_by! to prevent concurrent creation form = InProgressForm.form_for_user(form_id, @current_user, with_lock: true) || InProgressForm.create_or_find_by!(form_id:, user_uuid: @current_user.uuid) do |f| f.form_data = form_data f.metadata = params[:metadata] f.user_account = @current_user.user_account end form.user_account = @current_user.user_account if @current_user.user_account form.real_user_uuid = @current_user.uuid if Flipper.enabled?(:disability_compensation_sync_modern0781_flow_metadata) && (form_id == FormProfiles::VA526ez::FORM_ID) && params[:metadata].present? && form_data.present? form_hash = form_data.is_a?(String) ? JSON.parse(form_data) : form_data params[:metadata][:sync_modern0781_flow] = form_hash[:sync_modern0781_flow] || false end ClaimFastTracking::MaxCfiMetrics.log_form_update(form, params) form.update!(form_data:, metadata: params[:metadata], expires_at: form.next_expires_at) render json: InProgressFormSerializer.new(form) end end def form_for_user @form_for_user ||= InProgressForm.submission_pending.form_for_user(form_id, @current_user) end def form_id params[:id] end # the front end is always expecting camelCase # --this ensures that, even if the OliveBranch inflection header isn't used, camelCase keys are sent def camelized_prefill_for_user camelize_with_olivebranch(FormProfile.for(form_id: params[:id], user: @current_user).prefill.as_json) end def camelize_with_olivebranch(form_json) # camelize exactly as OliveBranch would # inspired by vets-api/blob/327b26c76ea7904744014ea35463022e8b50f3fb/lib/tasks/support/schema_camelizer.rb#L27 OliveBranch::Transformations.transform( form_json, OliveBranch::Transformations.method(:camelize) ) end end end
0
code_files/vets-api-private/app/controllers
code_files/vets-api-private/app/controllers/v0/onsite_notifications_controller.rb
# frozen_string_literal: true module V0 class OnsiteNotificationsController < ApplicationController service_tag 'on-site-notifications' BEARER_PATTERN = /^Bearer / skip_before_action :verify_authenticity_token, only: [:create] skip_before_action :authenticate, only: [:create] skip_after_action :set_csrf_header, only: [:create] before_action :authenticate_jwt, only: [:create] def index clean_pagination_params notifications = OnsiteNotification .for_user(current_user, include_dismissed: params[:include_dismissed]) .paginate(**pagination_params) options = { meta: pagination_meta(notifications) } render json: OnsiteNotificationSerializer.new(notifications, options) end def create onsite_notification = OnsiteNotification.new( params.require(:onsite_notification).permit(:va_profile_id, :template_id) ) raise Common::Exceptions::ValidationErrors, onsite_notification unless onsite_notification.save render json: OnsiteNotificationSerializer.new(onsite_notification) end def update onsite_notification = OnsiteNotification.find_by(id: params[:id], va_profile_id: current_user.vet360_id) raise Common::Exceptions::RecordNotFound, params[:id] if onsite_notification.nil? unless onsite_notification.update(params.require(:onsite_notification).permit(:dismissed)) raise Common::Exceptions::ValidationErrors, onsite_notification end render json: OnsiteNotificationSerializer.new(onsite_notification) end private def authenticity_error Common::Exceptions::Forbidden.new(detail: 'Invalid Authenticity Token') end def get_bearer_token header = request.authorization header.gsub(BEARER_PATTERN, '') if header&.match(BEARER_PATTERN) end def public_key OpenSSL::PKey::EC.new( Base64.decode64(Settings.onsite_notifications.public_key) ) end def authenticate_jwt bearer_token = get_bearer_token raise authenticity_error if bearer_token.blank? decoded_token = JWT.decode(bearer_token, public_key, true, { algorithm: 'ES256' }) raise authenticity_error unless token_valid? decoded_token rescue JWT::DecodeError raise authenticity_error end def token_valid?(token) token.first['user'] == 'va_notify' && token.first['iat'].present? && token.first['exp'].present? end def clean_pagination_params per_page = pagination_params[:per_page].to_i params[:per_page] = WillPaginate.per_page if per_page < 1 WillPaginate::PageNumber(pagination_params[:page]) rescue WillPaginate::InvalidPage params[:page] = 1 end def pagination_meta(notifications) { pagination: { current_page: notifications.current_page.to_i, per_page: notifications.per_page, total_pages: notifications.total_pages, total_entries: notifications.total_entries } } end end end
0
code_files/vets-api-private/app/controllers
code_files/vets-api-private/app/controllers/v0/form212680_controller.rb
# frozen_string_literal: true module V0 class Form212680Controller < ApplicationController include RetriableConcern service_tag 'form-21-2680' skip_before_action :authenticate before_action :load_user before_action :check_feature_enabled def create claim = saved_claim_class.new(form: filtered_params) Rails.logger.info "Begin ClaimGUID=#{claim.guid} Form=#{claim.class::FORM} UserID=#{current_user&.uuid}" if claim.save # NOTE: we are not calling process_attachments! because we are not submitting yet StatsD.increment("#{stats_key}.success") Rails.logger.info "Submitted job ClaimID=#{claim.confirmation_number} Form=#{claim.class::FORM} " \ "UserID=#{current_user&.uuid}" clear_saved_form(claim.form_id) render json: SavedClaimSerializer.new(claim) else StatsD.increment("#{stats_key}.failure") raise Common::Exceptions::ValidationErrors, claim end rescue JSON::ParserError raise Common::Exceptions::ParameterMissing, 'form' end # get /v0/form212680/download_pdf/{guid} # Generate and download a pre-filled PDF with veteran sections (I-V) completed # Physician sections (VI-VIII) are left blank for manual completion # def download_pdf claim = saved_claim_class.find_by!(guid: params[:guid]) source_file_path = with_retries('Generate 21-2680 PDF') do claim.generate_prefilled_pdf end raise Common::Exceptions::InternalServerError, 'Failed to generate PDF' unless source_file_path send_data File.read(source_file_path), filename: download_file_name(claim), type: 'application/pdf', disposition: 'attachment' rescue ActiveRecord::RecordNotFound raise Common::Exceptions::RecordNotFound, params[:guid] ensure File.delete(source_file_path) if defined?(source_file_path) && source_file_path && File.exist?(source_file_path) end private def short_name 'house_bound_status_claim' end def filtered_params params.require(:form) end def download_file_name(claim) "21-2680_#{claim.veteran_first_last_name.gsub(' ', '_')}.pdf" end def saved_claim_class SavedClaim::Form212680 end def stats_key 'api.form212680' end def check_feature_enabled routing_error unless Flipper.enabled?(:form_2680_enabled, current_user) end end end
0
code_files/vets-api-private/app/controllers
code_files/vets-api-private/app/controllers/v0/gi_bill_feedbacks_controller.rb
# frozen_string_literal: true module V0 class GIBillFeedbacksController < ApplicationController service_tag 'gibill-feedback' skip_before_action(:authenticate) before_action :load_user, only: :create def show gi_bill_feedback = GIBillFeedback.find(params[:id]) render json: GIBillFeedbackSerializer.new(gi_bill_feedback) end def create gi_bill_feedback = GIBillFeedback.new( params.require(:gi_bill_feedback).permit(:form).merge( user: current_user ) ) unless gi_bill_feedback.save Sentry.set_tags(validation: 'gibft') Rails.logger.error("GIBillFeedback failed to create: #{gi_bill_feedback.errors.full_messages.join(', ')}") raise Common::Exceptions::ValidationErrors, gi_bill_feedback end clear_saved_form(GIBillFeedback::FORM_ID) render json: GIBillFeedbackSerializer.new(gi_bill_feedback) end end end
0
code_files/vets-api-private/app/controllers
code_files/vets-api-private/app/controllers/v0/user_actions_controller.rb
# frozen_string_literal: true module V0 class UserActionsController < ApplicationController service_tag 'identity' before_action :set_query_date_range, only: [:index] def index page = params[:page].presence || 1 per_page = params[:per_page].presence || 10 subject_user_verification = current_user.user_verification q = UserAction.includes(:user_action_event).where(subject_user_verification:).ransack(params[:q]) @user_actions = q.result.page(page.to_i).per_page(per_page.to_i) render json: UserActionSerializer.new(@user_actions, **serializer_options), status: :ok end private def set_query_date_range params[:q] ||= {} params[:q][:created_at_gteq] ||= 1.month.ago.beginning_of_day params[:q][:created_at_lteq] ||= Time.zone.now.end_of_day end def links { first: url_for(page: 1, only_path: false), last: url_for(page: @user_actions.total_pages, only_path: false), prev: (url_for(page: @user_actions.previous_page, only_path: false) if @user_actions.previous_page), next: (url_for(page: @user_actions.next_page, only_path: false) if @user_actions.next_page) }.compact end def meta { current_page: @user_actions.current_page, total_pages: @user_actions.total_pages, per_page: @user_actions.per_page, total_count: @user_actions.count } end def serializer_options { is_collection: true, include: [:user_action_event], links:, meta: } end end end
0
code_files/vets-api-private/app/controllers
code_files/vets-api-private/app/controllers/v0/appeals_controller.rb
# frozen_string_literal: true module V0 class AppealsController < AppealsBaseController service_tag 'appeal-status' def index appeals_response = appeals_service.get_appeals(current_user) render json: appeals_response.body end end end
0
code_files/vets-api-private/app/controllers
code_files/vets-api-private/app/controllers/v0/csrf_token_controller.rb
# frozen_string_literal: true class V0::CsrfTokenController < ApplicationController service_tag 'csrf-token' skip_before_action :authenticate def index; end end
0
code_files/vets-api-private/app/controllers
code_files/vets-api-private/app/controllers/v0/forms_controller.rb
# frozen_string_literal: true require 'forms/client' module V0 class FormsController < ApplicationController include ActionView::Helpers::SanitizeHelper service_tag 'find-a-form' skip_before_action :authenticate def index response = Forms::Client.new(params[:query]).get_all render json: response.body, status: response.status end end end
0
code_files/vets-api-private/app/controllers
code_files/vets-api-private/app/controllers/v0/mpi_users_controller.rb
# frozen_string_literal: true module V0 # Formerly MviUsersController class MPIUsersController < ApplicationController service_tag 'identity' before_action { authorize :mpi, :access_add_person_proxy? } before_action :validate_form! before_action :validate_user_ids! ALLOWED_FORM_IDS = ['21-0966', FormProfiles::VA526ez::FORM_ID].freeze def submit add_response = MPIData.for_user(@current_user.identity).add_person_proxy if add_response.ok? render json: { message: 'Success' } else error_message = 'MPI add_person_proxy error' Rails.logger.error('[V0][MPIUsersController] submit error', error_message:) render(json: { errors: [{ error_message: }] }, status: :unprocessable_entity) end end private def validate_form! form_id = params[:id] return if ALLOWED_FORM_IDS.include?(form_id) raise Common::Exceptions::Forbidden.new( detail: "Action is prohibited with id parameter #{form_id}", source: 'MPIUsersController' ) end def validate_user_ids! return unless @current_user.birls_id.nil? && @current_user.participant_id.present? raise Common::Exceptions::UnprocessableEntity.new( detail: 'No birls_id while participant_id present', source: 'MPIUsersController' ) end end end
0
code_files/vets-api-private/app/controllers
code_files/vets-api-private/app/controllers/v0/education_benefits_claims_controller.rb
# frozen_string_literal: true module V0 class EducationBenefitsClaimsController < ApplicationController service_tag 'education-forms' skip_before_action(:authenticate) before_action :load_user def create claim = SavedClaim::EducationBenefits.form_class(form_type).new(education_benefits_claim_params) unless claim.save StatsD.increment("#{stats_key('create')}.failure") StatsD.increment("#{stats_key("create.22#{form_type}")}.failure") Rails.logger.error "EBCC::create Failed to create claim 22#{form_type}" raise Common::Exceptions::ValidationErrors, claim end StatsD.increment("#{stats_key('create')}.success") StatsD.increment("#{stats_key("create.22#{form_type}")}.success") Rails.logger.info "ClaimID=#{claim.id} RPO=#{claim.education_benefits_claim.region} Form=#{form_type}" claim.after_submit(@current_user) clear_saved_form(claim.in_progress_form_id) render json: EducationBenefitsClaimSerializer.new(claim.education_benefits_claim) end def stem_claim_status current_applications = [] current_applications = user_stem_automated_decision_claims unless @current_user.nil? render json: EducationStemClaimStatusSerializer.new(current_applications) end def download_pdf education_claim = EducationBenefitsClaim.find_by!(token: params[:id]) saved_claim = SavedClaim.find(education_claim.saved_claim_id) source_file_path = PdfFill::Filler.fill_form( saved_claim, SecureRandom.uuid, sign: false ) client_file_name = "education_benefits_claim_#{saved_claim.id}.pdf" file_contents = File.read(source_file_path) send_data file_contents, filename: client_file_name, type: 'application/pdf', disposition: 'attachment' StatsD.increment("#{stats_key('pdf_download')}.22#{education_claim.form_type}.success") rescue => e StatsD.increment("#{stats_key('pdf_download')}.failure") Rails.logger.error "EBCC::download_pdf Failed to download pdf ClaimID=#{params[:id]} #{e.message}" raise e ensure File.delete(source_file_path) if source_file_path && File.exist?(source_file_path) end private def form_type params[:form_type] || '1990' end def user_stem_automated_decision_claims EducationBenefitsClaim.joins(:education_stem_automated_decision) .where( 'education_stem_automated_decisions.user_account_id' => @current_user.user_account_uuid ).to_a end def education_benefits_claim_params params.require(:education_benefits_claim).permit(:form) end def stats_key(action) "api.education_benefits_claim.#{action}" end end end
0
code_files/vets-api-private/app/controllers
code_files/vets-api-private/app/controllers/v0/id_card_announcement_subscription_controller.rb
# frozen_string_literal: true module V0 class IdCardAnnouncementSubscriptionController < ApplicationController service_tag 'deprecated' skip_before_action :authenticate def create @subscription = IdCardAnnouncementSubscription.find_or_create_by(filtered_params) if @subscription.valid? render json: { status: 'OK' }, status: :accepted else raise Common::Exceptions::ValidationErrors, @subscription end end private def filtered_params params.require(:id_card_announcement_subscription).permit(:email) end end end
0
code_files/vets-api-private/app/controllers/v0
code_files/vets-api-private/app/controllers/v0/chatbot/token_controller.rb
# frozen_string_literal: true require 'erb' module V0 module Chatbot class TokenController < ApplicationController service_tag 'chatbot' skip_before_action :authenticate before_action :load_user rescue_from 'V0::Chatbot::TokenController::ServiceException', with: :service_exception_handler rescue_from Net::HTTPError, with: :service_exception_handler def create directline_response = fetch_connector_values if current_user&.icn code = SecureRandom.uuid ::Chatbot::CodeContainer.new(code:, icn: current_user.icn).save! render json: { token: directline_response[:token], conversationId: directline_response[:conversationId], apiSession: ERB::Util.url_encode(cookies[:api_session]), code:, expires_in: directline_response[:expires_in] } else render json: { token: directline_response[:token], conversationId: directline_response[:conversationId], apiSession: ERB::Util.url_encode(cookies[:api_session]), expires_in: directline_response[:expires_in] } end end private def fetch_connector_values connector_response = request_connector_values parse_connector_values(connector_response) end def request_connector_values req = Net::HTTP::Post.new(token_endpoint_uri) req['Authorization'] = chatbot_bearer_token Net::HTTP.start(token_endpoint_uri.hostname, token_endpoint_uri.port, use_ssl: true) do |http| http.request(req) end end def parse_connector_values(response) raise ServiceException.new(response.body), response.body unless response.code == '200' parsed = JSON.parse(response.body) { token: parsed['token'], conversationId: parsed['conversationId'], expires_in: parsed['expires_in'] } end def token_endpoint_uri return @token_uri if @token_uri.present? token_endpoint = 'https://directline.botframework.com/v3/directline/tokens/generate' @token_uri = URI(token_endpoint) end def chatbot_bearer_token secret = Settings.virtual_agent.webchat_root_bot_secret @chatbot_bearer_token ||= "Bearer #{secret}" end def service_exception_handler(exception) context = 'An error occurred with the Microsoft service that issues chatbot tokens' log_exception_to_sentry(exception, 'context' => context) render nothing: true, status: :service_unavailable end class ServiceException < RuntimeError; end end end end
0
code_files/vets-api-private/app/controllers/v0
code_files/vets-api-private/app/controllers/v0/chatbot/claim_status_controller.rb
# frozen_string_literal: true require 'date' require 'concurrent' require 'chatbot/report_to_cxi' require 'lighthouse/benefits_claims/service' require 'vets/shared_logging' module V0 module Chatbot class ClaimStatusController < SignIn::ServiceAccountApplicationController include IgnoreNotFound include Vets::SharedLogging service_tag 'chatbot' rescue_from 'EVSS::ErrorMiddleware::EVSSError', with: :service_exception_handler def index render json: { data: poll_claims_from_lighthouse, meta: { sync_status: 'SUCCESS' } } end def show render json: { data: get_claim_from_lighthouse(params[:id]), meta: { sync_status: 'SUCCESS' } } end private def icn @icn ||= @service_account_access_token.user_attributes['icn'] end def poll_claims_from_lighthouse cxi_reporting_service = ::Chatbot::ReportToCxi.new conversation_id = conversation_id_or_error claims = [] begin raw_claim_list = lighthouse_service.get_claims['data'] claims = order_claims_lighthouse(raw_claim_list) rescue Common::Exceptions::ResourceNotFound => e log_no_claims_found(e) claims = [] rescue Faraday::ClientError => e service_exception_handler(e) raise BenefitsClaims::ServiceException.new(e.response), 'Could not retrieve claims' ensure report_or_error(cxi_reporting_service, conversation_id) if conversation_id.present? end claims end def conversation_id_or_error conversation_id = params[:conversation_id] return conversation_id if conversation_id.present? Rails.logger.error(conversation_id_missing_message) raise ActionController::ParameterMissing, 'conversation_id' end def get_claim_from_lighthouse(id) claim = lighthouse_service.get_claim(id) # Manual status override for certain tracked items # See https://github.com/department-of-veterans-affairs/va.gov-team/issues/101447 # This should be removed when the items are re-categorized by BGS # We are not doing this in the Lighthouse service because we want web and mobile to have # separate rollouts and testing. claim = override_rv1(claim) # https://github.com/department-of-veterans-affairs/va.gov-team/issues/98364 # This should be removed when the items are removed by BGS claim = suppress_evidence_requests(claim) if Flipper.enabled?(:cst_suppress_evidence_requests_website) claim end def override_rv1(claim) tracked_items = claim.dig('data', 'attributes', 'trackedItems') return claim unless tracked_items tracked_items.select { |i| i['displayName'] == 'RV1 - Reserve Records Request' }.each do |i| i['status'] = 'NEEDED_FROM_OTHERS' end claim end def suppress_evidence_requests(claim) tracked_items = claim.dig('data', 'attributes', 'trackedItems') return unless tracked_items tracked_items.reject! { |i| BenefitsClaims::Constants::SUPPRESSED_EVIDENCE_REQUESTS.include?(i['displayName']) } claim end def lighthouse_service BenefitsClaims::Service.new(icn) end def report_or_error(cxi_reporting_service, conversation_id) cxi_reporting_service.report_to_cxi(icn, conversation_id) rescue => e report_exception_handler(e) end def order_claims_lighthouse(claims) Array(claims) .sort_by do |claim| Date.strptime(claim['attributes']['claimPhaseDates']['phaseChangeDate'], '%Y-%m-%d').to_time.to_i end .reverse end def service_exception_handler(exception) context = 'An error occurred while attempting to retrieve the claim(s).' log_exception_to_rails(exception, 'error', context) render nothing: true, status: :service_unavailable end def report_exception_handler(exception) context = 'An error occurred while attempting to report the claim(s).' log_exception_to_rails(exception, 'error', context) end def log_no_claims_found(exception) Rails.logger.info( 'V0::Chatbot::ClaimStatusController#poll_claims_from_lighthouse ' \ "no claims returned by Lighthouse: #{exception.message}" ) end def conversation_id_missing_message 'V0::Chatbot::ClaimStatusController#poll_claims_from_lighthouse ' \ 'conversation_id is missing in parameters' end class ServiceException < RuntimeError; end end end end
0
code_files/vets-api-private/app/controllers/v0
code_files/vets-api-private/app/controllers/v0/chatbot/users_controller.rb
# frozen_string_literal: true module V0 module Chatbot class UsersController < SignIn::ServiceAccountApplicationController service_tag 'identity' before_action :authenticate_one_time_code def show raise Common::Client::Errors::ClientError unless @icn render json: { icn: @icn, preferred_name: }, status: :ok rescue Common::Client::Errors::ClientError render json: invalid_code_error, status: :bad_request end private def preferred_name mpi_profile&.preferred_names&.first || mpi_profile&.given_names&.first end def mpi_profile @mpi_profile ||= MPI::Service.new.find_profile_by_identifier(identifier_type: MPI::Constants::ICN, identifier: @icn)&.profile end def authenticate_one_time_code chatbot_code_container = ::Chatbot::CodeContainer.find(params[:code]) @icn = chatbot_code_container&.icn ensure chatbot_code_container&.destroy end def invalid_code_error { error: 'invalid_request', error_description: 'Code is not valid.' } end end end end
0
code_files/vets-api-private/app/controllers/v0
code_files/vets-api-private/app/controllers/v0/contact_us/inquiries_controller.rb
# frozen_string_literal: true module V0 module ContactUs class InquiriesController < ApplicationController service_tag 'deprecated' skip_before_action :authenticate, only: :create def index return not_implemented unless Flipper.enabled?(:get_help_messages) render json: STUB_RESPONSE, status: :ok end def create return not_implemented unless Flipper.enabled?(:get_help_ask_form) claim = SavedClaim::Ask.new(form: form_submission) validate!(claim) render json: { confirmationNumber: '0000-0000-0000', dateSubmitted: DateTime.now.utc.strftime('%m-%d-%Y') }, status: :created end private def form_submission params.require(:inquiry).require(:form) end def validate!(claim) raise Common::Exceptions::ValidationErrors, claim unless claim.valid? end def not_implemented render nothing: true, status: :not_implemented, as: :json end STUB_RESPONSE = { inquiries: [ { subject: 'Prosthetics', confirmationNumber: '000-010', status: 'OPEN', creationTimestamp: '2020-11-01T14:58:00+01:00', lastActiveTimestamp: '2020-11-04T13:00:00+01:00', links: { thread: { href: '/v1/user/{:user-id}/inquiry/000-010' } } }, { subject: 'Eyeglasses', confirmationNumber: '000-011', status: 'RESOLVED', creationTimestamp: '2020-10-01T14:03:00+01:00', lastActiveTimestamp: '2020-11-01T09:30:00+01:00', links: { thread: { href: '/v1/user/{:user-id}/inquiry/000-011' } } }, { subject: 'Wheelchairs', confirmationNumber: '000-012', status: 'CLOSED', creationTimestamp: '2020-06-01T14:34:00+01:00', lastActiveTimestamp: '2020-06-15T18:21:00+01:00', links: { thread: { href: '/v1/user/{:user-id}/inquiry/000-012' } } } ] }.freeze end end end
0
code_files/vets-api-private/app/controllers/v0
code_files/vets-api-private/app/controllers/v0/gids/zipcode_rates_controller.rb
# frozen_string_literal: true module V0 module GIDS class ZipcodeRatesController < GIDSController def show render json: service.get_zipcode_rate_v0(scrubbed_params) end end end end
0
code_files/vets-api-private/app/controllers/v0
code_files/vets-api-private/app/controllers/v0/gids/institution_programs_controller.rb
# frozen_string_literal: true module V0 module GIDS class InstitutionProgramsController < GIDSController def autocomplete render json: service.get_institution_program_autocomplete_suggestions_v0(scrubbed_params) end def search render json: service.get_institution_program_search_results_v0(scrubbed_params) end end end end
0
code_files/vets-api-private/app/controllers/v0
code_files/vets-api-private/app/controllers/v0/gids/institutions_controller.rb
# frozen_string_literal: true module V0 module GIDS class InstitutionsController < GIDSController def autocomplete render json: service.get_institution_autocomplete_suggestions_v0(scrubbed_params) end def search render json: service.get_institution_search_results_v0(scrubbed_params) end def show render json: service.get_institution_details_v0(scrubbed_params) end def children render json: service.get_institution_children_v0(scrubbed_params) end end end end
0
code_files/vets-api-private/app/controllers/v0
code_files/vets-api-private/app/controllers/v0/gids/calculator_constants_controller.rb
# frozen_string_literal: true module V0 module GIDS class CalculatorConstantsController < GIDSController def index render json: service.get_calculator_constants_v0(scrubbed_params) end end end end
0
code_files/vets-api-private/app/controllers/v0
code_files/vets-api-private/app/controllers/v0/gids/yellow_ribbon_programs_controller.rb
# frozen_string_literal: true module V0 module GIDS class YellowRibbonProgramsController < GIDSController def index render json: service.get_yellow_ribbon_programs_v0(scrubbed_params) end end end end
0
code_files/vets-api-private/app/controllers/v0
code_files/vets-api-private/app/controllers/v0/preneeds/preneed_attachments_controller.rb
# frozen_string_literal: true module V0 module Preneeds class PreneedAttachmentsController < PreneedsController include FormAttachmentCreate skip_before_action(:authenticate, raise: false) FORM_ATTACHMENT_MODEL = ::Preneeds::PreneedAttachment private def serializer_klass PreneedAttachmentSerializer end end end end
0
code_files/vets-api-private/app/controllers/v0
code_files/vets-api-private/app/controllers/v0/preneeds/burial_forms_controller.rb
# frozen_string_literal: true require 'vets/shared_logging' module V0 module Preneeds class BurialFormsController < PreneedsController include Vets::SharedLogging FORM = '40-10007' def create @form = ::Preneeds::BurialForm.new(burial_form_params) validate!(Common::HashHelpers.deep_transform_parameters!(burial_form_params) { |k| k.camelize(:lower) }) @resource = client.receive_pre_need_application(@form) ::Preneeds::PreneedSubmission.create!( tracking_number: @resource.tracking_number, application_uuid: @resource.application_uuid, return_description: @resource.return_description, return_code: @resource.return_code ) send_confirmation_email clear_saved_form(FORM) render json: ReceiveApplicationSerializer.new(@resource) end def send_confirmation_email email = @form.claimant.email claimant = @form.applicant.name.first first_name = @form.applicant.name.first last_initial = @form.applicant.name.last.first if @form.applicant.applicant_relationship_to_claimant != 'Self' first_name = @form.claimant.name.first last_initial = @form.claimant.name.last.first end VANotify::EmailJob.perform_async( email, Settings.vanotify.services.va_gov.template_id.preneeds_burial_form_email, { 'form_name' => 'Burial Pre-Need (Form 40-10007)', 'first_name' => claimant&.upcase.presence, 'applicant_1_first_name_last_initial' => "#{first_name} #{last_initial}", 'confirmation_number' => @resource.application_uuid, 'date_submitted' => Time.zone.today.strftime('%B %d, %Y') } ) end private def burial_form_params params.require(:application).permit( :application_status, :has_currently_buried, :sending_code, preneed_attachments: ::Preneeds::PreneedAttachmentHash.permitted_params, applicant: ::Preneeds::Applicant.permitted_params, claimant: ::Preneeds::Claimant.permitted_params, currently_buried_persons: ::Preneeds::CurrentlyBuriedPerson.permitted_params, veteran: ::Preneeds::Veteran.permitted_params ) end def validate!(form) # Leave in for manual testing of new schemas before made available on Vets JSON Schema # schema = JSON.parse(File.read(Settings.preneeds.burial_form_schema)) schema = VetsJsonSchema::SCHEMAS[FORM] validation_errors = ::Preneeds::BurialForm.validate(schema, form) if validation_errors.present? Sentry.set_tags(validation: 'preneeds') raise Common::Exceptions::SchemaValidationErrors, validation_errors end end end end end
0
code_files/vets-api-private/app/controllers/v0
code_files/vets-api-private/app/controllers/v0/preneeds/cemeteries_controller.rb
# frozen_string_literal: true module V0 module Preneeds class CemeteriesController < PreneedsController def index resource = client.get_cemeteries render json: CemeterySerializer.new(resource.records) end end end end
0
code_files/vets-api-private/app/controllers/v0
code_files/vets-api-private/app/controllers/v0/user/mhv_user_accounts_controller.rb
# frozen_string_literal: true module V0 module User class MHVUserAccountsController < ApplicationController service_tag 'identity' rescue_from MHV::UserAccount::Errors::UserAccountError, with: :render_mhv_account_errors def show authorize MHVUserAccount mhv_user_account = MHV::UserAccount::Creator.new(user_verification: current_user.user_verification, break_cache: true).perform return render_mhv_account_errors('not_found', status: :not_found) if mhv_user_account.blank? log_result('success') render json: MHVUserAccountSerializer.new(mhv_user_account).serializable_hash, status: :ok end private def render_mhv_account_errors(exception) errors = exception.as_json log_result('error', errors:) render json: { errors: }, status: :unprocessable_entity end def log_result(result, **payload) Rails.logger.info("[User][MHVUserAccountsController] #{action_name} #{result}", payload) end end end end
0
code_files/vets-api-private/app/controllers/v0
code_files/vets-api-private/app/controllers/v0/mdot/supplies_controller.rb
# frozen_string_literal: true module V0 module MDOT class SuppliesController < ApplicationController service_tag 'medical-supply-reordering' def create render(json: client.submit_order(supply_params)) end private def address_params %i[ street street2 city state country postal_code ] end def supply_params params.permit( :use_veteran_address, :use_temporary_address, :additional_requests, :vet_email, order: [:product_id], permanent_address: address_params, temporary_address: address_params ).to_hash end def client @client ||= ::MDOT::Client.new(current_user) end end end end
0
code_files/vets-api-private/app/controllers/v0
code_files/vets-api-private/app/controllers/v0/profile/payment_history_controller.rb
# frozen_string_literal: true module V0 module Profile class PaymentHistoryController < ApplicationController service_tag 'payment-history' before_action { authorize :bgs, :access? } def index payment_history = PaymentHistory.new(payments: adapter.payments, return_payments: adapter.return_payments) render json: PaymentHistorySerializer.new(payment_history) end private def adapter @adapter ||= Adapters::PaymentHistoryAdapter.new(bgs_service_response) end def bgs_service_response person = BGS::People::Request.new.find_person_by_participant_id(user: current_user) payment_history = BGS::PaymentService.new(current_user).payment_history(person) if payment_history.nil? Rails.logger.error('BGS::PaymentService returned nil', { person_status: person.status, user_uuid: current_user&.uuid }) end payment_history end end end end
0
code_files/vets-api-private/app/controllers/v0
code_files/vets-api-private/app/controllers/v0/profile/direct_deposits_controller.rb
# frozen_string_literal: true require 'lighthouse/service_exception' require 'lighthouse/direct_deposit/client' require 'lighthouse/direct_deposit/error_parser' require 'lighthouse/direct_deposit/payment_account' module V0 module Profile class DirectDepositsController < ApplicationController service_tag 'direct-deposit' before_action { authorize :lighthouse, :direct_deposit_access? } after_action :log_sso_info, only: :update rescue_from(*Lighthouse::ServiceException::ERROR_MAP.values) do |exception| error = { status: exception.status_code, body: exception.errors.first } response = Lighthouse::DirectDeposit::ErrorParser.parse(error) if response.status.between?(500, 599) Rails.logger.error("Direct Deposit API error: #{exception.message}", { error_class: exception.class.to_s, error_message: exception.message, user_uuid: @current_user&.uuid, backtrace: exception.backtrace.first(3)&.join(' | ') }) end render status: response.status, json: response.body end def show response = client.get_payment_info render json: DirectDepositsSerializer.new(response.body), status: response.status end def update set_payment_account(payment_account_params) response = client.update_payment_info(@payment_account) send_confirmation_email render json: DirectDepositsSerializer.new(response.body), status: response.status end private def client @client ||= DirectDeposit::Client.new(@current_user.icn) end def set_payment_account(params) @payment_account ||= Lighthouse::DirectDeposit::PaymentAccount.new(params) end def payment_account_params params.require(:payment_account) .permit(:account_type, :account_number, :routing_number) end def send_confirmation_email VANotifyDdEmailJob.send_to_emails(current_user.all_emails) end end end end
0
code_files/vets-api-private/app/controllers/v0
code_files/vets-api-private/app/controllers/v0/profile/valid_va_file_numbers_controller.rb
# frozen_string_literal: true module V0 module Profile class ValidVAFileNumbersController < ApplicationController service_tag 'profile' before_action { authorize :bgs, :access? } def show response = BGS::People::Request.new.find_person_by_participant_id(user: current_user) valid_file_number = valid_va_file_number_data(response) render json: ValidVAFileNumberSerializer.new(valid_file_number) end private def valid_va_file_number_data(service_response) return { file_nbr: true } if service_response.file_number.present? { file_nbr: false } end end end end
0
code_files/vets-api-private/app/controllers/v0
code_files/vets-api-private/app/controllers/v0/profile/full_names_controller.rb
# frozen_string_literal: true module V0 module Profile class FullNamesController < ApplicationController service_tag 'profile' # Fetches the full name details for the current user. # Namely their first/middle/last name, and suffix. # # @return [Response] Sample response.body: # { # "data" => { # "id" => "", # "type" => "hashes", # "attributes" => { # "first" => "Jack", # "middle" => "Robert", # "last" => "Smith", # "suffix" => "Jr." # } # } # } # def show render json: FullNameSerializer.new(@current_user.full_name_normalized) end end end end
0
code_files/vets-api-private/app/controllers/v0
code_files/vets-api-private/app/controllers/v0/profile/preferred_names_controller.rb
# frozen_string_literal: true require 'va_profile/demographics/service' module V0 module Profile class PreferredNamesController < ApplicationController service_tag 'profile' before_action { authorize :demographics, :access? } before_action { authorize :mpi, :queryable? } after_action :invalidate_mpi_cache def update preferred_name = VAProfile::Models::PreferredName.new preferred_name_params if preferred_name.valid? response = service.save_preferred_name preferred_name Rails.logger.info('PreferredNamesController#create request completed', sso_logging_info) render json: PreferredNameSerializer.new(response) else raise Common::Exceptions::ValidationErrors, preferred_name end end private def invalidate_mpi_cache @current_user.invalidate_mpi_cache end def service VAProfile::Demographics::Service.new @current_user end def preferred_name_params params.permit(:text) end end end end
0
code_files/vets-api-private/app/controllers/v0
code_files/vets-api-private/app/controllers/v0/profile/connected_applications_controller.rb
# frozen_string_literal: true module V0 module Profile class ConnectedApplicationsController < ApplicationController include IgnoreNotFound service_tag 'profile' def index render json: apps_from_grants end def destroy icn = @current_user.icn client_id = connected_accounts_params[:id] if icn.nil? || client_id.nil? render json: { error: 'icn and/or clientId is missing' } return end url_with_params, headers = build_revocation_request(icn, client_id) begin response = Faraday.delete(url_with_params, nil, headers) if response.status == 204 head :no_content else render json: { error: 'Something went wrong cannot revoke grants' }, status: :unprocessable_entity end rescue render json: { error: 'Something went wrong cannot revoke grants' }, status: :unprocessable_entity end end def apps_from_grants data = [] icn = @current_user.icn url_with_params, headers = build_grant_request(icn) response = Faraday.get(url_with_params, {}, headers) if response.status == 200 parsed_response = JSON.parse(response.body) lhapps = parsed_response['apps'] lhapps.each do |lh_app| app = build_apps_from_data(lh_app) (data ||= []) << app end { 'data' => data } else { data: [] } end rescue { data: [] } end private def build_revocation_request(icn, client_id) revocation_url = Settings.connected_apps_api.connected_apps.revoke_url payload = { icn:, clientId: client_id } url_with_params = "#{revocation_url}?#{URI.encode_www_form(payload)}" headers = { apiKey: Settings.connected_apps_api.connected_apps.api_key, accesskey: Settings.connected_apps_api.connected_apps.auth_access_key } [url_with_params, headers] end def build_grant_request(icn) grant_url = Settings.connected_apps_api.connected_apps.url payload = { icn: } url_with_params = "#{grant_url}?#{URI.encode_www_form(payload)}" headers = { apiKey: Settings.connected_apps_api.connected_apps.api_key, accesskey: Settings.connected_apps_api.connected_apps.auth_access_key } [url_with_params, headers] end def build_apps_from_data(lh_app) app = {} app['id'] = lh_app['clientId'] app['type'] = 'lighthouse_consumer_app' app['attributes'] = {} app['attributes']['title'] = lh_app['label'] app['attributes']['logo'] = lh_app['href'] app['attributes']['privacyUrl'] = '' app['attributes']['grants'] = build_grants(lh_app['grants']) app end def build_grants(grants) grants.map do |grant| { title: grant['scopeTitle'], id: '', created: grant['connectionDate'] } end end def connected_accounts_params params.permit(:id) end end end end
0
code_files/vets-api-private/app/controllers/v0
code_files/vets-api-private/app/controllers/v0/profile/permissions_controller.rb
# frozen_string_literal: true module V0 module Profile class PermissionsController < ApplicationController include Vet360::Writeable service_tag 'profile' before_action { authorize :vet360, :access? } after_action :invalidate_cache def create write_to_vet360_and_render_transaction!( 'permission', permission_params ) Rails.logger.info('PermissionsController#create request completed', sso_logging_info) end def create_or_update write_to_vet360_and_render_transaction!( 'permission', permission_params, http_verb: 'update' ) end def update write_to_vet360_and_render_transaction!( 'permission', permission_params, http_verb: 'put' ) Rails.logger.info('PermissionsController#update request completed', sso_logging_info) end def destroy write_to_vet360_and_render_transaction!( 'permission', permission_params, http_verb: 'put' ) Rails.logger.info('PermissionsController#destroy request completed', sso_logging_info) end private def permission_params params.permit( :id, :permission_type, :permission_value, :transaction_id ) end end end end
0
code_files/vets-api-private/app/controllers/v0
code_files/vets-api-private/app/controllers/v0/profile/vet_verification_statuses_controller.rb
# frozen_string_literal: true module V0 module Profile class VetVerificationStatusesController < ApplicationController service_tag 'profile' before_action { authorize :lighthouse, :access_vet_status? } def show response = service.get_vet_verification_status(@current_user.icn) response['data']['id'] = '' render json: response end private def service @service ||= VeteranVerification::Service.new end end end end
0
code_files/vets-api-private/app/controllers/v0
code_files/vets-api-private/app/controllers/v0/profile/personal_informations_controller.rb
# frozen_string_literal: true require 'va_profile/demographics/service' module V0 module Profile class PersonalInformationsController < ApplicationController service_tag 'profile' before_action { authorize :demographics, :access? } before_action { authorize :mpi, :queryable? } # Fetches the personal information for the current user. # Namely their gender, birth date, preferred name, and gender identity. def show response = service.get_demographics handle_errors!(response) render json: PersonalInformationSerializer.new(response), status: response.status end private def service VAProfile::Demographics::Service.new @current_user end def handle_errors!(response) raise_error! if response.gender.blank? && response.birth_date.blank? log_errors_for(response) end def raise_error! raise Common::Exceptions::BackendServiceException.new( 'MVI_BD502', source: self.class.to_s ) end def log_errors_for(response) return unless response.gender.nil? || response.birth_date.nil? Rails.logger.error("mpi missing data: #{I18n.t('common.exceptions.MVI_BD502.detail')}", { response: sanitize_data(response.to_h), params: sanitize_data(params), gender: response.gender, birth_date: response.birth_date, mvi_status_code: I18n.t('common.exceptions.MVI_BD502.status') }) end def sanitize_data(data) data.except( :source_system_user, :address_line1, :address_line2, :address_line3, :city_name, :vet360_id, :county, :state_code, :zip_code5, :zip_code4, :phone_number, :country_code_iso3, :preferred_name ) end end end end
0
code_files/vets-api-private/app/controllers/v0
code_files/vets-api-private/app/controllers/v0/profile/email_addresses_controller.rb
# frozen_string_literal: true module V0 module Profile class EmailAddressesController < ApplicationController include Vet360::Writeable service_tag 'profile' before_action { authorize :va_profile, :access_to_v2? } after_action :invalidate_cache def create write_to_vet360_and_render_transaction!( 'email', email_address_params ) Rails.logger.info('EmailAddressesController#create request completed', sso_logging_info) end def create_or_update write_to_vet360_and_render_transaction!( 'email', email_address_params, http_verb: 'update' ) end def update write_to_vet360_and_render_transaction!( 'email', email_address_params, http_verb: 'put' ) Rails.logger.info('EmailAddressesController#update request completed', sso_logging_info) end def destroy write_to_vet360_and_render_transaction!( 'email', add_effective_end_date(email_address_params), http_verb: 'put' ) Rails.logger.info('EmailAddressesController#destroy request completed', sso_logging_info) end private def email_address_params params.permit( :email_address, :confirmation_date, :id, :transaction_id ) end end end end
0
code_files/vets-api-private/app/controllers/v0
code_files/vets-api-private/app/controllers/v0/profile/military_occupations_controller.rb
# frozen_string_literal: true require 'va_profile/profile/v3/service' module V0 module Profile class MilitaryOccupationsController < ApplicationController service_tag 'military-info' before_action :controller_enabled? before_action { authorize :vet360, :military_access? } def show response = service.get_military_occupations render(status: response.status, json: response) end private def controller_enabled? routing_error unless Flipper.enabled?(:profile_enhanced_military_info, @current_user) end def service @service ||= VAProfile::Profile::V3::Service.new(@current_user) end end end end
0
code_files/vets-api-private/app/controllers/v0
code_files/vets-api-private/app/controllers/v0/profile/gender_identities_controller.rb
# frozen_string_literal: true require 'va_profile/demographics/service' module V0 module Profile class GenderIdentitiesController < ApplicationController service_tag 'profile' before_action { authorize :demographics, :access? } before_action { authorize :mpi, :queryable? } def update gender_identity = VAProfile::Models::GenderIdentity.new gender_identity_params if gender_identity.valid? response = service.save_gender_identity gender_identity Rails.logger.info('GenderIdentitiesController#create request completed', sso_logging_info) render json: GenderIdentitySerializer.new(response) else raise Common::Exceptions::ValidationErrors, gender_identity end end private def service VAProfile::Demographics::Service.new @current_user end def gender_identity_params params.permit(:code) end end end end
0
code_files/vets-api-private/app/controllers/v0
code_files/vets-api-private/app/controllers/v0/profile/scheduling_preferences_controller.rb
# frozen_string_literal: true # Controller for managing user scheduling preferences in VA.gov profile. # This controller is still under development, with stubbed transaction responses gated # behind the profile_scheduling_preferences feature flag. module V0 module Profile class SchedulingPreferencesController < ApplicationController before_action { authorize :vet360, :access? } before_action :check_feature_flag! before_action :check_pilot_access! service_tag 'profile' def show preferences = [ { item_id: 1, option_ids: [5] }, { item_id: 2, option_ids: [7, 11] } ] preferences_data = { preferences: } render json: SchedulingPreferencesSerializer.new(preferences_data) end def create transaction_response = build_stub_transaction_response render json: transaction_response, status: :ok end def update transaction_response = build_stub_transaction_response render json: transaction_response, status: :ok end def destroy transaction_response = build_stub_transaction_response render json: transaction_response, status: :ok end private def check_feature_flag! unless Flipper.enabled?(:profile_scheduling_preferences, @current_user) raise Common::Exceptions::Forbidden, detail: 'Scheduling preferences not available' end end def check_pilot_access! visn_service = UserVisnService.new(@current_user) unless visn_service.in_pilot_visn? Rails.logger.info("Scheduling preferences not available for your facility for user #{@current_user.uuid}") raise Common::Exceptions::Forbidden, detail: 'Unable to verify access to scheduling preferences' end end def scheduling_preference_params params.permit(:item_id, option_ids: []) end def build_stub_transaction_response { data: { type: 'async_transaction_va_profile_person_option_transactions', id: SecureRandom.uuid, attributes: { transaction_id: SecureRandom.uuid, transaction_status: 'COMPLETED_SUCCESS', type: 'AsyncTransaction::VAProfile::PersonOptionTransaction', metadata: [] } } } end end end end
0
code_files/vets-api-private/app/controllers/v0
code_files/vets-api-private/app/controllers/v0/profile/contacts_controller.rb
# frozen_string_literal: true require 'va_profile/profile/v3/service' module V0 module Profile class ContactsController < ApplicationController service_tag 'profile' before_action { authorize :vet360, :access? } # GET /v0/profile/contacts def index @start_ms = current_time_ms @meta = nil log_upstream_request_start response = service.get_health_benefit_bio @meta = response.meta log_upstream_request_finish(response) render json: ContactSerializer.new(response.contacts, meta: @meta), status: response.status rescue => e log_exception(e) raise end private def current_time_ms Process.clock_gettime(Process::CLOCK_MONOTONIC, :millisecond) end def service VAProfile::Profile::V3::Service.new(current_user) end def log_upstream_request_start Rails.logger.info( event: 'profile.contacts.request.start', request_id: request.request_id, user_uuid: current_user.uuid, icn_present: current_user.icn.present?, idme_uuid_present: current_user.idme_uuid.present?, logingov_uuid_present: current_user.logingov_uuid.present? ) end def log_upstream_request_finish(response) elapsed = current_time_ms - @start_ms Rails.logger.info( event: 'profile.contacts.request.finish', request_id: request.request_id, upstream_status: response.status, contact_count: response.meta[:contact_count], latency_ms: elapsed ) StatsD.measure('profile.contacts.latency', elapsed) StatsD.increment('profile.contacts.empty') if response.meta[:contact_count].zero? StatsD.increment('profile.contacts.success') if response.ok? end def log_exception(e) elapsed = @start_ms ? current_time_ms - @start_ms : nil event = if e.is_a?(Common::Exceptions::BackendServiceException) 'profile.contacts.backend_error' else 'profile.contacts.unhandled_error' end Rails.logger.error( event:, request_id: request.request_id, error_class: e.class.name, error_message: e.message, upstream_message: @meta&.dig(:message), latency_ms: elapsed ) StatsD.increment('profile.contacts.error') end end end end
0
code_files/vets-api-private/app/controllers/v0
code_files/vets-api-private/app/controllers/v0/profile/transactions_controller.rb
# frozen_string_literal: true require 'va_profile/contact_information/v2/service' module V0 module Profile class TransactionsController < ApplicationController include Vet360::Transactionable include Vet360::Writeable service_tag 'profile' before_action { authorize :va_profile, :access_to_v2? } after_action :invalidate_cache def status check_transaction_status! end def statuses transactions = AsyncTransaction::VAProfile::Base.refresh_transaction_statuses(@current_user, service) render json: AsyncTransaction::BaseSerializer.new(transactions).serializable_hash end private def transaction_params params.permit :transaction_id end def service VAProfile::ContactInformation::V2::Service.new @current_user end end end end
0
code_files/vets-api-private/app/controllers/v0
code_files/vets-api-private/app/controllers/v0/profile/addresses_controller.rb
# frozen_string_literal: true module V0 module Profile class AddressesController < ApplicationController include Vet360::Writeable service_tag 'profile' before_action { authorize :va_profile, :access_to_v2? } after_action :invalidate_cache def create write_to_vet360_and_render_transaction!( 'address', address_params ) Rails.logger.warn('AddressesController#create request completed', sso_logging_info) end def create_or_update write_to_vet360_and_render_transaction!( 'address', address_params, http_verb: 'update' ) end def update write_to_vet360_and_render_transaction!( 'address', address_params, http_verb: 'put' ) Rails.logger.warn('AddressesController#update request completed', sso_logging_info) end def destroy write_to_vet360_and_render_transaction!( 'address', add_effective_end_date(address_params), http_verb: 'put' ) Rails.logger.warn('AddressesController#destroy request completed', sso_logging_info) end private def address_params params.permit( :address_line1, :address_line2, :address_line3, :address_pou, :address_type, :city, :country_code_iso3, :county_code, :county_name, :validation_key, :override_validation_key, :id, :international_postal_code, :province, :state_code, :transaction_id, :zip_code, :zip_code_suffix ) end end end end
0
code_files/vets-api-private/app/controllers/v0
code_files/vets-api-private/app/controllers/v0/profile/telephones_controller.rb
# frozen_string_literal: true module V0 module Profile class TelephonesController < ApplicationController include Vet360::Writeable service_tag 'profile' before_action { authorize :va_profile, :access_to_v2? } after_action :invalidate_cache def create write_to_vet360_and_render_transaction!( 'telephone', telephone_params ) Rails.logger.warn('TelephonesController#create request completed', sso_logging_info) end def create_or_update write_to_vet360_and_render_transaction!( 'telephone', telephone_params, http_verb: 'update' ) end def update write_to_vet360_and_render_transaction!( 'telephone', telephone_params, http_verb: 'put' ) Rails.logger.warn('TelephonesController#update request completed', sso_logging_info) end def destroy write_to_vet360_and_render_transaction!( 'telephone', add_effective_end_date(telephone_params), http_verb: 'put' ) Rails.logger.warn('TelephonesController#destroy request completed', sso_logging_info) end private def telephone_params params.permit( :area_code, :country_code, :extension, :id, :is_international, :is_textable, :is_text_permitted, :is_tty, :is_voicemailable, :phone_number, :phone_type, :transaction_id ) end end end end
0
code_files/vets-api-private/app/controllers/v0
code_files/vets-api-private/app/controllers/v0/profile/address_validation_controller.rb
# frozen_string_literal: true require 'va_profile/models/validation_address' require 'va_profile/address_validation/v3/service' module V0 module Profile class AddressValidationController < ApplicationController service_tag 'profile' skip_before_action :authenticate, only: [:create] def create address = VAProfile::Models::ValidationAddress.new(address_params) raise Common::Exceptions::ValidationErrors, address unless address.valid? Rails.logger.warn('AddressValidationController#create request completed', sso_logging_info) render(json: service.address_suggestions(address)) end private def address_params params.require(:address).permit( :address_line1, :address_line2, :address_line3, :address_pou, :address_type, :city, :country_code_iso3, :international_postal_code, :province, :state_code, :zip_code, :zip_code_suffix ) end def service @service ||= VAProfile::AddressValidation::V3::Service.new end end end end
0
code_files/vets-api-private/app/controllers/v0
code_files/vets-api-private/app/controllers/v0/profile/service_histories_controller.rb
# frozen_string_literal: true require 'va_profile/military_personnel/service' require 'lighthouse/benefits_discovery/params' require 'lighthouse/benefits_discovery/log_eligible_benefits_job' module V0 module Profile class ServiceHistoriesController < ApplicationController service_tag 'profile' before_action :check_authorization # Fetches the service history for the current user. # This is an array of select military service episode data. # # @return [Response] Sample response.body: # { # "data" => { # "id" => "", # "type" => "arrays", # "attributes" => { # "service_history" => [ # { # "branch_of_service" => "Air Force", # "begin_date" => "2007-04-01", # "end_date" => "2016-06-01", # "period_of_service_type_code" => "V", # "period_of_service_type_text" => "Reserve member" # } # ] # } # } # } # def show get_military_info end private def get_military_info service = VAProfile::MilitaryPersonnel::Service.new(@current_user) response = service.get_service_history handle_errors!(response.episodes) report_results(response.episodes) log_eligible_benefits(response.episodes) if Flipper.enabled?(:log_eligible_benefits) service_history_json = JSON.parse(response.to_json, symbolize_names: true) options = { is_collection: false } render json: ServiceHistorySerializer.new(service_history_json, options), status: response.status end def check_authorization report_edipi_presence authorize :vet360, :military_access? end def report_edipi_presence key = VAProfile::Stats::STATSD_KEY_PREFIX tag = @current_user.edipi.present? ? 'present:true' : 'present:false' StatsD.increment("#{key}.edipi", tags: [tag]) end def handle_errors!(response) raise_error! unless response.is_a?(Array) end def raise_error! raise Common::Exceptions::BackendServiceException.new( 'VET360_502', source: self.class.to_s ) end def report_results(response) key = VAProfile::Stats::STATSD_KEY_PREFIX tag = response.present? ? 'present:true' : 'present:false' StatsD.increment("#{key}.service_history", tags: [tag]) end def log_eligible_benefits(episodes) params = ::BenefitsDiscovery::Params.service_history_params(episodes) Lighthouse::BenefitsDiscovery::LogEligibleBenefitsJob.perform_async(current_user.uuid, params) rescue => e Rails.logger.error("Error logging eligible benefits: #{e.message}") end end end end
0
code_files/vets-api-private/app/controllers/v0
code_files/vets-api-private/app/controllers/v0/profile/persons_controller.rb
# frozen_string_literal: true require 'va_profile/person/service' module V0 module Profile class PersonsController < ApplicationController include Vet360::Transactionable service_tag 'profile' after_action :invalidate_mpi_cache def initialize_vet360_id response = VAProfile::Person::Service.new(@current_user).init_vet360_id transaction = AsyncTransaction::VAProfile::InitializePersonTransaction.start(@current_user, response) render json: AsyncTransaction::BaseSerializer.new(transaction).serializable_hash end def status check_transaction_status! end private def invalidate_mpi_cache @current_user.invalidate_mpi_cache end end end end
0
code_files/vets-api-private/app/controllers/v0
code_files/vets-api-private/app/controllers/v0/profile/communication_preferences_controller.rb
# frozen_string_literal: true require 'va_profile/communication/service' module V0 module Profile class CommunicationPreferencesController < ApplicationController service_tag 'profile' before_action { authorize :vet360, :access? } before_action { authorize :communication_preferences, :access? } def index items_and_permissions = service.get_items_and_permissions render json: CommunicationGroupsSerializer.new({ communication_groups: items_and_permissions }) end def create if communication_item.valid? log_request_complete('create') response = service.update_communication_permission(communication_item) render json: response else raise Common::Exceptions::ValidationErrors, communication_item end end def update if communication_item.valid? log_request_complete('update') communication_item.communication_channel.communication_permission.id = params[:id] response = service.update_communication_permission(communication_item) render json: response else raise Common::Exceptions::ValidationErrors, communication_item end end private def service VAProfile::Communication::Service.new(current_user) end def communication_item_params communication_channel = [:id, { communication_permission: :allowed }] params.require(:communication_item).permit(:id, communication_channel:) end def communication_item @communication_item ||= VAProfile::Models::CommunicationItem.new(communication_item_params) end def log_request_complete(action) message = "CommunicationPreferencesController##{action} request completed" Rails.logger.info(message, sso_logging_info) end end end end
0
code_files/vets-api-private/app/controllers/v0
code_files/vets-api-private/app/controllers/v0/my_va/submission_pdf_urls_controller.rb
# frozen_string_literal: true require 'forms/submission_statuses/pdf_urls' require 'faraday' module V0 module MyVA class SubmissionPdfUrlsController < ApplicationController before_action :check_flipper_flag service_tag 'form-submission-pdf' def create url = Forms::SubmissionStatuses::PdfUrls.new( form_id: request_params[:form_id], submission_guid: request_params[:submission_guid] ).fetch_url # This exception is raised if the fetch_url is not returned raise Common::Exceptions::RecordNotFound, request_params[:submission_guid] unless url.is_a?(String) # Check to make sure the returned URL is found in S3 Faraday::Connection.new do |conn| response = conn.get(url) raise Common::Exceptions::RecordNotFound, request_params[:submission_guid] if response.status != 200 end render json: { url: } end private def request_params params.require(%i[form_id submission_guid]) params end def check_flipper_flag raise Common::Exceptions::Forbidden unless Flipper.enabled?(:my_va_form_submission_pdf_link, current_user) end end end end
0
code_files/vets-api-private/app/controllers/v0
code_files/vets-api-private/app/controllers/v0/my_va/submission_statuses_controller.rb
# frozen_string_literal: true require 'forms/submission_statuses/report' module V0 module MyVA class SubmissionStatusesController < ApplicationController service_tag 'form-submission-statuses' def show report = Forms::SubmissionStatuses::Report.new( user_account: @current_user.user_account, allowed_forms: forms_based_on_feature_toggle, gateway_options: gateway_options_for_user ) result = report.run render json: serializable_from(result).to_json, status: status_from(result) end private def restricted_list_of_forms forms = [] # Always include benefits intake forms for backward compatibility forms += restricted_benefits_intake_forms forms += decision_reviews_forms_if_enabled forms end def restricted_benefits_intake_forms %w[ 20-10206 20-10207 21-0845 21-0972 21-10210 21-4142 21-4140 21-4142a 21P-0847 21P-527EZ 21P-530EZ 21P-0969 ] + uploadable_forms end def decision_reviews_forms_if_enabled return [] unless display_decision_reviews_forms? # we use form0995_form4142 here to distinguish SC 4142s from standalone 4142s %w[ 20-0995 20-0996 10182 form0995_form4142 ] end def uploadable_forms FormProfile::ALL_FORMS[:form_upload] end def serializable_from(result) hash = SubmissionStatusSerializer.new(result.submission_statuses).serializable_hash hash[:errors] = result.errors hash end def status_from(result) result.errors.present? ? 296 : 200 end def forms_based_on_feature_toggle return nil if display_all_forms? restricted_list_of_forms end def gateway_options_for_user { # ALWAYS enable benefits intake for backward compatibility # The feature flag only controls whether to show ALL forms vs restricted list benefits_intake_enabled: true, decision_reviews_enabled: display_decision_reviews_forms? } end def display_all_forms? # When this flag is true, show ALL forms without restriction (pass nil for allowed_forms) # When false, show the restricted list of forms Flipper.enabled?( :my_va_display_all_lighthouse_benefits_intake_forms, @current_user ) end def display_decision_reviews_forms? Flipper.enabled?( :my_va_display_decision_reviews_forms, @current_user ) end end end end
0
code_files/vets-api-private/app/controllers/v0
code_files/vets-api-private/app/controllers/v0/form1010cg/attachments_controller.rb
# frozen_string_literal: true module V0 module Form1010cg class AttachmentsController < ApplicationController include FormAttachmentCreate service_tag 'caregiver-application' skip_before_action :authenticate, raise: false FORM_ATTACHMENT_MODEL = ::Form1010cg::Attachment private def serializer_klass ::Form1010cg::AttachmentSerializer end end end end
0
code_files/vets-api-private/app/controllers
code_files/vets-api-private/app/controllers/sign_in/application_controller.rb
# frozen_string_literal: true module SignIn class ApplicationController < ActionController::API include SignIn::Authentication include SignIn::Instrumentation include Pundit::Authorization include ActionController::Cookies include ExceptionHandling include Headers include ControllerLoggingContext include SentryControllerLogging include Traceable service_tag 'identity' skip_before_action :authenticate, only: :cors_preflight around_action :tag_with_controller_name def cors_preflight head(:ok) end private attr_reader :current_user end end
0
code_files/vets-api-private/app/controllers
code_files/vets-api-private/app/controllers/sign_in/client_configs_controller.rb
# frozen_string_literal: true module SignIn class ClientConfigsController < SignIn::ServiceAccountApplicationController service_tag 'identity' rescue_from ActiveRecord::RecordNotFound, with: :not_found before_action :set_client_config, only: %i[show update destroy] def index client_configs = SignIn::ClientConfig.where(client_id: params[:client_ids]) render json: client_configs, status: :ok end def show render json: @client_config, status: :ok end def create client_config = SignIn::ClientConfig.new(client_config_params) if client_config.save render json: client_config, status: :created else render json: { errors: client_config.errors }, status: :unprocessable_entity end end def update if @client_config.update(client_config_params) render json: @client_config, status: :ok else render json: { errors: @client_config.errors }, status: :unprocessable_entity end end def destroy if @client_config.destroy head :no_content else render json: { errors: @client_config.errors }, status: :unprocessable_entity end end private def client_config_params params.require(:client_config).permit(:client_id, :authentication, :redirect_uri, :refresh_token_duration, :access_token_duration, :access_token_audience, :logout_redirect_uri, :pkce, :terms_of_use_url, :enforced_terms, :shared_sessions, :anti_csrf, :description, :json_api_compatibility, access_token_attributes: [], service_levels: [], credential_service_providers: [], certs_attributes: %i[id pem _destroy]) end def set_client_config @client_config = SignIn::ClientConfig.find_by!(client_id: params[:client_id]) end def not_found render json: { errors: { client_config: ['not found'] } }, status: :not_found end end end
0
code_files/vets-api-private/app/controllers
code_files/vets-api-private/app/controllers/sign_in/user_info_controller.rb
# frozen_string_literal: true module SignIn class UserInfoController < ApplicationController service_tag 'identity' def show authorize access_token, policy_class: SignIn::UserInfoPolicy user_info = SignIn::UserInfoGenerator.new(user: current_user).perform if user_info.valid? render json: user_info.serializable_hash, status: :ok else error = user_info.errors.full_messages.join(', ') Rails.logger.error('[SignIn][UserInfoController] Invalid user_info', error:) render json: { error: }, status: :bad_request end end private def user_verification current_user.user_verification end end end
0
code_files/vets-api-private/app/controllers
code_files/vets-api-private/app/controllers/sign_in/service_account_configs_controller.rb
# frozen_string_literal: true module SignIn class ServiceAccountConfigsController < ServiceAccountApplicationController service_tag 'identity' rescue_from ActiveRecord::RecordNotFound, with: :not_found before_action :set_service_account_config, only: %i[show update destroy] def index service_account_configs = ServiceAccountConfig.where(service_account_id: params[:service_account_ids]) render json: service_account_configs, status: :ok end def show render json: @service_account_config, status: :ok end def create service_account_config = ServiceAccountConfig.new(service_account_config_params) if service_account_config.save render json: service_account_config, status: :created else render json: { errors: service_account_config.errors }, status: :unprocessable_entity end end def update if @service_account_config.update(service_account_config_params) render json: @service_account_config, status: :ok else render json: { errors: @service_account_config.errors }, status: :unprocessable_entity end end def destroy if @service_account_config.destroy head :no_content else render json: { errors: @service_account_config.errors }, status: :unprocessable_entity end end private def service_account_config_params params.require(:service_account_config).permit(:service_account_id, :description, :access_token_audience, :access_token_duration, scopes: [], access_token_user_attributes: [], certs_attributes: %i[id pem _destroy]) end def set_service_account_config @service_account_config = ServiceAccountConfig.find_by!(service_account_id: params[:service_account_id]) end def not_found render json: { errors: { service_account_config: ['not found'] } }, status: :not_found end end end
0
code_files/vets-api-private/app/controllers
code_files/vets-api-private/app/controllers/sign_in/service_account_application_controller.rb
# frozen_string_literal: true module SignIn class ServiceAccountApplicationController < ActionController::API include SignIn::Authentication include SignIn::ServiceAccountAuthentication include Pundit::Authorization include ExceptionHandling include Headers include ControllerLoggingContext include SentryControllerLogging include Traceable before_action :authenticate_service_account skip_before_action :authenticate private attr_reader :current_user end end
0
code_files/vets-api-private/app/controllers
code_files/vets-api-private/app/controllers/sign_in/openid_connect_certificates_controller.rb
# frozen_string_literal: true module SignIn class OpenidConnectCertificatesController < SignIn::ApplicationController skip_before_action :authenticate def index render json: SignIn::OpenidConnectCertificatesPresenter.new.perform end end end
0
code_files/vets-api-private/app/controllers/sign_in
code_files/vets-api-private/app/controllers/sign_in/webhooks/logingov_controller.rb
# frozen_string_literal: true require 'sign_in/logingov/service' module SignIn module Webhooks class LogingovController < SignIn::ServiceAccountApplicationController Mime::Type.register 'application/secevent+jwt', :secevent_jwt service_tag 'identity' before_action :authenticate_service_account def risc Logingov::RiscEventHandler.new(payload: @risc_jwt).perform head :accepted rescue SignIn::Errors::LogingovRiscEventHandlerError => e render_error(e.message, :unprocessable_entity) end private def authenticate_service_account @risc_jwt = Logingov::Service.new.jwt_decode(request.raw_post) rescue => e render_error(e.message, :unauthorized) end def render_error(error_message, status) Rails.logger.error("[SignIn][Webhooks][LogingovController] #{action_name} error", error_message:) render json: { error: 'Failed to process RISC event' }, status: end end end end
0
code_files/vets-api-private/app/controllers
code_files/vets-api-private/app/controllers/concerns/json_api_pagination_links.rb
# frozen_string_literal: true module JsonApiPaginationLinks extend ActiveSupport::Concern private def pagination_links(collection) total_size = collection.try(:size) || collection.data.size per_page = pagination_params[:per_page].try(:to_i) || total_size current_page = pagination_params[:page].try(:to_i) || 1 total_pages = (total_size.to_f / per_page).ceil { self: build_page_url(current_page, per_page), first: build_page_url(1, per_page), prev: prev_link(current_page, per_page), next: next_link(current_page, per_page, total_pages), last: build_page_url(total_pages, per_page) } end def prev_link(current_page, per_page) return nil if current_page <= 1 build_page_url(current_page - 1, per_page) end def next_link(current_page, per_page, total_pages) return nil if current_page >= total_pages build_page_url(current_page + 1, per_page) end def build_page_url(page_number, per_page) url_params = { page: page_number, per_page:, query_parameters: request.query_parameters } path_partial = URI.parse(request.original_url).path url = "#{base_path}#{path_partial}?#{url_params.to_query}" URI.parse(url).to_s end def base_path "#{Rails.application.config.protocol}://#{Rails.application.config.hostname}" end end
0
code_files/vets-api-private/app/controllers
code_files/vets-api-private/app/controllers/concerns/ignore_not_found.rb
# frozen_string_literal: true module IgnoreNotFound def skip_sentry_exception_types ApplicationController::SKIP_SENTRY_EXCEPTION_TYPES + [Common::Exceptions::RecordNotFound] end end
0
code_files/vets-api-private/app/controllers
code_files/vets-api-private/app/controllers/concerns/controller_logging_context.rb
# frozen_string_literal: true module ControllerLoggingContext extend ActiveSupport::Concern included { before_action :set_context } private def set_context RequestStore.store['request_id'] = request.uuid RequestStore.store['additional_request_attributes'] = { 'remote_ip' => request.remote_ip, 'user_agent' => request.user_agent, 'user_uuid' => current_user&.uuid, 'source' => request.headers['Source-App-Name'] } end end
0
code_files/vets-api-private/app/controllers
code_files/vets-api-private/app/controllers/concerns/headers.rb
# frozen_string_literal: true module Headers extend ActiveSupport::Concern included { prepend_before_action :set_app_info_headers } def set_app_info_headers headers['X-Git-SHA'] = AppInfo::GIT_REVISION headers['X-GitHub-Repository'] = AppInfo::GITHUB_URL headers['Timing-Allow-Origin'] = Settings.web_origin # DataDog RUM end end
0
code_files/vets-api-private/app/controllers
code_files/vets-api-private/app/controllers/concerns/failed_request_loggable.rb
# frozen_string_literal: true module FailedRequestLoggable extend ActiveSupport::Concern class_methods do def exception_hash(exception) hash = {} %i[ as_json attributes backtrace body errors inspect instance_values key message original_body original_status response_values sentry_type serializable_hash status status_code to_a to_h to_json to_s ].each do |method| hash[method] = exception.send method rescue nil end hash end end private def current_user_hash hash = {} %i[first_name last_name birls_id icn edipi mhv_correlation_id participant_id vet360_id ssn] .each { |key| hash[key] = @current_user.try(key) } hash[:assurance_level] = begin @current_user.loa[:current] rescue nil end hash[:birth_date] = begin @current_user.birth_date_mpi.to_date.iso8601 rescue nil end hash end def log_exception_to_personal_information_log(exception, error_class:, **additional_data) data = { user: current_user_hash, error: self.class.exception_hash(exception) } data[:additional_data] = additional_data if additional_data.present? begin PersonalInformationLog.create!(error_class:, data:) rescue => e # Not sure if the error message could include PII # so just logging the backtrace as it would still tell us if there's a validation error or something Rails.logger.error('PersonalInformationLog error backtrace', e.backtrace) raise end end end
0
code_files/vets-api-private/app/controllers
code_files/vets-api-private/app/controllers/concerns/appointment_authorization.rb
# frozen_string_literal: true module AppointmentAuthorization extend ActiveSupport::Concern protected def authorize raise_access_denied unless current_user.loa3? raise_access_denied_no_icn if current_user.icn.blank? end def authorize_with_facilities authorize raise_access_denied_no_facilities unless current_user.authorize(:vaos, :facilities_access?) end def raise_access_denied raise Common::Exceptions::Forbidden, detail: 'You do not have access to online scheduling' end def raise_access_denied_no_icn raise Common::Exceptions::Forbidden, detail: 'No patient ICN found' end def raise_access_denied_no_facilities raise Common::Exceptions::Forbidden, detail: 'No facility associated with user' end end
0
code_files/vets-api-private/app/controllers
code_files/vets-api-private/app/controllers/concerns/form_attachment_create.rb
# frozen_string_literal: true module FormAttachmentCreate extend ActiveSupport::Concern def create debug_timestamp = Time.current.iso8601 Rails.logger.info('begin form attachment creation', { file_data_present: filtered_params[:file_data].present?, klass: filtered_params[:file_data]&.class&.name, debug_timestamp: }) validate_file_upload_class! save_attachment_to_cloud! save_attachment_to_db! serialized = serializer_klass.new(form_attachment) Rails.logger.info('finish form attachment creation', { serialized: serialized.present?, debug_timestamp: }) render json: serialized end private def serializer_klass raise NotImplementedError, 'Class must implement serializer method' end def validate_file_upload_class! # is it either ActionDispatch::Http::UploadedFile or Rack::Test::UploadedFile unless filtered_params[:file_data].class.name.include? 'UploadedFile' raise Common::Exceptions::InvalidFieldValue.new('file_data', filtered_params[:file_data].class.name) end rescue => e Rails.logger.info('form attachment error 1 - validate class', { phase: 'FAC_validate', klass: filtered_params[:file_data].class.name, exception: e.message }) raise e end def save_attachment_to_cloud! form_attachment.set_file_data!(filtered_params[:file_data], filtered_params[:password]) rescue => e Rails.logger.info('form attachment error 2 - save to cloud', { has_pass: filtered_params[:password].present?, ext: File.extname(filtered_params[:file_data]).last(5), phase: 'FAC_cloud', exception: e.message }) raise e end def save_attachment_to_db! form_attachment.save! rescue => e Rails.logger.info('form attachment error 3 - save to db', { phase: 'FAC_db', errors: form_attachment.errors, exception: e.message }) raise e end def form_attachment @form_attachment ||= form_attachment_model.new end def form_attachment_model @form_attachment_model ||= self.class::FORM_ATTACHMENT_MODEL end def filtered_params @filtered_params ||= extract_params_from_namespace end def extract_params_from_namespace namespace = form_attachment_model.to_s.underscore.split('/').last params.require(namespace).permit(:file_data, :password) end end
0
code_files/vets-api-private/app/controllers
code_files/vets-api-private/app/controllers/concerns/sentry_controller_logging.rb
# frozen_string_literal: true module SentryControllerLogging extend ActiveSupport::Concern included { before_action :set_sentry_tags_and_extra_context } private def set_sentry_tags_and_extra_context Sentry.set_extras(request_uuid: request.uuid) Sentry.set_user(user_context) if current_user Sentry.set_tags(tags_context) end def user_context { id: current_user&.uuid, authn_context: current_user&.authn_context, loa: current_user&.loa, mhv_icn: current_user&.mhv_icn } end def tags_context { controller_name: }.tap do |tags| # identity_sign_in for User, sign_in for AccreditedRepresentativePortal::RepresentativeUser sign_in = current_user.is_a?(User) ? current_user.identity_sign_in : current_user&.sign_in if sign_in.present? tags[:sign_in_method] = sign_in[:service_name] # account_type is filtered by sentry, because in other contexts it refers to a bank account type tags[:sign_in_acct_type] = sign_in[:account_type] else tags[:sign_in_method] = 'not-signed-in' end tags[:source] = request.headers['Source-App-Name'] if request.headers['Source-App-Name'] end end end
0
code_files/vets-api-private/app/controllers
code_files/vets-api-private/app/controllers/concerns/traceable.rb
# frozen_string_literal: true # Provides functionality to controllers for tagging them with specific services. # This tagging allows monitoring and tracing systems (like Datadog) to identify and group # the activities of specific controllers based on the service tags they are associated with. # # @example Setting a service tag for a controller # class MyController < ApplicationController # include Traceable # service_tag :my_service # end module Traceable extend ActiveSupport::Concern included do before_action :set_trace_tags # A class_attribute is appropriate here as it allows overriding within subclasses (child controllers) # It is set via the service_tag method during controller declaration, and only read thereafter class_attribute :trace_service_tag # rubocop:disable ThreadSafety/ClassAndModuleAttributes end class_methods do # Assigns a service tag to the controller class. # @param service_name [Symbol] the name of the service tag. # @return [Symbol] the set service tag. def service_tag(service_name) self.trace_service_tag = service_name end end # Sets trace tags for the current action. If no service tag is set, do nothing. # @note After all current controllers implement service tagging, this could raise an error instead. def set_trace_tags service = self.class.trace_service_tag # Not warning for now, re-introduce once we are at 100% of controllers tagged # return Rails.logger.warn('Service tag missing', class: self.class.name) if service.blank? Datadog::Tracing.active_span&.service = service if service.present? rescue => e Rails.logger.error('Error setting service tag', class: self.class.name, message: e.message) end # Wraps controller methods with the controller class name as "origin". def tag_with_controller_name(&) return yield if self.class.name.blank? SemanticLogger.named_tagged(origin: self.class.name.underscore, &) end end
0
code_files/vets-api-private/app/controllers
code_files/vets-api-private/app/controllers/concerns/exception_handling.rb
# frozen_string_literal: true require 'common/exceptions' require 'common/client/errors' require 'json_schema/json_api_missing_attribute' require 'datadog' require 'vets/shared_logging' module ExceptionHandling extend ActiveSupport::Concern include Vets::SharedLogging # In addition to Common::Exceptions::BackendServiceException that have sentry_type :none the following exceptions # will also be skipped. SKIP_SENTRY_EXCEPTION_TYPES = [ Breakers::OutageException, JsonSchema::JsonApiMissingAttribute, Pundit::NotAuthorizedError ].freeze private def skip_sentry_exception_types SKIP_SENTRY_EXCEPTION_TYPES end def skip_sentry_exception?(exception) return true if exception.class.in?(skip_sentry_exception_types) exception.respond_to?(:sentry_type) && !exception.log_to_sentry? end included do rescue_from 'Exception' do |exception| va_exception = case exception when Pundit::NotAuthorizedError Common::Exceptions::Forbidden.new(detail: 'User does not have access to the requested resource') when ActionController::InvalidAuthenticityToken Common::Exceptions::Forbidden.new(detail: 'Invalid Authenticity Token') when Common::Exceptions::TokenValidationError, Common::Exceptions::BaseError, JsonSchema::JsonApiMissingAttribute, Common::Exceptions::ServiceUnavailable, Common::Exceptions::BadGateway, Common::Exceptions::RoutingError exception when ActionController::ParameterMissing Common::Exceptions::ParameterMissing.new(exception.param) when Breakers::OutageException Common::Exceptions::ServiceOutage.new(exception.outage) when Common::Client::Errors::ClientError # SSLError, ConnectionFailed, SerializationError, etc Common::Exceptions::ServiceOutage.new(nil, detail: 'Backend Service Outage') else Common::Exceptions::InternalServerError.new(exception) end unless skip_sentry_exception?(exception) report_original_exception(exception) report_mapped_exception(exception, va_exception) end headers['WWW-Authenticate'] = 'Token realm="Application"' if va_exception.is_a?(Common::Exceptions::Unauthorized) render_errors(va_exception) end end def render_errors(va_exception) case va_exception when JsonSchema::JsonApiMissingAttribute render json: va_exception.to_json_api, status: va_exception.code else render json: { errors: va_exception.errors }, status: va_exception.status_code end end def report_original_exception(exception) # report the original 'cause' of the exception when present if skip_sentry_exception?(exception) Rails.logger.error "#{exception.message}.", backtrace: exception.backtrace elsif exception.is_a?(Common::Exceptions::BackendServiceException) && exception.generic_error? # Warn about VA900 needing to be added to exception.en.yml log_message_to_sentry(exception.va900_warning, :warn, i18n_exception_hint: exception.va900_hint) log_message_to_rails(exception.va900_warning, :warn, i18n_exception_hint: exception.va900_hint) end end def report_mapped_exception(exception, va_exception) extra = exception.respond_to?(:errors) ? { errors: exception.errors.map(&:to_h) } : {} # Add additional user specific context to the logs if exception.is_a?(Common::Exceptions::BackendServiceException) && current_user.present? extra[:icn] = current_user.icn extra[:mhv_credential_uuid] = current_user.mhv_credential_uuid end va_exception_info = { va_exception_errors: va_exception.errors.map(&:to_hash) } log_exception_to_sentry(exception, extra.merge(va_exception_info)) log_exception_to_rails(exception) # Because we are handling exceptions here and not re-raising, we need to set the error on the # Datadog span for it to be reported correctly. We also need to set it on the top-level # (Rack) span for errors to show up in the Datadog Error Tracking console. # Datadog does not support setting rich structured context on spans so we are ignoring # the extra va_exception and other context for now. We can set tags in Datadog as they are used # in Sentry, but tags are not suitable for complex objects. Datadog::Tracing.active_span&.set_error(exception) request.env[Datadog::Tracing::Contrib::Rack::Ext::RACK_ENV_REQUEST_SPAN]&.set_error(exception) end end
0
code_files/vets-api-private/app/controllers
code_files/vets-api-private/app/controllers/concerns/filterable.rb
# frozen_string_literal: true module Filterable extend ActiveSupport::Concern included do before_action :validate_filter_params!, only: :index end def validate_filter_params! if params[:filter].present? return true if valid_filters? raise Common::Exceptions::InvalidFiltersSyntax, filter_query end end private def filter_query @filter_query ||= begin q = URI.parse(request.url).query || '' q.split('&').select { |a| a.include?('filter') } end end def valid_filters? filter_query.map { |a| a.gsub('filter', '') }.all? { |s| s =~ /\A\[\[.+\]\[.+\]\]=.+\z/ } end def filter_params params.require(:filter).permit(Prescription.filterable_params.merge(Message.filterable_params)) end end
0
code_files/vets-api-private/app/controllers
code_files/vets-api-private/app/controllers/concerns/instrumentation.rb
# frozen_string_literal: true module Instrumentation extend ActiveSupport::Concern include SignIn::Authentication private def append_info_to_payload(payload) if @access_token.present? payload[:session] = @access_token.session_handle elsif session && session[:token] payload[:session] = Session.obscure_token(session[:token]) end payload[:user_uuid] = current_user.uuid if current_user.present? end end
0
code_files/vets-api-private/app/controllers
code_files/vets-api-private/app/controllers/concerns/pdf_filename_generator.rb
# frozen_string_literal: true module PdfFilenameGenerator extend ActiveSupport::Concern private # Generates a PDF filename based on form data and prefix. # # Creates a filename using the form prefix and veteran's name from the parsed form data. # If name fields are missing or empty, they are omitted from the filename gracefully. # # @param parsed_form [Hash] The parsed form data containing veteran information # @param field [String] The field name containing name data (e.g., 'veteranFullName', 'fullName') # @param form_prefix [String] The form identifier to prefix the filename (e.g., '10-10EZ', '10-10EZR') # # @return [String] The generated PDF filename with .pdf extension def file_name_for_pdf(parsed_form, field, form_prefix) first_name = parsed_form.dig(field, 'first').presence last_name = parsed_form.dig(field, 'last').presence "#{[form_prefix, first_name, last_name].compact.join('_')}.pdf" end end
0
code_files/vets-api-private/app/controllers
code_files/vets-api-private/app/controllers/concerns/authentication_and_sso_concerns.rb
# frozen_string_literal: true # This module only gets mixed in to one place, but is that cleanest way to organize everything in one place related # to this responsibility alone. module AuthenticationAndSSOConcerns # rubocop:disable Metrics/ModuleLength extend ActiveSupport::Concern include ActionController::Cookies include SignIn::Authentication include SignIn::AudienceValidator included do before_action :authenticate, :set_session_expiration_header validates_access_token_audience [IdentitySettings.sign_in.vaweb_client_id, ('vamock' if MockedAuthentication.mockable_env?)] end protected def authenticate if cookies[SignIn::Constants::Auth::ACCESS_TOKEN_COOKIE_NAME] super else validate_session || render_unauthorized end end def render_unauthorized raise Common::Exceptions::Unauthorized end def validate_inbound_login_params csp_type = params[:csp_type] ||= '' if csp_type == SAML::User::LOGINGOV_CSID ial = params[:ial] raise Common::Exceptions::ParameterMissing, 'ial' if ial.blank? raise Common::Exceptions::InvalidFieldValue.new('ial', ial) if %w[1 2].exclude?(ial) ial == '1' ? IAL::LOGIN_GOV_IAL1 : IAL::LOGIN_GOV_IAL2 else authn = params[:authn] raise Common::Exceptions::ParameterMissing, 'authn' if authn.blank? raise Common::Exceptions::InvalidFieldValue.new('authn', authn) if SAML::User::AUTHN_CONTEXTS.keys.exclude?(authn) authn end end def validate_session load_user if @session_object.nil? Rails.logger.debug('SSO: INVALID SESSION', sso_logging_info) clear_session return false end extend_session! @current_user.present? end def load_user(skip_terms_check: false) if cookies[SignIn::Constants::Auth::ACCESS_TOKEN_COOKIE_NAME] super() else set_session_object set_current_user(skip_terms_check) end end # Destroys the user's session in Redis def clear_session Rails.logger.debug('SSO: ApplicationController#clear_session', sso_logging_info) @session_object&.destroy @current_user&.destroy @session_object = nil @current_user = nil end # Destroys the users session in 1) Redis, 2) the MHV SSO Cookie, 3) and the Session Cookie def reset_session if Settings.test_user_dashboard.env == 'staging' && @current_user TestUserDashboard::UpdateUser.new(@current_user).call TestUserDashboard::AccountMetrics.new(@current_user).checkin end Rails.logger.info('SSO: ApplicationController#reset_session', sso_logging_info) clear_session super end # Extends the users session def extend_session! @session_object.expire(Session.redis_namespace_ttl) @current_user&.identity&.expire(UserIdentity.redis_namespace_ttl) @current_user&.expire(User.redis_namespace_ttl) end # Sets a cookie "api_session" with all of the key/value pairs from session object. def set_api_cookie return unless @session_object session.delete :value @session_object.to_hash.each { |k, v| session[k] = v } end def set_cerner_eligibility_cookie cookie_name = V1::SessionsController::CERNER_ELIGIBLE_COOKIE_NAME previous_value = ActiveModel::Type::Boolean.new.cast(cookies.signed[cookie_name] || cookies[cookie_name]) eligible = @current_user.cerner_eligible? cookies.permanent[cookie_name] = { value: eligible, domain: IdentitySettings.sign_in.info_cookie_domain } Rails.logger.info('[SessionsController] Cerner Eligibility', eligible:, previous_value:, cookie_action: :set, icn: @current_user.icn) end def set_session_expiration_header headers['X-Session-Expiration'] = @session_object.ttl_in_time.httpdate if @session_object.present? end def log_sso_info action = "#{self.class}##{action_name}" Rails.logger.info( "#{action} request completed", sso_logging_info ) end # Info for logging purposes related to SSO. def sso_logging_info { user_uuid: @current_user&.uuid, sso_cookie_contents: sso_cookie_content, request_host: request.host } end private def set_session_object @session_object = Session.find(session[:token]) end def set_current_user(skip_terms_check) return unless @session_object user = User.find(@session_object.uuid) if (skip_terms_check || !user&.needs_accepted_terms_of_use) && !user&.credential_lock && user&.identity @current_user = user end end def sso_cookie_content return nil if @current_user.blank? { 'patientIcn' => @current_user.icn, 'signIn' => @current_user.identity.sign_in.deep_transform_keys { |key| key.to_s.camelize(:lower) }, 'credential_used' => @current_user.identity.sign_in[:service_name], 'credential_uuid' => credential_uuid, 'session_uuid' => sign_in_service_session ? @access_token.session_handle : @session_object.token, 'expirationTime' => sign_in_service_session ? sign_in_service_exp_time : @session_object.ttl_in_time.iso8601(0) } end def credential_uuid case @current_user.identity.sign_in[:service_name] when SAML::User::IDME_CSID @current_user.identity.idme_uuid when SAML::User::LOGINGOV_CSID @current_user.identity.logingov_uuid when SAML::User::DSLOGON_CSID @current_user.identity.edipi end end def sign_in_service_exp_time sign_in_service_session.refresh_expiration.iso8601(0) end def sign_in_service_session return unless @access_token @sign_in_service_session ||= SignIn::OAuthSession.find_by(handle: @access_token.session_handle) end end
0
code_files/vets-api-private/app/controllers/concerns
code_files/vets-api-private/app/controllers/concerns/sign_in/service_account_authentication.rb
# frozen_string_literal: true require 'sign_in/logger' module SignIn module ServiceAccountAuthentication extend ActiveSupport::Concern BEARER_PATTERN = /^Bearer / protected def authenticate_service_account @service_account_access_token = authenticate_service_account_access_token validate_requested_scope @service_account_access_token.present? rescue Errors::AccessTokenExpiredError => e render json: { errors: e }, status: :forbidden rescue Errors::StandardError => e handle_authenticate_error(e) end private def authenticate_service_account_access_token ServiceAccountAccessTokenJwtDecoder.new(service_account_access_token_jwt: bearer_token).perform end def bearer_token header = request.authorization header.gsub(BEARER_PATTERN, '') if header&.match(BEARER_PATTERN) end def handle_authenticate_error(error) Rails.logger.error('[SignIn][ServiceAccountAuthentication] authentication error', access_token_authorization_header: bearer_token, errors: error.message) render json: { errors: error }, status: :unauthorized end def validate_requested_scope authorized_scopes = @service_account_access_token.scopes return if authorized_scopes.any? { |scope| request.url.include?(scope) } raise Errors::InvalidServiceAccountScope.new message: 'Required scope for requested resource not found' end end end
0
code_files/vets-api-private/app/controllers/concerns
code_files/vets-api-private/app/controllers/concerns/sign_in/authentication.rb
# frozen_string_literal: true require 'sign_in/logger' module SignIn module Authentication extend ActiveSupport::Concern BEARER_PATTERN = /^Bearer / included do before_action :authenticate end protected def authenticate @current_user = load_user_object validate_request_ip @current_user.present? rescue Errors::AccessTokenExpiredError => e render json: { errors: e }, status: :forbidden rescue Errors::StandardError => e handle_authenticate_error(e) end def load_user(skip_expiration_check: false) @current_user = load_user_object validate_request_ip @current_user.present? rescue Errors::AccessTokenExpiredError => e render json: { errors: e }, status: :forbidden unless skip_expiration_check rescue Errors::StandardError nil end def access_token_authenticate(skip_render_error: false, re_raise: false) access_token.present? rescue Errors::AccessTokenExpiredError => e raise if re_raise render json: { errors: e }, status: :forbidden unless skip_render_error rescue Errors::StandardError => e raise if re_raise handle_authenticate_error(e) unless skip_render_error end private def access_token @access_token ||= authenticate_access_token end def bearer_token header = request.authorization header.gsub(BEARER_PATTERN, '') if header&.match(BEARER_PATTERN) end def cookie_access_token(access_token_cookie_name: Constants::Auth::ACCESS_TOKEN_COOKIE_NAME) return unless defined?(cookies) cookies[access_token_cookie_name] end def authenticate_access_token(with_validation: true) access_token_jwt = bearer_token || cookie_access_token AccessTokenJwtDecoder.new(access_token_jwt:).perform(with_validation:) end def load_user_object UserLoader.new(access_token:, request_ip: request.remote_ip, cookies:).perform end def handle_authenticate_error(error, access_token_cookie_name: Constants::Auth::ACCESS_TOKEN_COOKIE_NAME) context = { access_token_authorization_header: scrub_bearer_token, access_token_cookie: cookie_access_token(access_token_cookie_name:) }.compact if context.present? Rails.logger.error('[SignIn][Authentication] authentication error', context.merge(errors: error.message)) end render json: { errors: error }, status: :unauthorized end def scrub_bearer_token bearer_token == 'undefined' ? nil : bearer_token end def validate_request_ip return if @current_user.fingerprint == request.remote_ip log_context = { request_ip: request.remote_ip, fingerprint: @current_user.fingerprint } Rails.logger.warn('[SignIn][Authentication] fingerprint mismatch', log_context) @current_user.fingerprint = request.remote_ip @current_user.save end end end
0
code_files/vets-api-private/app/controllers/concerns
code_files/vets-api-private/app/controllers/concerns/sign_in/audience_validator.rb
# frozen_string_literal: true module SignIn module AudienceValidator extend ActiveSupport::Concern included do prepend Authentication class_attribute :valid_audience # rubocop:disable ThreadSafety/ClassAndModuleAttributes end class_methods do def validates_access_token_audience(*audience) return if audience.empty? self.valid_audience = audience.flatten.compact end end protected def authenticate validate_audience! super rescue Errors::InvalidAudienceError => e render json: { errors: e }, status: :unauthorized rescue Errors::AccessTokenExpiredError => e render json: { errors: e }, status: :forbidden rescue Errors::StandardError => e handle_authenticate_error(e) end private def validate_audience! valid_audience = self.class.valid_audience return if valid_audience.blank? return if access_token.audience.any? { |aud| valid_audience.include?(aud) } Rails.logger.error('[SignIn][AudienceValidator] Invalid audience', { invalid_audience: access_token.audience, valid_audience: }) raise Errors::InvalidAudienceError.new(message: 'Invalid audience') end end end
0
code_files/vets-api-private/app/controllers/concerns
code_files/vets-api-private/app/controllers/concerns/sign_in/sso_authorizable.rb
# frozen_string_literal: true module SignIn module SSOAuthorizable extend ActiveSupport::Concern included do skip_before_action :authenticate, only: :authorize_sso before_action :authenticate_authorize_sso, only: :authorize_sso end def authorize_sso validate_authorize_sso_params! user_code_map = authorize_sso_user_code_map response_params = { code: user_code_map.login_code, type: user_code_map.type, state: user_code_map.client_state }.compact_blank redirect_url = RedirectUrlGenerator.new( redirect_uri: user_code_map.client_config.redirect_uri, terms_code: user_code_map.terms_code, terms_redirect_uri: user_code_map.client_config.terms_of_use_url, params_hash: response_params ).perform log_authorize_sso_success render body: redirect_url, content_type: 'text/html', status: :found rescue Errors::MalformedParamsError => e handle_authorize_sso_error(e, :error) rescue => e handle_authorize_sso_error(e, :redirect) end private def authorize_sso_user_code_map client_id = authorize_sso_params[:client_id] code_challenge = authorize_sso_params[:code_challenge] code_challenge_method = authorize_sso_params[:code_challenge_method] client_state = authorize_sso_params[:state] user_attributes = AuthSSO::SessionValidator.new(access_token: @access_token, client_id:).perform state_payload_jwt = StatePayloadJwtEncoder.new(code_challenge:, code_challenge_method:, client_state:, acr: user_attributes[:acr], type: user_attributes[:type], client_config: client_config(client_id)).perform state_payload = StatePayloadJwtDecoder.new(state_payload_jwt:).perform UserCodeMapCreator.new(user_attributes:, state_payload:, verified_icn: user_attributes[:icn], request_ip: request.remote_ip).perform end def authorize_sso_params @authorize_sso_params ||= params.permit(:client_id, :code_challenge, :code_challenge_method, :state) end def validate_authorize_sso_params! errors = [].tap do |err| err << 'client_id' if authorize_sso_params[:client_id].blank? err << 'code_challenge' if authorize_sso_params[:code_challenge].blank? unless authorize_sso_params[:code_challenge_method] == Constants::Auth::CODE_CHALLENGE_METHOD err << 'code_challenge_method' end end raise Errors::MalformedParamsError.new(message: "Invalid params: #{errors.join(', ')}") if errors.any? end def redirect_to_usip query_params = authorize_sso_params.to_h.merge(oauth: true) uri = URI.parse(IdentitySettings.sign_in.usip_uri) uri.query = query_params.to_query redirect_to uri, status: :found end def authenticate_authorize_sso access_token_authenticate(re_raise: true) rescue => e handle_authorize_sso_error(e, :redirect) end def handle_authorize_sso_error(error, handler) log_authorize_sso_error(error, handler) case handler when :error then render json: { error: error.message }, status: :bad_request when :redirect then redirect_to_usip end end def log_authorize_sso_success sign_in_logger.info('authorize sso', client_id: authorize_sso_params[:client_id]) StatsD.increment( Constants::Statsd::STATSD_SIS_AUTHORIZE_SSO_SUCCESS, tags: ["client_id:#{authorize_sso_params[:client_id]}"] ) end def log_authorize_sso_error(error, handler) statsd_key = if handler == :redirect Constants::Statsd::STATSD_SIS_AUTHORIZE_SSO_REDIRECT else Constants::Statsd::STATSD_SIS_AUTHORIZE_SSO_FAILURE end sign_in_logger.info("authorize sso #{handler}", error: error.message, client_id: authorize_sso_params[:client_id]) StatsD.increment(statsd_key) end end end
0
code_files/vets-api-private/app/controllers/concerns
code_files/vets-api-private/app/controllers/concerns/sign_in/instrumentation.rb
# frozen_string_literal: true module SignIn module Instrumentation extend ActiveSupport::Concern private def append_info_to_payload(payload) super payload[:session] = session if @access_token.present? payload[:user_uuid] = current_user.uuid if current_user.present? end def session @access_token.session_handle end end end
0
code_files/vets-api-private/app/controllers/concerns
code_files/vets-api-private/app/controllers/concerns/evss/authorizeable.rb
# frozen_string_literal: true module EVSS module Authorizeable extend ActiveSupport::Concern def authorize_evss! unless EVSSPolicy.new(@current_user, :evss).access? raise Common::Exceptions::Forbidden.new(detail: error_detail, source: 'EVSS') end end private def error_detail "User does not have access to the requested resource due to missing values: #{missing_values}" end # Returns a comma-separated string of the user's blank attributes. `participant_id` is AKA `corp_id`. # # @return [String] Comma-separated string of the attribute names # def missing_values missing = [] missing << 'corp_id' if @current_user.participant_id.blank? missing << 'edipi' if @current_user.edipi.blank? missing << 'ssn' if @current_user.ssn.blank? missing.join(', ') end end end
0
code_files/vets-api-private/app/controllers/concerns
code_files/vets-api-private/app/controllers/concerns/vet360/transactionable.rb
# frozen_string_literal: true require 'common/exceptions/record_not_found' require 'va_profile/contact_information/v2/service' module Vet360 module Transactionable extend ActiveSupport::Concern def check_transaction_status! transaction = AsyncTransaction::VAProfile::Base.refresh_transaction_status( @current_user, service, params[:transaction_id] ) raise Common::Exceptions::RecordNotFound, transaction unless transaction render json: AsyncTransaction::BaseSerializer.new(transaction).serializable_hash end private def service VAProfile::ContactInformation::V2::Service.new @current_user end end end
0
code_files/vets-api-private/app/controllers/concerns
code_files/vets-api-private/app/controllers/concerns/vet360/writeable.rb
# frozen_string_literal: true require 'common/exceptions/validation_errors' require 'va_profile/contact_information/v2/service' module Vet360 module Writeable extend ActiveSupport::Concern PROFILE_AUDIT_LOG_TYPES = { email: :update_email_address, address: :update_mailing_address, telephone: :update_phone_number }.with_indifferent_access.freeze # For the passed VAProfile model type and params, it: # - builds and validates a VAProfile models # - POSTs/PUTs the model data to VAProfile # - creates a new AsyncTransaction db record, based on the type # - renders the transaction through the base serializer # # @param type [String] the VAProfile::Models type (i.e. 'Email', 'Address', etc.) # @param params [ActionController::Parameters ] The strong params from the controller # @param http_verb [String] The type of write request being made to VAProfile ('post' or 'put') # @return [Response] Normal controller `render json:` response with a response.body, .status, etc. # def write_to_vet360_and_render_transaction!(type, params, http_verb: 'post') record = build_record(type, params) validate!(record) response = write_valid_record!(http_verb, type, record) create_user_audit_log(type) if PROFILE_AUDIT_LOG_TYPES[type].present? render_new_transaction!(type, response) end def invalidate_cache VAProfileRedis::V2::Cache.invalidate(@current_user) end private def build_record(type, params) # This needs to be refactored after V2 upgrade is complete if type == 'address' model = 'VAProfile::Models::Address' Rails.logger.info("Override Key Present? #{params[:override_validation_key].present?}, Validation present? #{params[:validation_key].present?}") # Validation Key was deprecated with ContactInformationV2 params[:override_validation_key] ||= params[:validation_key] params[:validation_key] ||= params[:override_validation_key] # Ensures the address_pou is valid if params[:address_pou] == 'RESIDENCE/CHOICE' params[:address_pou] = 'RESIDENCE' Rails.logger.info('RESIDENCE/CHOICE POU conversion detected') end else model = "VAProfile::Models::#{type.capitalize}" end model.constantize .new(params) .set_defaults(@current_user) end def create_user_audit_log(type) UserAudit.logger.success(event: PROFILE_AUDIT_LOG_TYPES[type], user_verification: @current_user.user_verification) end def validate!(record) return if record.valid? PersonalInformationLog.create!( data: record.to_h, error_class: "#{record.class} ValidationError" ) raise Common::Exceptions::ValidationErrors, record end def service VAProfile::ContactInformation::V2::Service.new @current_user end def write_valid_record!(http_verb, type, record) Rails.logger.info('Contact Info', http_verb, type) # This will be removed after the upgrade. Permission was removed in the upgraded service. # Permissions are not used in ContactInformationV1 either. service.send("#{http_verb}_#{type.downcase}", record) end def render_new_transaction!(type, response) transaction = "AsyncTransaction::VAProfile::#{type.capitalize}Transaction".constantize.start( @current_user, response ) render json: AsyncTransaction::BaseSerializer.new(transaction).serializable_hash end def add_effective_end_date(params) params[:effective_end_date] = Time.now.utc.iso8601 params end end end
0
code_files/vets-api-private/app/controllers
code_files/vets-api-private/app/controllers/sts/terms_of_use_controller.rb
# frozen_string_literal: true require 'mhv/account_creation/configuration' module Sts class TermsOfUseController < SignIn::ServiceAccountApplicationController service_tag 'identity' before_action :set_current_terms_of_use_agreement, only: %i[current_status] def current_status Rails.logger.info('[Sts][TermsOfUseController] current_status success', icn:) render json: serialized_response, status: :ok end private def set_current_terms_of_use_agreement @current_terms_of_use_agreement = TermsOfUseAgreement.joins(:user_account) .where(user_account: { icn: }) .current.last end def icn @service_account_access_token.user_attributes['icn'] end def serialized_response { agreement_status: @current_terms_of_use_agreement&.response }.tap { |h| h[:metadata] = metadata if include_metadata? } end def include_metadata? params[:metadata] == 'true' && @current_terms_of_use_agreement&.accepted? end def metadata { va_terms_of_use_doc_title: MHV::AccountCreation::Configuration::TOU_DOC_TITLE, va_terms_of_use_legal_version: MHV::AccountCreation::Configuration::TOU_LEGAL_VERSION, va_terms_of_use_revision: MHV::AccountCreation::Configuration::TOU_REVISION, va_terms_of_use_status: MHV::AccountCreation::Configuration::TOU_STATUS, va_terms_of_use_datetime: @current_terms_of_use_agreement&.created_at } end end end
0
code_files/vets-api-private/app
code_files/vets-api-private/app/helpers/parameter_filter_helper.rb
# frozen_string_literal: true # ParameterFilterHelper # # This helper provides a method to filter parameters using the lambda # defined in Rails.application.config.filter_parameters. # # Note: # When running in Rails Console, Rails.application.config.filter_parameters == [] # The filtering lambda gets reset in `console_filter_toggles.rb#reveal!` # The filter_parameters chain will return nil since there is no lambda to call. module ParameterFilterHelper def filter_params(params) Rails.application.config.filter_parameters.first&.call(nil, params.deep_dup) || params end module_function :filter_params end
0
code_files/vets-api-private/app
code_files/vets-api-private/app/services/debt_transaction_log_service.rb
# frozen_string_literal: true class DebtTransactionLogService STATS_KEY = 'api.debt_transaction_log' def self.track_dispute(submission, user) create_transaction_log( transactionable: submission, transaction_type: 'dispute', user_uuid: user.uuid, debt_identifiers: submission.debt_identifiers || [], summary_data: DebtTransactionLog::SummaryBuilders::DisputeSummaryBuilder.build(submission) ) end def self.track_waiver(submission, user) create_transaction_log( transactionable: submission, transaction_type: 'waiver', user_uuid: user.uuid, debt_identifiers: extract_waiver_debt_identifiers(submission), summary_data: DebtTransactionLog::SummaryBuilders::WaiverSummaryBuilder.build(submission) ) end def self.mark_submitted(transaction_log:, external_reference_id: nil) update_state(transaction_log, 'submitted', external_reference_id:) end def self.mark_completed(transaction_log:, external_reference_id: nil) update_state(transaction_log, 'completed', external_reference_id:, completed_at: Time.current) end def self.mark_failed(transaction_log:, external_reference_id: nil) update_state(transaction_log, 'failed', external_reference_id:, completed_at: Time.current) end class << self private def create_transaction_log(transactionable:, transaction_type:, user_uuid:, debt_identifiers:, summary_data:) attributes = build_transaction_log_attributes( transactionable:, transaction_type:, user_uuid:, debt_identifiers:, summary_data: ) log = DebtTransactionLog.create!(attributes) StatsD.increment("#{STATS_KEY}.#{transaction_type}.created") log rescue => e Rails.logger.error("Failed to create #{transaction_type} transaction log: #{e.message}") Rails.logger.error(e.backtrace.join("\n")) StatsD.increment("#{STATS_KEY}.#{transaction_type}.creation_failed") nil end def build_transaction_log_attributes(transactionable:, transaction_type:, user_uuid:, debt_identifiers:, summary_data:) { transactionable_type: transactionable.class.name, transactionable_id: resolve_transactionable_id(transactionable), transaction_type:, user_uuid:, debt_identifiers:, summary_data:, state: 'pending', transaction_started_at: Time.current } end def resolve_transactionable_id(transactionable) if transactionable.is_a?(DebtsApi::V0::DigitalDisputeSubmission) transactionable.guid else transactionable.id end end def update_state(transaction_log, new_state, external_reference_id: nil, completed_at: nil) return false unless transaction_log update_data = { state: new_state } update_data[:external_reference_id] = external_reference_id if external_reference_id update_data[:transaction_completed_at] = completed_at if completed_at transaction_log.update!(update_data) StatsD.increment("#{STATS_KEY}.#{transaction_log.transaction_type}.state.#{new_state}") true rescue => e Rails.logger.error("Failed to update debt transaction log state to #{new_state}: #{e.message}") StatsD.increment("#{STATS_KEY}.state_update_failed") false end def extract_waiver_debt_identifiers(submission) # Format: "#{deductionCode}#{originalAR.to_i}" for VBA debts, UUID for VHA copays submission.debt_identifiers rescue => e Rails.logger.warn("Failed to extract debt identifiers for waiver submission #{submission.id}: #{e.message}") [] end end end
0
code_files/vets-api-private/app
code_files/vets-api-private/app/services/mhv_account_type_service.rb
# frozen_string_literal: true require 'bb/client' require 'vets/collection' ## # Models logic pertaining to the verification and logging of MHV accounts # # @param user [User] the user object # class MHVAccountTypeService ELIGIBLE_DATA_CLASS_COUNT_TO_ACCOUNT_LEVEL = { 32 => 'Premium', 18 => 'Advanced', 16 => 'Basic' }.freeze DEFAULT_ACCOUNT_LEVEL = 'Unknown' MHV_DOWN_MESSAGE = 'MHVAccountTypeService: could not fetch eligible data classes' UNEXPECTED_DATA_CLASS_COUNT_MESSAGE = 'MHVAccountTypeService: eligible data class mapping inconsistency' def initialize(user) @user = user @eligible_data_classes = fetch_eligible_data_classes if mhv_account? end attr_reader :user, :eligible_data_classes ## # Retrieve the MHV account type # # @return [NilClass] if the account is not an MHV account # @return [String] if the account is an MHV account, returns the account type # def mhv_account_type return nil unless mhv_account? if account_type_known? user.identity.mhv_account_type elsif eligible_data_classes.nil? 'Error' else ELIGIBLE_DATA_CLASS_COUNT_TO_ACCOUNT_LEVEL.fetch(eligible_data_classes.size) end rescue KeyError log_account_type_heuristic(UNEXPECTED_DATA_CLASS_COUNT_MESSAGE) DEFAULT_ACCOUNT_LEVEL end ## # @return [Boolean] does the user have an MHV correlation ID? # def mhv_account? user.mhv_correlation_id.present? end ## # @return [Boolean] is the user MHV account type known? # def account_type_known? user.identity.mhv_account_type.present? end private def fetch_eligible_data_classes if cached_eligible_data_class json = Oj.load(cached_eligible_data_class).symbolize_keys collection = Vets::Collection.new(json[:data], EligibleDataClass, metadata: json[:metadata], errors: json[:errors]) collection.records.map(&:name) else bb_client = BB::Client.new(session: { user_id: @user.mhv_correlation_id }) bb_client.authenticate bb_client.get_eligible_data_classes.members.map(&:name) end rescue => e log_account_type_heuristic(MHV_DOWN_MESSAGE, error_message: e.message) nil end def cached_eligible_data_class namespace = Redis::Namespace.new('common_collection', redis: $redis) cache_key = "#{user.mhv_correlation_id}:geteligibledataclass" namespace.get(cache_key) end def log_account_type_heuristic(message, extra_context = {}) extra_context.merge!( uuid: user.uuid, mhv_correlation_id: user.mhv_correlation_id, eligible_data_classes:, authn_context: user.authn_context, va_patient: user.va_patient?, mhv_acct_type: user.identity.mhv_account_type ) Rails.logger.warn("#{message}, #{extra_context}") end end
0
code_files/vets-api-private/app
code_files/vets-api-private/app/services/feature_toggles_service.rb
# frozen_string_literal: true class FeatureTogglesService attr_reader :current_user, :cookie_id # Initialize the service with the current user and cookie ID # # @param [User] current_user - The current authenticated user (optional) # @param [String] cookie_id - The cookie ID for anonymous users (optional) def initialize(current_user: nil, cookie_id: nil) @current_user = current_user @cookie_id = cookie_id end # Get specific features based on provided feature names # # @param [Array<String>] features_params - List of feature names to check # @return [Array<Hash>] - Array of feature name/value pairs def get_features(features_params) features_params.collect do |feature_name| underscored_feature_name = feature_name.underscore actor_type = FLIPPER_FEATURE_CONFIG['features'].dig(feature_name, 'actor_type') { name: feature_name, value: Flipper.enabled?(underscored_feature_name, resolve_actor(actor_type)) } end end # Get all features and their values # # @return [Array<Hash>] - Array of all feature name/value pairs def get_all_features features = fetch_features_with_gate_keys add_feature_gate_values(features) format_features(features) end private # Fetch features with their gate keys # # @return [Array<Hash>] - Array of features with gate keys def fetch_features_with_gate_keys Rails.cache.fetch('features_with_gate_keys', expires_in: 1.minute) do FLIPPER_FEATURE_CONFIG['features'] .map { |name, config| { name:, enabled: false, actor_type: config['actor_type'] } } .tap do |features| # Update enabled to true if globally enabled feature_gates.each do |row| feature = features.find { |f| f[:name] == row['feature_name'] } next unless feature # Ignore features not in config/features.yml feature[:gate_key] = row['gate_key'] # Add gate_key for use in add_feature_gate_values feature[:enabled] = true if row['gate_key'] == 'boolean' && row['value'] == 'true' end end end end # Add feature gate values to features # # @param [Array<Hash>] features - Features to add gate values to def add_feature_gate_values(features) features.each do |feature| # If globally enabled, don't disable for percentage or actors next if feature[:enabled] || %w[actors percentage_of_actors percentage_of_time].exclude?(feature[:gate_key]) # There's only a handful of these so individually querying them doesn't take long feature[:enabled] = if Settings.flipper.mute_logs ActiveRecord::Base.logger.silence do Flipper.enabled?(feature[:name], resolve_actor(feature[:actor_type])) end else Flipper.enabled?(feature[:name], resolve_actor(feature[:actor_type])) end end end # Format features for response # # @param [Array<Hash>] features - Features to format # @return [Array<Hash>] - Formatted features def format_features(features) features.flat_map do |feature| [ { name: feature[:name].camelize(:lower), value: feature[:enabled] }, { name: feature[:name], value: feature[:enabled] } ] end end # Resolve the actor for Flipper based on actor type # # @param [String] actor_type - The type of actor # @return [User, Flipper::Actor] - The resolved actor def resolve_actor(actor_type) if actor_type == FLIPPER_ACTOR_STRING Flipper::Actor.new(cookie_id) else current_user end end # Get feature gates from the database # # @return [Array<Hash>] - Database results with feature gates def feature_gates ActiveRecord::Base.connection.select_all(<<-SQL.squish) SELECT flipper_features.key AS feature_name, flipper_gates.key AS gate_key, flipper_gates.value FROM flipper_features LEFT JOIN flipper_gates ON flipper_features.key = flipper_gates.feature_key SQL end end
0
code_files/vets-api-private/app
code_files/vets-api-private/app/services/email_verification_service.rb
# frozen_string_literal: true require 'email_verification/jwt_generator' require 'sidekiq/attr_package' class EmailVerificationService TOKEN_VALIDITY_DURATION = EmailVerification::JwtGenerator::TOKEN_VALIDITY_DURATION REDIS_EXPIRATION = (TOKEN_VALIDITY_DURATION + 10.minutes).to_i # revocation + cleanup + time skew buffer REDIS_NAMESPACE = 'email_verification' def initialize(user) @user = user @redis = Redis::Namespace.new(REDIS_NAMESPACE, redis: $redis) end def initiate_verification(template_name = 'initial_verification') token = generate_token store_token_in_redis(token) # initial_verification, annual_verification, and email_change_verification template_type = template_name.to_s # Store PII in Redis via AttrPackage to avoid exposing it in Sidekiq job arguments cache_key = Sidekiq::AttrPackage.create( expires_in: REDIS_EXPIRATION, email: @user.email, first_name: @user.first_name, verification_link: generate_verification_link(token) ) EmailVerificationJob.perform_async(template_type, cache_key) token rescue Redis::BaseError, Redis::CannotConnectError => e log_redis_error('Redis error during email verification initiation', e) raise Common::Exceptions::BackendServiceException.new( 'VA900', { detail: "Redis error during email verification: #{e.class} - #{e.message}", source: 'EmailVerificationService#initiate_verification' } ) end def verify_email!(token) stored_token = @redis.get(redis_key) if stored_token == token @redis.del(redis_key) send_verification_success_email true else log_invalid_token_attempt(token) false end rescue Redis::BaseError, Redis::CannotConnectError => e log_redis_error('Redis error during email verification', e) raise Common::Exceptions::BackendServiceException.new( 'VA900', { detail: "Redis error during email verification: #{e.class} - #{e.message}", source: 'EmailVerificationService#verify_email!' } ) end private def generate_verification_link(token) # TODO: Implement actual link once endpoints are created (controller ticket) "https://va.gov/email/verify?token=#{token}&uuid=#{@user.uuid}" end def generate_token EmailVerification::JwtGenerator.new(@user).encode_jwt end def store_token_in_redis(token) @redis.del(redis_key) @redis.set(redis_key, token) @redis.expire(redis_key, REDIS_EXPIRATION) end def redis_key @user.uuid end def log_redis_error(message, error) error_data = { error_class: error.class.name, error_message: error.message, user_uuid: @user&.uuid } Rails.logger.error(message, error_data) end def log_invalid_token_attempt(attempted_token) Rails.logger.warn("Email verification failed: invalid token for user #{@user.uuid}", { user_uuid: @user.uuid, token_provided: attempted_token.present?, stored_token_exists: @redis.exists(redis_key) }) end def send_verification_success_email # TODO: Update VA Profile with verification date once integration is complete # email = VAProfile::Models::Email.new(verification_date: Time.now.utc.iso8601) # VAProfile::ContactInformation::V2::Service.new(@user).update_email(email) # Store PII in Redis via AttrPackage to avoid exposing it in Sidekiq job arguments cache_key = Sidekiq::AttrPackage.create( expires_in: REDIS_EXPIRATION, first_name: @user.first_name, email: @user.email ) EmailVerificationJob.perform_async('verification_success', cache_key) end end
0
code_files/vets-api-private/app
code_files/vets-api-private/app/services/evss_claim_service.rb
# frozen_string_literal: true require 'evss/claims_service' require 'evss/documents_service' require 'evss/auth_headers' require 'lighthouse/benefits_documents/constants' require 'lighthouse/benefits_documents/utilities/helpers' require 'vets/shared_logging' # EVSS Claims Status Tool class EVSSClaimService include Vets::SharedLogging EVSS_CLAIM_KEYS = %w[open_claims historical_claims].freeze def initialize(user) @user = user end def all raw_claims = client.all_claims.body claims = EVSS_CLAIM_KEYS.each_with_object([]) do |key, claim_accum| next unless raw_claims[key] claim_accum << raw_claims[key].map do |raw_claim| create_or_update_claim(raw_claim) end end.flatten [claims, true] rescue Breakers::OutageException, EVSS::ErrorMiddleware::EVSSBackendServiceError [claims_scope.all, false] end def update_from_remote(claim) begin raw_claim = client.find_claim_by_id(claim.evss_id).body.fetch('claim', {}) claim.update(data: raw_claim) successful_sync = true rescue Breakers::OutageException, EVSS::ErrorMiddleware::EVSSBackendServiceError successful_sync = false end [claim, successful_sync] end def request_decision(claim) # Workaround for non-Veteran users headers = auth_headers.clone headers_supplemented = supplement_auth_headers(claim.evss_id, headers) job_id = EVSS::RequestDecision.perform_async(headers, claim.evss_id) record_workaround('request_decision', claim.evss_id, job_id) if headers_supplemented job_id end # upload file to s3 and enqueue job to upload to EVSS, used by Claim Status Tool # EVSS::DocumentsService is where the uploading of documents actually happens def upload_document(evss_claim_document) uploader = EVSSClaimDocumentUploader.new(@user.user_account_uuid, evss_claim_document.uploader_ids) uploader.store!(evss_claim_document.file_obj) # the uploader sanitizes the filename before storing, so set our doc to match evss_claim_document.file_name = uploader.final_filename # Workaround for non-Veteran users headers = auth_headers.clone headers_supplemented = supplement_auth_headers(evss_claim_document.evss_claim_id, headers) evidence_submission_id = nil if Flipper.enabled?(:cst_send_evidence_submission_failure_emails) evidence_submission_id = create_initial_evidence_submission(evss_claim_document).id end job_id = EVSS::DocumentUpload.perform_async(headers, @user.user_account_uuid, evss_claim_document.to_serializable_hash, evidence_submission_id) record_workaround('document_upload', evss_claim_document.evss_claim_id, job_id) if headers_supplemented job_id rescue CarrierWave::IntegrityError => e log_exception_to_sentry(e, nil, nil, 'warn') log_exception_to_rails(e) raise Common::Exceptions::UnprocessableEntity.new( detail: e.message, source: 'EVSSClaimService.upload_document' ) end private def bgs_service @bgs ||= BGS::Services.new(external_uid: @user.participant_id, external_key: @user.participant_id) end def get_claim(claim_id) bgs_service.ebenefits_benefit_claims_status.find_benefit_claim_details_by_benefit_claim_id( benefit_claim_id: claim_id ) end def client @client ||= EVSS::ClaimsService.new(auth_headers) end def auth_headers @auth_headers ||= EVSS::AuthHeaders.new(@user).to_h end def supplement_auth_headers(claim_id, headers) # Assuming this header has a value of "", we want to get the Veteran # associated with the claims' participant ID. We can get this by fetching # the claim details from BGS and looking at the Participant ID of the # Veteran associated with the claim blank_header = headers['va_eauth_birlsfilenumber'].blank? if blank_header claim = get_claim(claim_id) veteran_participant_id = claim[:benefit_claim_details_dto][:ptcpnt_vet_id] headers['va_eauth_pid'] = veteran_participant_id # va_eauth_pnid maps to the users SSN. Using this here so that the header # has a value headers['va_eauth_birlsfilenumber'] = headers['va_eauth_pnid'] end blank_header end def record_workaround(task, claim_id, job_id) ::Rails.logger.info('Supplementing EVSS headers', { message_type: "evss.#{task}.no_birls_id", claim_id:, job_id:, revision: 2 }) end def create_initial_evidence_submission(document) user_account = UserAccount.find(@user.user_account_uuid) es = EvidenceSubmission.create( claim_id: document.evss_claim_id, tracked_item_id: document.tracked_item_id, upload_status: BenefitsDocuments::Constants::UPLOAD_STATUS[:CREATED], user_account:, template_metadata: { personalisation: create_personalisation(document) }.to_json ) StatsD.increment('cst.evss.document_uploads.evidence_submission_record_created') ::Rails.logger.info('EVSS - Created Evidence Submission Record', { claim_id: document.evss_claim_id, evidence_submission_id: es.id }) es end def create_personalisation(document) first_name = auth_headers['va_eauth_firstName'].titleize unless auth_headers['va_eauth_firstName'].nil? { first_name:, document_type: document.description, file_name: document.file_name, obfuscated_file_name: BenefitsDocuments::Utilities::Helpers.generate_obscured_file_name(document.file_name), date_submitted: BenefitsDocuments::Utilities::Helpers.format_date_for_mailers(Time.zone.now), date_failed: nil } end def claims_scope EVSSClaim.for_user(@user) end def create_or_update_claim(raw_claim) claim = claims_scope.where(evss_id: raw_claim['id']).first if claim.blank? claim = EVSSClaim.new(user_uuid: @user.uuid, user_account: @user.user_account, evss_id: raw_claim['id'], data: {}) end claim.update(list_data: raw_claim) claim end end
0
code_files/vets-api-private/app
code_files/vets-api-private/app/services/user_audit.rb
# frozen_string_literal: true module UserAudit LOG_FILTER = ->(log) { log.name != 'UserAudit' } SemanticLogger.add_appender(appender: Appenders::UserActionAppender.new, filter: LOG_FILTER) SemanticLogger.add_appender(appender: Appenders::AuditLogAppender.new, filter: LOG_FILTER) def self.logger @logger ||= Logger.new # rubocop:disable ThreadSafety/ClassInstanceVariable end end
0
code_files/vets-api-private/app
code_files/vets-api-private/app/services/email_verification_callback.rb
# frozen_string_literal: true class EmailVerificationCallback def self.call(notification) tags = extract_tags(notification) base_metric = 'api.vanotify.email_verification' case notification.status when 'delivered' StatsD.increment("#{base_metric}.delivered", tags:) StatsD.increment('silent_failure_avoided', tags:) when 'permanent-failure' StatsD.increment("#{base_metric}.permanent_failure", tags:) Rails.logger.error('Email verification permanent failure', build_log_payload(notification, tags)) when 'temporary-failure' StatsD.increment("#{base_metric}.temporary_failure", tags:) Rails.logger.warn('Email verification temporary failure', build_log_payload(notification, tags)) else StatsD.increment("#{base_metric}.other", tags:) Rails.logger.warn('Email verification unhandled status', build_log_payload(notification, tags)) end end def self.extract_tags(notification) metadata = begin notification.callback_metadata.to_h.deep_stringify_keys rescue {} end statsd_tags = metadata['statsd_tags'] || {} tags = statsd_tags.to_h { |k, v| [k.to_s, v.to_s] } tags.presence || { 'service' => 'vagov-profile-email-verification', 'function' => 'email_verification_callback' } end def self.build_log_payload(notification, tags) { notification_id: notification.notification_id, notification_type: notification.notification_type, status: notification.status, status_reason: notification.status_reason, tags:, timestamp: Time.current } end end
0
code_files/vets-api-private/app
code_files/vets-api-private/app/services/user_visn_service.rb
# frozen_string_literal: true class UserVisnService # Hardcoded pilot VISNs for MVP - easy to update as pilot expands PILOT_VISNS = %w[2 15 21].freeze CACHE_KEY_PREFIX = 'va_profile:facility_visn' def initialize(user) @user = user end def in_pilot_visn? return false unless @user.va_treatment_facility_ids.any? user_visns = @user.va_treatment_facility_ids.filter_map do |facility_id| get_cached_visn_for_facility(facility_id) end user_visns.intersect?(PILOT_VISNS) end private def get_cached_visn_for_facility(facility_id) cache_key = "#{CACHE_KEY_PREFIX}:#{facility_id}" # Lazy loading with 24-hour cache Rails.cache.fetch(cache_key, expires_in: 24.hours) do fetch_visn_from_lighthouse(facility_id) end end def fetch_visn_from_lighthouse(facility_id) facilities_client = Lighthouse::Facilities::V1::Client.new # Use facilityIds parameter to get specific facility facilities = facilities_client.get_facilities(facilityIds: "vha_#{facility_id}") return nil if facilities.blank? facility = facilities.first return nil unless facility&.attributes facility.attributes['visn']&.to_s rescue => e Rails.logger.warn("Failed to fetch VISN for facility #{facility_id}: #{e.message}") nil end end
0
code_files/vets-api-private/app/services
code_files/vets-api-private/app/services/medical_copays/vista_account_numbers.rb
# frozen_string_literal: true module MedicalCopays ## # Object for building a list of the user's vista account numbers # # @!attribute data # @return [Hash] class VistaAccountNumbers attr_reader :data, :user ## # Builds a VistaAccountNumbers instance # # @param opts [Hash] # @return [VistaAccountNumbers] an instance of this class # def self.build(opts = {}) new(opts) end def initialize(opts) @user = opts[:user] @data = treatment_facility_data(opts[:data]) end ## # The calculated list of Vista Account Numbers for the VBS service # # @return [Array] # def list return default if data.blank? data.each_with_object([]) do |(key, values), accumulator| next if values.blank? values.each do |id| accumulator << vista_account_id(key, id) end end end ## # Create the Vista Account Number using the facility id, # the associated vista id and the calculated number of '0's # required between the facility id and the vista id. # # @return [String] # def vista_account_id(key, id) Rails.logger.info( 'Building Vista Account ID', user_uuid: user.uuid, facility_id: key, vista_id_length: id.to_s.length ) offset = 16 - (key + id).length padding = '0' * offset if offset >= 0 "#{key}#{padding}#{id}".to_i end ## # Default array and value if the user's `vha_facility_hash` is blank # # @return [Array] # def default [1_234_567_891_011_121] end def treatment_facility_data(complete_facility_hash) complete_facility_hash.select do |facility_id| user.va_treatment_facility_ids.include?(facility_id) end end end end
0
code_files/vets-api-private/app/services
code_files/vets-api-private/app/services/medical_copays/zero_balance_statements.rb
# frozen_string_literal: true require 'lighthouse/facilities/client' module MedicalCopays ## # Object for building a list of the user's zero balance statements # # @!attribute facility_hash # @!attribute statements # @return [Array<Hash>] # class ZeroBalanceStatements attr_reader :facility_hash, :statements attr_accessor :facilities ## # Builds a ZeroBalanceStatements instance # # @param opts [Hash] # @return [ZeroBalanceStatements] an instance of this class # def self.build(opts = {}) new(opts) end def initialize(opts) @facility_hash = opts[:facility_hash] @statements = opts[:statements] @facilities = get_facilities || [] end ## # Format collection of facilities to match VBS response # # @return [Array<Lighthouse::Facilities::Facility>] # def list facilities.map do |facility| { 'pH_AMT_DUE' => 0, 'pS_STATEMENT_DATE' => Time.zone.today.strftime('%m%d%Y'), 'station' => { 'facilitY_NUM' => facility.id.sub('vha_', ''), 'city' => facility.address['physical']['city'].upcase } } end end private ## # The list of vista keys associated with the user's profile # # @return [Array<String>] # def facilities_ids facility_hash&.keys end ## # The list of facility ids found from the VBS response # # @return [Array<String>] # def statements_facilities_ids statements.pluck('pS_FACILITY_NUM') end ## # The unique list of facilities with zero balance # # @return [Array<String>] # def zero_balance_facilities_ids facilities_ids.uniq - statements_facilities_ids unless facilities_ids.nil? end ## # Formatted object to pass to the Lightouse API # # @return [Hash] # def request_data vha_formatted_ids = zero_balance_facilities_ids.map { |i| i.dup.prepend('vha_') }.join(',') { ids: vha_formatted_ids } end ## # Get facilities that have zero balance from Lighthouse # # @return [Array<Lighthouse::Facilities::Facility>] # def get_facilities facility_api.get_facilities(request_data) if zero_balance_facilities_ids.present? rescue Common::Exceptions::BackendServiceException [] end def facility_api Lighthouse::Facilities::Client.new end end end
0
code_files/vets-api-private/app/services
code_files/vets-api-private/app/services/medical_copays/request.rb
# frozen_string_literal: true module MedicalCopays ## # An object responsible for making HTTP calls to the VBS service # # @!attribute settings # @return [Config::Options] # @!attribute host # @return (see Config::Options#host) # @!attribute service_name # @return (see Config::Options#service_name) # @!attribute url # @return (see Config::Options#url) class Request extend Forwardable include Common::Client::Concerns::Monitoring STATSD_KEY_PREFIX = 'api.medical_copays.request' attr_reader :settings def_delegators :settings, :base_path, :host, :service_name, :url ## # Builds a MedicalCopays::Request instance # # @return [MedicalCopays::Request] an instance of this class # def self.build new end def initialize @settings = endpoint_settings end ## # Make a HTTP POST call to the VBS service in order to obtain user copays # # @param path [String] # @param params [Hash] # # @return [Faraday::Response] # def post(path, params) if Flipper.enabled?(:debts_copay_logging) && !Rails.env.development? with_monitoring_and_error_handling do connection.post(path) do |req| req.body = Oj.dump(params) end end else with_monitoring do connection.post(path) do |req| req.body = Oj.dump(params) end end end end def with_monitoring_and_error_handling(&) with_monitoring(2, &) rescue => e handle_error(e) end def handle_error(error) Rails.logger.error("MedicalCopays::Request error: #{error.message}") raise error end ## # Make a HTTP GET call to the VBS service in order to obtain copays or PDFs by id # # @param path [String] # # @return [Faraday::Response] # def get(path) with_monitoring do connection.get(path) end end ## # Create a connection object that manages the attributes # and the middleware stack for making our HTTP requests to VBS # # @return [Faraday::Connection] # def connection Faraday.new(url:, headers:, request: request_options) do |conn| conn.request :json conn.use(:breakers, service_name:) conn.use Faraday::Response::RaiseError conn.response :raise_custom_error, error_prefix: service_name conn.response :json conn.response :betamocks if mock_enabled? conn.adapter Faraday.default_adapter end end ## # Request options can be passed to the connection constructor # and will be applied to all requests. This is the Common::Client config # see: lib/common/client/configuration/base.rb # # open_timeout: The max number of seconds to wait for the connection to be established. # time_out: The max number of seconds to wait for the request to complete. # # @return [Hash] def request_options { open_timeout: 15, timeout: 50 } end ## # HTTP request headers for the VBS API # # @return [Hash] # def headers { 'Host' => host, 'Content-Type' => 'application/json', api_key => settings.api_key } end ## # Betamocks enabled status from settings # # @return [Boolean] # def mock_enabled? settings.mock || false end private def api_key 'apiKey' end def endpoint_settings Settings.mcp.vbs_v2 end end end
0
code_files/vets-api-private/app/services/medical_copays
code_files/vets-api-private/app/services/medical_copays/vbs/request_data.rb
# frozen_string_literal: true module MedicalCopays module VBS ## # Object for handling VBS request parameters # # @!attribute user # @return [User] # @!attribute edipi # @return [String] # @!attribute vha_facility_hash # @return [Hash] # @!attribute errors # @return [Array] class RequestData MOCK_VISTA_ACCOUNT_NUMBERS = [5_160_000_000_012_345].freeze attr_reader :user, :edipi, :vha_facility_hash, :vista_account_numbers attr_accessor :errors ## # Builds a RequestData instance # # @param opts [Hash] # @return [RequestData] an instance of this class # def self.build(opts = {}) new(opts) end ## # The schema for validating attribute data # # @return [Hash] # def self.statements_schema { 'type' => 'object', 'additionalProperties' => false, 'required' => %w[edipi vistaAccountNumbers], 'properties' => { 'edipi' => { 'type' => 'string' }, 'vistaAccountNumbers' => { 'type' => 'array', 'items' => { 'type' => 'integer', 'minLength' => 16, 'maxLength' => 16 } } } } end ## # The options to be passed to {JSON::Validator#fully_validate} # # @return [Hash] # def self.schema_validation_options { errors_as_objects: true, version: :draft6 } end def initialize(opts) @user = opts[:user] @edipi = user.edipi @vha_facility_hash = user.vha_facility_hash @vista_account_numbers = MedicalCopays::VistaAccountNumbers.build(data: vha_facility_hash, user: @user) @errors = [] end ## # The data to be posted to VBS # # @return [Hash] # def to_hash { 'edipi' => edipi, 'vistaAccountNumbers' => Settings.mcp.vbs.mock_vista ? MOCK_VISTA_ACCOUNT_NUMBERS : vista_account_numbers.list } end ## # Determine if the instance is valid based upon attribute data # # @return [Boolean] # def valid? errors = JSON::Validator.fully_validate( self.class.statements_schema, to_hash, self.class.schema_validation_options ) errors.blank? end end end end
0
code_files/vets-api-private/app/services/medical_copays
code_files/vets-api-private/app/services/medical_copays/vbs/invalid_vbs_request_error.rb
# frozen_string_literal: true module MedicalCopays module VBS ## # Custom error object for handling invalid VBS request params # # @!attribute errors # @return [Array] class InvalidVBSRequestError < StandardError attr_accessor :errors def initialize(json_schema_errors) @errors = json_schema_errors message = json_schema_errors.pluck(:message) StatsD.increment('api.mcp.vbs.failure') super(message) end end end end
0
code_files/vets-api-private/app/services/medical_copays
code_files/vets-api-private/app/services/medical_copays/vbs/response_data.rb
# frozen_string_literal: true module MedicalCopays module VBS ## # Object for handling VBS responses # # @!attribute body # @return [String] # @!attribute status # @return [Integer] class ResponseData attr_reader :body, :status STATSD_KEY_PREFIX = 'api.mcp.vbs' ## # Builds a ResponseData instance # # @param opts [Hash] # @return [ResponseData] an instance of this class # def self.build(opts = {}) new(opts) end def initialize(opts) @body = opts[:response].body || [] @status = opts[:response].status end ## # The response hash to be returned to the {MedicalCopaysController} # # @return [Hash] # def handle case status when 200 StatsD.increment("#{STATSD_KEY_PREFIX}.success") { data: transformed_body, status: } when 400 StatsD.increment("#{STATSD_KEY_PREFIX}.failure") { data: { message: 'Bad request' }, status: } when 401 StatsD.increment("#{STATSD_KEY_PREFIX}.failure") { data: { message: 'Unauthorized' }, status: } when 403 StatsD.increment("#{STATSD_KEY_PREFIX}.failure") { data: { message: 'Forbidden' }, status: } when 404 StatsD.increment("#{STATSD_KEY_PREFIX}.failure") { data: { message: 'Resource not found' }, status: } else StatsD.increment("#{STATSD_KEY_PREFIX}.failure") { data: { message: 'Something went wrong' }, status: } end end ## # Camelize and lowercase all keys in the response body # # @return [Array] # def transformed_body statements = Flipper.enabled?(:medical_copays_six_mo_window) ? last_six_months_statements : body statements.each do |copay| calculate_cerner_account_number(copay) copay.deep_transform_keys! { |key| key.camelize(:lower) } end end private ## # Filter statements by only the last six months # # @return [Array] # def last_six_months_statements cutoff_date = Time.zone.today - 6.months body.select do |statement| statement_date(statement) > cutoff_date end end ## # Custom cerner account number to match PDF # # @return [Hash] # def calculate_cerner_account_number(statement) return unless account_number_present?(statement['pH_CERNER_ACCOUNT_NUMBER']) facility_id = statement['pS_FACILITY_NUM'] patient_id = statement['pH_CERNER_PATIENT_ID'] offset = 15 - (facility_id + patient_id).length padding = '0' * offset if offset >= 0 statement['pH_CERNER_ACCOUNT_NUMBER'] = "#{facility_id}1#{padding}#{patient_id}" end ## # The Date object of the statement date string # # @return [Date] # def statement_date(statement) Time.zone.strptime(statement['pS_STATEMENT_DATE'], '%m%d%Y') end def account_number_present?(n) n.present? && n != 0 && n != '0' end end end end
0
code_files/vets-api-private/app/services/medical_copays
code_files/vets-api-private/app/services/medical_copays/vbs/service.rb
# frozen_string_literal: true module MedicalCopays module VBS ## # Service object for isolating dependencies in the {MedicalCopaysController} # # @!attribute request # @return [MedicalCopays::Request] # @!attribute request_data # @return [RequestData] # @!attribute response_data # @return [ResponseData] class Service include RedisCaching class StatementNotFound < StandardError end attr_reader :request, :request_data, :user STATSD_KEY_PREFIX = 'api.mcp.vbs' ## # Builds a Service instance # # @param opts [Hash] # @return [Service] an instance of this class # def self.build(opts = {}) new(opts) end def initialize(opts) @request = MedicalCopays::Request.build @user = opts[:user] @request_data = RequestData.build(user:) unless user.nil? end ## # Gets the user's medical copays by edipi and vista account numbers # # @return [Hash] # def get_copays raise InvalidVBSRequestError, request_data.errors unless request_data.valid? if Flipper.enabled?(:debts_copay_logging) Rails.logger.info("MedicalCopays::VBS::Service#get_copays request data: #{@user.uuid}") end response = get_cached_copay_response # enable zero balance debt feature if flip is on if Flipper.enabled?(:medical_copays_zero_debt) zero_balance_statements = MedicalCopays::ZeroBalanceStatements.build( statements: response.body, facility_hash: user.vha_facility_hash ) response.body.concat(zero_balance_statements.list) end ResponseData.build(response:).handle end def get_cached_copay_response StatsD.increment("#{STATSD_KEY_PREFIX}.init_cached_copays.fired") cached_response = get_user_cached_response if cached_response StatsD.increment("#{STATSD_KEY_PREFIX}.init_cached_copays.cached_response_returned") return cached_response end response = request.post( "#{settings.base_path}/GetStatementsByEDIPIAndVistaAccountNumber", request_data.to_hash ) response_body = response.body if response_body.is_a?(Array) && response_body.empty? StatsD.increment("#{STATSD_KEY_PREFIX}.init_cached_copays.empty_response_cached") Rails.cache.write("vbs_copays_data_#{user.uuid}", response, expires_in: self.class.time_until_5am_utc) end response end ## # Get's the users' medical copay by statement id from list # # @param id [UUID] - uuid of the statement # @return [Hash] - JSON data of statement and status # def get_copay_by_id(id) all_statements = get_copays # Return hash with error information if bad response return all_statements unless all_statements[:status] == 200 statement = get_copays[:data].find { |copay| copay['id'] == id } raise StatementNotFound if statement.nil? { data: statement, status: 200 } end ## # Gets the PDF medical copay statment by statment_id # # @return [Hash] # def get_pdf_statement_by_id(statement_id) StatsD.increment("#{STATSD_KEY_PREFIX}.pdf.total") response = request.get("#{settings.base_path}/GetPDFStatementById/#{statement_id}") Base64.decode64(response.body['statement']) rescue => e StatsD.increment("#{STATSD_KEY_PREFIX}.pdf.failure") raise e end def get_user_cached_response cache_key = "vbs_copays_data_#{user.uuid}" Rails.cache.read(cache_key) end def send_statement_notifications(_statements_json_byte) # Commenting for now since we are causingissues in production # when the child job runs: "NewStatementNotificationJob" # CopayNotifications::ParseNewStatementsJob.perform_async(statements_json_byte) true end def settings Settings.mcp.vbs_v2 end end end end
0
code_files/vets-api-private/app/services/medical_copays
code_files/vets-api-private/app/services/medical_copays/lighthouse_integration/service.rb
# frozen_string_literal: true require 'lighthouse/healthcare_cost_and_coverage/invoice/service' require 'lighthouse/healthcare_cost_and_coverage/account/service' require 'lighthouse/healthcare_cost_and_coverage/charge_item/service' require 'lighthouse/healthcare_cost_and_coverage/encounter/service' require 'lighthouse/healthcare_cost_and_coverage/medication_dispense/service' require 'lighthouse/healthcare_cost_and_coverage/medication/service' require 'lighthouse/healthcare_cost_and_coverage/payment_reconciliation/service' require 'concurrent-ruby' module MedicalCopays module LighthouseIntegration class Service # Encounter API lacks _id filter; fetch all and filter client-side ENCOUNTER_FETCH_LIMIT = 200 CHARGE_ITEM_FETCH_LIMIT = 100 PAYMENT_FETCH_LIMIT = 100 def initialize(icn) @icn = icn end def list(count:, page:) raw_invoices = invoice_service.list(count:, page:) entries = raw_invoices['entry'].map do |entry| Lighthouse::HCC::Invoice.new(entry) end Lighthouse::HCC::Bundle.new(raw_invoices, entries) rescue => e Rails.logger.error("MedicalCopays::LighthouseIntegration::Service#list error: #{e.message}") raise e end def get_detail(id:) invoice_data = invoice_service.read(id) invoice_deps = fetch_invoice_dependencies(invoice_data, id) charge_item_deps = fetch_charge_item_dependencies(invoice_deps[:charge_items]) medications = fetch_medications(charge_item_deps[:medication_dispenses]) Lighthouse::HCC::CopayDetail.new( invoice_data:, account_data: invoice_deps[:account], charge_items: invoice_deps[:charge_items], encounters: charge_item_deps[:encounters], medication_dispenses: charge_item_deps[:medication_dispenses], medications:, payments: invoice_deps[:payments] ) rescue => e Rails.logger.error( "MedicalCopays::LighthouseIntegration::Service#get_detail error for invoice #{id}: #{e.message}" ) raise e end private def fetch_invoice_dependencies(invoice_data, invoice_id) account_future = Concurrent::Promises.future { fetch_account(invoice_data) } charge_items_future = Concurrent::Promises.future { fetch_charge_items(invoice_data) } payments_future = Concurrent::Promises.future { fetch_payments(invoice_id) } { account: account_future.value!, charge_items: charge_items_future.value!, payments: payments_future.value! } end def fetch_charge_item_dependencies(charge_items) encounters_future = Concurrent::Promises.future { fetch_encounters(charge_items) } medication_dispenses_future = Concurrent::Promises.future { fetch_medication_dispenses(charge_items) } { encounters: encounters_future.value!, medication_dispenses: medication_dispenses_future.value! } end def fetch_account(invoice_data) account_ref = invoice_data.dig('account', 'reference') return nil unless account_ref account_id = extract_id_from_reference(account_ref) return nil unless account_id response = account_service.list(id: account_id) response.dig('entry', 0, 'resource') rescue => e Rails.logger.warn { "Failed to fetch account #{account_id}: #{e.message}" } nil end def fetch_charge_items(invoice_data) charge_item_ids = extract_charge_item_ids(invoice_data) return {} if charge_item_ids.empty? response = charge_item_service.list(count: CHARGE_ITEM_FETCH_LIMIT) entries = response['entry'] || [] entries.each_with_object({}) do |entry, hash| resource = entry['resource'] hash[resource['id']] = resource if resource && charge_item_ids.include?(resource['id']) end rescue => e Rails.logger.warn { "Failed to fetch charge items: #{e.message}" } {} end def fetch_encounters(charge_items) encounter_ids = charge_items.values.filter_map do |ci| ref = ci.dig('context', 'reference') extract_id_from_reference(ref) if ref end return {} if encounter_ids.empty? response = encounter_service.list(count: ENCOUNTER_FETCH_LIMIT) entries = response['entry'] || [] entries.each_with_object({}) do |entry, hash| resource = entry['resource'] hash[resource['id']] = resource if resource && encounter_ids.include?(resource['id']) end rescue => e Rails.logger.warn { "Failed to fetch encounters: #{e.message}" } {} end def fetch_medication_dispenses(charge_items) dispense_ids = charge_items.values.flat_map do |ci| (ci['service'] || []).filter_map do |svc| ref = svc['reference'] extract_id_from_reference(ref) if ref&.include?('MedicationDispense') end end fetch_and_index('medication dispenses', dispense_ids, medication_dispense_service) end def fetch_medications(medication_dispenses) medication_ids = medication_dispenses.values.filter_map do |md| ref = md.dig('medicationReference', 'reference') extract_id_from_reference(ref) if ref end fetch_and_index('medications', medication_ids, medication_service) end def fetch_and_index(data_type, ids, service) return {} if ids.empty? response = service.list(id: ids.join(',')) entries = response['entry'] || [] entries.each_with_object({}) do |entry, hash| resource = entry['resource'] hash[resource['id']] = resource if resource && resource['id'] end rescue => e Rails.logger.warn { "Failed to fetch #{data_type}: #{e.message}" } {} end def fetch_payments(invoice_id) response = payment_reconciliation_service.list(count: PAYMENT_FETCH_LIMIT) entries = response['entry'] || [] entries.filter_map do |entry| resource = entry['resource'] next unless resource invoice_ref = find_invoice_reference(resource) resource if invoice_ref == invoice_id end rescue => e Rails.logger.warn { "Failed to fetch payments: #{e.message}" } [] end def find_invoice_reference(payment) extensions = payment['extension'] || [] target_ext = extensions.find { |e| e['url']&.include?('allocation.target') } return nil unless target_ext ref = target_ext.dig('valueReference', 'reference') extract_id_from_reference(ref) end def extract_charge_item_ids(invoice_data) line_items = invoice_data['lineItem'] || [] line_items.filter_map do |li| ref = li.dig('chargeItemReference', 'reference') extract_id_from_reference(ref) if ref end end def extract_id_from_reference(reference) return nil unless reference reference.split('/').last end def invoice_service @invoice_service ||= ::Lighthouse::HealthcareCostAndCoverage::Invoice::Service.new(@icn) end def account_service @account_service ||= ::Lighthouse::HealthcareCostAndCoverage::Account::Service.new(@icn) end def charge_item_service @charge_item_service ||= ::Lighthouse::HealthcareCostAndCoverage::ChargeItem::Service.new(@icn) end def encounter_service @encounter_service ||= ::Lighthouse::HealthcareCostAndCoverage::Encounter::Service.new(@icn) end def medication_dispense_service @medication_dispense_service ||= ::Lighthouse::HealthcareCostAndCoverage::MedicationDispense::Service.new(@icn) end def medication_service @medication_service ||= ::Lighthouse::HealthcareCostAndCoverage::Medication::Service.new(@icn) end def payment_reconciliation_service @payment_reconciliation_service ||= ::Lighthouse::HealthcareCostAndCoverage::PaymentReconciliation::Service.new(@icn) end end end end
0
code_files/vets-api-private/app/services/debt_transaction_log
code_files/vets-api-private/app/services/debt_transaction_log/summary_builders/waiver_summary_builder.rb
# frozen_string_literal: true class DebtTransactionLog::SummaryBuilders::WaiverSummaryBuilder def self.build(submission) { debt_type: submission.public_metadata&.dig('debt_type') || 'unknown', combined: submission.public_metadata&.dig('combined') == true, streamlined: submission.public_metadata&.dig('streamlined', 'value') == true } end end