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
|
code_files/vets-api-private/app/serializers/service_history_serializer.rb
|
# frozen_string_literal: true
class ServiceHistorySerializer
include JSONAPI::Serializer
set_id { '' }
attributes :service_history do |object|
object[:episodes]
end
attributes :vet_status_eligibility do |object|
object[:vet_status_eligibility]
end
end
|
0
|
code_files/vets-api-private/app
|
code_files/vets-api-private/app/serializers/tsa_letter_serializer.rb
|
# frozen_string_literal: true
class TsaLetterSerializer
include JSONAPI::Serializer
set_id { '' }
attribute :document_id, :doc_type, :type_description, :received_at
end
|
0
|
code_files/vets-api-private/app
|
code_files/vets-api-private/app/serializers/archived_claim_serializer.rb
|
# frozen_string_literal: true
class ArchivedClaimSerializer < SavedClaimSerializer
attribute :pdf_url, if: proc { |_record, params| params && params[:pdf_url].present? } do |_record, params|
params[:pdf_url]
end
end
|
0
|
code_files/vets-api-private/app
|
code_files/vets-api-private/app/serializers/disability_contention_serializer.rb
|
# frozen_string_literal: true
class DisabilityContentionSerializer
include JSONAPI::Serializer
attribute :code
attribute :medical_term
attribute :lay_term
end
|
0
|
code_files/vets-api-private/app
|
code_files/vets-api-private/app/serializers/maintenance_window_serializer.rb
|
# frozen_string_literal: true
class MaintenanceWindowSerializer
include JSONAPI::Serializer
attributes :id, :external_service, :start_time, :end_time, :description
end
|
0
|
code_files/vets-api-private/app
|
code_files/vets-api-private/app/serializers/education_benefits_claim_serializer.rb
|
# frozen_string_literal: true
class EducationBenefitsClaimSerializer
include JSONAPI::Serializer
set_id :token
attributes :form, :regional_office, :confirmation_number
end
|
0
|
code_files/vets-api-private/app
|
code_files/vets-api-private/app/serializers/gi_bill_feedback_serializer.rb
|
# frozen_string_literal: true
class GIBillFeedbackSerializer
include JSONAPI::Serializer
attributes :guid, :state, :parsed_response
end
|
0
|
code_files/vets-api-private/app
|
code_files/vets-api-private/app/serializers/submission_status_serializer.rb
|
# frozen_string_literal: true
class SubmissionStatusSerializer
include JSONAPI::Serializer
attributes :id, :detail, :form_type, :message, :status, :created_at, :updated_at, :pdf_support
end
|
0
|
code_files/vets-api-private/app
|
code_files/vets-api-private/app/serializers/preferred_name_serializer.rb
|
# frozen_string_literal: true
class PreferredNameSerializer
include JSONAPI::Serializer
set_id { '' }
attributes :preferred_name
end
|
0
|
code_files/vets-api-private/app
|
code_files/vets-api-private/app/serializers/user_action_event_serializer.rb
|
# frozen_string_literal: true
class UserActionEventSerializer
include JSONAPI::Serializer
attribute :details, :created_at, :updated_at, :event_type, :identifier
end
|
0
|
code_files/vets-api-private/app
|
code_files/vets-api-private/app/serializers/evss_claim_base_helper.rb
|
# frozen_string_literal: true
module EVSSClaimBaseHelper
PHASE_MAPPING = {
'claim received' => 1,
'under review' => 2,
'gathering of evidence' => 3,
'review of evidence' => 4,
'preparation for decision' => 5,
'pending decision approval' => 6,
'preparation for notification' => 7,
'complete' => 8
}.freeze
def phase_from_keys(phase)
PHASE_MAPPING[phase&.downcase]
end
def date_attr(date, format: '%m/%d/%Y')
return unless date
Date.strptime(date, format)
end
def yes_no_attr(value, *names)
return unless value
case value.downcase
when 'yes' then true
when 'no' then false
else
Rails.logger.error "Expected key EVSS '#{names.join('/')}' to be Yes/No. Got '#{value}'."
nil
end
end
end
|
0
|
code_files/vets-api-private/app
|
code_files/vets-api-private/app/serializers/rating_info_serializer.rb
|
# frozen_string_literal: true
class RatingInfoSerializer
include JSONAPI::Serializer
set_id { '' }
attribute :user_percent_of_disability
attribute :source_system do |_|
'EVSS'
end
end
|
0
|
code_files/vets-api-private/app
|
code_files/vets-api-private/app/serializers/decision_review_evidence_attachment_serializer.rb
|
# frozen_string_literal: true
class DecisionReviewEvidenceAttachmentSerializer
include JSONAPI::Serializer
set_type :decision_review_evidence_attachments
attribute :guid
end
|
0
|
code_files/vets-api-private/app
|
code_files/vets-api-private/app/serializers/cemetery_serializer.rb
|
# frozen_string_literal: true
class CemeterySerializer
include JSONAPI::Serializer
set_type :preneeds_cemeteries
attribute :name
attribute :cemetery_type
attribute :num
attribute :cemetery_id, &:id
end
|
0
|
code_files/vets-api-private/app
|
code_files/vets-api-private/app/serializers/intent_to_file_serializer.rb
|
# frozen_string_literal: true
class IntentToFileSerializer
include JSONAPI::Serializer
set_id { '' }
attribute :intent_to_file
end
|
0
|
code_files/vets-api-private/app
|
code_files/vets-api-private/app/serializers/dependents_serializer.rb
|
# frozen_string_literal: true
START_EVENTS = %w[EMC SCHATTB].freeze
LATER_START_EVENTS = %w[SCHATTB].freeze
END_EVENTS = %w[T18 SCHATTT].freeze
FUTURE_EVENTS = (LATER_START_EVENTS + END_EVENTS).freeze
module DependentsHelper
def max_time(a, b)
a[:award_effective_date] <=> b[:award_effective_date]
end
def in_future(decision)
Time.zone.parse(decision[:award_effective_date].to_s) > Time.zone.now
end
def still_pending(decision, award_event_id)
decision[:award_event_id] == award_event_id && in_future(decision)
end
def trim_whitespace(str)
str&.gsub(/\s+/, ' ')
end
def upcoming_removals(decisions)
decisions.transform_values do |decs|
decs.filter { |dec| END_EVENTS.include?(dec[:dependency_decision_type]) }.max { |a, b| max_time(a, b) }
end
end
def dependent_benefit_types(decisions)
decisions.transform_values do |decs|
dec = decs.find { |d| START_EVENTS.include?(d[:dependency_decision_type]) }
dec && trim_whitespace(dec[:dependency_status_type_description])
end
end
def current_and_pending_decisions(diaries)
# Filter by eligible minor child or school attendance types and if they are the current or future decisions
decisions = dependency_decisions(diaries)
.filter do |dec|
(START_EVENTS.include?(dec[:dependency_decision_type]) && !in_future(dec)) ||
(END_EVENTS.include?(dec[:dependency_decision_type]) && in_future(dec))
end
decisions.group_by { |dec| dec[:person_id] }
.transform_values do |decs|
# get only most recent active decision and add back to array
active =
decs.filter do |dec|
START_EVENTS.include?(dec[:dependency_decision_type]) &&
decs.any? { |d| still_pending(d, dec[:award_event_id]) }
end
most_recent = active.max { |a, b| max_time(a, b) }
# include all future events (including school attendance begins)
(decs.filter do |dec|
FUTURE_EVENTS.include?(dec[:dependency_decision_type]) && in_future(dec)
end + [most_recent]).compact
end
end
def dependency_decisions(diaries)
decisions = if diaries.is_a?(Hash)
diaries[:dependency_decs]
else
Rails.logger.warn('Diaries is not a hash! Diaries value: ', diaries)
nil
end
return if decisions.nil?
decisions.is_a?(Hash) ? [decisions] : decisions
end
end
class DependentsSerializer
extend DependentsHelper
include JSONAPI::Serializer
set_id { '' }
set_type :dependents
attribute :persons do |object|
next [object[:persons]] if object[:persons].instance_of?(Hash)
arr = object[:persons].instance_of?(Hash) ? [object[:persons]] : object[:persons]
diaries = object[:diaries]
next arr if dependency_decisions(diaries).blank?
decisions = current_and_pending_decisions(diaries)
arr.each do |person|
upcoming_removal = person[:upcoming_removal] = upcoming_removals(decisions)[person[:ptcpnt_id]]
if upcoming_removal
person[:upcoming_removal_date] = if upcoming_removal[:award_effective_date].present?
Time.zone.parse(upcoming_removal[:award_effective_date].to_s)
end
person[:upcoming_removal_reason] = trim_whitespace(upcoming_removal[:dependency_decision_type_description])
end
person[:dependent_benefit_type] = dependent_benefit_types(decisions)[person[:ptcpnt_id]]
end
end
end
|
0
|
code_files/vets-api-private/app/serializers
|
code_files/vets-api-private/app/serializers/async_transaction/base_serializer.rb
|
# frozen_string_literal: true
module AsyncTransaction
class BaseSerializer
include JSONAPI::Serializer
set_id { '' }
attribute :transaction_id
attribute :transaction_status
attribute :type
attribute :metadata, &:parsed_metadata
# This is needed to set the correct type based on the object(s) being serialized
def serializable_hash
hash = super
if hash[:data].is_a?(Array)
hash[:data].each_with_index { |h, i| h[:type] = @resource[i].class.name.underscore.gsub('/', '_').pluralize }
else
hash[:data][:type] = @resource.class.name.underscore.gsub('/', '_').pluralize
end
hash
end
end
end
|
0
|
code_files/vets-api-private/app/serializers
|
code_files/vets-api-private/app/serializers/form1010cg/claim_serializer.rb
|
# frozen_string_literal: true
module Form1010cg
class ClaimSerializer
include JSONAPI::Serializer
end
end
|
0
|
code_files/vets-api-private/app/serializers
|
code_files/vets-api-private/app/serializers/form1010cg/attachment_serializer.rb
|
# frozen_string_literal: true
module Form1010cg
class AttachmentSerializer
include JSONAPI::Serializer
set_type :form1010cg_attachments
attribute :guid
end
end
|
0
|
code_files/vets-api-private/app/serializers
|
code_files/vets-api-private/app/serializers/form1010cg/submission_serializer.rb
|
# frozen_string_literal: true
module Form1010cg
class SubmissionSerializer
include JSONAPI::Serializer
set_id { '' }
attribute :confirmation_number, &:carma_case_id
attribute :submitted_at, &:accepted_at
end
end
|
0
|
code_files/vets-api-private/app/serializers/lighthouse
|
code_files/vets-api-private/app/serializers/lighthouse/hcc/invoice_serializer.rb
|
# frozen_string_literal: true
class Lighthouse::HCC::InvoiceSerializer
include JSONAPI::Serializer
set_type :medical_copays
set_key_transform :camel_lower
set_id :external_id
attributes :url,
:facility,
:external_id,
:latest_billing_ref,
:current_balance,
:previous_balance,
:previous_unpaid_balance
end
|
0
|
code_files/vets-api-private/app/serializers/lighthouse
|
code_files/vets-api-private/app/serializers/lighthouse/hcc/copay_detail_serializer.rb
|
# frozen_string_literal: true
module Lighthouse
module HCC
class CopayDetailSerializer
include JSONAPI::Serializer
set_key_transform :camel_lower
set_type :medical_copay_details
set_id :external_id
attributes :external_id,
:facility,
:bill_number,
:status,
:status_description,
:invoice_date,
:payment_due_date,
:account_number,
:original_amount,
:principal_balance,
:interest_balance,
:administrative_cost_balance,
:principal_paid,
:interest_paid,
:administrative_cost_paid,
:line_items,
:payments
meta do |object|
{
line_item_count: object.line_items.size,
payment_count: object.payments.size
}
end
end
end
end
|
0
|
code_files/vets-api-private/app/serializers/lighthouse
|
code_files/vets-api-private/app/serializers/lighthouse/facilities/facility_serializer.rb
|
# frozen_string_literal: true
class Lighthouse::Facilities::FacilitySerializer
include JSONAPI::Serializer
set_key_transform :camel_lower
attribute :access do |obj|
obj.access&.deep_stringify_keys&.deep_transform_keys { |key| key.camelize(:lower) }
end
attribute :active_status
attribute :address do |obj|
obj.address&.deep_stringify_keys&.deep_transform_keys { |key| key.camelize(:lower) }
end
attribute :classification
attribute :detailed_services do |obj|
obj.detailed_services&.collect { |ds| ds&.deep_stringify_keys&.deep_transform_keys { |key| key.camelize(:lower) } }
end
attribute :facility_type
attribute :feedback do |obj|
obj.feedback&.deep_stringify_keys&.deep_transform_keys { |key| key.camelize(:lower) }
end
attribute :hours do |obj|
obj.hours&.deep_stringify_keys&.deep_transform_keys { |key| key.camelize(:lower) }
end
attribute :id
attribute :lat
attribute :long
attribute :mobile
attribute :name
attribute :operating_status do |obj|
obj.operating_status&.deep_stringify_keys&.deep_transform_keys { |key| key.camelize(:lower) }
end
attribute :operational_hours_special_instructions
attribute :phone do |obj|
obj.phone&.deep_stringify_keys&.deep_transform_keys { |key| key.camelize(:lower) }
end
attribute :services do |obj|
obj.services&.deep_stringify_keys&.deep_transform_keys { |key| key.camelize(:lower) }
end
attribute :unique_id
attribute :visn
attribute :website
end
|
0
|
code_files/vets-api-private/app
|
code_files/vets-api-private/app/validators/folder_name_convention_validator.rb
|
# frozen_string_literal: true
class FolderNameConventionValidator < ActiveModel::EachValidator
def validate_each(record, field, value)
unless value.nil?
unless value.match?(/^[[:alnum:]\s]+$/)
record.errors.add(field, 'is not alphanumeric (letters, numbers, or spaces)')
end
record.errors.add(field, 'contains illegal characters') if value.match?(/[\n\t\f\b\r]/)
record.errors.add(field, 'contains illegal characters') unless value.ascii_only?
end
end
end
|
0
|
code_files/vets-api-private/app
|
code_files/vets-api-private/app/validators/token_util.rb
|
# frozen_string_literal: true
class TokenUtil
def self.validate_token(token)
raise error_klass('Invalid audience') unless TokenUtil.valid_audience?(token)
# Only static and ssoi tokens utilize this validator at this time
token.static? || token.ssoi_token?
end
# Validates the token audience against the service caller supplied `aud` payload.
# If none, it validates against the configured default.
def self.valid_audience?(token)
if token.aud.nil?
token.payload['aud'] == Settings.oidc.isolated_audience.default
else
# Temporarily accept the default audience or the API specified audience
[Settings.oidc.isolated_audience.default, *token.aud].include?(token.payload['aud'])
end
end
def self.error_klass(error_detail_string)
# Errors from the jwt gem (and other dependencies) are reraised with
# this class so we can exclude them from Sentry without needing to know
# all the classes used by our dependencies.
Common::Exceptions::TokenValidationError.new(detail: error_detail_string)
end
end
|
0
|
code_files/vets-api-private/app
|
code_files/vets-api-private/app/controllers/application_controller.rb
|
# frozen_string_literal: true
require 'feature_flipper'
require 'aes_256_cbc_encryptor'
require 'vets/shared_logging'
class ApplicationController < ActionController::API
include AuthenticationAndSSOConcerns
include ActionController::RequestForgeryProtection
include ExceptionHandling
include Headers
include Instrumentation
include Pundit::Authorization
include ControllerLoggingContext
include Vets::SharedLogging
include SentryControllerLogging
include Traceable
protect_from_forgery with: :exception, if: -> { ActionController::Base.allow_forgery_protection }
after_action :set_csrf_header, if: -> { ActionController::Base.allow_forgery_protection }
# also see AuthenticationAndSSOConcerns, Headers, ControllerLoggingContext, and SentryControllerLogging
# for more before filters
skip_before_action :authenticate, only: %i[cors_preflight routing_error]
skip_before_action :verify_authenticity_token, only: :routing_error
around_action :tag_with_controller_name
VERSION_STATUS = {
draft: 'Draft Version',
current: 'Current Version',
previous: 'Previous Version',
deprecated: 'Deprecated Version'
}.freeze
def cors_preflight
head(:ok)
end
def routing_error
raise Common::Exceptions::RoutingError, params[:path]
end
def clear_saved_form(form_id)
InProgressForm.form_for_user(form_id, current_user)&.destroy if current_user
end
private
attr_reader :current_user
def set_csrf_header
token = form_authenticity_token
response.set_header('X-CSRF-Token', token)
end
def pagination_params
{
page: params[:page],
per_page: params[:per_page]
}
end
def render_job_id(jid)
render json: { job_id: jid }, status: :accepted
end
end
|
0
|
code_files/vets-api-private/app
|
code_files/vets-api-private/app/controllers/claims_base_controller.rb
|
# frozen_string_literal: true
# Abstract base controller for Claims controllers that use the SavedClaim
# and optionally, PersistentAttachment models. Subclasses must have:
#
# * `short_name()`, which returns an identifier that matches the parameter
# that the form will be set as in the JSON submission.
# * `claim_class()` must return a sublass of SavedClaim, which will run
# json-schema validations and perform any storage and attachment processing
require 'common/exceptions/validation_errors'
class ClaimsBaseController < ApplicationController
skip_before_action(:authenticate)
before_action :load_user, only: :create
def show
submission = CentralMailSubmission.joins(:central_mail_claim).find_by(saved_claims: { guid: params[:id] })
render json: BenefitsIntakeSubmissionSerializer.new(submission)
end
# Creates and validates an instance of the class, removing any copies of
# the form that had been previously saved by the user.
def create
claim = claim_class.new(form: filtered_params[:form])
user_uuid = current_user&.uuid
Rails.logger.info "Begin ClaimGUID=#{claim.guid} Form=#{claim.class::FORM} UserID=#{user_uuid}"
unless claim.save
StatsD.increment("#{stats_key}.failure")
raise Common::Exceptions::ValidationErrors, claim
end
claim.process_attachments!
StatsD.increment("#{stats_key}.success")
Rails.logger.info "Submitted job ClaimID=#{claim.confirmation_number} Form=#{claim.class::FORM} UserID=#{user_uuid}"
clear_saved_form(claim.form_id)
render json: SavedClaimSerializer.new(claim)
end
private
def filtered_params
params.require(short_name.to_sym).permit(:form)
end
def stats_key
"api.#{short_name}"
end
end
|
0
|
code_files/vets-api-private/app
|
code_files/vets-api-private/app/controllers/preneeds_controller.rb
|
# frozen_string_literal: true
require 'preneeds/service'
class PreneedsController < ApplicationController
service_tag 'preneed-burial-application'
skip_before_action(:authenticate)
protected
def client
@client ||= Preneeds::Service.new
end
end
|
0
|
code_files/vets-api-private/app
|
code_files/vets-api-private/app/controllers/gids_controller.rb
|
# frozen_string_literal: true
class GIDSController < ApplicationController
service_tag 'gibill-comparison'
skip_before_action :authenticate
private
def service
GIDSRedis.new
end
def scrubbed_params
params.except(:action, :controller, :format)
end
end
|
0
|
code_files/vets-api-private/app
|
code_files/vets-api-private/app/controllers/flipper_controller.rb
|
# frozen_string_literal: true
class FlipperController < ApplicationController
service_tag 'feature-flag'
skip_before_action :authenticate
def login
# Swallow auth token and redirect to /flipper/features with a param for redirecting
redirect_to "/flipper/features?redirect=#{params[:feature_name]}"
end
def logout
cookies.delete :api_session
redirect_to '/flipper/features'
end
end
|
0
|
code_files/vets-api-private/app
|
code_files/vets-api-private/app/controllers/appeals_base_controller.rb
|
# frozen_string_literal: true
require 'caseflow/service'
class AppealsBaseController < ApplicationController
include FailedRequestLoggable
before_action { authorize :appeals, :access? }
private
def appeals_service
Caseflow::Service.new
end
def request_body_debug_data
{
request_body_class_name: request.try(:body).class.name,
request_body_string: request.try(:body).try(:string)
}
end
end
|
0
|
code_files/vets-api-private/app/controllers
|
code_files/vets-api-private/app/controllers/v1/medical_copays_controller.rb
|
# frozen_string_literal: true
module V1
class MedicalCopaysController < ApplicationController
service_tag 'debt-resolution'
def index
invoice_bundle = medical_copay_service.list(count: params[:count] || 10, page: params[:page] || 1)
render json: Lighthouse::HCC::InvoiceSerializer.new(
invoice_bundle.entries, links: invoice_bundle.links, meta: invoice_bundle.meta
)
end
def show
copay_detail = medical_copay_service.get_detail(id: params[:id])
render json: Lighthouse::HCC::CopayDetailSerializer.new(copay_detail)
end
private
def medical_copay_service
MedicalCopays::LighthouseIntegration::Service.new(current_user.icn)
end
end
end
|
0
|
code_files/vets-api-private/app/controllers
|
code_files/vets-api-private/app/controllers/v1/apidocs_controller.rb
|
# frozen_string_literal: true
module V1
class ApidocsController < ApplicationController
include Swagger::Blocks
service_tag 'platform-base'
skip_before_action :authenticate
swagger_root do
key :swagger, '2.0'
info do
key :version, '1.0.0'
key :title, 'va.gov API'
key :description, 'The API for managing va.gov'
key :termsOfService, ''
contact do
key :name, 'va.gov team'
end
license do
key :name, 'Creative Commons Zero v1.0 Universal'
end
end
# Tags are used to group endpoints in tools like swagger-ui
# Groups/tags are displayed in the order declared here, followed
# by the order they first appear in the swaggered_classes below, so
# declare all tags here in desired order.
tag do
key :name, 'ivc_champva_forms'
key :description, 'Creating and submitting IVC Champva applications'
end
tag do
key :name, 'higher_level_reviews'
key :description, 'Request a senior reviewer take a new look at a case'
end
tag do
key :name, 'income_limits'
key :description, 'Get income limit thresholds for veteran benefits.'
end
tag do
key :name, 'benefits_status'
key :description, 'Check status of benefits claims and appeals'
end
key :host, Settings.hostname
key :schemes, %w[https http]
key :basePath, '/'
key :consumes, ['application/json']
key :produces, ['application/json']
[true, false].each do |required|
parameter :"#{required ? '' : 'optional_'}authorization" do
key :name, 'Authorization'
key :in, :header
key :description, 'The authorization method and token value'
key :required, required
key :type, :string
end
end
parameter :optional_page_number,
name: :page,
in: :query,
required: false,
type: :integer,
description: 'Page of results, greater than 0 (default: 1)'
parameter :optional_page_length,
name: :per_page,
in: :query,
required: false,
type: :integer,
description: 'number of results, between 1 and 99 (default: 10)'
end
# A list of all classes that have swagger_* declarations.
SWAGGERED_CLASSES = [
Swagger::V1::Requests::IncomeLimits,
Swagger::V1::Schemas::IncomeLimits,
Swagger::V1::Schemas::Errors,
Swagger::V1::Requests::Appeals::Appeals,
Swagger::V1::Schemas::Appeals::Requests,
Swagger::V1::Schemas::Appeals::HigherLevelReview,
Swagger::V1::Schemas::Appeals::NoticeOfDisagreement,
Swagger::V1::Schemas::Appeals::SupplementalClaims,
Swagger::V1::Schemas::Appeals::DecisionReviewEvidence,
Swagger::V1::Requests::Post911GIBillStatuses,
Swagger::V1::Requests::IvcChampvaForms,
Swagger::V1::Requests::Gibct::VersionPublicExports,
Swagger::V1::Requests::MedicalCopays,
self
].freeze
def index
render json: Swagger::Blocks.build_root_json(SWAGGERED_CLASSES)
end
end
end
|
0
|
code_files/vets-api-private/app/controllers
|
code_files/vets-api-private/app/controllers/v1/sessions_controller.rb
|
# frozen_string_literal: true
require 'base64'
require 'saml/errors'
require 'saml/post_url_service'
require 'saml/responses/login'
require 'saml/responses/logout'
require 'saml/ssoe_settings_service'
require 'login/after_login_actions'
module V1
class SessionsController < ApplicationController
service_tag 'identity'
skip_before_action :verify_authenticity_token
REDIRECT_URLS = %w[signup mhv mhv_verified dslogon dslogon_verified idme idme_verified idme_signup
idme_signup_verified logingov logingov_verified logingov_signup
logingov_signup_verified custom mfa verify slo].freeze
STATSD_SSO_NEW_KEY = 'api.auth.new'
STATSD_SSO_SAMLREQUEST_KEY = 'api.auth.saml_request'
STATSD_SSO_SAMLRESPONSE_KEY = 'api.auth.saml_response'
STATSD_SSO_CALLBACK_KEY = 'api.auth.saml_callback'
STATSD_SSO_CALLBACK_TOTAL_KEY = 'api.auth.login_callback.total'
STATSD_SSO_CALLBACK_FAILED_KEY = 'api.auth.login_callback.failed'
STATSD_LOGIN_NEW_USER_KEY = 'api.auth.new_user'
STATSD_LOGIN_STATUS_SUCCESS = 'api.auth.login.success'
STATSD_LOGIN_STATUS_FAILURE = 'api.auth.login.failure'
STATSD_LOGIN_LATENCY = 'api.auth.latency'
VERSION_TAG = 'version:v1'
FIM_INVALID_MESSAGE_TIMESTAMP = 'invalid_message_timestamp'
OPERATION_TYPES = [AUTHORIZE = 'authorize',
INTERSTITIAL_VERIFY = 'interstitial_verify',
INTERSTITIAL_SIGNUP = 'interstitial_signup',
MHV_EXCEPTION = 'mhv_exception',
MYHEALTHEVET_TEST_ACCOUNT = 'myhealthevet_test_account',
VERIFY_CTA_AUTHENTICATED = 'verify_cta_authenticated',
VERIFY_PAGE_AUTHENTICATED = 'verify_page_authenticated',
VERIFY_PAGE_UNAUTHENTICATED = 'verify_page_unauthenticated'].freeze
CERNER_ELIGIBLE_COOKIE_NAME = 'CERNER_ELIGIBLE'
# Collection Action: auth is required for certain types of requests
# @type is set automatically by the routes in config/routes.rb
# For more details see SAML::SSOeSettingsService and SAML::URLService
# rubocop:disable Metrics/MethodLength
def new
type = params[:type]
client_id = params[:application] || 'vaweb'
operation = params[:operation] || 'authorize'
validate_operation_params(operation)
# As a temporary measure while we have the ability to authenticate either through SessionsController
# or through SignInController, we will delete all SignInController cookies when authenticating with SSOe
# to prevent undefined authentication behavior
delete_sign_in_service_cookies
if type == 'slo'
Rails.logger.info("SessionsController version:v1 LOGOUT of type #{type}", sso_logging_info)
reset_session
url = URI.parse(url_service.ssoe_slo_url)
app_key = if ActiveModel::Type::Boolean.new.cast(params[:agreements_declined])
IdentitySettings.saml_ssoe.tou_decline_logout_app_key
else
IdentitySettings.saml_ssoe.logout_app_key
end
query_strings = { appKey: CGI.escape(app_key), clientId: params[:client_id] }.compact
url.query = query_strings.to_query
redirect_to url.to_s
else
render_login(type)
end
new_stats(type, client_id, operation)
end
# rubocop:enable Metrics/MethodLength
def ssoe_slo_callback
Rails.logger.info("SessionsController version:v1 ssoe_slo_callback, user_uuid=#{@current_user&.uuid}")
if ActiveModel::Type::Boolean.new.cast(params[:agreements_declined])
redirect_to url_service.tou_declined_logout_redirect_url
else
redirect_to url_service.logout_redirect_url
end
end
def saml_callback
set_sentry_context_for_callback if html_escaped_relay_state['type'] == 'mfa'
saml_response = SAML::Responses::Login.new(params[:SAMLResponse], settings: saml_settings)
saml_response_stats(saml_response)
raise_saml_error(saml_response) unless saml_response.valid?
user_login(saml_response)
callback_stats(:success, saml_response)
Rails.logger.info("SessionsController version:v1 saml_callback complete, user_uuid=#{@current_user&.uuid}")
rescue SAML::SAMLError => e
handle_callback_error(e, :failure, saml_response, e.context, e.code, e.tag)
rescue => e
# the saml_response variable may or may not be defined depending on
# where the exception was raised
resp = defined?(saml_response) && saml_response
handle_callback_error(e, :failed_unknown, resp)
ensure
callback_stats(:total)
end
def metadata
meta = OneLogin::RubySaml::Metadata.new
render xml: meta.generate(saml_settings), content_type: 'application/xml'
end
private
def delete_sign_in_service_cookies
cookies.delete(SignIn::Constants::Auth::ACCESS_TOKEN_COOKIE_NAME)
cookies.delete(SignIn::Constants::Auth::REFRESH_TOKEN_COOKIE_NAME)
cookies.delete(SignIn::Constants::Auth::ANTI_CSRF_COOKIE_NAME)
cookies.delete(SignIn::Constants::Auth::INFO_COOKIE_NAME)
end
def set_sentry_context_for_callback
temp_session_object = Session.find(session[:token])
temp_current_user = User.find(temp_session_object.uuid) if temp_session_object&.uuid
Sentry.set_extras(
current_user_uuid: temp_current_user.try(:uuid),
current_user_icn: temp_current_user.try(:mhv_icn)
)
end
def saml_settings(force_authn: true)
SAML::SSOeSettingsService.saml_settings(force_authn:)
end
def raise_saml_error(form)
code = form.error_code
if code == SAML::Responses::Base::AUTH_TOO_LATE_ERROR_CODE && validate_session
code = UserSessionForm::ERRORS[:saml_replay_valid_session][:code]
end
raise SAML::FormError.new(form, code)
end
def authenticate
return unless action_name == 'new'
if %w[mfa verify].include?(params[:type])
super
elsif params[:type] == 'slo'
# load the session object and current user before attempting to destroy
load_user
reset_session
else
reset_session
end
end
def user_login(saml_response)
user_session_form = UserSessionForm.new(saml_response)
raise_saml_error(user_session_form) unless user_session_form.valid?
mhv_unverified_validation(user_session_form.user)
@current_user, @session_object = user_session_form.persist
set_cookies
after_login_actions
user_verification = current_user.user_verification
if user_verification.user_account.needs_accepted_terms_of_use?
redirect_to url_service.terms_of_use_redirect_url
else
redirect_to url_service.login_redirect_url
end
UserAudit.logger.success(event: :sign_in, user_verification:)
login_stats(:success)
end
def mhv_unverified_validation(user)
if html_escaped_relay_state['type'] == 'mhv_verified' && user.loa[:current] < LOA::THREE
mhv_unverified_error = SAML::UserAttributeError::ERRORS[:mhv_unverified_blocked]
Rails.logger.warn("SessionsController version:v1 #{mhv_unverified_error[:message]}")
raise SAML::UserAttributeError.new(message: mhv_unverified_error[:message],
code: mhv_unverified_error[:code],
tag: mhv_unverified_error[:tag])
end
end
def render_login(type)
check_cerner_eligibility
login_url, post_params = login_params(type)
renderer = ActionController::Base.renderer
renderer.controller.prepend_view_path(Rails.root.join('lib', 'saml', 'templates'))
result = renderer.render template: 'sso_post_form',
locals: { url: login_url, params: post_params },
format: :html
render body: result, content_type: 'text/html'
set_sso_saml_cookie!
saml_request_stats
end
def set_sso_saml_cookie!
cookies[IdentitySettings.ssoe_eauth_cookie.name] = {
value: saml_cookie_content.to_json,
expires: nil,
secure: IdentitySettings.ssoe_eauth_cookie.secure,
httponly: true,
domain: IdentitySettings.ssoe_eauth_cookie.domain
}
end
def saml_cookie_content
{
'timestamp' => Time.now.iso8601,
'transaction_id' => url_service.tracker&.payload_attr(:transaction_id),
'saml_request_id' => url_service.tracker&.uuid,
'saml_request_query_params' => url_service.query_params
}
end
# rubocop:disable Metrics/MethodLength
def login_params(type)
raise Common::Exceptions::RoutingError, type unless REDIRECT_URLS.include?(type)
case type
when 'mhv'
url_service.login_url('mhv', 'myhealthevet', AuthnContext::MHV)
when 'mhv_verified'
url_service.login_url('mhv_verified', 'myhealthevet', AuthnContext::MHV)
when 'dslogon', 'dslogon_verified'
url_service.login_url('dslogon', 'dslogon', AuthnContext::DSLOGON)
when 'idme'
url_service.login_url('idme', LOA::IDME_LOA1_VETS, AuthnContext::ID_ME, AuthnContext::MINIMUM)
when 'idme_verified'
url_service.login_url('idme', LOA::IDME_LOA3, AuthnContext::ID_ME, AuthnContext::MINIMUM)
when 'idme_signup'
url_service.idme_signup_url(LOA::IDME_LOA1_VETS)
when 'idme_signup_verified'
url_service.idme_signup_url(LOA::IDME_LOA3)
when 'logingov'
url_service.login_url(
'logingov',
[IAL::LOGIN_GOV_IAL1, AAL::LOGIN_GOV_AAL2],
AuthnContext::LOGIN_GOV,
AuthnContext::MINIMUM
)
when 'logingov_verified'
url_service.login_url(
'logingov',
[IAL::LOGIN_GOV_IAL2, AAL::LOGIN_GOV_AAL2],
AuthnContext::LOGIN_GOV
)
when 'logingov_signup'
url_service.logingov_signup_url([IAL::LOGIN_GOV_IAL1, AAL::LOGIN_GOV_AAL2])
when 'logingov_signup_verified'
url_service.logingov_signup_url([IAL::LOGIN_GOV_IAL2, AAL::LOGIN_GOV_AAL2])
when 'mfa'
url_service.mfa_url
when 'verify'
url_service.verify_url
when 'custom'
authn = validate_inbound_login_params
url_service(false).custom_url authn
end
end
# rubocop:enable Metrics/MethodLength
def saml_request_stats
tracker = url_service.tracker
authn_context = tracker&.payload_attr(:authn_context)
values = {
'id' => tracker&.uuid,
'authn' => authn_context,
'type' => tracker&.payload_attr(:type),
'transaction_id' => tracker&.payload_attr(:transaction_id)
}
Rails.logger.info("SSOe: SAML Request => #{values}")
normalized_authn = authn_context.is_a?(Array) ? authn_context.join('_').prepend('_') : authn_context
StatsD.increment(STATSD_SSO_SAMLREQUEST_KEY,
tags: ["type:#{tracker&.payload_attr(:type)}",
"context:#{normalized_authn}",
"client_id:#{tracker&.payload_attr(:application)}",
VERSION_TAG])
end
def saml_response_stats(saml_response)
uuid = saml_response.in_response_to
tracker = SAMLRequestTracker.find(uuid)
values = {
'id' => uuid,
'authn' => saml_response.authn_context,
'type' => tracker&.payload_attr(:type),
'transaction_id' => tracker&.payload_attr(:transaction_id),
'authentication_time' => tracker&.created_at ? Time.zone.now.to_i - tracker.created_at : 'unknown'
}
Rails.logger.info("SSOe: SAML Response => #{values}")
StatsD.increment(STATSD_SSO_SAMLRESPONSE_KEY,
tags: ["type:#{tracker&.payload_attr(:type)}",
"client_id:#{tracker&.payload_attr(:application)}",
"context:#{saml_response.authn_context}",
VERSION_TAG])
end
def check_cerner_eligibility
cookie = cookies.signed[CERNER_ELIGIBLE_COOKIE_NAME] || cookies[CERNER_ELIGIBLE_COOKIE_NAME]
value = ActiveModel::Type::Boolean.new.cast(cookie)
Rails.logger.info('[SessionsController] Cerner Eligibility',
eligible: value.nil? ? :unknown : value,
cookie_action: value.nil? ? :not_found : :found)
end
def new_stats(type, client_id, operation)
tags = ["type:#{type}", VERSION_TAG, "client_id:#{client_id}", "operation:#{operation}"]
StatsD.increment(STATSD_SSO_NEW_KEY, tags:)
Rails.logger.info("SSO_NEW_KEY, tags: #{tags}")
end
def login_stats(status, error = nil)
type = url_service.tracker.payload_attr(:type)
client_id = url_service.tracker.payload_attr(:application)
operation = url_service.tracker.payload_attr(:operation)
tags = ["type:#{type}", VERSION_TAG, "client_id:#{client_id}", "operation:#{operation}"]
case status
when :success
StatsD.increment(STATSD_LOGIN_NEW_USER_KEY, tags: [VERSION_TAG]) if type == 'signup'
StatsD.increment(STATSD_LOGIN_STATUS_SUCCESS, tags:)
context = { icn: @current_user.icn, version: 'v1', client_id:, type:, operation: }
Rails.logger.info('LOGIN_STATUS_SUCCESS', context)
Rails.logger.info("SessionsController version:v1 login complete, user_uuid=#{@current_user.uuid}")
StatsD.measure(STATSD_LOGIN_LATENCY, url_service.tracker.age, tags:)
when :failure
tags_and_error_code = tags << "error:#{error.try(:code) || SAML::Responses::Base::UNKNOWN_OR_BLANK_ERROR_CODE}"
error_message = error.try(:message) || 'Unknown'
StatsD.increment(STATSD_LOGIN_STATUS_FAILURE, tags: tags_and_error_code)
Rails.logger.info("LOGIN_STATUS_FAILURE, tags: #{tags_and_error_code}, message: #{error_message}")
Rails.logger.info("SessionsController version:v1 login failure, user_uuid=#{@current_user&.uuid}")
end
end
def callback_stats(status, saml_response = nil, failure_tag = nil)
tracker_tags = ["type:#{url_service.tracker.payload_attr(:type)}",
"client_id:#{url_service.tracker.payload_attr(:application)}",
"operation:#{url_service.tracker.payload_attr(:operation)}"]
case status
when :success
tags = ['status:success', "context:#{saml_response&.authn_context}", VERSION_TAG].concat(tracker_tags)
StatsD.increment(STATSD_SSO_CALLBACK_KEY, tags:)
when :failure
parsed_failure_tag = failure_tag.to_s.starts_with?('error:') ? failure_tag : "error:#{failure_tag}"
tags = ['status:failure', "context:#{saml_response&.authn_context}", VERSION_TAG].concat(tracker_tags)
StatsD.increment(STATSD_SSO_CALLBACK_KEY, tags:)
StatsD.increment(STATSD_SSO_CALLBACK_FAILED_KEY, tags: [parsed_failure_tag, VERSION_TAG])
when :failed_unknown
tags = ['status:failure', 'context:unknown', VERSION_TAG].concat(tracker_tags)
StatsD.increment(STATSD_SSO_CALLBACK_KEY, tags:)
StatsD.increment(STATSD_SSO_CALLBACK_FAILED_KEY, tags: ['error:unknown', VERSION_TAG])
when :total
StatsD.increment(STATSD_SSO_CALLBACK_TOTAL_KEY, tags: [VERSION_TAG])
end
end
# rubocop:disable Metrics/ParameterLists
def handle_callback_error(exc, status, response, context = {},
code = SAML::Responses::Base::UNKNOWN_OR_BLANK_ERROR_CODE, tag = nil)
# replaces bundled Sentry error message with specific XML messages
message = if response && response.normalized_errors.count > 1 && response.status_detail
response.status_detail
else
exc.message
end
Rails.logger.error('[V1][Sessions Controller] error', context:, message:)
Rails.logger.info("SessionsController version:v1 saml_callback failure, user_uuid=#{@current_user&.uuid}")
unless performed?
redirect_to url_service.login_redirect_url(auth: 'fail', code:,
request_id: request.request_id)
end
login_stats(:failure, exc) unless response.nil?
callback_stats(status, response, tag)
PersonalInformationLog.create(
error_class: exc,
data: {
request_id: request.uuid,
payload: response&.response || params[:SAMLResponse]
}
)
end
# rubocop:enable Metrics/ParameterLists
def invalid_message_timestamp_error?(message)
message.match(FIM_INVALID_MESSAGE_TIMESTAMP)
end
def set_cookies
Rails.logger.info('SSO: LOGIN', sso_logging_info)
set_api_cookie
set_cerner_eligibility_cookie
end
def after_login_actions
Login::AfterLoginActions.new(@current_user, skip_mhv_account_creation).perform
log_persisted_session_and_warnings
end
def skip_mhv_account_creation
skip_mhv_account_creation_client = url_service.tracker.payload_attr(:application) == SAML::User::MHV_ORIGINAL_CSID
skip_mhv_account_creation_type = url_service.tracker.payload_attr(:type) == 'custom'
skip_mhv_account_creation_client || skip_mhv_account_creation_type
end
def log_persisted_session_and_warnings
obscure_token = Session.obscure_token(@session_object.token)
Rails.logger.info("Logged in user with id #{@session_object&.uuid}, token #{obscure_token}")
end
def html_escaped_relay_state
JSON.parse(CGI.unescapeHTML(params[:RelayState] || '{}'))
end
def originating_request_id
html_escaped_relay_state['originating_request_id']
rescue
'UNKNOWN'
end
def url_service(force_authn = true)
@url_service ||= SAML::PostURLService.new(saml_settings(force_authn:),
session: @session_object,
user: current_user,
params:,
loa3_context: LOA::IDME_LOA3)
end
def validate_operation_params(operation)
raise Common::Exceptions::InvalidFieldValue.new('operation', operation) unless OPERATION_TYPES.include?(operation)
end
end
end
|
0
|
code_files/vets-api-private/app/controllers
|
code_files/vets-api-private/app/controllers/v1/post911_gi_bill_statuses_controller.rb
|
# frozen_string_literal: true
require 'formatters/date_formatter'
require 'lighthouse/benefits_education/service'
module V1
class Post911GIBillStatusesController < ApplicationController
include IgnoreNotFound
service_tag 'gibill-statement'
STATSD_KEY_PREFIX = 'api.post911_gi_bill_status'
def show
response = service.get_gi_bill_status
render json: Post911GIBillStatusSerializer.new(response)
rescue Breakers::OutageException => e
raise e
rescue => e
handle_error(e)
ensure
StatsD.increment("#{STATSD_KEY_PREFIX}.total")
end
private
def handle_error(e)
status = e.errors.first[:status].to_i
log_vet_not_found(@current_user, Time.now.in_time_zone('Eastern Time (US & Canada)')) if status == 404
StatsD.increment("#{STATSD_KEY_PREFIX}.fail", tags: ["error:#{status}"])
render json: { errors: e.errors }, status: status || :internal_server_error
end
def log_vet_not_found(user, timestamp)
PersonalInformationLog.create(
data: { timestamp:, user: user_json(user) },
error_class: 'BenefitsEducation::NotFound'
)
end
def user_json(user)
{
first_name: user.first_name,
last_name: user.last_name,
assurance_level: user.loa[:current].to_s,
birls_id: user.birls_id,
icn: user.icn,
edipi: user.edipi,
mhv_correlation_id: user.mhv_correlation_id,
participant_id: user.participant_id,
vet360_id: user.vet360_id,
ssn: user.ssn,
birth_date: Formatters::DateFormatter.format_date(user.birth_date, :datetime_iso8601)
}.to_json
end
def service
BenefitsEducation::Service.new(@current_user&.icn)
end
end
end
|
0
|
code_files/vets-api-private/app/controllers/v1
|
code_files/vets-api-private/app/controllers/v1/gids/zipcode_rates_controller.rb
|
# frozen_string_literal: true
module V1
module GIDS
class ZipcodeRatesController < GIDSController
def show
render json: service.get_zipcode_rate_v1(scrubbed_params)
end
end
end
end
|
0
|
code_files/vets-api-private/app/controllers/v1
|
code_files/vets-api-private/app/controllers/v1/gids/institution_programs_controller.rb
|
# frozen_string_literal: true
module V1
module GIDS
class InstitutionProgramsController < GIDSController
def autocomplete
render json: service.get_institution_program_autocomplete_suggestions_v1(scrubbed_params)
end
def search
render json: service.get_institution_program_search_results_v1(scrubbed_params)
end
end
end
end
|
0
|
code_files/vets-api-private/app/controllers/v1
|
code_files/vets-api-private/app/controllers/v1/gids/institutions_controller.rb
|
# frozen_string_literal: true
module V1
module GIDS
class InstitutionsController < GIDSController
def autocomplete
render json: service.get_institution_autocomplete_suggestions_v1(scrubbed_params)
end
def search
render json: service.get_institution_search_results_v1(scrubbed_params)
end
def show
render json: service.get_institution_details_v1(scrubbed_params)
end
def children
render json: service.get_institution_children_v1(scrubbed_params)
end
end
end
end
|
0
|
code_files/vets-api-private/app/controllers/v1
|
code_files/vets-api-private/app/controllers/v1/gids/calculator_constants_controller.rb
|
# frozen_string_literal: true
module V1
module GIDS
class CalculatorConstantsController < GIDSController
def index
render json: service.get_calculator_constants_v1(scrubbed_params)
end
end
end
end
|
0
|
code_files/vets-api-private/app/controllers/v1
|
code_files/vets-api-private/app/controllers/v1/gids/yellow_ribbon_programs_controller.rb
|
# frozen_string_literal: true
module V1
module GIDS
class YellowRibbonProgramsController < GIDSController
def index
render json: service.get_yellow_ribbon_programs_v1(scrubbed_params)
end
end
end
end
|
0
|
code_files/vets-api-private/app/controllers/v1
|
code_files/vets-api-private/app/controllers/v1/gids/version_public_exports_controller.rb
|
# frozen_string_literal: true
require 'gi/client'
module V1
module GIDS
class VersionPublicExportsController < GIDSController
def show
client = ::GI::Client.new
client_response = client.get_public_export_v1(scrubbed_params)
if client_response.status == 200
send_data(
client_response.body,
content_type: client_response.response_headers['Content-Type'],
disposition: client_response.response_headers['Content-Disposition']
)
else
render client_response
end
end
end
end
end
|
0
|
code_files/vets-api-private/app/controllers/v1
|
code_files/vets-api-private/app/controllers/v1/gids/lcpe_controller.rb
|
# frozen_string_literal: true
require 'gi/lcpe/client'
module V1
module GIDS
class LCPEController < GIDSController
rescue_from LCPERedis::ClientCacheStaleError, with: :version_invalid
FILTER_PARAMS = %i[edu_lac_type_nm state lac_nm page per_page].freeze
private
def service
return super if bypass_versioning?
lcpe_client
end
def lcpe_client
GI::LCPE::Client.new(v_client: preload_version_id, lcpe_type: controller_name)
end
def preload_version_id
preload_from_enriched_id || preload_from_etag
end
# '<record id>v<preload version>'
def preload_from_enriched_id
params[:id]&.split('v')&.last
end
def preload_from_etag
request.headers['If-None-Match']&.match(%r{W/"(\d+)"})&.captures&.first
end
def set_headers(version)
response.headers.delete('Cache-Control')
response.headers.delete('Pragma')
response.set_header('Expires', 1.week.since.to_s)
response.set_header('ETag', "W/\"#{version}\"")
end
# If additional filter params present, bypass versioning
def bypass_versioning?
params.keys.map(&:to_sym).intersect?(FILTER_PARAMS)
end
def version_invalid
render json: { error: 'Version invalid' }, status: :conflict
end
end
end
end
|
0
|
code_files/vets-api-private/app/controllers/v1/gids
|
code_files/vets-api-private/app/controllers/v1/gids/lcpe/exams_controller.rb
|
# frozen_string_literal: true
module V1
module GIDS
module LCPE
class ExamsController < GIDS::LCPEController
def index
exams = service.get_exams_v1(scrubbed_params)
set_headers(exams[:version]) unless bypass_versioning?
render json: exams
end
def show
render json: service.get_exam_details_v1(scrubbed_params)
end
end
end
end
end
|
0
|
code_files/vets-api-private/app/controllers/v1/gids
|
code_files/vets-api-private/app/controllers/v1/gids/lcpe/lacs_controller.rb
|
# frozen_string_literal: true
module V1
module GIDS
module LCPE
class LacsController < GIDS::LCPEController
def index
lacs = service.get_licenses_and_certs_v1(scrubbed_params)
set_headers(lacs[:version]) unless bypass_versioning?
render json: lacs
end
def show
render json: service.get_license_and_cert_details_v1(scrubbed_params)
end
end
end
end
end
|
0
|
code_files/vets-api-private/app/controllers/v1
|
code_files/vets-api-private/app/controllers/v1/profile/military_infos_controller.rb
|
# frozen_string_literal: true
require 'va_profile/profile/v3/service'
module V1
module Profile
# NOTE: This controller is used for discovery purposes.
# Please contact the Authenticated Experience Profile team before using.
class MilitaryInfosController < ApplicationController
service_tag 'military-info'
before_action :controller_enabled?
before_action { authorize :vet360, :military_access? }
def show
response = service.get_military_info
render status: response.status, json: response.body
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
|
code_files/vets-api-private/app/controllers/v0/veteran_onboardings_controller.rb
|
# frozen_string_literal: true
module V0
class VeteranOnboardingsController < ApplicationController
service_tag 'veteran-onboarding'
before_action :set_veteran_onboarding
def show
render json: @veteran_onboarding, status: :ok
end
def update
if @veteran_onboarding.update(veteran_onboarding_params)
render json: @veteran_onboarding, status: :ok
else
render json: { errors: @veteran_onboarding.errors }, status: :unprocessable_entity
end
end
private
def set_veteran_onboarding
@veteran_onboarding = current_user.onboarding
end
def veteran_onboarding_params
params.require(:veteran_onboarding).permit(:display_onboarding_flow)
end
end
end
|
0
|
code_files/vets-api-private/app/controllers
|
code_files/vets-api-private/app/controllers/v0/datadog_action_controller.rb
|
# frozen_string_literal: true
module V0
class DatadogActionController < ApplicationController
service_tag 'datadog-metrics'
skip_before_action :authenticate
def create
metric = params[:metric]
tags = params[:tags] || []
unless DatadogMetrics::ALLOWLIST.include?(metric)
render json: { error: 'Metric not allowed' }, status: :bad_request and return
end
StatsD.increment("web.frontend.#{metric}", tags:)
head :no_content
end
end
end
|
0
|
code_files/vets-api-private/app/controllers
|
code_files/vets-api-private/app/controllers/v0/caregivers_assistance_claims_controller.rb
|
# frozen_string_literal: true
module V0
# Application for the Program of Comprehensive Assistance for Family Caregivers (Form 10-10CG)
class CaregiversAssistanceClaimsController < ApplicationController
include RetriableConcern
include PdfFilenameGenerator
service_tag 'caregiver-application'
AUDITOR = ::Form1010cg::Auditor.new
skip_before_action :authenticate
before_action :load_user, only: :create
before_action :record_submission_attempt, only: :create
before_action :initialize_claim, only: %i[create download_pdf]
rescue_from ::Form1010cg::Service::InvalidVeteranStatus, with: :backend_service_outage
def create
if @claim.valid?
Sentry.set_tags(claim_guid: @claim.guid)
auditor.record_caregivers(@claim)
::Form1010cg::Service.new(@claim).assert_veteran_status
@claim.save!
::Form1010cg::SubmissionJob.perform_async(@claim.id)
render json: ::Form1010cg::ClaimSerializer.new(@claim)
else
PersonalInformationLog.create!(data: { form: @claim.parsed_form }, error_class: '1010CGValidationError')
auditor.record(:submission_failure_client_data, claim_guid: @claim.guid, errors: @claim.errors.full_messages)
raise(Common::Exceptions::ValidationErrors, @claim)
end
rescue => e
unless e.is_a?(Common::Exceptions::ValidationErrors) || e.is_a?(::Form1010cg::Service::InvalidVeteranStatus)
Rails.logger.error('CaregiverAssistanceClaim: error submitting claim',
{ saved_claim_guid: @claim.guid, error: e })
end
raise e
end
def download_pdf
file_name = SecureRandom.uuid
source_file_path = with_retries('Generate 10-10CG PDF') do
@claim.to_pdf(file_name, sign: false)
end
client_file_name = file_name_for_pdf(@claim.veteran_data, 'fullName', '10-10CG')
file_contents = File.read(source_file_path)
auditor.record(:pdf_download)
send_data file_contents, filename: client_file_name, type: 'application/pdf', disposition: 'attachment'
ensure
File.delete(source_file_path) if source_file_path && File.exist?(source_file_path)
end
def facilities
lighthouse_facilities = lighthouse_facilities_service.get_paginated_facilities(lighthouse_facilities_params)
render(json: lighthouse_facilities)
end
private
def lighthouse_facilities_service
@lighthouse_facilities_service ||= FacilitiesApi::V2::Lighthouse::Client.new
end
def lighthouse_facilities_params
permitted_params = params.permit(
:zip,
:state,
:lat,
:long,
:radius,
:visn,
:type,
:mobile,
:page,
:per_page,
:facility_ids,
services: [],
bbox: []
)
# The Lighthouse Facilities api expects the facility ids param as `facilityIds`
permitted_params.to_h.transform_keys { |key| key == 'facility_ids' ? 'facilityIds' : key }
end
def record_submission_attempt
auditor.record(:submission_attempt)
end
def form_submission
params.require(:caregivers_assistance_claim).require(:form)
rescue => e
auditor.record(:submission_failure_client_data, errors: [e.original_message])
raise e
end
def initialize_claim
@claim = SavedClaim::CaregiversAssistanceClaim.new(form: form_submission)
end
def backend_service_outage
auditor.record(
:submission_failure_client_qualification,
claim_guid: @claim.guid
)
render_errors Common::Exceptions::ServiceOutage.new(nil, detail: 'Backend Service Outage')
end
def auditor
self.class::AUDITOR
end
end
end
|
0
|
code_files/vets-api-private/app/controllers
|
code_files/vets-api-private/app/controllers/v0/event_bus_gateway_controller.rb
|
# frozen_string_literal: true
module V0
class EventBusGatewayController < SignIn::ServiceAccountApplicationController
service_tag 'event_bus_gateway'
def send_email
EventBusGateway::LetterReadyEmailJob.perform_async(
participant_id,
send_email_params.require(:template_id)
)
head :ok
end
def send_push
EventBusGateway::LetterReadyPushJob.perform_async(
participant_id,
send_push_params.require(:template_id)
)
head :ok
end
def send_notifications
validate_at_least_one_template!
return if performed?
EventBusGateway::LetterReadyNotificationJob.perform_async(
participant_id,
send_notifications_params[:email_template_id],
send_notifications_params[:push_template_id]
)
head :ok
end
private
def participant_id
@participant_id ||= @service_account_access_token.user_attributes['participant_id']
end
def send_email_params
params.permit(:template_id)
end
def send_push_params
params.permit(:template_id)
end
def send_notifications_params
params.permit(:email_template_id, :push_template_id)
end
def validate_at_least_one_template!
return if send_notifications_params[:email_template_id].present? ||
send_notifications_params[:push_template_id].present?
render json: {
errors: [{
title: 'Bad Request',
detail: 'At least one of email_template_id or push_template_id is required',
status: '400'
}]
}, status: :bad_request
end
end
end
|
0
|
code_files/vets-api-private/app/controllers
|
code_files/vets-api-private/app/controllers/v0/documents_controller.rb
|
# frozen_string_literal: true
# Upload documents associated with a claim in the Claim Status Tool, to be sent to EVSS in a Job
module V0
class DocumentsController < ApplicationController
before_action { authorize :evss, :access? }
service_tag 'claim-status'
def create
params.require :file
claim = EVSSClaim.for_user(current_user).find_by(evss_id: params[:evss_claim_id])
raise Common::Exceptions::RecordNotFound, params[:evss_claim_id] unless claim
document_data = EVSSClaimDocument.new(
evss_claim_id: claim.evss_id,
file_obj: params[:file],
uuid: SecureRandom.uuid,
file_name: params[:file].original_filename,
tracked_item_id: params[:tracked_item_id],
document_type: params[:document_type],
password: params[:password]
)
raise Common::Exceptions::ValidationErrors, document_data unless document_data.valid?
jid = service.upload_document(document_data)
render_job_id(jid)
end
private
def service
EVSSClaimService.new(current_user)
end
end
end
|
0
|
code_files/vets-api-private/app/controllers
|
code_files/vets-api-private/app/controllers/v0/debt_letters_controller.rb
|
# frozen_string_literal: true
require 'debt_management_center/debt_letter_downloader'
module V0
class DebtLettersController < ApplicationController
service_tag 'debt-resolution'
before_action { authorize :debt_letters, :access? }
def index
render(json: service.list_letters)
end
def show
send_data(
service.get_letter(params[:id]),
type: 'application/pdf',
filename: service.file_name(params[:id])
)
end
private
def service
@service ||= DebtManagementCenter::DebtLetterDownloader.new(@current_user)
end
end
end
|
0
|
code_files/vets-api-private/app/controllers
|
code_files/vets-api-private/app/controllers/v0/letters_discrepancy_controller.rb
|
# frozen_string_literal: true
# NOTE: extra imports shouldn't be needed in theory, but
# they sometimes cause the services to not load if they're not there
# imports needed for evss
require 'common/exceptions/record_not_found' # this shouldn't be needed
require 'evss/letters/download_service' # this shouldn't be needed
require 'evss/letters/service'
# imports needed for lighthouse
require 'lighthouse/letters_generator/service'
require 'lighthouse/letters_generator/service_error' # this shouldn't be needed
module V0
class LettersDiscrepancyController < ApplicationController
service_tag 'letters'
before_action { authorize :evss, :access_letters? }
before_action { authorize :lighthouse, :access? }
def index
# Call lighthouse endpoint
lh_response = lh_service.get_eligible_letter_types(@current_user.icn)
# Format response into lh_letters array
lh_letters = lh_response[:letters].pluck(:letterType)
# Call evss endpoint
evss_response = evss_service.get_letters
# Format response into evss_letters array
evss_letters = evss_response.letters.map(&:letter_type)
# Return if there are no differences
unless lh_letters.sort == evss_letters.sort
# Find difference between letters returned by each service
lh_letter_diff = lh_letters.difference(evss_letters).count
evss_letter_diff = evss_letters.difference(lh_letters).count
# Log differences (will be monitored in DataDog)
log_title = 'Letters Generator Discrepancies'
::Rails.logger.info(log_title,
{ message_type: 'lh.letters_generator.letters_discrepancy',
lh_letter_diff:,
evss_letter_diff:,
lh_letters: lh_letters.sort.join(', '),
evss_letters: evss_letters.sort.join(', ') })
end
render json: []
end
private
def evss_service
EVSS::Letters::Service.new(@current_user)
end
# Lighthouse Service
def lh_service
@lh_service ||= Lighthouse::LettersGenerator::Service.new
end
end
end
|
0
|
code_files/vets-api-private/app/controllers
|
code_files/vets-api-private/app/controllers/v0/terms_of_use_agreements_controller.rb
|
# frozen_string_literal: true
require 'terms_of_use/exceptions'
module V0
class TermsOfUseAgreementsController < ApplicationController
service_tag 'terms-of-use'
skip_before_action :verify_authenticity_token, only: [:update_provisioning]
skip_before_action :authenticate
before_action :terms_authenticate
def latest
terms_of_use_agreement = find_latest_agreement_by_version(params[:version])
render_success(action: 'latest', body: { terms_of_use_agreement: })
end
def accept
terms_of_use_agreement = acceptor.perform!
unless terms_code_temporary_auth?
recache_user
current_user.create_mhv_account_async unless skip_mhv_account_creation?
end
render_success(action: 'accept', body: { terms_of_use_agreement: }, status: :created)
rescue TermsOfUse::Errors::AcceptorError => e
render_error(action: 'accept', message: e.message)
end
def accept_and_provision
terms_of_use_agreement = acceptor(sync: true).perform!
if terms_of_use_agreement.accepted?
provisioner.perform
create_cerner_cookie
unless terms_code_temporary_auth?
recache_user
current_user.create_mhv_account_async unless skip_mhv_account_creation?
end
render_success(action: 'accept_and_provision', body: { terms_of_use_agreement:, provisioned: true },
status: :created)
else
render_error(action: 'accept_and_provision', message: 'Failed to accept and provision')
end
rescue TermsOfUse::Errors::AcceptorError, Identity::Errors::CernerProvisionerError => e
render_error(action: 'accept_and_provision', message: e.message)
end
def decline
terms_of_use_agreement = decliner.perform!
recache_user unless terms_code_temporary_auth?
render_success(action: 'decline', body: { terms_of_use_agreement: }, status: :created)
rescue TermsOfUse::Errors::DeclinerError => e
render_error(action: 'decline', message: e.message)
end
def update_provisioning
provisioner.perform
create_cerner_cookie
render_success(action: 'update_provisioning', body: { provisioned: true }, status: :ok)
rescue Identity::Errors::CernerProvisionerError => e
render_error(action: 'update_provisioning', message: e.message)
end
private
def acceptor(sync: false)
TermsOfUse::Acceptor.new(user_account: @user_account, version: params[:version], sync:)
end
def decliner
TermsOfUse::Decliner.new(user_account: @user_account, version: params[:version])
end
def provisioner
Identity::CernerProvisioner.new(icn: @user_account.icn, source: :tou)
end
def recache_user
current_user.needs_accepted_terms_of_use = current_user.user_account&.needs_accepted_terms_of_use?
current_user.save
end
def create_cerner_cookie
cookies[Identity::CernerProvisioner::COOKIE_NAME] = {
value: Identity::CernerProvisioner::COOKIE_VALUE,
expires: Identity::CernerProvisioner::COOKIE_EXPIRATION.from_now,
path: Identity::CernerProvisioner::COOKIE_PATH,
domain: Identity::CernerProvisioner::COOKIE_DOMAIN
}
end
def find_latest_agreement_by_version(version)
@user_account.terms_of_use_agreements.where(agreement_version: version).last
end
def authenticate_one_time_terms_code
terms_code_container = SignIn::TermsCodeContainer.find(params[:terms_code])
return unless terms_code_container
@user_account = UserAccount.find(terms_code_container.user_account_uuid)
ensure
terms_code_container&.destroy
end
def authenticate_current_user
load_user(skip_terms_check: true)
return unless current_user
@user_account = current_user.user_account
end
def terms_code_temporary_auth?
params[:terms_code].present?
end
def terms_authenticate
terms_code_temporary_auth? ? authenticate_one_time_terms_code : authenticate_current_user
raise Common::Exceptions::Unauthorized unless @user_account
end
def mpi_profile
@mpi_profile ||= MPI::Service.new.find_profile_by_identifier(identifier: @user_account.icn,
identifier_type: MPI::Constants::ICN)&.profile
end
def skip_mhv_account_creation?
ActiveModel::Type::Boolean.new.cast(params[:skip_mhv_account_creation])
end
def render_success(action:, body:, status: :ok, icn: @user_account.icn)
Rails.logger.info("[TermsOfUseAgreementsController] #{action} success", { icn: })
render json: body, status:
end
def render_error(action:, message:, status: :unprocessable_entity)
Rails.logger.error("[TermsOfUseAgreementsController] #{action} error: #{message}", { icn: @user_account.icn })
render json: { error: message }, status:
end
end
end
|
0
|
code_files/vets-api-private/app/controllers
|
code_files/vets-api-private/app/controllers/v0/mhv_opt_in_flags_controller.rb
|
# frozen_string_literal: true
module V0
class MHVOptInFlagsController < ApplicationController
service_tag 'deprecated'
def show
opt_in_flag = MHVOptInFlag.find_by(user_account_id: current_user.user_account, feature: params[:feature])
raise Common::Exceptions::RecordNotFound, message: 'Record not found' if opt_in_flag.nil?
render json: { mhv_opt_in_flag: { user_account_id: opt_in_flag.user_account_id, feature: opt_in_flag.feature } }
rescue => e
render json: { errors: e.message }, status: :not_found
end
def create
feature = params[:feature]
unless MHVOptInFlag::FEATURES.include?(feature)
raise MHVOptInFlagFeatureNotValid.new message: 'Feature param is not valid'
end
status = :ok
opt_in_flag = MHVOptInFlag.find_or_create_by(user_account: current_user.user_account,
feature:) do |_mhv_opt_in_flag|
status = :created
end
render json: { mhv_opt_in_flag: { user_account_id: opt_in_flag.user_account_id, feature: opt_in_flag.feature } },
status:
rescue MHVOptInFlagFeatureNotValid => e
render json: { errors: e }, status: :bad_request
rescue
render json: { errors: 'Internal Server Error' }, status: :internal_server_error
end
class MHVOptInFlagFeatureNotValid < StandardError; end
end
end
|
0
|
code_files/vets-api-private/app/controllers
|
code_files/vets-api-private/app/controllers/v0/apps_controller.rb
|
# frozen_string_literal: true
require 'apps/client'
module V0
class AppsController < ApplicationController
include ActionView::Helpers::SanitizeHelper
service_tag 'third-party-apps'
skip_before_action :authenticate
def index
response = Apps::Client.new.get_all
render json: response.body,
status: response.status
end
def show
response = Apps::Client.new(params[:id]).get_app
render json: response.body,
status: response.status
end
def scopes
response = Apps::Client.new(params[:category]).get_scopes
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/upload_supporting_evidences_controller.rb
|
# frozen_string_literal: true
require 'logging/third_party_transaction'
module V0
class UploadSupportingEvidencesController < ApplicationController
include FormAttachmentCreate
extend Logging::ThirdPartyTransaction::MethodWrapper
service_tag 'disability-application'
FORM_ATTACHMENT_MODEL = SupportingEvidenceAttachment
wrap_with_logging(
:save_attachment_to_cloud!,
additional_class_logs: {
form: '526ez supporting evidence attachment',
action: "upload: #{FORM_ATTACHMENT_MODEL}",
upstream: 'User provided file',
downstream: "S3 bucket: #{Settings.evss.s3.bucket}"
},
additional_instance_logs: {
user_uuid: %i[current_user account_uuid]
}
)
private
def serializer_klass
SupportingEvidenceAttachmentSerializer
end
end
end
|
0
|
code_files/vets-api-private/app/controllers
|
code_files/vets-api-private/app/controllers/v0/medical_copays_controller.rb
|
# frozen_string_literal: true
module V0
class MedicalCopaysController < ApplicationController
service_tag 'debt-resolution'
before_action(except: :send_statement_notifications) { authorize :medical_copays, :access? }
before_action(only: :send_statement_notifications) { authorize :medical_copays, :access_notifications? }
before_action :authorize_vbs_api, only: [:send_statement_notifications]
skip_before_action :verify_authenticity_token, only: [:send_statement_notifications]
skip_before_action :authenticate, only: [:send_statement_notifications]
skip_after_action :set_csrf_header, only: [:send_statement_notifications]
rescue_from ::MedicalCopays::VBS::Service::StatementNotFound, with: :render_not_found
def index
StatsD.increment('api.mcp.total')
render json: vbs_service.get_copays
end
def show
render json: vbs_service.get_copay_by_id(params[:id])
end
def get_pdf_statement_by_id
send_data(
vbs_service.get_pdf_statement_by_id(params[:statement_id]),
type: 'application/pdf',
filename: statement_params[:file_name]
)
end
def send_statement_notifications
vbs_service.send_statement_notifications(params[:statements])
render json: { message: 'Parsing and sending notifications' }, status: :ok
end
private
def authorization_error
Common::Exceptions::Unauthorized.new(detail: 'Invalid API key')
end
def authorize_vbs_api
request_key = request.headers['apiKey']
raise authorization_error if request_key.blank?
raise authorization_error unless request_key == Settings.mcp.vbs_client_key
end
def statement_params
params.permit(:file_name)
end
def vbs_service
MedicalCopays::VBS::Service.build(user: current_user)
end
def render_not_found
render json: nil, status: :not_found
end
end
end
|
0
|
code_files/vets-api-private/app/controllers
|
code_files/vets-api-private/app/controllers/v0/tsa_letter_controller.rb
|
# frozen_string_literal: true
require 'efolder/service'
module V0
class TsaLetterController < ApplicationController
service_tag 'tsa_letter'
def index
letters = service.list_tsa_letters
render(json: TsaLetterSerializer.new(letters))
end
def show
send_data(
service.get_tsa_letter(params[:id]),
type: 'application/pdf',
filename: 'VETS Safe Travel Outreach Letter.pdf'
)
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/sign_in_controller.rb
|
# frozen_string_literal: true
require 'sign_in/logger'
module V0
class SignInController < SignIn::ApplicationController
include SignIn::SSOAuthorizable
skip_before_action :authenticate,
only: %i[authorize callback token refresh revoke revoke_all_sessions logout
logingov_logout_proxy]
before_action :access_token_authenticate, only: :revoke_all_sessions
def authorize # rubocop:disable Metrics/MethodLength
type = params[:type].presence
client_state = params[:state].presence
code_challenge = params[:code_challenge].presence
code_challenge_method = params[:code_challenge_method].presence
client_id = params[:client_id].presence
acr = params[:acr].presence
operation = params[:operation].presence || SignIn::Constants::Auth::AUTHORIZE
scope = params[:scope].presence
validate_authorize_params(type, client_id, acr, operation)
delete_cookies if token_cookies
acr_for_type = SignIn::AcrTranslator.new(acr:, type:).perform
state = SignIn::StatePayloadJwtEncoder.new(code_challenge:,
code_challenge_method:,
acr:,
client_config: client_config(client_id),
type:,
client_state:,
scope:).perform
context = { type:, client_id:, acr:, operation: }
sign_in_logger.info('authorize', context)
StatsD.increment(SignIn::Constants::Statsd::STATSD_SIS_AUTHORIZE_SUCCESS,
tags: ["type:#{type}", "client_id:#{client_id}", "acr:#{acr}", "operation:#{operation}"])
render body: auth_service(type, client_id).render_auth(state:, acr: acr_for_type, operation:),
content_type: 'text/html'
rescue => e
sign_in_logger.info('authorize error', { errors: e.message, client_id:, type:, acr:, operation: })
StatsD.increment(SignIn::Constants::Statsd::STATSD_SIS_AUTHORIZE_FAILURE)
handle_pre_login_error(e, client_id)
end
def callback # rubocop:disable Metrics/MethodLength
code = params[:code].presence
state = params[:state].presence
error = params[:error].presence
validate_callback_params(code, state, error)
state_payload = SignIn::StatePayloadJwtDecoder.new(state_payload_jwt: state).perform
SignIn::StatePayloadVerifier.new(state_payload:).perform
handle_credential_provider_error(error, state_payload&.type) if error
service_token_response = auth_service(state_payload.type, state_payload.client_id).token(code)
raise SignIn::Errors::CodeInvalidError.new message: 'Code is not valid' unless service_token_response
user_info = auth_service(state_payload.type,
state_payload.client_id).user_info(service_token_response[:access_token])
credential_level = SignIn::CredentialLevelCreator.new(requested_acr: state_payload.acr,
type: state_payload.type,
logingov_acr: service_token_response[:logingov_acr],
user_info:).perform
if credential_level.can_uplevel_credential?
render_uplevel_credential(state_payload)
else
create_login_code(state_payload, user_info, credential_level)
end
rescue => e
error_details = {
type: state_payload&.type,
client_id: state_payload&.client_id,
acr: state_payload&.acr
}
sign_in_logger.info('callback error', error_details.merge(errors: e.message))
StatsD.increment(SignIn::Constants::Statsd::STATSD_SIS_CALLBACK_FAILURE,
tags: ["type:#{error_details[:type]}",
"client_id:#{error_details[:client_id]}",
"acr:#{error_details[:acr]}"])
handle_pre_login_error(e, state_payload&.client_id)
end
def token
SignIn::TokenParamsValidator.new(params: token_params).perform
request_attributes = { remote_ip: request.remote_ip, user_agent: request.user_agent }
response_body = SignIn::TokenResponseGenerator.new(params: token_params,
cookies: token_cookies,
request_attributes:).perform
sign_in_logger.info('token')
StatsD.increment(SignIn::Constants::Statsd::STATSD_SIS_TOKEN_SUCCESS)
render json: response_body, status: :ok
rescue SignIn::Errors::StandardError => e
sign_in_logger.info('token error', { errors: e.message, grant_type: token_params[:grant_type] })
StatsD.increment(SignIn::Constants::Statsd::STATSD_SIS_TOKEN_FAILURE)
render json: { errors: e }, status: :bad_request
end
def refresh
refresh_token = refresh_token_param.presence
anti_csrf_token = anti_csrf_token_param.presence
raise SignIn::Errors::MalformedParamsError.new message: 'Refresh token is not defined' unless refresh_token
decrypted_refresh_token = SignIn::RefreshTokenDecryptor.new(encrypted_refresh_token: refresh_token).perform
session_container = SignIn::SessionRefresher.new(refresh_token: decrypted_refresh_token,
anti_csrf_token:).perform
serializer_response = SignIn::TokenSerializer.new(session_container:,
cookies: token_cookies).perform
sign_in_logger.info('refresh', session_container.context)
StatsD.increment(SignIn::Constants::Statsd::STATSD_SIS_REFRESH_SUCCESS)
render json: serializer_response, status: :ok
rescue SignIn::Errors::MalformedParamsError => e
sign_in_logger.info('refresh error', { errors: e.message })
StatsD.increment(SignIn::Constants::Statsd::STATSD_SIS_REFRESH_FAILURE)
render json: { errors: e }, status: :bad_request
rescue SignIn::Errors::StandardError => e
sign_in_logger.info('refresh error', { errors: e.message })
StatsD.increment(SignIn::Constants::Statsd::STATSD_SIS_REFRESH_FAILURE)
render json: { errors: e }, status: :unauthorized
end
def revoke
refresh_token = params[:refresh_token].presence
anti_csrf_token = params[:anti_csrf_token].presence
device_secret = params[:device_secret].presence
raise SignIn::Errors::MalformedParamsError.new message: 'Refresh token is not defined' unless refresh_token
decrypted_refresh_token = SignIn::RefreshTokenDecryptor.new(encrypted_refresh_token: refresh_token).perform
SignIn::SessionRevoker.new(refresh_token: decrypted_refresh_token, anti_csrf_token:, device_secret:).perform
sign_in_logger.info('revoke', decrypted_refresh_token.to_s)
StatsD.increment(SignIn::Constants::Statsd::STATSD_SIS_REVOKE_SUCCESS)
render status: :ok
rescue SignIn::Errors::MalformedParamsError => e
sign_in_logger.info('revoke error', { errors: e.message })
StatsD.increment(SignIn::Constants::Statsd::STATSD_SIS_REVOKE_FAILURE)
render json: { errors: e }, status: :bad_request
rescue SignIn::Errors::StandardError => e
sign_in_logger.info('revoke error', { errors: e.message })
StatsD.increment(SignIn::Constants::Statsd::STATSD_SIS_REVOKE_FAILURE)
render json: { errors: e }, status: :unauthorized
end
def revoke_all_sessions
session = SignIn::OAuthSession.find_by(handle: @access_token.session_handle)
raise SignIn::Errors::SessionNotFoundError.new message: 'Session not found' if session.blank?
SignIn::RevokeSessionsForUser.new(user_account: session.user_account).perform
sign_in_logger.info('revoke all sessions', @access_token.to_s)
StatsD.increment(SignIn::Constants::Statsd::STATSD_SIS_REVOKE_ALL_SESSIONS_SUCCESS)
render status: :ok
rescue SignIn::Errors::StandardError => e
sign_in_logger.info('revoke all sessions error', { errors: e.message })
StatsD.increment(SignIn::Constants::Statsd::STATSD_SIS_REVOKE_ALL_SESSIONS_FAILURE)
render json: { errors: e }, status: :unauthorized
end
def logout # rubocop:disable Metrics/MethodLength
client_id = params[:client_id].presence
anti_csrf_token = anti_csrf_token_param.presence
if client_config(client_id).blank?
raise SignIn::Errors::MalformedParamsError.new message: 'Client id is not valid'
end
unless access_token_authenticate(skip_render_error: true)
raise SignIn::Errors::LogoutAuthorizationError.new message: 'Unable to authorize access token'
end
session = SignIn::OAuthSession.find_by(handle: @access_token.session_handle)
raise SignIn::Errors::SessionNotFoundError.new message: 'Session not found' if session.blank?
credential_type = session.user_verification.credential_type
SignIn::SessionRevoker.new(access_token: @access_token, anti_csrf_token:).perform
delete_cookies if token_cookies
sign_in_logger.info('logout', @access_token.to_s)
StatsD.increment(SignIn::Constants::Statsd::STATSD_SIS_LOGOUT_SUCCESS)
logout_redirect = SignIn::LogoutRedirectGenerator.new(credential_type:,
client_config: client_config(client_id)).perform
logout_redirect ? redirect_to(logout_redirect) : render(status: :ok)
rescue SignIn::Errors::LogoutAuthorizationError,
SignIn::Errors::SessionNotAuthorizedError,
SignIn::Errors::SessionNotFoundError => e
sign_in_logger.info('logout error', { errors: e.message, client_id: })
StatsD.increment(SignIn::Constants::Statsd::STATSD_SIS_LOGOUT_FAILURE)
logout_redirect = SignIn::LogoutRedirectGenerator.new(client_config: client_config(client_id)).perform
logout_redirect ? redirect_to(logout_redirect) : render(status: :ok)
rescue => e
sign_in_logger.info('logout error', { errors: e.message, client_id: })
StatsD.increment(SignIn::Constants::Statsd::STATSD_SIS_LOGOUT_FAILURE)
render json: { errors: e }, status: :bad_request
end
def logingov_logout_proxy
state = params[:state].presence
raise SignIn::Errors::MalformedParamsError.new message: 'State is not defined' unless state
render body: auth_service(SignIn::Constants::Auth::LOGINGOV).render_logout_redirect(state),
content_type: 'text/html'
rescue => e
sign_in_logger.info('logingov_logout_proxy error', { errors: e.message })
render json: { errors: e }, status: :bad_request
end
private
def validate_authorize_params(type, client_id, acr, operation)
if client_config(client_id).blank?
raise SignIn::Errors::MalformedParamsError.new message: 'Client id is not valid'
end
unless client_config(client_id).valid_credential_service_provider?(type)
raise SignIn::Errors::MalformedParamsError.new message: 'Type is not valid'
end
unless SignIn::Constants::Auth::OPERATION_TYPES.include?(operation)
raise SignIn::Errors::MalformedParamsError.new message: 'Operation is not valid'
end
unless client_config(client_id).valid_service_level?(acr)
raise SignIn::Errors::MalformedParamsError.new message: 'ACR is not valid'
end
end
def validate_callback_params(code, state, error)
raise SignIn::Errors::MalformedParamsError.new message: 'Code is not defined' unless code || error
raise SignIn::Errors::MalformedParamsError.new message: 'State is not defined' unless state
end
def token_params
params.permit(:grant_type, :code, :code_verifier, :client_assertion, :client_assertion_type,
:assertion, :subject_token, :subject_token_type, :actor_token, :actor_token_type, :client_id)
end
def handle_pre_login_error(error, client_id)
if cookie_authentication?(client_id)
error_code = error.try(:code) || SignIn::Constants::ErrorCode::INVALID_REQUEST
params_hash = { auth: 'fail', code: error_code, request_id: request.request_id }
render body: SignIn::RedirectUrlGenerator.new(redirect_uri: client_config(client_id).redirect_uri,
params_hash:).perform,
content_type: 'text/html'
else
render json: { errors: error }, status: :bad_request
end
end
def handle_credential_provider_error(error, type)
if error == SignIn::Constants::Auth::ACCESS_DENIED
error_message = 'User Declined to Authorize Client'
error_code = if type == SignIn::Constants::Auth::LOGINGOV
SignIn::Constants::ErrorCode::LOGINGOV_VERIFICATION_DENIED
else
SignIn::Constants::ErrorCode::IDME_VERIFICATION_DENIED
end
raise SignIn::Errors::AccessDeniedError.new message: error_message, code: error_code
else
error_message = 'Unknown Credential Provider Issue'
error_code = SignIn::Constants::ErrorCode::GENERIC_EXTERNAL_ISSUE
raise SignIn::Errors::CredentialProviderError.new message: error_message, code: error_code
end
end
def render_uplevel_credential(state_payload)
acr_for_type = SignIn::AcrTranslator.new(acr: state_payload.acr, type: state_payload.type, uplevel: true).perform
state = SignIn::StatePayloadJwtEncoder.new(code_challenge: state_payload.code_challenge,
code_challenge_method: SignIn::Constants::Auth::CODE_CHALLENGE_METHOD,
acr: state_payload.acr,
client_config: client_config(state_payload.client_id),
type: state_payload.type,
client_state: state_payload.client_state).perform
render body: auth_service(state_payload.type, state_payload.client_id).render_auth(state:, acr: acr_for_type),
content_type: 'text/html'
end
def create_login_code(state_payload, user_info, credential_level) # rubocop:disable Metrics/MethodLength
user_attributes = auth_service(state_payload.type,
state_payload.client_id).normalized_attributes(user_info, credential_level)
verified_icn = SignIn::AttributeValidator.new(user_attributes:).perform
user_code_map = SignIn::UserCodeMapCreator.new(
user_attributes:, state_payload:, verified_icn:, request_ip: request.remote_ip
).perform
context = {
type: state_payload.type,
client_id: state_payload.client_id,
ial: credential_level.current_ial,
acr: state_payload.acr,
icn: verified_icn,
credential_uuid: user_info.sub,
authentication_time: Time.zone.now.to_i - state_payload.created_at
}
sign_in_logger.info('callback', context)
StatsD.increment(SignIn::Constants::Statsd::STATSD_SIS_CALLBACK_SUCCESS,
tags: ["type:#{state_payload.type}",
"client_id:#{state_payload.client_id}",
"ial:#{credential_level.current_ial}",
"acr:#{state_payload.acr}"])
params_hash = { code: user_code_map.login_code, type: user_code_map.type }
params_hash.merge!(state: user_code_map.client_state) if user_code_map.client_state.present?
render body: SignIn::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:).perform,
content_type: 'text/html'
end
def refresh_token_param
params[:refresh_token] || token_cookies[SignIn::Constants::Auth::REFRESH_TOKEN_COOKIE_NAME]
end
def anti_csrf_token_param
params[:anti_csrf_token] || token_cookies[SignIn::Constants::Auth::ANTI_CSRF_COOKIE_NAME]
end
def token_cookies
@token_cookies ||= defined?(cookies) ? cookies : nil
end
def delete_cookies
cookies.delete(SignIn::Constants::Auth::ACCESS_TOKEN_COOKIE_NAME, domain: :all)
cookies.delete(SignIn::Constants::Auth::REFRESH_TOKEN_COOKIE_NAME)
cookies.delete(SignIn::Constants::Auth::ANTI_CSRF_COOKIE_NAME)
cookies.delete(SignIn::Constants::Auth::INFO_COOKIE_NAME, domain: IdentitySettings.sign_in.info_cookie_domain)
end
def auth_service(type, client_id = nil)
SignIn::AuthenticationServiceRetriever.new(type:, client_config: client_config(client_id)).perform
end
def cookie_authentication?(client_id)
client_config(client_id)&.cookie_auth?
end
def client_config(client_id)
@client_config ||= {}
@client_config[client_id] ||= SignIn::ClientConfig.find_by(client_id:)
end
def sign_in_logger
@sign_in_logger = SignIn::Logger.new(prefix: self.class)
end
end
end
|
0
|
code_files/vets-api-private/app/controllers
|
code_files/vets-api-private/app/controllers/v0/claim_letters_controller.rb
|
# frozen_string_literal: true
require 'claim_letters/claim_letter_downloader'
require 'claim_letters/providers/claim_letters/lighthouse_claim_letters_provider'
module V0
class ClaimLettersController < ApplicationController
before_action :set_api_provider
Sentry.set_tags(feature: 'claim-letters')
service_tag 'claim-status'
VBMS_LIGHTHOUSE_MIGRATION_STATSD_KEY_PREFIX = 'vbms_lighthouse_claim_letters_provider_error'
def index
docs = service.get_letters
log_metadata_to_datadog(docs)
render json: docs
rescue => e
log_api_provider_error(e)
raise e
end
def show
document_id = CGI.unescape(params[:document_id])
service.get_letter(document_id) do |data, mime_type, disposition, filename|
send_data(data, type: mime_type, disposition:, filename:)
end
rescue => e
log_api_provider_error(e)
raise e
end
private
def set_api_provider
@use_lighthouse = Flipper.enabled?(:cst_claim_letters_use_lighthouse_api_provider, @current_user)
@api_provider = @use_lighthouse ? 'lighthouse' : 'VBMS'
end
def service
::Rails.logger.info('Choosing Claim Letters API Provider via cst_claim_letters_use_lighthouse_api_provider',
{ message_type: 'cst.api_provider',
api_provider: @api_provider,
action: action_name })
Datadog::Tracing.active_trace&.set_tag('api_provider', @api_provider)
if @use_lighthouse
LighthouseClaimLettersProvider.new(@current_user)
else
ClaimStatusTool::ClaimLetterDownloader.new(@current_user)
end
end
def log_metadata_to_datadog(docs)
docs_metadata = []
docs.each do |d|
docs_metadata << { doc_type: d[:doc_type], type_description: d[:type_description] }
end
::Rails.logger.info('DDL Document Types Metadata',
{ message_type: 'ddl.doctypes_metadata',
document_type_metadata: docs_metadata })
end
def log_api_provider_error(error)
metric_key = "#{VBMS_LIGHTHOUSE_MIGRATION_STATSD_KEY_PREFIX}.#{action_name}.#{@api_provider}"
StatsD.increment(metric_key)
::Rails.logger.info("#{metric_key} error", {
message_type: 'cst.api_provider.error',
error_type: error.class.to_s,
error_backtrace: error.backtrace&.first(3),
api_provider: @api_provider,
action: action_name
})
end
end
end
|
0
|
code_files/vets-api-private/app/controllers
|
code_files/vets-api-private/app/controllers/v0/intent_to_files_controller.rb
|
# frozen_string_literal: true
require 'disability_compensation/factories/api_provider_factory'
require 'logging/third_party_transaction'
require 'lighthouse/benefits_claims/intent_to_file/api_response'
require 'lighthouse/benefits_claims/intent_to_file/monitor'
module V0
class IntentToFilesController < ApplicationController
extend Logging::ThirdPartyTransaction::MethodWrapper
service_tag 'intent-to-file'
class MissingICNError < StandardError; end
class MissingParticipantIDError < StandardError; end
class InvalidITFTypeError < StandardError; end
before_action :authorize_service
before_action :validate_type_param, only: %i[submit]
wrap_with_logging(
:index,
:submit,
additional_class_logs: {
action: 'load Intent To File for 526 form flow'
},
additional_instance_logs: {
user_uuid: %i[current_user account_uuid]
}
)
TYPES = %w[compensation pension survivor].freeze
ITF_FORM_IDS = {
'compensation' => '21-526EZ',
'pension' => '21P-527EZ',
'survivor' => '21P-534EZ'
}.freeze
def index
type = params['itf_type'] || 'compensation'
if %w[pension survivor].include? type
form_id = ITF_FORM_IDS[type]
validate_data(@current_user, 'get', form_id, type)
monitor.track_show_itf(form_id, type, @current_user.uuid)
itf = BenefitsClaims::Service.new(@current_user.icn).get_intent_to_file(type, nil, nil)
response = BenefitsClaims::IntentToFile::ApiResponse::GET.new(itf['data'])
return render json: IntentToFileSerializer.new(response)
end
if Flipper.enabled?(:disability_compensation_production_tester, @current_user)
Rails.logger.info("ITF GET call skipped for user #{@current_user.uuid}")
response = set_success_response
else
response = intent_to_file_provider.get_intent_to_file(type, nil, nil)
end
render json: IntentToFileSerializer.new(response)
rescue => e
Rails.logger.error("Error occurred while processing ITF GET request: #{e.message}")
monitor.track_itf_controller_error('get', form_id, type, e.message)
raise e
end
def submit
type = params['itf_type'] || 'compensation'
if %w[pension survivor].include? type
form_id = ITF_FORM_IDS[type]
validate_data(@current_user, 'post', form_id, type)
monitor.track_submit_itf(form_id, type, @current_user.uuid)
itf = BenefitsClaims::Service.new(@current_user.icn).create_intent_to_file(type, @current_user.ssn, nil)
response = BenefitsClaims::IntentToFile::ApiResponse::POST.new(itf['data'])
return render json: IntentToFileSerializer.new(response)
end
if Flipper.enabled?(:disability_compensation_production_tester, @current_user)
Rails.logger.info("ITF submit call skipped for user #{@current_user.uuid}")
response = set_success_response
else
response = intent_to_file_provider.create_intent_to_file(type, nil, nil)
end
render json: IntentToFileSerializer.new(response)
rescue => e
Rails.logger.error("Error occurred while processing ITF submit request: #{e.message}")
monitor.track_itf_controller_error('post', form_id, type, e.message)
raise e
end
private
def intent_to_file_provider
ApiProviderFactory.call(
type: ApiProviderFactory::FACTORIES[:intent_to_file],
provider: ApiProviderFactory::API_PROVIDER[:lighthouse],
options: {},
current_user: @current_user,
feature_toggle: nil
)
end
def set_success_response
DisabilityCompensation::ApiProvider::IntentToFilesResponse.new(
intent_to_file: [
DisabilityCompensation::ApiProvider::IntentToFile.new(
id: '0',
creation_date: DateTime.now,
expiration_date: DateTime.now + 1.year,
source: '',
participant_id: 0,
status: 'active',
type: 'compensation'
)
]
)
end
def authorize_service
authorize :lighthouse, :itf_access?
end
def validate_type_param
raise Common::Exceptions::InvalidFieldValue.new('itf_type', params[:itf_type]) unless
TYPES.include?(params[:itf_type])
end
# This is temporary. Testing logged data to ensure this is being hit properly
# rubocop:disable Metrics/MethodLength
def validate_data(user, method, form_id, itf_type)
if Flipper.enabled?(:pension_itf_validate_data_logger, user)
context = {
user_icn_present: user.icn.present?,
user_participant_id_present: user.participant_id.present?,
itf_type:,
user_uuid: user.uuid
}
Rails.logger.info('IntentToFilesController ITF Validate Data', context)
end
user_uuid = user.uuid
if user.icn.blank?
error_message = 'ITF request failed. No veteran ICN provided'
monitor.track_missing_user_icn_itf_controller(method, form_id, itf_type, user_uuid, error_message)
raise MissingICNError, error_message
end
if user.participant_id.blank?
info_message = 'User missing participant ID which will be created by Lighthouse within MPI'
monitor.track_missing_user_pid_itf_controller(method, form_id, itf_type, user_uuid, info_message)
end
if form_id.blank?
error_message = 'ITF request failed. ITF type not supported'
monitor.track_invalid_itf_type_itf_controller(method, form_id, itf_type, user_uuid, error_message)
raise InvalidITFTypeError, error_message
end
end
# rubocop:enable Metrics/MethodLength
def monitor
@monitor ||= BenefitsClaims::IntentToFile::Monitor.new
end
end
end
|
0
|
code_files/vets-api-private/app/controllers
|
code_files/vets-api-private/app/controllers/v0/form1095_bs_controller.rb
|
# frozen_string_literal: true
require_relative '../../../lib/veteran_enrollment_system/form1095_b/service'
require_relative '../../../lib/veteran_enrollment_system/enrollment_periods/service'
module V0
class Form1095BsController < ApplicationController
service_tag 'form-1095b'
before_action { authorize :form1095, :access? }
before_action :validate_year, only: %i[download_pdf download_txt], if: -> { fetch_from_enrollment_system? }
before_action :validate_pdf_template, only: %i[download_pdf], if: -> { fetch_from_enrollment_system? }
before_action :validate_txt_template, only: %i[download_txt], if: -> { fetch_from_enrollment_system? }
def available_forms
if fetch_from_enrollment_system?
forms = fetch_enrollment_periods
else
current_form = Form1095B.find_by(veteran_icn: current_user.icn, tax_year: Form1095B.current_tax_year)
forms = current_form.nil? ? [] : [{ year: current_form.tax_year, last_updated: current_form.updated_at }]
end
render json: { available_forms: forms }
end
def download_pdf
file_name = "1095B_#{tax_year}.pdf"
send_data form.pdf_file, filename: file_name, type: 'application/pdf', disposition: 'inline'
end
def download_txt
file_name = "1095B_#{tax_year}.txt"
send_data form.txt_file, filename: file_name, type: 'text/plain', disposition: 'inline'
end
private
def fetch_enrollment_periods
periods = VeteranEnrollmentSystem::EnrollmentPeriods::Service.new.get_enrollment_periods(icn: current_user.icn)
years = model_class.available_years(periods)
forms = years.map { |year| { year:, last_updated: nil } } # last_updated is not used on front end.
forms.sort_by! { |f| f[:year] }
rescue Common::Exceptions::ResourceNotFound
[] # if user is not known by enrollment system, return empty list
end
def form
if fetch_from_enrollment_system?
service = VeteranEnrollmentSystem::Form1095B::Service.new
form_data = service.get_form_by_icn(icn: current_user[:icn], tax_year:)
model_class.parse(form_data)
else
return current_form_record if current_form_record.present?
Rails.logger.error("Form 1095-B for #{tax_year} not found", user_uuid: current_user&.uuid)
raise Common::Exceptions::RecordNotFound, tax_year
end
end
def current_form_record
@current_form_record ||= Form1095B.find_by(veteran_icn: current_user[:icn], tax_year:)
end
def download_params
params.permit(:tax_year)
end
def tax_year
download_params[:tax_year]
end
def validate_year
unless Integer(tax_year).between?(*model_class.available_years_range)
raise Common::Exceptions::UnprocessableEntity, detail: "1095-B for tax year #{tax_year} not supported",
source: self.class.name
end
end
def validate_txt_template
unless File.exist?(model_class.txt_template_path(tax_year))
raise Common::Exceptions::UnprocessableEntity, detail: "1095-B for tax year #{tax_year} not supported",
source: self.class.name
end
end
def validate_pdf_template
unless File.exist?(model_class.pdf_template_path(tax_year))
raise Common::Exceptions::UnprocessableEntity, detail: "1095-B for tax year #{tax_year} not supported",
source: self.class.name
end
end
def model_class
VeteranEnrollmentSystem::Form1095B::Form1095B
end
def fetch_from_enrollment_system?
Flipper.enabled?(:fetch_1095b_from_enrollment_system, current_user)
end
end
end
|
0
|
code_files/vets-api-private/app/controllers
|
code_files/vets-api-private/app/controllers/v0/average_days_for_claim_completion_controller.rb
|
# frozen_string_literal: true
module V0
class AverageDaysForClaimCompletionController < ApplicationController
service_tag 'average-days-to-completion'
skip_before_action :authenticate, only: :index
def index
rtn = AverageDaysForClaimCompletion.order('created_at DESC').first
render json: {
average_days: rtn.present? ? rtn.average_days : -1.0
}
end
end
end
|
0
|
code_files/vets-api-private/app/controllers
|
code_files/vets-api-private/app/controllers/v0/search_click_tracking_controller.rb
|
# frozen_string_literal: true
require 'search_click_tracking/service'
module V0
class SearchClickTrackingController < ApplicationController
include ActionView::Helpers::SanitizeHelper
service_tag 'search'
skip_before_action :authenticate
skip_before_action :verify_authenticity_token
# Sends click tracking data to search.gov analytics, based on the passed url,
# query, position, client_ip, and user_agent.
#
def create
response = SearchClickTracking::Service.new(url, query, position, user_agent, module_code).track_click
if response.success?
render nothing: true, status: :no_content
else
render json: response.body, status: :bad_request
end
end
private
def click_params
params.permit(:url, :query, :position, :module_code, :user_agent)
end
# Returns a sanitized, permitted version of the passed url params.
#
# @return [String]
# @see https://api.rubyonrails.org/v4.2/classes/ActionView/Helpers/SanitizeHelper.html#method-i-sanitize
#
def url
sanitize click_params['url']
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 click_params['query']
end
# Returns a sanitized, permitted version of the passed position params.
#
# @return [String]
# @see https://api.rubyonrails.org/v4.2/classes/ActionView/Helpers/SanitizeHelper.html#method-i-sanitize
#
def position
sanitize click_params['position']
end
# Returns a sanitized, permitted version of the passed module_code params.
#
# @return [String]
# @see https://api.rubyonrails.org/v4.2/classes/ActionView/Helpers/SanitizeHelper.html#method-i-sanitize
#
def module_code
sanitize click_params['module_code']
end
# Returns a sanitized, permitted version of the passed user_agent params.
#
# @return [String]
# @see https://api.rubyonrails.org/v4.2/classes/ActionView/Helpers/SanitizeHelper.html#method-i-sanitize
#
def user_agent
sanitize click_params['user_agent']
end
end
end
|
0
|
code_files/vets-api-private/app/controllers
|
code_files/vets-api-private/app/controllers/v0/coe_controller.rb
|
# frozen_string_literal: true
require 'lgy/service'
module V0
class CoeController < ApplicationController
service_tag 'home-loan-status'
def status
coe_status = lgy_service.coe_status
render json: { data: { attributes: coe_status } }, status: :ok
end
def download_coe
res = lgy_service.get_coe_file
send_data(res.body, type: 'application/pdf', disposition: 'attachment')
end
def submit_coe_claim
claim = SavedClaim::CoeClaim.new(form: filtered_params[:form])
unless claim.save
StatsD.increment("#{stats_key}.failure")
Sentry.set_tags(team: 'vfs-ebenefits') # tag sentry logs with team name
raise Common::Exceptions::ValidationErrors, claim
end
response = claim.send_to_lgy(edipi: current_user.edipi, icn: current_user.icn)
Rails.logger.info "ClaimID=#{claim.confirmation_number} Form=#{claim.class::FORM}"
clear_saved_form(claim.form_id)
render json: { data: { attributes: { reference_number: response, claim: } } }
end
def documents
documents = lgy_service.get_coe_documents.body
# Vet-uploaded docs have documentType `Veteran Correspondence`. We are not
# currently displaying these on the COE status page, so they are omitted.
# In the near future, we will display them, and can remove this `reject`
# block.
notification_letters = documents.reject { |doc| doc['document_type']&.include?('Veteran Correspondence') }
# Documents should be sorted from most to least recent
sorted_notification_letters = notification_letters.sort_by { |doc| doc['create_date'] }.reverse
render json: { data: { attributes: sorted_notification_letters } }, status: :ok
end
def document_upload
status = 201
# Each document is uploaded individually
attachments.each do |attachment|
file_extension = attachment['file_type']
if %w[jpg jpeg png pdf].include? file_extension.downcase
document_data = build_document_data(attachment)
status = post_document(document_data)
break unless status == 201
end
end
render(json: status, status: status == 201 ? 200 : 500)
end
def post_document(document_data)
response = lgy_service.post_document(payload: document_data)
response.status
rescue Common::Client::Errors::ClientError => e
# 502-503 errors happen frequently from LGY endpoint at the time of implementation
# and have not been corrected yet. We would like to seperate these from our monitoring for now
# See https://github.com/department-of-veterans-affairs/va.gov-team/issues/90411
# and https://github.com/department-of-veterans-affairs/va.gov-team/issues/91111
if [503, 504].include?(e.status)
Rails.logger.info('LGY server unavailable or unresponsive',
{ status: e.status, messsage: e.message, body: e.body })
else
Rails.logger.error('LGY API returned error', { status: e.status, messsage: e.message, body: e.body })
end
e.status
end
def document_download
res = lgy_service.get_document(params[:id])
send_data(res.body, type: 'application/pdf', disposition: 'attachment')
end
private
def lgy_service
@lgy_service ||= LGY::Service.new(edipi: @current_user.edipi, icn: @current_user.icn)
end
def filtered_params
params.require(:lgy_coe_claim).permit(:form)
end
def attachments
params[:files]
end
def stats_key
'api.lgy_coe'
end
def build_document_data(attachment)
file_data = attachment['file']
index = file_data.index(';base64,') || 0
file_data = file_data[(index + 8)..] if index.positive?
{
'documentType' => attachment['file_type'],
'description' => attachment['document_type'],
'contentsBase64' => file_data,
'fileName' => attachment['file_name']
}
end
end
end
|
0
|
code_files/vets-api-private/app/controllers
|
code_files/vets-api-private/app/controllers/v0/benefits_documents_controller.rb
|
# frozen_string_literal: true
require 'lighthouse/benefits_documents/service'
module V0
class BenefitsDocumentsController < ApplicationController
before_action { authorize :lighthouse, :access? }
Sentry.set_tags(team: 'benefits-claim-appeal-status', feature: 'benefits-documents')
service_tag 'claims-shared'
def create
params.require :file
# Service expects a different claim ID param
params[:claim_id] = params[:benefits_claim_id]
# The frontend may pass a stringified Array of tracked item ids
# because of the way array values are handled by formData
if params[:tracked_item_ids].instance_of?(String)
# Value should look "[123,456]" before it's parsed
params[:tracked_item_ids] = JSON.parse(params[:tracked_item_ids])
end
jid = service.queue_document_upload(params)
render_job_id(jid)
end
private
def service
BenefitsDocuments::Service.new(@current_user)
end
end
end
|
0
|
code_files/vets-api-private/app/controllers
|
code_files/vets-api-private/app/controllers/v0/veteran_readiness_employment_claims_controller.rb
|
# frozen_string_literal: true
module V0
class VeteranReadinessEmploymentClaimsController < ClaimsBaseController
service_tag 'vre-application'
before_action :authenticate
skip_before_action :load_user
def create
if claim.save
Rails.logger.info "Submitting VR&E claim via #{modular_api_enabled ? 'modular' : 'legacy'} VRE API"
if modular_api_enabled
submission_id = setup_form_submission_tracking(claim, user_account)
VRE::VRESubmit1900Job.perform_async(claim.id, encrypted_user, submission_id)
else
VRE::Submit1900Job.perform_async(claim.id, encrypted_user)
end
Rails.logger.info "ClaimID=#{claim.confirmation_number} Form=#{claim.class::FORM}"
# FIXME: revert to this with issue CVE-2253
# clear_saved_form(claim.form_id)
clear_saved_form('28-1900')
clear_saved_form('28-1900-V2')
render json: SavedClaimSerializer.new(claim)
else
StatsD.increment("#{stats_key}.failure")
Rails.logger.error('VR&E claim was not saved', { error_messages: claim.errors,
user_logged_in: current_user.present?,
current_user_uuid: current_user&.uuid })
raise Common::Exceptions::ValidationErrors, claim
end
end
private
def modular_api_enabled
@modular_api_enabled ||= Flipper.enabled?(:vre_modular_api)
end
def user_account
@user_account ||= UserAccount.find_by(icn: current_user.icn) if current_user.icn.present?
end
def claim
@claim ||= SavedClaim::VeteranReadinessEmploymentClaim.new(form: filtered_params[:form], user_account:)
end
def setup_form_submission_tracking(claim, user_account)
return nil unless Flipper.enabled?(:vre_track_submissions)
submission = claim.form_submissions.create(
form_type: claim.form_id,
user_account:
)
if submission.persisted?
Rails.logger.info('VR&E Form Submission created',
claim_id: claim.id,
form_type: claim.form_id,
submission_id: submission.id)
submission.id
else
Rails.logger.warn('VR&E Form Submission creation failed - continuing without tracking',
claim_id: claim.id,
form_type: claim.form_id,
errors: submission.errors.full_messages)
nil
end
end
def filtered_params
if params[:veteran_readiness_employment_claim]
params.require(:veteran_readiness_employment_claim).permit(:form)
else
params.permit(:form)
end
end
def short_name
'veteran_readiness_employment_claim'
end
def encrypted_user
user_struct = OpenStruct.new(
participant_id: current_user.participant_id,
pid: current_user.participant_id,
edipi: current_user.edipi,
vet360_id: current_user.vet360_id,
birth_date: current_user.birth_date,
ssn: current_user.ssn,
loa3?: current_user.loa3?,
uuid: current_user.uuid,
icn: current_user.icn,
first_name: current_user.first_name,
va_profile_email: current_user.va_profile_email
)
KmsEncrypted::Box.new.encrypt(user_struct.to_h.to_json)
end
end
end
|
0
|
code_files/vets-api-private/app/controllers
|
code_files/vets-api-private/app/controllers/v0/evss_claims_controller.rb
|
# frozen_string_literal: true
module V0
class EVSSClaimsController < ApplicationController
include IgnoreNotFound
service_tag 'claim-status'
before_action { authorize :evss, :access? }
def index
claims, synchronized = service.all
options = { meta: { successful_sync: synchronized } }
render json: EVSSClaimListSerializer.new(claims, options)
end
def show
claim = EVSSClaim.for_user(current_user).find_by(evss_id: params[:id])
unless claim
Sentry.set_tags(team: 'benefits-memorial-1') # tag sentry logs with team name
raise Common::Exceptions::RecordNotFound, params[:id]
end
claim, synchronized = service.update_from_remote(claim)
options = { meta: { successful_sync: synchronized } }
render json: EVSSClaimDetailSerializer.new(claim, options)
end
def request_decision
claim = EVSSClaim.for_user(current_user).find_by(evss_id: params[:id])
unless claim
Sentry.set_tags(team: 'benefits-memorial-1') # tag sentry logs with team name
raise Common::Exceptions::RecordNotFound, params[:id]
end
jid = service.request_decision(claim)
claim.update(requested_decision: true)
render_job_id(jid)
end
private
def skip_sentry_exception_types
super + [Common::Exceptions::BackendServiceException]
end
def service
EVSSClaimService.new(current_user)
end
end
end
|
0
|
code_files/vets-api-private/app/controllers
|
code_files/vets-api-private/app/controllers/v0/dependents_applications_controller.rb
|
# frozen_string_literal: true
require 'dependents/monitor'
module V0
class DependentsApplicationsController < ApplicationController
service_tag 'dependent-change'
def show
dependents = create_dependent_service.get_dependents
dependents[:diaries] = dependency_verification_service.read_diaries
render json: DependentsSerializer.new(dependents)
rescue => e
monitor.track_event(:error, e.message, 'dependents_controller.show_error')
raise Common::Exceptions::BackendServiceException.new(nil, detail: e.message)
end
def create
form = dependent_params.to_json
use_v2 = form.present? ? JSON.parse(form)&.dig('dependents_application', 'use_v2') : nil
claim = SavedClaim::DependencyClaim.new(form:, use_v2:)
monitor.track_create_attempt(claim, current_user)
# Populate the form_start_date from the IPF if available
in_progress_form = current_user ? InProgressForm.form_for_user(claim.form_id, current_user) : nil
claim.form_start_date = in_progress_form.created_at if in_progress_form
unless claim.save
monitor.track_create_validation_error(in_progress_form, claim, current_user)
log_validation_error_to_metadata(in_progress_form, claim)
raise Common::Exceptions::ValidationErrors, claim
end
claim.process_attachments!
# reinstantiate as v1 dependent service if use_v2 is blank
dependent_service = use_v2.blank? ? BGS::DependentService.new(current_user) : create_dependent_service
dependent_service.submit_686c_form(claim)
monitor.track_create_success(in_progress_form, claim, current_user)
claim.send_submitted_email(current_user)
# clear_saved_form(claim.form_id) # We do not want to destroy the InProgressForm for this submission
render json: SavedClaimSerializer.new(claim)
rescue => e
monitor.track_create_error(in_progress_form, claim, current_user, e)
raise e
end
private
def dependent_params
params.permit(
:add_spouse,
:veteran_was_married_before,
:add_child,
:report674,
:report_divorce,
:spouse_was_married_before,
:report_stepchild_not_in_household,
:report_death,
:report_marriage_of_child_under18,
:report_child18_or_older_is_not_attending_school,
:statement_of_truth_signature,
:statement_of_truth_certified,
'view:selectable686_options': {},
dependents_application: {},
supporting_documents: []
)
end
##
# Include validation error on in_progress_form metadata.
# `noop` if in_progress_form is `blank?`
#
# @param in_progress_form [InProgressForm]
# @param claim [SavedClaim::DependencyClaim]
#
# @return [void]
def log_validation_error_to_metadata(in_progress_form, claim)
return if in_progress_form.blank?
metadata = in_progress_form.metadata || {}
metadata['submission'] ||= {}
metadata['submission']['error_message'] = claim&.errors&.errors&.to_s
in_progress_form.update(metadata:)
end
def create_dependent_service
@dependent_service ||= BGS::DependentV2Service.new(current_user)
end
def dependency_verification_service
@dependency_verification_service ||= BGS::DependencyVerificationService.new(current_user)
end
def stats_key
'api.dependents_application'
end
def monitor(claim_id = nil)
@monitor ||= Dependents::Monitor.new(claim_id)
end
end
end
|
0
|
code_files/vets-api-private/app/controllers
|
code_files/vets-api-private/app/controllers/v0/feature_toggles_controller.rb
|
# frozen_string_literal: true
module V0
class FeatureTogglesController < ApplicationController
service_tag 'feature-flag'
# the feature toggle does not require authentication, but if a user is logged we might use @current_user
skip_before_action :authenticate
before_action :load_user
def index
if params[:features].present?
features_params = params[:features].split(',')
features = feature_toggles_service.get_features(features_params)
else
features = feature_toggles_service.get_all_features
end
render json: { data: { type: 'feature_toggles', features: } }
end
private
def feature_toggles_service
@feature_toggles_service ||= FeatureTogglesService.new(
current_user: @current_user,
cookie_id: params[:cookie_id]
)
end
end
end
|
0
|
code_files/vets-api-private/app/controllers
|
code_files/vets-api-private/app/controllers/v0/claim_documents_controller.rb
|
# frozen_string_literal: true
require 'lgy/tag_sentry'
require 'claim_documents/monitor'
require 'lighthouse/benefits_intake/service'
require 'pdf_utilities/datestamp_pdf'
module V0
class ClaimDocumentsController < ApplicationController
service_tag 'claims-shared'
skip_before_action(:authenticate)
before_action :load_user
INPUT_ERRORS = [Common::Exceptions::ValidationErrors,
Common::Exceptions::UnprocessableEntity,
BenefitsIntake::Service::InvalidDocumentError].freeze
def create
uploads_monitor.track_document_upload_attempt(form_id, current_user)
@attachment = klass&.new(form_id:, doctype:)
# add the file after so that we have a form_id and guid for the uploader to use
@attachment.file = unlock_file(params['file'], params['password'])
if @attachment.respond_to?(:requires_stamped_pdf_validation?) &&
@attachment.requires_stamped_pdf_validation? &&
Flipper.enabled?(:document_upload_validation_enabled) && !stamped_pdf_valid?
raise Common::Exceptions::ValidationErrors, @attachment
end
raise Common::Exceptions::ValidationErrors, @attachment unless @attachment.valid?
@attachment.save
uploads_monitor.track_document_upload_success(form_id, @attachment.id, current_user)
render json: PersistentAttachmentSerializer.new(@attachment)
rescue *INPUT_ERRORS => e
uploads_monitor.track_document_upload_input_error(form_id, @attachment&.id, current_user, e)
raise e
rescue => e
uploads_monitor.track_document_upload_failed(form_id, @attachment&.id, current_user, e)
raise e
end
private
def klass
case form_id
when '21-686C', '686C-674', '686C-674-V2'
PersistentAttachments::DependencyClaim
when '26-1880'
LGY::TagSentry.tag_sentry
PersistentAttachments::LgyClaim
else
PersistentAttachments::ClaimEvidence
end
end
def form_id
params[:form_id].upcase
end
def doctype
params[:doctype] || 10 # Unknown
end
def unlock_file(file, file_password)
return file unless File.extname(file) == '.pdf' && file_password.present?
pdftk = PdfForms.new(Settings.binaries.pdftk)
tmpf = Tempfile.new(['decrypted_form_attachment', '.pdf'])
begin
pdftk.call_pdftk(file.tempfile.path, 'input_pw', file_password, 'output', tmpf.path)
rescue PdfForms::PdftkError => e
file_regex = %r{/(?:\w+/)*[\w-]+\.pdf\b}
password_regex = /(input_pw).*?(output)/
sanitized_message = e.message.gsub(file_regex, '[FILTERED FILENAME]').gsub(password_regex, '\1 [FILTERED] \2')
log_message_to_sentry(sanitized_message, 'warn')
raise Common::Exceptions::UnprocessableEntity.new(
detail: I18n.t('errors.messages.uploads.pdf.incorrect_password'),
source: 'PersistentAttachment.unlock_file'
)
end
file.tempfile.unlink
file.tempfile = tmpf
file
end
def stamped_pdf_valid?
validate_extension(File.extname(@attachment&.file&.id))
validate_min_file_size(@attachment&.file&.size)
validate_pdf_document(@attachment.to_pdf)
rescue BenefitsIntake::Service::InvalidDocumentError => e
@attachment.errors.add(:attachment, e.message)
false
rescue PdfForms::PdftkError
@attachment.errors.add(:attachment, 'File is corrupt and cannot be uploaded')
false
end
def validate_extension(extension)
allowed_types = PersistentAttachment::ALLOWED_DOCUMENT_TYPES
unless allowed_types.include?(extension)
detail = I18n.t('errors.messages.extension_allowlist_error', extension:, allowed_types:)
source = 'PersistentAttachment.stamped_pdf_valid?'
raise Common::Exceptions::UnprocessableEntity.new(detail:, source:)
end
end
def validate_min_file_size(size)
unless size.to_i >= PersistentAttachment::MINIMUM_FILE_SIZE
detail = 'File size must not be less than 1.0 KB'
source = 'PersistentAttachment.stamped_pdf_valid?'
raise Common::Exceptions::UnprocessableEntity.new(detail:, source:)
end
end
def validate_pdf_document(pdf)
document = PDFUtilities::DatestampPdf.new(pdf).run(text: 'VA.GOV', x: 5, y: 5)
intake_service.valid_document?(document:)
end
def intake_service
@intake_service ||= BenefitsIntake::Service.new
end
def uploads_monitor
@uploads_monitor ||= ClaimDocuments::Monitor.new
end
end
end
|
0
|
code_files/vets-api-private/app/controllers
|
code_files/vets-api-private/app/controllers/v0/example_controller.rb
|
# frozen_string_literal: true
# example controller to show use of logging in with sessions controller
module V0
class ExampleController < ApplicationController
service_tag 'platform-base'
before_action :authenticate, only: [:welcome]
def index
render json: { message: 'Welcome to the va.gov API' }
end
def limited
render json: { message: 'Rate limited action' }
end
def welcome
msg = "You are logged in as #{@current_user.email}"
render json: { message: msg }
end
def healthcheck
render status: :ok
end
def startup_healthcheck
render status: :ok
end
end
end
|
0
|
code_files/vets-api-private/app/controllers
|
code_files/vets-api-private/app/controllers/v0/education_career_counseling_claims_controller.rb
|
# frozen_string_literal: true
module V0
class EducationCareerCounselingClaimsController < ClaimsBaseController
service_tag 'career-guidance-application'
def create
claim = SavedClaim::EducationCareerCounselingClaim.new(form: filtered_params[:form])
unless claim.save
StatsD.increment("#{stats_key}.failure")
Sentry.set_tags(team: 'vfs-ebenefits') # tag sentry logs with team name
raise Common::Exceptions::ValidationErrors, claim
end
Lighthouse::SubmitCareerCounselingJob.perform_async(claim.id, @current_user&.uuid)
Rails.logger.info "ClaimID=#{claim.confirmation_number} Form=#{claim.class::FORM}"
clear_saved_form(claim.form_id)
render json: SavedClaimSerializer.new(claim)
end
private
def short_name
'education_career_counseling_claim'
end
end
end
|
0
|
code_files/vets-api-private/app/controllers
|
code_files/vets-api-private/app/controllers/v0/form210779_controller.rb
|
# frozen_string_literal: true
module V0
class Form210779Controller < ApplicationController
include RetriableConcern
service_tag 'nursing-home-information'
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
claim.process_attachments!
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
def download_pdf
claim = saved_claim_class.find_by!(guid: params[:guid])
source_file_path = with_retries('Generate 21-0779 PDF') do
claim.to_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 filtered_params
params.require(:form)
end
def download_file_name(claim)
"21-0779_#{claim.veteran_name.gsub(' ', '_')}.pdf"
end
def saved_claim_class
SavedClaim::Form210779
end
def stats_key
'api.form210779'
end
def check_feature_enabled
routing_error unless Flipper.enabled?(:form_0779_enabled, current_user)
end
end
end
|
0
|
code_files/vets-api-private/app/controllers
|
code_files/vets-api-private/app/controllers/v0/disability_compensation_forms_controller.rb
|
# frozen_string_literal: true
require 'evss/common_service'
require 'evss/disability_compensation_auth_headers'
require 'evss/disability_compensation_form/form4142'
require 'evss/disability_compensation_form/service'
require 'lighthouse/benefits_reference_data/response_strategy'
require 'disability_compensation/factories/api_provider_factory'
require 'disability_compensation/loggers/monitor'
module V0
class DisabilityCompensationFormsController < ApplicationController
service_tag 'disability-application'
before_action(except: :rating_info) { authorize :evss, :access? }
before_action :auth_rating_info, only: [:rating_info]
before_action :validate_name_part, only: [:suggested_conditions]
def rated_disabilities
invoker = 'V0::DisabilityCompensationFormsController#rated_disabilities'
api_provider = ApiProviderFactory.call(
type: ApiProviderFactory::FACTORIES[:rated_disabilities],
provider: :lighthouse,
options: { icn: @current_user.icn.to_s, auth_headers: },
current_user: @current_user,
feature_toggle: nil
)
response = api_provider.get_rated_disabilities(nil, nil, { invoker: })
render json: RatedDisabilitiesSerializer.new(response)
end
def separation_locations
response = Lighthouse::ReferenceData::ResponseStrategy.new.cache_by_user_and_type(
:all_users,
:get_separation_locations
) do
# A separate provider is needed in order to interact with LH Staging and test BRD e2e properly
# We use vsp_environment here as RAILS_ENV is set to 'production' in staging
provider = Settings.vsp_environment == 'staging' ? :lighthouse_staging : :lighthouse
api_provider = ApiProviderFactory.call(
type: ApiProviderFactory::FACTORIES[:brd],
provider:,
options: {},
current_user: @current_user,
feature_toggle: nil
)
api_provider.get_separation_locations
end
render json: SeparationLocationSerializer.new(response)
end
def suggested_conditions
results = DisabilityContention.suggested(params[:name_part])
render json: DisabilityContentionSerializer.new(results)
end
def add_0781_metadata(form526)
if form526['syncModern0781Flow'].present?
{ sync_modern0781_flow: form526['syncModern0781Flow'],
sync_modern0781_flow_answered_online: form526['form0781'].present? }.to_json
end
end
def submit_all_claim
temp_separation_location_fix if Flipper.enabled?(:disability_compensation_temp_separation_location_code_string,
@current_user)
purge_toxic_exposure_orphaned_data if toxic_exposure_dates_fix_enabled?
saved_claim = SavedClaim::DisabilityCompensation::Form526AllClaim.from_hash(form_content)
if Flipper.enabled?(:disability_compensation_sync_modern0781_flow_metadata) && form_content['form526'].present?
saved_claim.metadata = add_0781_metadata(form_content['form526'])
end
saved_claim.save ? log_success(saved_claim) : log_failure(saved_claim)
# if jid = 0 then the submission was prevented from going any further in the process
submission = create_submission(saved_claim)
if Flipper.enabled?(:disability_526_toxic_exposure_opt_out_data_purge, @current_user)
log_toxic_exposure_changes(saved_claim, submission)
end
jid = 0
# Feature flag to stop submission from being submitted to third-party service
# With this on, the submission will NOT be processed by EVSS or Lighthouse,
# nor will it go to VBMS,
# but the line of code before this one creates the submission in the vets-api database
if Flipper.enabled?(:disability_compensation_prevent_submission_job, @current_user)
Rails.logger.info("Submission ID: #{submission.id} prevented from sending to third party service.")
else
jid = submission.start
end
render json: { data: { attributes: { job_id: jid } } },
status: :ok
end
def submission_status
job_status = Form526JobStatus.where(job_id: params[:job_id]).first
raise Common::Exceptions::RecordNotFound, params[:job_id] unless job_status
render json: Form526JobStatusSerializer.new(job_status)
end
def rating_info
if lighthouse?
service = LighthouseRatedDisabilitiesProvider.new(@current_user.icn)
disability_rating = service.get_combined_disability_rating
rating_info = { user_percent_of_disability: disability_rating }
render json: LighthouseRatingInfoSerializer.new(rating_info)
else
rating_info_service = EVSS::CommonService.new(auth_headers)
response = rating_info_service.get_rating_info
render json: RatingInfoSerializer.new(response)
end
end
private
def auth_rating_info
api = lighthouse? ? :lighthouse : :evss
authorize(api, :rating_info_access?)
end
def form_content
@form_content ||= JSON.parse(request.body.string)
end
def lighthouse?
Flipper.enabled?(:profile_lighthouse_rating_info, @current_user)
end
def create_submission(saved_claim)
Rails.logger.info('Creating 526 submission', user_uuid: @current_user&.uuid, saved_claim_id: saved_claim&.id)
submission = Form526Submission.new(
user_uuid: @current_user.uuid,
user_account: @current_user.user_account,
saved_claim_id: saved_claim.id,
auth_headers_json: auth_headers.to_json,
form_json: saved_claim.to_submission_data(@current_user),
submit_endpoint: 'claims_api'
) { |sub| sub.add_birls_ids @current_user.birls_id }
if missing_disabilities?(submission)
raise Common::Exceptions::UnprocessableEntity.new(
detail: 'no new or increased disabilities were submitted', source: 'DisabilityCompensationFormsController'
)
end
submission.save! && submission
rescue PG::NotNullViolation => e
Rails.logger.error(
'Creating 526 submission: PG::NotNullViolation', user_uuid: @current_user&.uuid, saved_claim_id: saved_claim&.id
)
raise e
end
def log_failure(claim)
if Flipper.enabled?(:disability_526_track_saved_claim_error) && claim&.errors
begin
in_progress_form =
@current_user ? InProgressForm.form_for_user(FormProfiles::VA526ez::FORM_ID, @current_user) : nil
ensure
monitor.track_saved_claim_save_error(
# Array of ActiveModel::Error instances from the claim that failed to save
claim&.errors&.errors,
in_progress_form&.id,
@current_user.uuid
)
end
end
raise Common::Exceptions::ValidationErrors, claim
end
def log_success(claim)
monitor.track_saved_claim_save_success(
claim,
@current_user.uuid
)
end
def validate_name_part
raise Common::Exceptions::ParameterMissing, 'name_part' if params[:name_part].blank?
end
def auth_headers
EVSS::DisabilityCompensationAuthHeaders.new(@current_user).add_headers(EVSS::AuthHeaders.new(@current_user).to_h)
end
def stats_key
'api.disability_compensation'
end
def missing_disabilities?(submission)
if submission.form['form526']['form526']['disabilities'].none?
StatsD.increment("#{stats_key}.failure")
Rails.logger.error(
'Creating 526 submission: no new or increased disabilities were submitted', user_uuid: @current_user&.uuid
)
return true
end
false
end
# TEMPORARY
# Turn separation location into string
# 11/18/2024 BRD EVSS -> Lighthouse migration caused separation location to turn into an integer,
# while SavedClaim (vets-json-schema) is expecting a string
def temp_separation_location_fix
if form_content.is_a?(Hash) && form_content['form526'].is_a?(Hash)
separation_location_code = form_content.dig('form526', 'serviceInformation', 'separationLocation',
'separationLocationCode')
unless separation_location_code.nil?
form_content['form526']['serviceInformation']['separationLocation']['separationLocationCode'] =
separation_location_code.to_s
end
end
end
# [Toxic Exposure] Users are failing SavedClaim creation when exposure dates are incomplete, i.e. "XXXX-01-XX"
# #106340 - https://github.com/department-of-veterans-affairs/va.gov-team/issues/106340
# malformed dates are coming through because the forms date component does not validate data if the user
# backs out of any Toxic Exposure section
# This temporary fix:
# 1. removes the malformed dates from the Toxic Exposure section
# 2. logs which section had the bad date to track which sections users are backing out of
def purge_toxic_exposure_orphaned_data
return unless form_content.is_a?(Hash) && form_content['form526'].is_a?(Hash)
toxic_exposure = form_content.dig('form526', 'toxicExposure')
return unless toxic_exposure
transformer = EVSS::DisabilityCompensationForm::Form526ToLighthouseTransform.new
prefix = 'V0::DisabilityCompensationFormsController#submit_all_claim purge_toxic_exposure_orphaned_data:'
Form526Submission::TOXIC_EXPOSURE_DETAILS_MAPPING.each_key do |key|
next unless toxic_exposure[key].is_a?(Hash)
# Fix malformed dates for each sub-location
toxic_exposure[key].each do |location, values|
next unless values.is_a?(Hash)
fix_date_error(values, 'startDate', { prefix:, section: key, location: }, transformer)
fix_date_error(values, 'endDate', { prefix:, section: key, location: }, transformer)
end
# Also fix malformed top-level dates if needed
next unless %w[otherHerbicideLocations specifyOtherExposures].include?(key)
fix_date_error(toxic_exposure[key], 'startDate', { prefix:, section: key }, transformer)
fix_date_error(toxic_exposure[key], 'endDate', { prefix:, section: key }, transformer)
end
end
def fix_date_error(hash, date_key, context, transformer)
return if hash[date_key].blank?
date = transformer.send(:convert_date_no_day, hash[date_key])
return if date.present?
hash.delete(date_key)
# If `context[:location]` is nil, this squeezes out the extra space
Rails.logger.info(
"#{context[:prefix]} #{context[:section]} #{context[:location]} #{date_key} was malformed"
.squeeze(' ')
)
end
# END TEMPORARY
def toxic_exposure_dates_fix_enabled?
Flipper.enabled?(:disability_compensation_temp_toxic_exposure_optional_dates_fix, @current_user)
end
def monitor
@monitor ||= DisabilityCompensation::Loggers::Monitor.new
end
# Logs toxic exposure data changes during Form 526 submission
#
# Compares the user's InProgressForm with the submitted claim to detect
# when toxic exposure data has been changed or removed by the frontend. This is wrapped
# in error handling to ensure logging failures do not impact veteran submissions.
#
# @param submitted_claim [SavedClaim::DisabilityCompensation::Form526AllClaim] The submitted claim
# @param submission [Form526Submission] The submission record
# @return [void]
def log_toxic_exposure_changes(submitted_claim, submission)
in_progress_form = InProgressForm.form_for_user(FormProfiles::VA526ez::FORM_ID, @current_user)
return unless in_progress_form
monitor.track_toxic_exposure_changes(
in_progress_form:,
submitted_claim:,
submission:
)
rescue => e
# Don't fail submission if logging fails
Rails.logger.error(
'Error logging toxic exposure changes',
user_uuid: @current_user&.uuid,
saved_claim_id: submitted_claim&.id,
submission_id: submission&.id,
error: e.message,
backtrace: e.backtrace&.first(5)
)
end
end
end
|
0
|
code_files/vets-api-private/app/controllers
|
code_files/vets-api-private/app/controllers/v0/id_card_attributes_controller.rb
|
# frozen_string_literal: true
require 'vic/url_helper'
require 'vic/id_card_attribute_error'
module V0
class IdCardAttributesController < ApplicationController
service_tag 'veteran-id-card'
before_action :authorize
def show
id_attributes = IdCardAttributes.for_user(current_user)
signed_attributes = ::VIC::URLHelper.generate(id_attributes)
render json: signed_attributes
rescue
raise ::VIC::IDCardAttributeError, status: 502, code: 'VIC011',
detail: 'Could not verify military service attributes'
end
private
def skip_sentry_exception_types
super + [::VIC::IDCardAttributeError]
end
def authorize
# TODO: Clean up this method, particularly around need to blanket rescue from
# VeteranStatus method
raise Common::Exceptions::Forbidden, detail: 'You do not have access to ID card attributes' unless
current_user.loa3?
raise ::VIC::IDCardAttributeError, ::VIC::IDCardAttributeError::VIC002 if current_user.edipi.blank?
title38_status = begin
current_user.veteran_status.title38_status
rescue VAProfile::VeteranStatus::VAProfileError => e
if e.status == 404
nil
else
log_exception_to_sentry(e)
raise ::VIC::IDCardAttributeError, ::VIC::IDCardAttributeError::VIC010
end
end
raise ::VIC::IDCardAttributeError, ::VIC::IDCardAttributeError::VIC002 if title38_status.blank?
unless current_user.can_access_id_card?
raise ::VIC::IDCardAttributeError, ::VIC::IDCardAttributeError::NOT_ELIGIBLE.merge(
code: "VIC#{title38_status}"
)
end
end
end
end
|
0
|
code_files/vets-api-private/app/controllers
|
code_files/vets-api-private/app/controllers/v0/map_services_controller.rb
|
# frozen_string_literal: true
require 'map/security_token/service'
module V0
class MapServicesController < SignIn::ServiceAccountApplicationController
service_tag 'identity'
# POST /v0/map_services/:application/token
def token
icn = @service_account_access_token.user_attributes['icn']
result = MAP::SecurityToken::Service.new.token(application: params[:application].to_sym, icn:, cache: false)
render json: result, status: :ok
rescue Common::Client::Errors::ClientError, Common::Exceptions::GatewayTimeout, JWT::DecodeError
render json: sts_client_error, status: :bad_gateway
rescue MAP::SecurityToken::Errors::ApplicationMismatchError
render json: application_mismatch_error, status: :bad_request
rescue MAP::SecurityToken::Errors::MissingICNError
render json: missing_icn_error, status: :bad_request
end
private
def sts_client_error
{
error: 'server_error',
error_description: 'STS failed to return a valid token.'
}
end
def application_mismatch_error
{
error: 'invalid_request',
error_description: 'Application mismatch detected.'
}
end
def missing_icn_error
{
error: 'invalid_request',
error_description: 'Service account access token does not contain an ICN in `user_attributes` claim.'
}
end
end
end
|
0
|
code_files/vets-api-private/app/controllers
|
code_files/vets-api-private/app/controllers/v0/form21p530a_controller.rb
|
# frozen_string_literal: true
module V0
class Form21p530aController < ApplicationController
include RetriableConcern
include PdfFill::Forms::FormHelper
service_tag 'state-tribal-interment-allowance'
skip_before_action :authenticate, only: %i[create download_pdf]
before_action :load_user, :check_feature_enabled
def create
claim = build_and_save_claim!
handle_successful_claim(claim)
clear_saved_form(claim.form_id)
render json: SavedClaimSerializer.new(claim)
rescue Common::Exceptions::ValidationErrors => e
handle_validation_error(e)
rescue => e
handle_general_error(e, claim)
end
def download_pdf
# Parse raw JSON to get camelCase keys (bypasses OliveBranch transformation)
raw_payload = request.raw_post
transformed_payload = transform_country_codes(raw_payload)
parsed_form = JSON.parse(transformed_payload)
source_file_path = with_retries('Generate 21P-530A PDF') do
PdfFill::Filler.fill_ancillary_form(parsed_form, SecureRandom.uuid, '21P-530a')
end
# Stamp signature (SignatureStamper returns original path if signature is blank)
source_file_path = PdfFill::Forms::Va21p530a.stamp_signature(source_file_path, parsed_form)
client_file_name = "21P-530a_#{SecureRandom.uuid}.pdf"
file_contents = File.read(source_file_path)
send_data file_contents, filename: client_file_name, type: 'application/pdf', disposition: 'attachment'
rescue Common::Exceptions::ValidationErrors
# Re-raise validation errors so they're handled by the exception handling concern
# This ensures they return 422 instead of 500
raise
rescue => e
handle_pdf_generation_error(e)
ensure
File.delete(source_file_path) if source_file_path && File.exist?(source_file_path)
end
private
def check_feature_enabled
routing_error unless Flipper.enabled?(:form_530a_enabled, current_user)
end
def handle_pdf_generation_error(error)
Rails.logger.error('Form21p530a: Error generating PDF', error: error.message, backtrace: error.backtrace)
render json: {
errors: [{
title: 'PDF Generation Failed',
detail: 'An error occurred while generating the PDF',
status: '500'
}]
}, status: :internal_server_error
end
def stats_key
'api.form21p530a'
end
def transform_country_codes(payload)
parsed = JSON.parse(payload)
address = parsed.dig('burialInformation', 'recipientOrganization', 'address')
if address&.key?('country')
transformed_country = extract_country(address)
if transformed_country
validate_country_code!(transformed_country)
address['country'] = transformed_country
end
end
parsed.to_json
end
def validate_country_code!(country_code)
return if country_code.blank?
IsoCountryCodes.find(country_code)
rescue IsoCountryCodes::UnknownCodeError
claim = SavedClaim::Form21p530a.new
claim.errors.add '/burialInformation/recipientOrganization/address/country',
"'#{country_code}' is not a valid country code"
raise Common::Exceptions::ValidationErrors, claim
end
def build_and_save_claim!
# Body parsed by Rails,schema validated by committee before hitting here.
payload = request.raw_post
transformed_payload = transform_country_codes(payload)
claim = SavedClaim::Form21p530a.new(form: transformed_payload)
raise Common::Exceptions::ValidationErrors, claim unless claim.save
claim
end
def handle_successful_claim(claim)
claim.process_attachments!
Rails.logger.info("ClaimID=#{claim.confirmation_number} Form=#{claim.class::FORM}")
StatsD.increment("#{stats_key}.success")
end
def handle_validation_error(error)
StatsD.increment("#{stats_key}.failure")
Rails.logger.error(
'Form21p530a: error submitting claim',
{ error: error.message, claim_errors: error.resource&.errors&.full_messages }
)
raise
end
def handle_general_error(error, claim)
Rails.logger.error(
'Form21p530a: error submitting claim',
{ error: error.message, claim_errors: defined?(claim) && claim&.errors&.full_messages }
)
raise
end
end
end
|
0
|
code_files/vets-api-private/app/controllers
|
code_files/vets-api-private/app/controllers/v0/hca_attachments_controller.rb
|
# frozen_string_literal: true
module V0
class HCAAttachmentsController < ApplicationController
include FormAttachmentCreate
service_tag 'healthcare-application'
skip_before_action(:authenticate, raise: false)
FORM_ATTACHMENT_MODEL = HCAAttachment
private
def serializer_klass
HCAAttachmentSerializer
end
end
end
|
0
|
code_files/vets-api-private/app/controllers
|
code_files/vets-api-private/app/controllers/v0/maintenance_windows_controller.rb
|
# frozen_string_literal: true
module V0
class MaintenanceWindowsController < ApplicationController
service_tag 'maintenance-windows'
skip_before_action :authenticate
def index
@maintenance_windows = MaintenanceWindow.end_after(Time.zone.now)
render json: MaintenanceWindowSerializer.new(@maintenance_windows)
end
end
end
|
0
|
code_files/vets-api-private/app/controllers
|
code_files/vets-api-private/app/controllers/v0/apidocs_controller.rb
|
# frozen_string_literal: true
module V0
class ApidocsController < ApplicationController
include Swagger::Blocks
service_tag 'platform-base'
skip_before_action :authenticate
swagger_root do
key :swagger, '2.0'
info do
key :version, '1.0.0'
key :title, 'va.gov API'
key :description, 'The API for managing va.gov'
key :termsOfService, ''
contact do
key :name, 'va.gov team'
end
license do
key :name, 'Creative Commons Zero v1.0 Universal'
end
end
# Tags are used to group endpoints in tools like swagger-ui
# Groups/tags are displayed in the order declared here, followed
# by the order they first appear in the swaggered_classes below, so
# declare all tags here in desired order.
tag do
key :name, 'authentication'
key :description, 'Authentication operations'
end
tag do
key :name, 'user'
key :description, 'Current authenticated user data'
end
tag do
key :name, 'profile'
key :description, 'User profile information'
end
tag do
key :name, 'benefits_info'
key :description, 'Veteran benefits profile information'
end
tag do
key :name, 'benefits_forms'
key :description, 'Apply for and claim Veteran benefits'
end
tag do
key :name, 'benefits_status'
key :description, 'Check status of benefits claims and appeals'
end
tag do
key :name, 'form_526'
key :description, 'Creating and submitting compensation applications'
end
tag do
key :name, 'prescriptions'
key :description, 'Prescription refill/tracking operations'
end
tag do
key :name, 'secure_messaging'
key :description, 'Send and receive secure messages to health providers'
end
tag do
key :name, 'gi_bill_institutions'
key :description, 'Discover institutions at which GI Bill benefits may be used'
end
tag do
key :name, 'in_progress_forms'
key :description, 'In-progress form operations'
end
tag do
key :name, 'claim_status_tool'
key :description, 'Claim Status Tool'
end
tag do
key :name, 'site'
key :description, 'Site service availability and feedback'
end
tag do
key :name, 'medical_copays'
key :description, 'Veteran Medical Copay information for VA facilities'
end
tag do
key :name, 'banners'
key :description, 'VAMC Situation Update Banners'
end
tag do
key :name, 'digital_disputes'
key :description, 'Submit digital dispute PDFs to the Debt Management Center and VBS'
end
key :host, Settings.hostname
key :schemes, %w[https http]
key :basePath, '/'
key :consumes, ['application/json']
key :produces, ['application/json']
[true, false].each do |required|
parameter :"#{required ? '' : 'optional_'}authorization" do
key :name, 'Authorization'
key :in, :header
key :description, 'The authorization method and token value'
key :required, required
key :type, :string
end
end
parameter :optional_page_number, name: :page, in: :query, required: false, type: :integer,
description: 'Page of results, greater than 0 (default: 1)'
parameter :optional_page_length, name: :per_page, in: :query, required: false, type: :integer,
description: 'number of results, between 1 and 99 (default: 10)'
parameter :optional_sort, name: :sort, in: :query, required: false, type: :string,
description: "Comma separated sort field(s), prepend with '-' for descending"
parameter :optional_filter, name: :filter, in: :query, required: false, type: :string,
description: 'Filter on refill_status: [[refill_status][logical operator]=status]'
end
# A list of all classes that have swagger_* declarations.
SWAGGERED_CLASSES = [
Swagger::Requests::Appeals::Appeals,
Swagger::Requests::ContactUs::Inquiries,
Swagger::Requests::BackendStatuses,
Swagger::Requests::Banners,
Swagger::Requests::BenefitsClaims,
Swagger::Requests::DatadogAction,
Swagger::Requests::BurialClaims,
Swagger::Requests::BenefitsReferenceData,
Swagger::Requests::ClaimDocuments,
Swagger::Requests::ClaimStatus,
Swagger::Requests::ClaimLetters,
Swagger::Requests::Coe,
Swagger::Requests::Debts,
Swagger::Requests::DebtLetters,
Swagger::Requests::DependentsApplications,
Swagger::Requests::DigitalDisputes,
Swagger::Requests::DependentsVerifications,
Swagger::Requests::DisabilityCompensationForm,
Swagger::Requests::DisabilityCompensationInProgressForms,
Swagger::Requests::EducationBenefitsClaims,
Swagger::Requests::Efolder,
Swagger::Requests::EventBusGateway,
Swagger::Requests::FeatureToggles,
Swagger::Requests::FinancialStatusReports,
Swagger::Requests::Form1010cg::Attachments,
Swagger::Requests::Form1010EzrAttachments,
Swagger::Requests::Form1010Ezrs,
Swagger::Requests::Form1095Bs,
Swagger::Requests::Form210779,
Swagger::Requests::Form212680,
Swagger::Requests::Forms,
Swagger::Requests::Gibct::CalculatorConstants,
Swagger::Requests::Gibct::Institutions,
Swagger::Requests::Gibct::InstitutionPrograms,
Swagger::Requests::Gibct::YellowRibbonPrograms,
Swagger::Requests::HealthCareApplications,
Swagger::Requests::HCAAttachments,
Swagger::Requests::InProgressForms,
Swagger::Requests::IntentToFile,
Swagger::Requests::MaintenanceWindows,
Swagger::Requests::MDOT::Supplies,
Swagger::Requests::MedicalCopays,
Swagger::Requests::MviUsers,
Swagger::Requests::OnsiteNotifications,
Swagger::Requests::MyVA::SubmissionStatuses,
Swagger::Requests::IncomeAndAssetsClaims,
Swagger::Requests::PensionClaims,
Swagger::Requests::PreneedsClaims,
Swagger::Requests::Profile,
Swagger::Requests::Search,
Swagger::Requests::SearchClickTracking,
Swagger::Requests::SearchTypeahead,
Swagger::Requests::SignIn,
Swagger::Requests::TravelPay,
Swagger::Requests::UploadSupportingEvidence,
Swagger::Requests::User,
Swagger::Requests::CaregiversAssistanceClaims,
Swagger::Requests::EducationCareerCounselingClaims,
Swagger::Requests::VeteranReadinessEmploymentClaims,
Swagger::Responses::AuthenticationError,
Swagger::Responses::ForbiddenError,
Swagger::Responses::RecordNotFoundError,
Swagger::Responses::SavedForm,
Swagger::Responses::UnprocessableEntityError,
Swagger::Schemas::Address,
Swagger::Schemas::Appeals::Requests,
Swagger::Schemas::Appeals::NoticeOfDisagreement,
Swagger::Schemas::ContactUs::SuccessfulInquiryCreation,
Swagger::Schemas::ContactUs::InquiriesList,
Swagger::Schemas::AsyncTransaction::Vet360,
Swagger::Schemas::BenefitsClaims,
Swagger::Schemas::Countries,
Swagger::Schemas::ConnectedApplications,
Swagger::Schemas::Contacts,
Swagger::Schemas::Dependents,
Swagger::Schemas::DependentsVerifications,
Swagger::Schemas::Email,
Swagger::Schemas::Errors,
Swagger::Schemas::EVSSAuthError,
Swagger::Schemas::FinancialStatusReports,
Swagger::Schemas::Form526::Address,
Swagger::Schemas::Form526::DateRange,
Swagger::Schemas::Form526::Disability,
Swagger::Schemas::Form526::Form0781,
Swagger::Schemas::Form526::Form4142,
Swagger::Schemas::Form526::Form526SubmitV2,
Swagger::Schemas::Form526::Form8940,
Swagger::Schemas::Form526::SeparationLocations,
Swagger::Schemas::Form526::JobStatus,
Swagger::Schemas::Form526::RatedDisabilities,
Swagger::Schemas::Form526::SubmitDisabilityForm,
Swagger::Schemas::Form526::SuggestedConditions,
Swagger::Schemas::Form526::RatingInfo,
Swagger::Schemas::Forms,
Swagger::Schemas::Gibct::CalculatorConstants,
Swagger::Schemas::Gibct::Institutions,
Swagger::Schemas::Gibct::InstitutionPrograms,
Swagger::Schemas::Gibct::YellowRibbonPrograms,
Swagger::Schemas::Gibct::Meta,
Swagger::Schemas::Health::Folders,
Swagger::Schemas::Health::Links,
Swagger::Schemas::Health::Messages,
Swagger::Schemas::Health::Meta,
Swagger::Schemas::Health::Prescriptions,
Swagger::Schemas::Health::Trackings,
Swagger::Schemas::Health::TriageTeams,
Swagger::Schemas::IntentToFile,
Swagger::Schemas::LetterBeneficiary,
Swagger::Schemas::Letters,
Swagger::Schemas::MaintenanceWindows,
Swagger::Schemas::OnsiteNotifications,
Swagger::Schemas::PhoneNumber,
Swagger::Schemas::SavedForm,
Swagger::Schemas::SignIn,
Swagger::Schemas::States,
Swagger::Schemas::TravelPay,
Swagger::Schemas::UploadSupportingEvidence,
Swagger::Schemas::UserInternalServices,
Swagger::Schemas::Permission,
Swagger::Schemas::ValidVAFileNumber,
Swagger::Schemas::PaymentHistory,
Swagger::Schemas::Vet360::Address,
Swagger::Schemas::Vet360::Email,
Swagger::Schemas::Vet360::Telephone,
Swagger::Schemas::Vet360::Permission,
Swagger::Schemas::Vet360::PreferredName,
Swagger::Schemas::Vet360::GenderIdentity,
Swagger::Schemas::Vet360::ContactInformation,
Swagger::Schemas::Vet360::Countries,
Swagger::Schemas::Vet360::States,
Swagger::Schemas::Vet360::Zipcodes,
FacilitiesApi::V2::Schemas::Facilities,
self
].freeze
def index
render json: Swagger::Blocks.build_root_json(SWAGGERED_CLASSES)
end
end
end
|
0
|
code_files/vets-api-private/app/controllers
|
code_files/vets-api-private/app/controllers/v0/health_care_applications_controller.rb
|
# frozen_string_literal: true
require 'hca/service'
require 'bgs/service'
require 'pdf_fill/filler'
require 'lighthouse/facilities/v1/client'
module V0
class HealthCareApplicationsController < ApplicationController
include IgnoreNotFound
include RetriableConcern
include PdfFilenameGenerator
service_tag 'healthcare-application'
FORM_ID = '1010ez'
skip_before_action(:authenticate, only: %i[create show enrollment_status healthcheck facilities download_pdf])
before_action :record_submission_attempt, only: :create
before_action :load_user, only: %i[create enrollment_status]
before_action(only: :rating_info) { authorize(:hca_disability_rating, :access?) }
def rating_info
if Flipper.enabled?(:hca_disable_bgs_service)
# Return 0 when not calling the actual BGS::Service
render json: HCARatingInfoSerializer.new({ user_percent_of_disability: 0 })
return
end
service = BGS::Service.new(current_user)
disability_rating = service.find_rating_data[:disability_rating_record][:service_connected_combined_degree]
hca_rating_info = { user_percent_of_disability: disability_rating }
render json: HCARatingInfoSerializer.new(hca_rating_info)
end
def show
application = HealthCareApplication.find(params[:id])
render json: HealthCareApplicationSerializer.new(application)
end
def create
health_care_application.google_analytics_client_id = params[:ga_client_id]
health_care_application.user = current_user
begin
result = health_care_application.process!
rescue HCA::SOAPParser::ValidationError
raise Common::Exceptions::BackendServiceException.new('HCA422', status: 422)
end
DeleteInProgressFormJob.perform_in(5.minutes, FORM_ID, current_user.uuid) if current_user
if result[:id]
render json: HealthCareApplicationSerializer.new(result)
else
render json: result
end
end
def enrollment_status
loa3 = current_user&.loa3?
icn = if loa3
current_user.icn
elsif request.get?
# Return nil if `GET` request and user is not loa3
nil
else
Sentry.set_extras(user_loa: current_user&.loa)
user_attributes = params[:user_attributes]&.deep_transform_keys! do |key|
key.to_s.camelize(:lower).to_sym
end || params[:userAttributes]
HealthCareApplication.user_icn(HealthCareApplication.user_attributes(user_attributes))
end
raise Common::Exceptions::RecordNotFound, nil if icn.blank?
render(json: HealthCareApplication.enrollment_status(icn, loa3))
end
def healthcheck
render(json: HCA::Service.new.health_check)
end
def facilities
import_facilities_if_empty
facilities = HealthFacility.where(postal_name: params[:state])
render json: facilities.map { |facility| { id: facility.station_number, name: facility.name } }
end
def download_pdf
file_name = SecureRandom.uuid
source_file_path = with_retries('Generate 10-10EZ PDF') do
PdfFill::Filler.fill_form(health_care_application, file_name)
end
client_file_name = file_name_for_pdf(health_care_application.parsed_form, 'veteranFullName', '10-10EZ')
file_contents = File.read(source_file_path)
send_data file_contents, filename: client_file_name, type: 'application/pdf', disposition: 'attachment'
ensure
File.delete(source_file_path) if source_file_path && File.exist?(source_file_path)
end
private
def health_care_application
@health_care_application ||= HealthCareApplication.new(params.permit(:form))
end
def import_facilities_if_empty
HCA::StdInstitutionImportJob.new.import_facilities(run_sync: true) unless HealthFacility.exists?
end
def record_submission_attempt
StatsD.increment("#{HCA::Service::STATSD_KEY_PREFIX}.submission_attempt")
if health_care_application.short_form?
StatsD.increment("#{HCA::Service::STATSD_KEY_PREFIX}.submission_attempt_short_form")
end
end
def skip_sentry_exception_types
super + [Common::Exceptions::BackendServiceException]
end
end
end
|
0
|
code_files/vets-api-private/app/controllers
|
code_files/vets-api-private/app/controllers/v0/disability_compensation_in_progress_forms_controller.rb
|
# frozen_string_literal: true
module V0
class DisabilityCompensationInProgressFormsController < InProgressFormsController
service_tag 'disability-application'
def show
if form_for_user
# get IPF
data = data_and_metadata_with_updated_rated_disabilities
log_started_form_version(data, 'get IPF')
else
# create IPF
data = camelized_prefill_for_user
log_started_form_version(data, 'create IPF')
end
render json: data
end
private
def form_id
FormProfiles::VA526ez::FORM_ID
end
def data_and_metadata_with_updated_rated_disabilities
parsed_form_data = JSON.parse(form_for_user.form_data)
metadata = form_for_user.metadata
# If EVSS's list of rated disabilities does not match our prefilled rated disabilities
if rated_disabilities_evss.present? &&
arr_to_compare(parsed_form_data['ratedDisabilities']) !=
arr_to_compare(rated_disabilities_evss.rated_disabilities.map(&:attributes))
if parsed_form_data['ratedDisabilities'].present? &&
parsed_form_data.dig('view:claimType', 'view:claimingIncrease')
metadata['returnUrl'] = '/disabilities/rated-disabilities'
end
evss_rated_disabilities = JSON.parse(rated_disabilities_evss.rated_disabilities.to_json)
parsed_form_data['updatedRatedDisabilities'] = camelize_with_olivebranch(evss_rated_disabilities)
end
# for Toxic Exposure 1.1 - add indicator to In Progress Forms
# moving forward, we don't want to change the version if it is already there
parsed_form_data = set_started_form_version(parsed_form_data)
{
formData: parsed_form_data,
metadata:
}
end
def set_started_form_version(data)
if data['started_form_version'].blank? || data['startedFormVersion'].blank?
log_started_form_version(data, 'existing IPF missing startedFormVersion')
data['startedFormVersion'] = '2019'
end
data
end
def rated_disabilities_evss
@rated_disabilities_evss ||= FormProfiles::VA526ez.for(form_id:, user: @current_user)
.initialize_rated_disabilities_information
rescue
# if the call to EVSS fails we can skip updating. EVSS fails around an hour each night.
nil
end
def arr_to_compare(rated_disabilities)
rated_disabilities&.collect do |rd|
diagnostic_code = rd['diagnostic_code'] || rd['diagnosticCode']
rated_disability_id = rd['rated_disability_id'] || rd['ratedDisabilityId']
"#{diagnostic_code}#{rated_disability_id}#{rd['name']}"
end&.sort
end
# temp: for https://github.com/department-of-veterans-affairs/va.gov-team/issues/97932
# tracking down a possible issue with prefill
def log_started_form_version(data, location)
cloned_data = data.deep_dup
cloned_data_as_json = cloned_data.as_json.deep_transform_keys { |k| k.camelize(:lower) }
if cloned_data_as_json['formData'].present?
started_form_version = cloned_data_as_json['formData']['startedFormVersion']
message = "Form526 InProgressForm startedFormVersion = #{started_form_version} #{location}"
Rails.logger.info(message)
end
if started_form_version.blank?
raise Common::Exceptions::ServiceError.new(
detail: "no startedFormVersion detected in #{location}",
source: 'DisabilityCompensationInProgressFormsController#show'
)
end
rescue => e
Rails.logger.error("Form526 InProgressForm startedFormVersion retrieval failed #{location} #{e.message}")
end
end
end
|
0
|
code_files/vets-api-private/app/controllers
|
code_files/vets-api-private/app/controllers/v0/form1010_ezrs_controller.rb
|
# frozen_string_literal: true
require 'form1010_ezr/service'
require 'pdf_fill/filler'
module V0
class Form1010EzrsController < ApplicationController
include RetriableConcern
include PdfFilenameGenerator
service_tag 'health-information-update'
before_action :record_submission_attempt, only: :create
def create
parsed_form = parse_form(params[:form])
result = Form1010Ezr::Service.new(@current_user).submit_form(parsed_form)
clear_saved_form('10-10EZR')
render(json: result)
end
def download_pdf
parsed_form = parse_form(params[:form])
file_name = SecureRandom.uuid
source_file_path = with_retries('Generate 10-10EZR PDF') do
PdfFill::Filler.fill_ancillary_form(parsed_form, file_name, '10-10EZR')
end
client_file_name = file_name_for_pdf(parsed_form, 'veteranFullName', '10-10EZR')
file_contents = File.read(source_file_path)
send_data file_contents, filename: client_file_name, type: 'application/pdf', disposition: 'attachment'
ensure
File.delete(source_file_path) if source_file_path && File.exist?(source_file_path)
end
private
def record_submission_attempt
StatsD.increment("#{Form1010Ezr::Service::STATSD_KEY_PREFIX}.submission_attempt")
end
def parse_form(form)
JSON.parse(form)
end
end
end
|
0
|
code_files/vets-api-private/app/controllers
|
code_files/vets-api-private/app/controllers/v0/debts_controller.rb
|
# frozen_string_literal: true
require 'debt_management_center/debts_service'
module V0
class DebtsController < ApplicationController
service_tag 'debt-resolution'
before_action { authorize :debt, :access? }
rescue_from ::DebtManagementCenter::DebtsService::DebtNotFound, with: :render_not_found
def index
count_only = ActiveModel::Type::Boolean.new.cast(params[:count_only])
render json: service.get_debts(count_only:)
end
def show
render json: service.get_debt_by_id(params[:id])
end
private
def service
DebtManagementCenter::DebtsService.new(@current_user)
end
def render_not_found
render json: nil, status: :not_found
end
end
end
|
0
|
code_files/vets-api-private/app/controllers
|
code_files/vets-api-private/app/controllers/v0/open_api_controller.rb
|
# frozen_string_literal: true
module V0
class OpenApiController < ApplicationController
service_tag 'platform-base'
skip_before_action :authenticate
def index
spec = openapi_spec
if spec
# Clone the spec so we can modify servers without affecting the cached version
response_spec = spec.dup
response_spec['servers'] = [{ 'url' => request.base_url }]
render json: response_spec, content_type: 'application/vnd.oai.openapi+json'
else
render json: { error: 'OpenAPI specification not found' }, status: :not_found
end
end
private
def openapi_spec
path = Rails.public_path.join('openapi.json')
return unless File.exist?(path)
cache_key = "openapi_spec_#{File.mtime(path).to_i}"
Rails.cache.fetch(cache_key) do
JSON.parse(File.read(path))
rescue JSON::ParserError => e
Rails.logger.error("Invalid openapi.json: #{e.message}")
nil
end
end
end
end
|
0
|
code_files/vets-api-private/app/controllers
|
code_files/vets-api-private/app/controllers/v0/test_account_user_emails_controller.rb
|
# frozen_string_literal: true
module V0
class TestAccountUserEmailsController < ApplicationController
service_tag 'identity'
skip_before_action :authenticate
NAMESPACE = 'test_account_user_email'
TTL = 2_592_000
def create
email_redis_key = Digest::SHA256.hexdigest(create_params)
Rails.cache.write(email_redis_key, create_params, namespace: NAMESPACE, expires_in: TTL)
Rails.logger.info("[V0][TestAccountUserEmailsController] create, key:#{email_redis_key}")
render json: { test_account_user_email_uuid: email_redis_key }, status: :created
rescue
render json: { errors: 'invalid params' }, status: :bad_request
end
def create_params
params.require(:email)
end
end
end
|
0
|
code_files/vets-api-private/app/controllers
|
code_files/vets-api-private/app/controllers/v0/dependents_verifications_controller.rb
|
# frozen_string_literal: true
module V0
class DependentsVerificationsController < ApplicationController
service_tag 'dependency-verification'
def index
dependents = dependency_verification_service.read_diaries
render json: DependentsVerificationsSerializer.new(dependents)
end
def create
return if filtered_params[:form][:update_diaries] == 'false'
claim = SavedClaim::DependencyVerificationClaim.new(form: filtered_params[:form].to_json)
claim.add_claimant_info(current_user) if current_user&.loa3?
unless claim.save
StatsD.increment('api.dependency_verification_claim.failure')
Sentry.set_tags(team: 'vfs-ebenefits') # tag sentry logs with team name
raise Common::Exceptions::ValidationErrors, claim
end
claim.send_to_central_mail! if current_user&.loa3?
Rails.logger.info "ClaimID=#{claim.confirmation_number} Form=#{claim.class::FORM}"
clear_saved_form(claim.form_id)
render json: SavedClaimSerializer.new(claim)
end
private
def dependency_verification_service
@dependent_service ||= BGS::DependencyVerificationService.new(current_user)
end
def filtered_params
params.require(:dependency_verification_claim)
end
end
end
|
0
|
code_files/vets-api-private/app/controllers
|
code_files/vets-api-private/app/controllers/v0/benefits_reference_data_controller.rb
|
# frozen_string_literal: true
require 'lighthouse/benefits_reference_data/service'
module V0
class BenefitsReferenceDataController < ApplicationController
service_tag 'disability-application'
def get_data
render json: benefits_reference_data_service
.get_data(path: params[:path], params: request.query_parameters).body
end
private
def benefits_reference_data_service
BenefitsReferenceData::Service.new
end
end
end
|
0
|
code_files/vets-api-private/app/controllers
|
code_files/vets-api-private/app/controllers/v0/users_controller.rb
|
# frozen_string_literal: true
require 'logging/third_party_transaction'
module V0
class UsersController < ApplicationController
service_tag 'identity'
def show
pre_serialized_profile = Users::Profile.new(current_user, @session_object).pre_serialize
options = { meta: { errors: pre_serialized_profile.errors } }
render json: UserSerializer.new(pre_serialized_profile, options), status: pre_serialized_profile.status
end
def icn
render json: { icn: current_user.icn }, status: :ok
end
def credential_emails
credential_emails = UserCredentialEmail.where(user_verification: current_user.user_account.user_verifications)
credential_emails_hash = credential_emails.each_with_object({}) do |credential_email, email_hash|
email_hash[credential_email.user_verification.credential_type.to_sym] = credential_email.credential_email
end
render json: credential_emails_hash
end
end
end
|
0
|
code_files/vets-api-private/app/controllers
|
code_files/vets-api-private/app/controllers/v0/benefits_claims_controller.rb
|
# frozen_string_literal: true
require 'benefits_claims/title_generator'
require 'lighthouse/benefits_claims/service'
require 'lighthouse/benefits_claims/constants'
require 'lighthouse/benefits_documents/constants'
require 'lighthouse/benefits_claims/utilities/helpers'
require 'lighthouse/benefits_documents/documents_status_polling_service'
require 'lighthouse/benefits_documents/update_documents_status_service'
module V0
class BenefitsClaimsController < ApplicationController
before_action { authorize :lighthouse, :access? }
service_tag 'claims-shared'
STATSD_METRIC_PREFIX = 'api.benefits_claims'
STATSD_TAGS = [
'service:benefits-claims',
'team:cross-benefits-crew',
'team:benefits',
'itportfolio:benefits-delivery',
'dependency:lighthouse'
].freeze
FEATURE_USE_TITLE_GENERATOR_WEB = 'cst_use_claim_title_generator_web'
def index
claims = service.get_claims
check_for_birls_id
check_for_file_number
claims['data'].each do |claim|
update_claim_type_language(claim)
end
claim_ids = claims['data'].map { |claim| claim['id'] }
evidence_submissions = fetch_evidence_submissions(claim_ids, 'index')
if Flipper.enabled?(:cst_show_document_upload_status, @current_user)
add_evidence_submissions_to_claims(claims['data'], evidence_submissions, 'index')
end
tap_claims(claims['data'])
report_evidence_submission_metrics('index', evidence_submissions)
render json: claims
end
def show
claim = service.get_claim(params[:id])
update_claim_type_language(claim['data'])
# 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 = rename_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)
# Document uploads to EVSS require a birls_id; This restriction should
# be removed when we move to Lighthouse Benefits Documents for document uploads
claim['data']['attributes']['canUpload'] = !@current_user.birls_id.nil?
evidence_submissions = fetch_evidence_submissions(claim['data']['id'], 'show')
if Flipper.enabled?(:cst_show_document_upload_status, @current_user)
update_evidence_submissions_for_claim(claim['data']['id'], evidence_submissions)
add_evidence_submissions_to_claims([claim['data']], evidence_submissions, 'show')
end
# We want to log some details about claim type patterns to track in DataDog
log_claim_details(claim['data']['attributes'])
tap_claims([claim['data']])
report_evidence_submission_metrics('show', evidence_submissions)
render json: claim
end
def submit5103
# Log if the user doesn't have a file number
# NOTE: We are treating the BIRLS ID as a substitute
# for file number here
::Rails.logger.info('[5103 Submission] No file number') if @current_user.birls_id.nil?
json_payload = request.body.read
data = JSON.parse(json_payload)
tracked_item_id = data['trackedItemId'] || nil
res = service.submit5103(params[:id], tracked_item_id)
render json: res
end
def failed_upload_evidence_submissions
if Flipper.enabled?(:cst_show_document_upload_status, @current_user)
render json: { data: filter_failed_evidence_submissions }
else
render json: { data: [] }
end
end
private
def failed_evidence_submissions
@failed_evidence_submissions ||= EvidenceSubmission.failed.where(user_account: current_user_account.id)
end
def current_user_account
UserAccount.find(@current_user.user_account_uuid)
end
def claims_scope
EVSSClaim.for_user(@current_user)
end
def service
@service ||= BenefitsClaims::Service.new(@current_user.icn)
end
def check_for_birls_id
::Rails.logger.info('[BenefitsClaims#index] No birls id') if current_user.birls_id.nil?
end
def check_for_file_number
bgs_file_number = BGS::People::Request.new.find_person_by_participant_id(user: current_user).file_number
::Rails.logger.info('[BenefitsClaims#index] No file number') if bgs_file_number.blank?
end
def tap_claims(claims)
claims.each do |claim|
record = claims_scope.where(evss_id: claim['id']).first
if record.blank?
EVSSClaim.create(
user_uuid: @current_user.uuid,
user_account: @current_user.user_account,
evss_id: claim['id'],
data: {}
)
else
# If there is a record, we want to set the updated_at field
# to Time.zone.now
record.touch # rubocop:disable Rails/SkipsModelValidations
end
end
end
def update_claim_type_language(claim)
if Flipper.enabled?(:cst_use_claim_title_generator_web)
# Adds displayTitle and claimTypeBase to the claim response object
BenefitsClaims::TitleGenerator.update_claim_title(claim)
else
language_map = BenefitsClaims::Constants::CLAIM_TYPE_LANGUAGE_MAP
if language_map.key?(claim.dig('attributes', 'claimType'))
claim['attributes']['claimType'] = language_map[claim['attributes']['claimType']]
end
end
end
def add_evidence_submissions(claim, evidence_submissions)
tracked_items = claim['attributes']['trackedItems']
filter_evidence_submissions(evidence_submissions, tracked_items, claim)
end
def filter_evidence_submissions(evidence_submissions, tracked_items, claim)
non_duplicate_submissions = filter_duplicate_evidence_submissions(evidence_submissions, claim)
filtered_evidence_submissions = []
non_duplicate_submissions.each do |es|
filtered_evidence_submissions.push(build_filtered_evidence_submission_record(es, tracked_items))
end
filtered_evidence_submissions
end
def filter_duplicate_evidence_submissions(evidence_submissions, claim)
supporting_documents = claim['attributes']['supportingDocuments'] || []
received_file_names = supporting_documents.map { |doc| doc['originalFileName'] }.compact
return evidence_submissions if received_file_names.empty?
evidence_submissions.reject do |evidence_submission|
file_name = extract_evidence_submission_file_name(evidence_submission)
file_name && received_file_names.include?(file_name)
end
end
def extract_evidence_submission_file_name(evidence_submission)
return nil if evidence_submission.template_metadata.nil?
metadata = JSON.parse(evidence_submission.template_metadata)
personalisation = metadata['personalisation']
if personalisation.is_a?(Hash) && personalisation['file_name']
personalisation['file_name']
else
::Rails.logger.warn(
'[BenefitsClaimsController] Missing or invalid personalisation in evidence submission metadata',
{ evidence_submission_id: evidence_submission.id }
)
nil
end
rescue JSON::ParserError, TypeError
::Rails.logger.error(
'[BenefitsClaimsController] Error parsing evidence submission metadata',
{ evidence_submission_id: evidence_submission.id }
)
nil
end
def filter_failed_evidence_submissions
filtered_evidence_submissions = []
claims = {}
failed_evidence_submissions.each do |es|
# When we get a claim we add it to claims so that we prevent calling lighthouse multiple times
# to get the same claim.
claim = claims[es.claim_id]
if claim.nil?
claim = service.get_claim(es.claim_id)
claims[es.claim_id] = claim
end
tracked_items = claim['data']['attributes']['trackedItems']
filtered_evidence_submissions.push(build_filtered_evidence_submission_record(es, tracked_items))
end
filtered_evidence_submissions
end
def build_filtered_evidence_submission_record(evidence_submission, tracked_items)
personalisation = JSON.parse(evidence_submission.template_metadata)['personalisation']
tracked_item_display_name = BenefitsClaims::Utilities::Helpers.get_tracked_item_display_name(
evidence_submission.tracked_item_id,
tracked_items
)
tracked_item_friendly_name = BenefitsClaims::Constants::FRIENDLY_DISPLAY_MAPPING[tracked_item_display_name]
{ acknowledgement_date: evidence_submission.acknowledgement_date,
claim_id: evidence_submission.claim_id,
created_at: evidence_submission.created_at,
delete_date: evidence_submission.delete_date,
document_type: personalisation['document_type'],
failed_date: evidence_submission.failed_date,
file_name: personalisation['file_name'],
id: evidence_submission.id,
lighthouse_upload: evidence_submission.job_class == 'Lighthouse::EvidenceSubmissions::DocumentUpload',
tracked_item_id: evidence_submission.tracked_item_id,
tracked_item_display_name:,
tracked_item_friendly_name:,
upload_status: evidence_submission.upload_status,
va_notify_status: evidence_submission.va_notify_status }
end
def log_claim_details(claim_info)
::Rails.logger.info('Claim Type Details',
{ message_type: 'lh.cst.claim_types',
claim_type: claim_info['claimType'],
claim_type_code: claim_info['claimTypeCode'],
num_contentions: claim_info['contentions'].count,
ep_code: claim_info['endProductCode'],
current_phase_back: claim_info['claimPhaseDates']['currentPhaseBack'],
latest_phase_type: claim_info['claimPhaseDates']['latestPhaseType'],
decision_letter_sent: claim_info['decisionLetterSent'],
development_letter_sent: claim_info['developmentLetterSent'],
claim_id: params[:id] })
log_evidence_requests(params[:id], claim_info)
end
def log_evidence_requests(claim_id, claim_info)
tracked_items = claim_info['trackedItems']
tracked_items.each do |ti|
::Rails.logger.info('Evidence Request Types',
{ message_type: 'lh.cst.evidence_requests',
claim_id:,
tracked_item_id: ti['id'],
tracked_item_type: ti['displayName'],
tracked_item_status: ti['status'] })
end
end
def rename_rv1(claim)
tracked_items = claim.dig('data', 'attributes', 'trackedItems')
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 report_evidence_submission_metrics(endpoint, evidence_submissions)
status_counts = evidence_submissions.group(:upload_status).count
BenefitsDocuments::Constants::UPLOAD_STATUS.each_value do |status|
count = status_counts[status] || 0
next if count.zero?
StatsD.increment("#{STATSD_METRIC_PREFIX}.#{endpoint}", count, tags: STATSD_TAGS + ["status:#{status}"])
end
rescue => e
::Rails.logger.error(
"BenefitsClaimsController##{endpoint} Error reporting evidence submission upload status metrics: #{e.message}"
)
end
def fetch_evidence_submissions(claim_ids, endpoint)
EvidenceSubmission.where(claim_id: claim_ids)
rescue => e
::Rails.logger.error(
"BenefitsClaimsController##{endpoint} Error fetching evidence submissions",
{
claim_ids: Array(claim_ids),
error_message: e.message,
error_class: e.class.name,
timestamp: Time.now.utc
}
)
EvidenceSubmission.none
end
def update_evidence_submissions_for_claim(claim_id, evidence_submissions)
# Poll for updated statuses on pending evidence submissions if feature flag is enabled
if Flipper.enabled?(:cst_update_evidence_submission_on_show, @current_user)
# Get pending evidence submissions as an ActiveRecord relation
# PENDING = successfully sent to Lighthouse with request_id, awaiting final status
# Note: We chain scopes on the provided relation because UpdateDocumentsStatusService
# requires an ActiveRecord::Relation with find_by! method (not an Array)
pending_submissions = evidence_submissions.where(
upload_status: BenefitsDocuments::Constants::UPLOAD_STATUS[:PENDING]
).where.not(request_id: nil)
unless pending_submissions.empty?
request_ids = pending_submissions.pluck(:request_id)
# Check if we recently polled for the same request_ids (cache hit)
if recently_polled_request_ids?(claim_id, request_ids)
StatsD.increment("#{STATSD_METRIC_PREFIX}.show.evidence_submission_cache_hit", tags: STATSD_TAGS)
return
end
# Cache miss - proceed with polling
StatsD.increment("#{STATSD_METRIC_PREFIX}.show.evidence_submission_cache_miss", tags: STATSD_TAGS)
process_evidence_submissions(claim_id, pending_submissions, request_ids)
end
end
end
def process_evidence_submissions(claim_id, pending_submissions, request_ids)
poll_response = poll_lighthouse_for_status(claim_id, request_ids)
return unless poll_response
process_status_update(claim_id, pending_submissions, poll_response, request_ids)
end
def poll_lighthouse_for_status(claim_id, request_ids)
# Call the same polling service used by the hourly job
poll_response = BenefitsDocuments::DocumentsStatusPollingService.call(request_ids)
# Validate successful response with expected data structure
if poll_response.status == 200
if poll_response.body&.dig('data', 'statuses').blank?
# Handle case where Lighthouse response doesn't have statuses
error_response = OpenStruct.new(status: 200, body: poll_response.body)
handle_error(claim_id, error_response, request_ids, 'polling')
return nil
end
poll_response
else
# Log non-200 responses
handle_error(claim_id, poll_response, request_ids, 'polling')
end
rescue => e
# Catch unexpected exceptions from polling service (network errors, timeouts, etc.)
error_response = OpenStruct.new(status: nil, body: e.message)
handle_error(claim_id, error_response, request_ids, 'polling')
end
def process_status_update(claim_id, pending_submissions, poll_response, request_ids)
update_result = BenefitsDocuments::UpdateDocumentsStatusService.call(
pending_submissions,
poll_response.body
)
# Handle case where update service found unknown request IDs
if update_result && !update_result[:success]
response_struct = OpenStruct.new(update_result[:response])
handle_error(claim_id, response_struct, response_struct.unknown_ids.map(&:to_s), 'update')
else
# Log success metric when polling and update complete successfully
StatsD.increment("#{STATSD_METRIC_PREFIX}.show.upload_status_success", tags: STATSD_TAGS)
# Cache the polled request_ids to prevent redundant polling within TTL window
cache_polled_request_ids(claim_id, request_ids)
end
rescue => e
# Catch unexpected exceptions from update operations
# Log error but don't fail the request - graceful degradation
error_response = OpenStruct.new(status: 200, body: e.message)
handle_error(claim_id, error_response, request_ids, 'update')
end
def handle_error(claim_id, response, lighthouse_document_request_ids, error_source)
::Rails.logger.error(
'BenefitsClaimsController#show Error polling evidence submissions',
{
claim_id:,
error_source:,
response_status: response.status,
response_body: response.body,
lighthouse_document_request_ids:,
timestamp: Time.now.utc
}
)
StatsD.increment(
"#{STATSD_METRIC_PREFIX}.show.upload_status_error",
tags: STATSD_TAGS + ["error_source:#{error_source}"]
)
end
def add_evidence_submissions_to_claims(claims, all_evidence_submissions, endpoint)
return if claims.empty?
# Group evidence submissions by claim_id for efficient lookup
evidence_submissions_by_claim = all_evidence_submissions.group_by(&:claim_id)
# Add evidence submissions to each claim
claims.each do |claim|
claim_id = claim['id'].to_i
evidence_submissions = evidence_submissions_by_claim[claim_id] || []
claim['attributes']['evidenceSubmissions'] =
add_evidence_submissions(claim, evidence_submissions)
end
rescue => e
# Log error but don't fail the request - graceful degradation
# Frontend already handles missing evidenceSubmissions attribute
claim_ids = claims.map { |claim| claim['id'] }
::Rails.logger.error(
"BenefitsClaimsController##{endpoint} Error adding evidence submissions",
{
claim_ids:,
error_class: e.class.name
}
)
end
def recently_polled_request_ids?(claim_id, request_ids)
cache_record = EvidenceSubmissionPollStore.find(claim_id.to_s)
return false if cache_record.nil?
cache_record.request_ids.sort == request_ids.sort
rescue => e
::Rails.logger.error(
'BenefitsClaimsController#show Error reading evidence submission poll cache',
{
claim_id:,
request_ids:,
error_class: e.class.name,
error_message: e.message
}
)
false
end
def cache_polled_request_ids(claim_id, request_ids)
EvidenceSubmissionPollStore.create(
claim_id: claim_id.to_s,
request_ids:
)
rescue => e
::Rails.logger.error(
'BenefitsClaimsController#show Error writing evidence submission poll cache',
{
claim_id:,
request_ids:,
error_class: e.class.name,
error_message: e.message
}
)
end
end
end
|
0
|
code_files/vets-api-private/app/controllers
|
code_files/vets-api-private/app/controllers/v0/form1010_ezr_attachments_controller.rb
|
# frozen_string_literal: true
require 'form1010_ezr/service'
require 'benchmark'
module V0
class Form1010EzrAttachmentsController < ApplicationController
include FormAttachmentCreate
service_tag 'health-information-update'
FORM_ATTACHMENT_MODEL = Form1010EzrAttachment
def create
validate_file_upload_class!
Form1010EzrAttachments::FileTypeValidator.new(
filtered_params['file_data']
).validate
save_attachment_to_cloud!
save_attachment_to_db!
render json: serializer_klass.new(form_attachment)
end
private
def serializer_klass
Form1010EzrAttachmentSerializer
end
end
end
|
0
|
code_files/vets-api-private/app/controllers
|
code_files/vets-api-private/app/controllers/v0/enrollment_periods_controller.rb
|
# frozen_string_literal: true
require 'veteran_enrollment_system/enrollment_periods/service'
module V0
class EnrollmentPeriodsController < ApplicationController
service_tag 'enrollment-periods'
before_action { authorize :enrollment_periods, :access? }
def index
service = VeteranEnrollmentSystem::EnrollmentPeriods::Service.new
periods = service.get_enrollment_periods(icn: @current_user.icn)
render json: { enrollment_periods: periods }
end
end
end
|
0
|
code_files/vets-api-private/app/controllers
|
code_files/vets-api-private/app/controllers/v0/search_controller.rb
|
# frozen_string_literal: true
require 'search/service'
require 'search_gsa/service'
module V0
class SearchController < ApplicationController
include ActionView::Helpers::SanitizeHelper
service_tag 'search'
skip_before_action :authenticate
# Returns a page of search results from the Search.gov API, based on the passed query and page.
#
# Pagination schema follows precedent from other controllers that return pagination.
# For example, the app/controllers/v0/prescriptions_controller.rb.
#
def index
response = search_service.results
options = { meta: { pagination: response.pagination } }
render json: SearchSerializer.new(response, options)
end
private
def search_params
params.permit(:query, :page)
end
def search_service
@search_service ||= if Flipper.enabled?(:search_use_v2_gsa)
SearchGsa::Service.new(query, page)
else
Search::Service.new(query, page)
end
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 search_params['query']
end
# This is the page (number) of results the FE is requesting to have returned.
#
# Returns a sanitized, permitted version of the passed page params. If 'page'
# is not supplied, it returns nil.
#
# @return [String]
# @return [NilClass]
# @see https://api.rubyonrails.org/v4.2/classes/ActionView/Helpers/SanitizeHelper.html#method-i-sanitize
#
def page
sanitize search_params['page']
end
end
end
|
0
|
code_files/vets-api-private/app/controllers
|
code_files/vets-api-private/app/controllers/v0/banners_controller.rb
|
# frozen_string_literal: true
module V0
class BannersController < ApplicationController
service_tag 'banners'
skip_before_action :authenticate
def by_path
# Default to 'full_width_banner_alert' banner (bundle) type.
banner_type = params.fetch(:type, 'full_width_banner_alert')
return render json: { error: 'Path parameter is required' }, status: :unprocessable_entity if path.blank?
banners = Banner.where(entity_bundle: banner_type).by_path(path)
render json: { banners:, path:, banner_type: }
end
private
def path
params[:path]
end
end
end
|
0
|
code_files/vets-api-private/app/controllers
|
code_files/vets-api-private/app/controllers/v0/form214192_controller.rb
|
# frozen_string_literal: true
module V0
class Form214192Controller < ApplicationController
include RetriableConcern
service_tag 'employment-information'
skip_before_action :authenticate, only: %i[create download_pdf]
before_action :load_user, :check_feature_enabled
def create
# Body parsed by Rails; schema validated by committee before hitting here.
payload = request.raw_post
claim = SavedClaim::Form214192.new(form: payload)
if claim.save
claim.process_attachments!
Rails.logger.info(
"ClaimID=#{claim.confirmation_number} Form=#{claim.class::FORM}"
)
StatsD.increment("#{stats_key}.success")
clear_saved_form(claim.form_id)
render json: SavedClaimSerializer.new(claim)
else
StatsD.increment("#{stats_key}.failure")
raise Common::Exceptions::ValidationErrors, claim
end
rescue => e
# Include validation errors when present; helpful in logs/Sentry.
Rails.logger.error(
'Form214192: error submitting claim',
{ error: e.message, claim_errors: defined?(claim) && claim&.errors&.full_messages }
)
raise
end
def download_pdf
# Parse raw JSON to get camelCase keys (bypasses OliveBranch transformation)
parsed_form = JSON.parse(request.raw_post)
source_file_path = with_retries('Generate 21-4192 PDF') do
PdfFill::Filler.fill_ancillary_form(parsed_form, SecureRandom.uuid, '21-4192')
end
# Stamp signature (SignatureStamper returns original path if signature is blank)
source_file_path = PdfFill::Forms::Va214192.stamp_signature(source_file_path, parsed_form)
client_file_name = "21-4192_#{SecureRandom.uuid}.pdf"
file_contents = File.read(source_file_path)
send_data file_contents, filename: client_file_name, type: 'application/pdf', disposition: 'attachment'
rescue => e
handle_pdf_generation_error(e)
ensure
File.delete(source_file_path) if source_file_path && File.exist?(source_file_path)
end
private
def check_feature_enabled
routing_error unless Flipper.enabled?(:form_4192_enabled, current_user)
end
def handle_pdf_generation_error(error)
Rails.logger.error('Form214192: Error generating PDF', error: error.message, backtrace: error.backtrace)
render json: {
errors: [{
title: 'PDF Generation Failed',
detail: 'An error occurred while generating the PDF',
status: '500'
}]
}, status: :internal_server_error
end
def stats_key
'api.form214192'
end
end
end
|
0
|
code_files/vets-api-private/app/controllers
|
code_files/vets-api-private/app/controllers/v0/letters_generator_controller.rb
|
# frozen_string_literal: true
require 'lighthouse/letters_generator/service'
require 'lighthouse/letters_generator/service_error'
module V0
class LettersGeneratorController < ApplicationController
service_tag 'letters'
before_action { authorize :lighthouse, :access? }
before_action :validate_letter_type, only: %i[download]
Sentry.set_tags(team: 'benefits-claim-appeal-status', feature: 'letters-generator')
DOWNLOAD_PARAMS = %i[
id
format
military_service
service_connected_disabilities
service_connected_evaluation
non_service_connected_pension
monthly_award
unemployable
special_monthly_compensation
adapted_housing
chapter35_eligibility
death_result_of_disability
survivors_award
letters_generator
].freeze
def index
response = service.get_eligible_letter_types(@current_user.icn)
render json: response
end
def download
icns = { icn: @current_user.icn }
response = service.download_letter(icns, params[:id], letter_options)
send_data response, filename: "#{params[:id]}.pdf", type: 'application/pdf', disposition: 'attachment'
end
def beneficiary
response = service.get_benefit_information(@current_user.icn)
render json: response
end
private
def download_params
params.permit(DOWNLOAD_PARAMS)
end
def validate_letter_type
unless service.valid_type?(params[:id])
detail = "Letter type of #{params[:id]} is not one of the expected options"
raise Common::Exceptions::BadRequest.new({ detail:, source: self.class.name })
end
end
def service
@service ||= Lighthouse::LettersGenerator::Service.new
end
def letter_options
download_params.to_h
.except('id')
.transform_values { |v| ActiveModel::Type::Boolean.new.cast(v) }
.transform_keys { |k| k.camelize(:lower) }
end
end
end
|
0
|
code_files/vets-api-private/app/controllers
|
code_files/vets-api-private/app/controllers/v0/evss_benefits_claims_controller.rb
|
# frozen_string_literal: true
module V0
class EVSSBenefitsClaimsController < ApplicationController
include IgnoreNotFound
service_tag 'claim-status'
before_action { authorize :evss, :access? }
def index
claims = get_claims
render json: claims
end
def show
claim = get_claim(params[:id])
render json: claim
end
private
def get_auth_headers
EVSS::AuthHeaders.new(@current_user).to_h
end
def get_claims
headers = get_auth_headers
EVSS::ClaimsService.new(headers).all_claims.body
end
def get_claim(evss_id)
# Make sure that the claim ID belongs to the authenticated user
claim = EVSSClaim.for_user(current_user).find_by(evss_id:)
raise Common::Exceptions::RecordNotFound, params[:id] unless claim
headers = get_auth_headers
EVSS::ClaimsService.new(headers).find_claim_with_docs_by_id(evss_id).body
end
end
end
|
0
|
code_files/vets-api-private/app/controllers
|
code_files/vets-api-private/app/controllers/v0/rated_disabilities_controller.rb
|
# frozen_string_literal: true
require 'lighthouse/veteran_verification/service'
module V0
class RatedDisabilitiesController < ApplicationController
service_tag 'disability-rating'
before_action { authorize :lighthouse, :access? }
def show
response = service.get_rated_disabilities(@current_user.icn)
# We only want active ratings
if response.dig('data', 'attributes', 'individual_ratings')
remove_inactive_ratings!(response['data']['attributes']['individual_ratings'])
end
# LH returns the ICN of the Veteran in the data.id field
# We want to scrub it out before sending to the FE
response['data']['id'] = ''
render json: response
end
private
def active?(rating)
end_date = rating['rating_end_date']
end_date.nil? || Date.parse(end_date).future?
end
def remove_inactive_ratings!(ratings)
ratings.select! { |rating| active?(rating) }
end
def service
@service ||= VeteranVerification::Service.new
end
end
end
|
0
|
code_files/vets-api-private/app/controllers
|
code_files/vets-api-private/app/controllers/v0/admin_controller.rb
|
# frozen_string_literal: true
require 'admin/postgres_check'
require 'admin/redis_health_checker'
module V0
class AdminController < ApplicationController
service_tag 'platform-base'
skip_before_action :authenticate, only: :status
def status
app_status = {
git_revision: AppInfo::GIT_REVISION,
db_url: nil,
postgres_up: DatabaseHealthChecker.postgres_up,
redis_up: RedisHealthChecker.redis_up,
redis_details: {
app_data_redis: RedisHealthChecker.app_data_redis_up,
rails_cache: RedisHealthChecker.rails_cache_up,
sidekiq_redis: RedisHealthChecker.sidekiq_redis_up
}
}
render json: app_status
end
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.