23516. EPMO Open Source Coordination Office Redaction File Detail Report

Produced by Araxis Merge on 5/28/2019 3:18:24 PM Eastern Daylight Time. See www.araxis.com for information about Merge. This report uses XHTML and CSS2, and is best viewed with a modern standards-compliant browser. For optimum results when printing this report, use landscape orientation and enable printing of background images and colours in your browser.

23516.1 Files compared

# Location File Last Modified
1 CV_src.zip\CV-VAS\grails-app\conf SecurityFilters.groovy Wed May 1 18:46:26 2019 UTC
2 CV_src.zip\CV-VAS\grails-app\conf SecurityFilters.groovy Fri May 24 18:28:47 2019 UTC

23516.2 Comparison summary

Description Between
Files 1 and 2
Text Blocks Lines
Unchanged 2 1360
Changed 1 2
Inserted 0 0
Removed 0 0

23516.3 Comparison options

Whitespace
Character case Differences in character case are significant
Line endings Differences in line endings (CR and LF characters) are ignored
CR/LF characters Not shown in the comparison detail

23516.4 Active regular expressions

No regular expressions were active.

23516.5 Comparison detail

  1   /*
  2    * Janus 4 .0 (c)
  3    * Copyrig ht (c) 201 1 Hawaii R esource Gr oup LLC. A ll Rights  Reserved.
  4    * Develop ed for the  Pacific T elehealth  & Technolo gy Hui and  the Pacif ic Joint I nformation  Technolog y Center
  5    * Contrib utors:
  6    *              Honor able Senat or Daniel  K. Inouye
  7    *              VA Pa cific Isla nds Health  Care Syst em
  8    *              Tripl er Army Me dical Cent er
  9    *
  10    * License d under th e Apache L icense, Ve rsion 2.0  (the "Lice nse"); you  may not u se this fi le except  in complia nce with t he License .
  11    *
  12    * You may  obtain a  copy of th e License  at:
  13    *
  14    *             http:/ /www.apach e.org/lice nses/LICEN SE-2.0.txt
  15    *
  16    * Unless  required b y applicab le law or  agreed to  in writing , software
  17    * distrib uted under  the Licen se is dist ributed on  an "AS IS " BASIS,
  18    * WITHOUT  WARRANTIE S OR CONDI TIONS OF A NY KIND, e ither expr ess or imp lied.
  19    * See the  License f or the spe cific lang uage gover ning permi ssions and  limitatio ns under t he License .
  20    */
  21  
  22  
  23   import gov .va.med.co mmon.HttpK eys
  24   import gov .va.med.da o.DaoExcep tion
  25   import gov .va.med.fo undations. utilities. EncryptUti l
  26   import gov .va.med.fo undations. utilities. VistaKerne lHash
  27   import gov .va.med.gr oovy.user. AppUser
  28   import gov .va.med.gu ibeans.CGU IProvider
  29   import gov .va.med.gu ibeans.GUI Site
  30   import gov .va.med.gu ibeans.GUI User
  31   import gov .va.med.jm eadows.web service.Au thUserInfo
  32   import gov .va.med.jm eadows.web service.Ie hrUserProf ile
  33   import gra ils.util.E nvironment
  34   import org .apache.co mmons.lang 3.StringUt ils
  35  
  36   import jav a.security .cert.Cert ificateExp iredExcept ion
  37   import jav a.security .cert.Cert ificateNot YetValidEx ception
  38   import jav a.security .cert.X509 Certificat e
  39   import jav a.util.reg ex.Pattern
  40  
  41   /**
  42    *
  43    *
  44    */
  45   class Secu rityFilter s {
  46       static  final Str ing cardId Default =  "987654321 ";
  47       static  long seqC ardIdSelMi nId;
  48       static  long seqC ardIdSelMa xId;
  49       static  long seqC ardIdSelCu rId;
  50       static  boolean s eqCardIdSe lInit = tr ue;
  51  
  52       def ap pConfig
  53       def to kenUtils
  54  
  55       def us erDao
  56       def pa tientDao
  57  
  58       def au thUserDao;
  59       def au ditDao
  60  
  61       def co mmunityDao
  62  
  63       def fi lters = {
  64           hs ts(control ler: '*',  action: '* ') {
  65                after =  { Map mode l ->
  66                    if (  request.i sSecure()  || request .getHeader ('X-Forwar ded-Proto' )?.toLower Case() ==  'https' )  {
  67                         response.s etHeader(' Strict-Tra nsport-Sec urity', ap pConfig.ge tHstsHeade rValue())
  68                    }
  69                }
  70           }
  71  
  72           ge tAndPostOn ly(control ler: '*',  action: '* ')
  73                    {
  74                         before = {
  75                             // To  prevent un allowed HT TP methods
  76                             if (re quest.meth od != 'GET ' && reque st.method  != 'POST')  {
  77                                 re sponse.sen dError 405
  78                             }
  79                         }
  80                    }
  81  
  82           /* * check cs rf token t o filter p otential c srf **/
  83  
  84           cs rfCheck(co ntroller:  '*', actio n: '*')
  85                    {
  86                         before = {
  87  
  88                             if (re quest.meth od != 'GET ') { //onl y filter ' destructiv e' request s
  89                                 de f csrfToke nServer =  session.ge tAttribute ("X-CSRF-T oken");
  90                                 de f csrfToke nClient =  '';
  91  
  92                                 if  (controll erName ==  'authentic ate') //au thenticate  controlle r does not  send toke n in heade r
  93                                 {
  94                                      csrfToke nClient =  params['cs rf-token']
  95                                 }  else if (( controller Name == 'p atientSele ct' || con trollerNam e == 'cont ext') && p arams['csr fToken'] ! = null) {
  96                                      csrfToke nClient =  params['cs rfToken']
  97                                 }  else if (c ontrollerN ame == 'co mmunity' & & actionNa me == 'res et') {
  98                                      csrfToke nClient =  params['cs rf-token']
  99                                 }  else {
  100                                      csrfToke nClient =  request.ge tHeader("X -CSRF-Toke n");
  101                                 }
  102  
  103                                 if  (!csrfTok enServer.e quals(csrf TokenClien t) && (csr fTokenServ er != null  && contro llerName ! = 'AHLTALo gin')) {
  104                                      log.debu g("server  and client  csrfToken s do not m atch.")
  105                                      return f alse;
  106                                 }
  107                             }
  108                         }
  109                    }
  110  
  111           /* *
  112            *  If invali d session,  send user  to authen ticate log in action
  113            *  or if res t action,  send 403 e rror
  114            * /
  115           se ssionCheck (controlle r: '*', ac tion: '*')
  116                    {
  117                         before = {
  118  
  119                             // No  session fo r Communit y Viewer C CP Passwor d Reset re quest
  120                             if (co ntrollerNa me == 'com munity' &&  actionNam e == 'rese t') {
  121                                 re turn true;
  122                             }
  123  
  124                             if (co ntrollerNa me != 'aut henticate'
  125                                      && contr ollerName  != "assets ") {
  126                                 if  (!session .appUser)  {
  127                                      //redire ct to logi n screen
  128                                      if (acti onName ==  "index" ||
  129                                               controller Name == "a pp" ||
  130                                               controller Name == "c ontext" ||
  131                                               controller Name == "p atientMedW eb" ||
  132                                               controller Name == "v iew") {
  133                                          log. debug("No  appUser in  session,  redirectin g to login  screen")
  134                                          redi rect(contr oller: 'au thenticate ', action:  'login')
  135                                          retu rn false
  136                                      }
  137  
  138                                      // Only  show if no t coming f rom AHLTA  link
  139                                      if (cont rollerName  != "AHLTA Login") {
  140                                          //if  rest cont roller/act ion, send  403 error
  141                                          log. debug("RES T call: No  appUser i n session,  sending 4 03 Forbidd en")
  142                                          resp onse.sendE rror 403;
  143                                          retu rn false;
  144                                      }
  145                                 }  else {
  146  
  147                                      def acce ptedAgreem ent = sess ion.getAtt ribute("ac ceptedAgre ement") ||  session.a hltaLoginF lag;
  148                                      if (!acc eptedAgree ment) {
  149                                          redi rect(contr oller: 'au thenticate ', action:  'disclaim er')
  150                                          retu rn false;
  151                                      }
  152  
  153                                      def guiO utsideProv ider = (CG UIProvider ) session. getAttribu te("guiOut sideProvid er")
  154  
  155                                      if (guiO utsideProv ider != nu ll && !gui OutsidePro vider.isSe curityAgre ement()) {
  156                                          redi rect(contr oller: 'au thenticate ', action:  'security Agreement' )
  157                                          retu rn false;
  158                                      }
  159                                 }
  160                             }
  161  
  162                         }
  163                    }
  164  
  165           /* *
  166            *  Do not al low browse r caching  for all co ntrollers/ actions
  167            * /
  168           no CacheCheck (controlle r: '*', ac tion: '*')
  169                    {
  170                         before = {
  171                             respon se.setHead er('Cache- Control',  'no-cache,  no-store' )
  172                             respon se.setDate Header('Ex pires', (n ew Date()  - 1).time)
  173                             respon se.setHead er('Pragma ', 'no-cac he')
  174                         }
  175                    }
  176  
  177           /* *
  178            *  If login  action and  a valid s ession exi sts, send
  179            *  user to t he provide r page
  180            * /
  181           lo ginRedirec t(controll er: "authe nticate",  action: "l ogin")
  182                    {
  183                         before = {
  184                             if (se ssion.appU ser) {
  185                                 re direct(con troller: ' app')
  186                                 re turn false
  187                             }
  188                         }
  189                    }
  190  
  191           /* *
  192            *  Filter pa rses and v erifies pa tient and  record sec urity toke ns.
  193            *
  194            * /
  195           se curityToke nCheck(con troller: ' *', action : '*')
  196                    {
  197                         before = {
  198  
  199                             /**
  200                              * If  valid pati ent token  exists in  request pa rams,
  201                              * pat ient tied  to the tok en will be  placed in  the reque st object  (request.p atient).
  202                              *
  203                              * A p atient tok en is an A ES encrypt ed base 64  string th at consist s
  204                              * of  four param eters: pat ient id, p atient loo kup site ( site assoc iated with  the patie nt id),
  205                              * use r session  id, and ti mestamp.
  206                              */
  207                             if (pa rams[HttpK eys.PATIEN T_TOKEN] & & controll erName !=  "patientSe lect") {
  208                                 lo g.debug("P rocessing  patient to ken")
  209  
  210                                 tr y {
  211                                      def pati entToken =  params[Ht tpKeys.PAT IENT_TOKEN ]
  212                                      def appU ser = sess ion.appUse r
  213                                      def sele ctedPatien tMap = ses sion.appUs er.selecte dPatientMa p
  214  
  215                                      if (pati entToken = = null ||  patientTok en.isEmpty ()) {
  216                                          log. error("sec urityToken Check::Pat ient token  null or e mpty")
  217                                          thro w new Runt imeExcepti on("Invali d patient  token")
  218                                      } else i f (appUser  == null | | selected PatientMap  == null)  {
  219                                          log. error("sec urityToken Check::Pro vider or s elected pa tient map  is null")
  220                                          thro w new Runt imeExcepti on("Uninit ialized se ssion")
  221                                      }
  222  
  223                                      if (log. debugEnabl ed) {
  224                                          log. debug("Dec rypted pat ient token : ${tokenU tils.decry ptTokenToS tring(sess ion.appUse r.security Key, patie ntToken)}" );
  225                                      }
  226  
  227                                      //first  check to s ee if pati ent is alr eady mappe d
  228                                      def sele ctedPatien t = select edPatientM ap.get(pat ientToken)
  229  
  230                                      if (sele ctedPatien t == null)  {
  231                                          log. debug("Can not find p atient tok en in map,  calling s elect pati ent")
  232  
  233                                          def  patientPar ams = toke nUtils.dec ryptTokenT oMap(sessi on.appUser .securityK ey, patien tToken)
  234  
  235                                          log. debug("Pat ient param s from tok en: ${pati entParams} ")
  236  
  237                                          def  paramPatie ntSiteCode  = patient Params[Htt pKeys.PATI ENT_SITE_C ODE]
  238                                          def  paramIdTyp e = patien tParams[Ht tpKeys.ID_ TYPE];
  239                                          def  paramPatie ntId = pat ientParams [HttpKeys. PATIENT_ID ]
  240  
  241                                          def  responseGU IPatientSe lect = pat ientDao.se lectPatien t(appUser,  null, par amPatientI d, paramId Type, para mPatientSi teCode)
  242                                          sele ctedPatien t = respon seGUIPatie ntSelect.g etGUIPatie nt()
  243  
  244                                          if ( selectedPa tient == n ull) {
  245                                               log.error( "securityT okenCheck: :selected  patient is  null")
  246                                               throw new  RuntimeExc eption("In valid pati ent token" )
  247                                          }
  248                                          sele ctedPatien tMap.put(p atientToke n, selecte dPatient)
  249                                          log. debug("Pat ient selec t success,  mapping p atient to  patientTok en: ${pati entToken}" )
  250                                      }
  251  
  252                                      request. patient =  selectedPa tient
  253                                 }
  254                                 ca tch (Excep tion e) {
  255                                      response .sendError  500
  256                                      return f alse;
  257                                 }
  258                             }
  259                             /**
  260                              * If  a valid re cord detai ls exists  in request  params,
  261                              * nec essary rec ord variab les (recor d query, i sSessionCa chedRecord )
  262                              * wil l be added  to the re quest obje ct.
  263                              *
  264                              * A r ecord deta ils token  is tied to  the user  session.
  265                              */
  266                             if (pa rams[HttpK eys.RECORD _DETAILS_T OKEN]) {
  267                                 lo g.debug("P rocessing  record det ails token ")
  268  
  269                                 tr y {
  270                                      def reco rdDetailsT oken = par ams[HttpKe ys.RECORD_ DETAILS_TO KEN]
  271                                      def prov ider = ses sion.appUs er
  272  
  273                                      if (reco rdDetailsT oken == nu ll || reco rdDetailsT oken.isEmp ty()) {
  274                                          log. error("sec urityToken Check::Rec ord detail s token is  null or e mpty")
  275                                          thro w new Runt imeExcepti on("Invali d record d etails tok en")
  276                                      } else i f (provide r == null)  {
  277                                          log. error("sec urityToken Check::Pro vider is n ull")
  278                                          thro w new Runt imeExcepti on("Uninit ialized se ssion")
  279                                      }
  280  
  281                                      if (log. isDebugEna bled()) {
  282                                          log. debug("Dec rypted rec ord detail s token: $ {tokenUtil s.decryptT okenToStri ng(session .appUser.s ecurityKey , recordDe tailsToken )}")
  283                                      }
  284  
  285                                      def deta ilsParams  = tokenUti ls.decrypt TokenToMap (session.a ppUser.sec urityKey,  recordDeta ilsToken)
  286  
  287                                      def para mRecordCon trollerNam e = detail sParams[Ht tpKeys.REC ORD_CONTRO LLER_NAME]
  288                                      def para mSessionCa chedRecord  = details Params[Htt pKeys.SESS ION_CACHED _RECORD]
  289  
  290                                      //record  token sec urity chec ks
  291                                      if (cont rollerName  != paramR ecordContr ollerName)  {
  292                                          log. error("sec urityToken Check::rec ord detail s token's  controller  name is i nvalid.")
  293                                          thro w new Runt imeExcepti on("Invali d record d etails tok en")
  294                                      }
  295  
  296                                      request. recordQuer y = detail sParams
  297  
  298                                      request. isSessionC achedRecor d = Boolea n.valueOf( paramSessi onCachedRe cord)
  299  
  300                                      return t rue
  301                                 }
  302                                 ca tch (Excep tion e) {
  303                                      response .sendError  500
  304                                      return f alse;
  305                                 }
  306                             }
  307                         }
  308                    }
  309  
  310           sm artCardChe ck(control ler: 'auth enticate',  action: ' login')
  311                    {
  312                         before = {
  313                             // We  only want  to do the  smart card  check whe n requesti ng login p age, not w hen loggin g into JLV .
  314                             if (re quest.meth od == 'POS T' || (app Config.isC ommunityLo gin() && ( Environmen t.current  == Environ ment.PRODU CTION))) {
  315                                 re turn;
  316                             }
  317  
  318                             String  subjectDN  = "";
  319                             String  certifica te = "";
  320                             String  agency =  "";
  321                             String  lastName  = "";
  322                             String  firstName  = "";
  323                             String  middleNam e = "";
  324                             String  scId = "" ;
  325                             String  scEmail =  "";
  326  
  327                             // Cou ld not hav e min/max  values set  at variab le creatio n, so I cr eated a st atic
  328                             // var iable flag  to ensure  setting t he min/max  from appc onfig prop erties fil e
  329                             // onl y happens  once at ap plication  startup an d first ac cess to sm artCardChe ck.
  330                             if (se qCardIdSel Init) {
  331                                 se qCardIdSel MinId = ap pConfig.ge tSeqCardId SelMinId() ;
  332                                 se qCardIdSel MaxId = ap pConfig.ge tSeqCardId SelMaxId() ;
  333  
  334                                 if  (seqCardI dSelMinId  == -1L) {
  335                                      seqCardI dSelMinId  = Long.par seLong(car dIdDefault );
  336                                 }
  337  
  338                                 if  (seqCardI dSelMaxId  == -1L) {
  339                                      seqCardI dSelMaxId  = Long.par seLong(car dIdDefault );
  340                                 }
  341  
  342                                 se qCardIdSel CurId = se qCardIdSel MinId;
  343                                 se qCardIdSel Init = fal se;
  344                             }
  345  
  346                             //get  person nam e and id f rom CAC x. 509 certif icate
  347                             X509Ce rtificate[ ] certs =  (X509Certi ficate[])  request.ge tAttribute ("javax.se rvlet.requ est.X509Ce rtificate" );
  348  
  349                             if (ap pConfig.ge tSmartCard Bypass() & & (request .getScheme () != "htt ps")) {
  350                                 su bjectDN =  "CN=this,O U=is_a_tes t";
  351                                 se ssion.subj ectDN = su bjectDN;
  352                                 ag ency = "VA ";
  353                                 la stName = " McLuvin";
  354                                 fi rstName =  "Dood";
  355                                 mi ddleName =  "";
  356                                 sc Email = "d ood@mcluvi n.com"
  357  
  358                                 //  Sequence  Card ID Se lect is ac tive
  359                                 if  (appConfi g.getSeqCa rdIdSelEna bled()) {
  360                                      scId = s eqCardIdSe lCurId.toS tring();
  361  
  362                                      // Loop  card ID to  min once  it exceeds  the max v alue
  363                                      if (++se qCardIdSel CurId > se qCardIdSel MaxId) {
  364                                          seqC ardIdSelCu rId = seqC ardIdSelMi nId;
  365                                      }
  366                                 }  else {
  367                                      scId = a ppConfig.g etTestSmar tCard();
  368  
  369                                      // appco nfig prope rty file d oes NOT ha ve ID set,  use defau lt
  370                                      if (Stri ngUtils.is Blank(scId )) {
  371                                          scId  = cardIdD efault  //  default c ard ID
  372                                      }
  373                                 }
  374  
  375                                 se ssion.scEm ail = scEm ail;
  376                                 se ssion.scId  = scId;
  377                                 se ssion.scAg ency = age ncy;
  378  
  379                             } else  {
  380  
  381                                 //  App serve r will han dle the ss l connecti on. If no  cert, ssl  is not ena bled (http ), else
  382                                 //  ssl is en abled (htt ps) and th e server h as authent icated it  by this po int (cert  exist).
  383                                 if  (request. getScheme( ) != "http s") {
  384                                      response .sendError (403, "SSL Required") ;
  385                                      return f alse;
  386                                 }
  387  
  388                                 if  (certs ==  null) {
  389                                      response .sendError (403, "Sma rtCardRequ ired");
  390                                      return f alse;
  391                                 }
  392  
  393                                 if  (log.debu gEnabled)  {
  394                                      for (X50 9Certifica te cert :  certs) {
  395                                          log. debug("cer t::key usa ge: ${cert .getKeyUsa ge()}");
  396                                          log. debug("cer t::extende d key usag e: ${cert. getExtende dKeyUsage( )}");
  397                                          log. debug("cer t::serial  number: ${ cert.getSe rialNumber ()}");
  398                                          log. debug("cer t::subject  DN: ${cer t.getSubje ctDN()}");
  399                                      }
  400                                 }
  401  
  402                                 X5 09Certific ate cert =  certs[0];
  403  
  404                                 tr y {
  405                                      cert.che ckValidity ();
  406                                 }
  407                                 ca tch (Certi ficateExpi redExcepti on e) {
  408                                      log.info ("Could no t grant us er access:  ${e.getMe ssage()}") ;
  409                                      response .sendError (403, "Use rAccessDen ied-Expire d")
  410                                      return f alse;
  411                                 }
  412                                 ca tch (Certi ficateNotY etValidExc eption e)  {
  413                                      log.info ("Could no t grant us er access:  ${e.getMe ssage()}") ;
  414                                      response .sendError (403, "Use rAccessDen ied-NotYet Valid")
  415                                      return f alse;
  416                                 }
  417                                 ce rtificate  = javax.xm l.bind.Dat atypeConve rter.print Base64Bina ry(cert.ge tEncoded() );
  418                                 se ssion.cert ificate =  certificat e;
  419  
  420                                 su bjectDN =  cert.getSu bjectDN();
  421                                 se ssion.subj ectDN = su bjectDN;
  422  
  423                                 //  Check for  card issu er's agenc y
  424  
  425                                 if  (Pattern. compile(Pa ttern.quot e("ou=dod" ), Pattern .CASE_INSE NSITIVE).m atcher(sub jectDN).fi nd() ||
  426                                          Patt ern.compil e(Pattern. quote("dc= dod"), Pat tern.CASE_ INSENSITIV E).matcher (subjectDN ).find())  {
  427                                      agency =  "DOD";
  428                                 }  else if (P attern.com pile(Patte rn.quote(" ou=va"), P attern.CAS E_INSENSIT IVE).match er(subject DN).find()  ||
  429                                          Patt ern.compil e(Pattern. quote("dc= va"), Patt ern.CASE_I NSENSITIVE ).matcher( subjectDN) .find()) {
  430                                      agency =  "VA";
  431                                 }  else {
  432                                      response .sendError (403, "Use rAccessDen ied-Invali d")
  433                                      return f alse;
  434                                 }
  435                                 se ssion.scAg ency = age ncy;
  436  
  437                                 // parse pers on name an d id from  the subjec tDN of pri mary cert
  438                                 St ring[] spl it = subje ctDN.split (",");
  439  
  440                                 in t cnIdx =  -1;
  441                                 in t emailIdx  = -1;
  442  
  443                                 fo r (int i =  0; i < sp lit.length ; i++) {
  444                                      if (spli t[i].conta ins("CN=")  && cnIdx  < 0) {
  445                                          cnId x = i;
  446                                      }
  447                                      if  PII                           ")) {
  448                                          emai lIdx = i;
  449                                      }
  450                                 }
  451  
  452                                 if  (cnIdx <  0) {
  453                                      response .sendError (403, "Use rAccessDen ied-Invali d")
  454                                      return f alse;
  455                                 }
  456  
  457                                 if  (emailIdx  > 0) {
  458                                      scEmail  = split[em ailIdx].su bstring(sp lit[emailI dx].indexO f("UID=")  + 4, split [emailIdx] .length()) ;
  459                                      session. scEmail =  scEmail;
  460                                 }
  461  
  462                                 St ring cn =  split[cnId x];
  463  
  464                                 cn  = cn.subs tring(cn.i ndexOf("=" ) + 1);
  465  
  466                                 la stName = " ";
  467                                 fi rstName =  "";
  468                                 mi ddleName =  "";
  469                                 sc Id = "";
  470  
  471                                 if  (agency.e qualsIgnor eCase("DoD ")) {
  472                                      StringTo kenizer to k = new St ringTokeni zer(cn, ". ");
  473  
  474                                      while (t ok.hasMore Tokens())  {
  475                                          Stri ng token =  tok.nextT oken();
  476                                          //as suming tha t person i d is alway s the last  item in s tring
  477                                          if ( !tok.hasMo reTokens() ) scId = t oken;
  478                                          else  {
  479                                               if (lastNa me.isEmpty ()) lastNa me = token ;
  480                                               else if (f irstName.i sEmpty())  firstName  = token;
  481                                               else if (m iddleName. isEmpty())  middleNam e = token;
  482                                          }
  483                                      }
  484                                 }  else {
  485                                      StringTo kenizer to k = new St ringTokeni zer(cn, "  ");
  486  
  487                                      while (t ok.hasMore Tokens())  {
  488                                          Stri ng token =  tok.nextT oken();
  489  
  490                                          if ( !token.mat ches("\\d+ ")) {
  491                                               if (firstN ame.isEmpt y()) first Name = tok en;
  492                                               else if (l astName.is Empty()) l astName =  token;
  493                                               else if (m iddleName. isEmpty())  {
  494                                                   middle Name = las tName;
  495                                                   lastNa me = token ;
  496                                               }
  497                                          } el se {
  498                                               scId = tok en;
  499                                               session.sc Id = scId;
  500                                               //token is  the last  item we wa nt, exit w hile loop
  501                                               break;
  502                                          }
  503                                      }
  504                                 }
  505  
  506                             }
  507  
  508                             log.de bug("Perso nName: ${l astName},  ${firstNam e} ${middl eName} scI d: ${scId} ")
  509                             sessio n.profileN ame = last Name + ",  " + firstN ame + " "  + middleNa me;
  510  
  511                             if (se ssion.user Profile ==  null) {
  512                                 Ie hrUserProf ile userPr ofile = nu ll
  513  
  514                                 tr y {
  515  
  516                                      userProf ile = user Dao.getIeh rUserProfi le(scId, a gency, scE mail);
  517                                      if(scEma il != null  && !"".eq uals(scEma il)){
  518                                          user Profile.se tEmailAddr ess(scEmai l);
  519                                      }
  520                                      if (user Profile !=  null && u serProfile .dbUserID  != null &&  userProfi le.dbUserI D != "") {
  521                                          if ( userProfil e.flags ==  null)
  522                                               userProfil e.setFlags ("");
  523                                          if ( userProfil e.locID ==  null)
  524                                               userProfil e.setLocID ("");
  525                                          if ( userProfil e.cfg == n ull)
  526                                               userProfil e.setCfg(" ");
  527                                          if(u serProfile .emailAddr ess == nul l)
  528                                               userProfil e.setEmail Address("" );
  529                                          if(u serProfile .subjectDN  == null)
  530                                               userProfil e.setSubje ctDN("");
  531                                      } else {
  532                                          user Profile.se tDbUserID( "");
  533                                          user Profile.se tLocID("") ;
  534                                          user Profile.se tCfg("");
  535                                          user Profile.se tFlags("") ;
  536                                          user Profile.se tSmartCard ID(scId);
  537                                          user Profile.se tSmartCard Agency(age ncy);
  538                                          user Profile.se tEmailAddr ess(scEmai l);
  539                                          user Profile.se tSubjectDN (subjectDN );
  540                                      }
  541                                      session. userProfil e = userPr ofile;
  542                                 }
  543                                 ca tch (Excep tion e) {
  544                                      log.info ("Could no t process  JLV User P rofile: ${ e.getMessa ge()}");
  545                                      response .sendError (403, "Pro fileRetrie ve")
  546                                      return f alse;
  547                                 }
  548                             }
  549  
  550                             // If  organizati on's acces s flag is  enabled, t hen do dat abase chec k to verif y user
  551                             // is  authorized  to access  JLV
  552  
  553                             //Retr ieve the u serRole
  554                             String  userRole  = communit yDao.retri eveUserRol e(scEmail)
  555  
  556                             if ((a ppConfig.g etDodUserA uthEnabled () && agen cy.equalsI gnoreCase( appConfig. getAgencyD OD()))
  557                                      || (appC onfig.getV aUserAuthE nabled() & & agency.e qualsIgnor eCase(appC onfig.getA gencyVA()) )
  558                                      || (user Role.equal sIgnoreCas e('SDU')))  {
  559                                 tr y {
  560  
  561                                      //audit  login atte mpt
  562                                      GUIUser  auditUser  = new GUIU ser();
  563                                      auditUse r.setCardI d(scId);
  564                                      auditUse r.setAgenc y(agency);
  565                                      auditUse r.setEmail (scEmail);
  566                                      auditUse r.setName( lastName+" ,"+firstNa me)
  567  
  568                                      StringBu ilder audi tAttempt =  new Strin gBuilder()
  569  
  570                                      if(agenc y.equalsIg noreCase(a ppConfig.g etAgencyDO D())){
  571                                          audi tAttempt.a ppend("Sna reworksLog inAttempt" );
  572                                      } else {
  573                                          audi tAttempt.a ppend("Get AuthUser") ;
  574                                      }
  575   //                                   auditA ttempt.app end("^user EDIPI=" +  scId)
  576   //                                   auditA ttempt.app end("^scEm ail=" + sc Email)
  577                                      auditDao .auditDeta ilsQuery(a uditAttemp t.toString (), auditU ser, null,  null, nul l, null, n ull)
  578  
  579   //                                   AuthUs erInfo aut hUserInfo  = new Auth UserInfo() ;
  580   //
  581   //                                   authUs erInfo.set CardId(scI d);
  582   //                                   authUs erInfo.set Organizati on(agency) ;
  583   //                                   authUs erInfo.set Email(scEm ail);
  584   //                                   authUs erInfo.set Certificat e(certific ate);
  585   //                                   authUs erInfo = a uthUserDao .getAuthUs er(authUse rInfo);
  586   //
  587   //
  588   //                                   if (au thUserInfo  == null)  {
  589   //                                       re sponse.sen dError(403 , "UserAcc essDenied" );
  590   //                                       re turn false ;
  591   //                                   }
  592  
  593                                      log.debu g("userRol e: ${userR ole}")
  594   //                                   if (au thUserInfo .getSnareF lag()) {
  595   //                                       se ssion.snar eFlag = tr ue;
  596   //                                   }
  597                                      if (user Role.equal sIgnoreCas e('SDU'))  {
  598                                          Stri ng loginAg ency = 'VA '
  599  
  600                                          GUIS ite hostSi te = new G UISite()
  601                                          host Site.setAg ency(login Agency)
  602                                          host Site.setDm isId("VA")
  603                                          host Site.setMo niker("VA" )
  604                                          host Site.setNa me("Servic e Desk Use r")
  605                                          host Site.setSi teCode("ZZ Z")
  606                                          host Site.setSt atus("acti ve")
  607  
  608                                          GUIU ser user =  new GUIUs er()
  609                                          user .setHostSi te(hostSit e)
  610                                          user .setAgency (loginAgen cy)
  611                                          user .setName(l astName +  "," + firs tName)
  612                                          user .setUserIe n(scId)
  613                                          user .setEncryp tedFederat edUid(Encr yptUtil.en crypt("123 456789"))
  614                                          user .setEncryp tedAvCode( VistaKerne lHash.encr ypt(lastNa me + "," +  firstName  + ";" + s cId, false ))
  615                                          user .setEncryp tedFederat edUid(Encr yptUtil.en crypt("123 456789"))
  616                                          user .setBseTok en("~1XWBA S1899-1519 7_3")
  617                                          user .setCardId (scId)
  618                                          user .setEmail( scEmail)
  619                                          user .setUserRo le(userRol e)
  620  
  621                                          // A udit Succe ssful logi n audit
  622                                          Stri ngBuilder  auditSucce ss = new S tringBuild er()
  623                                          audi tSuccess.a ppend("Sma rtCardSucc ess")
  624                                          audi tSuccess.a ppend("^sm artCardId= " + scId)
  625                                          audi tSuccess.a ppend("^us erName=" +  lastName  + "," + fi rstName)
  626                                          audi tSuccess.a ppend("^sm artCardEma il=" + scE mail)
  627                                          audi tDao.audit DetailsQue ry("Login" , auditSuc cess.toStr ing(), use r,null,nul l,null, nu ll, agency )
  628  
  629                                          AppU ser appUse r = new Ap pUser(user )
  630                                          appU ser.setSec urityKey(t okenUtils. generateSe curityKey( ))
  631  
  632                                          //ch eck for va lid profil e
  633                                          if ( session.us erProfile. getDbUserI D() == nul l || "".eq ualsIgnore Case(sessi on.userPro file.getDb UserID()))  {
  634                                               //user doe sn' have p rofile, le t's create  one.
  635                                               try {
  636                                                   if (us erDao.setI ehrUserPro file(sessi on.userPro file)) {
  637                                                       Ie hrUserProf ile userPr ofile = se ssion.user Profile
  638                                                       us erProfile  = userDao. getIehrUse rProfile(u serProfile .smartCard ID, userPr ofile.smar tCardAgenc y,userProf ile.getEma ilAddress( ))
  639                                                       ap pUser.setU serId(user Profile.ge tDbUserID( ))
  640                                                       ap pUser.setC fg(userPro file.getCf g())
  641                                                   }
  642                                               }
  643                                               catch (Exc eption e)  {
  644                                                   errorT ext = "Cou ld not sav e the User  Profile."
  645                                                   log.er ror("Secur ityFilters ::setIehrU serProfile ", e)
  646                                                   respon se.sendErr or(403, 'E rrorCreati ngProfile' )
  647                                                   return
  648                                               }
  649  
  650                                          } el se {
  651                                               appUser.se tUserId(se ssion.user Profile.ge tDbUserID( ))
  652                                               appUser.se tCfg(sessi on.userPro file.getCf g())
  653                                          }
  654                                          sess ion.appUse r = appUse r
  655                                          redi rect(contr oller: 'ap p')
  656                                      }
  657                                 }
  658                                 ca tch (DaoEx ception e)  {
  659                                      if(agenc y.equalsIg noreCase(a ppConfig.g etAgencyVA ())){
  660                                          log. debug("DAO  EXCEPTION  - USER AC CESS DENIE D")
  661                                          resp onse.sendE rror(403,  "UserAcces sDenied");
  662                                      } else {
  663                                          resp onse.sendE rror(403,  "SmartCard Issue");
  664                                      }
  665  
  666                                      return f alse;
  667                                 }
  668                             }
  669  
  670                             return  true;
  671                         }
  672                         after = {  Map model  ->
  673  
  674                         }
  675                         afterView  = { Except ion e ->
  676  
  677                         }
  678                    }
  679       }
  680   }
  681