forked from OpenBankProject/OBP-API
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathAPIUtil.scala
More file actions
5380 lines (4766 loc) · 244 KB
/
APIUtil.scala
File metadata and controls
5380 lines (4766 loc) · 244 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
Open Bank Project - API
Copyright (C) 2011-2019, TESOBE GmbH.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Email: contact@tesobe.com
TESOBE GmbH.
Osloer Strasse 16/17
Berlin 13359, Germany
This product includes software developed at
TESOBE (http://www.tesobe.com/)
*/
package code.api.util
import bootstrap.liftweb.CustomDBVendor
import cats.effect.IO
import code.abacrule.AbacRuleEngine
import code.accountholders.AccountHolders
import code.api.Constant._
import code.api.UKOpenBanking.v2_0_0.OBP_UKOpenBanking_200
import code.api.UKOpenBanking.v3_1_0.OBP_UKOpenBanking_310
import code.api._
import code.api.berlin.group.ConstantsBG
import code.api.berlin.group.v1_3.JSONFactory_BERLIN_GROUP_1_3.{ErrorMessageBG, ErrorMessagesBG}
import code.api.cache.Caching
import code.api.dynamic.endpoint.OBPAPIDynamicEndpoint
import code.api.dynamic.endpoint.helper.{DynamicEndpointHelper, DynamicEndpoints}
import code.api.dynamic.entity.OBPAPIDynamicEntity
import code.api.dynamic.entity.helper.DynamicEntityHelper
import code.api.util.APIUtil.ResourceDoc.{findPathVariableNames, isPathVariable}
import code.api.util.ApiRole._
import code.api.util.ApiTag.{ResourceDocTag, apiTagBank}
import code.api.util.BerlinGroupSigning.getCertificateFromTppSignatureCertificate
import code.api.util.Consent.getConsumerKey
import code.api.util.FutureUtil.{EndpointContext, EndpointTimeout}
import code.api.util.Glossary.GlossaryItem
import code.api.util.newstyle.ViewNewStyle
import code.api.v1_2.ErrorMessage
import code.api.v2_0_0.CreateEntitlementJSON
import code.api.v2_2_0.OBPAPI2_2_0.Implementations2_2_0
import code.api.v6_0_0.OBPAPI6_0_0
import code.authtypevalidation.AuthenticationTypeValidationProvider
import code.bankconnectors.Connector
import code.consumer.Consumers
import code.customer.CustomerX
import code.entitlement.Entitlement
import code.etag.MappedETag
import code.metrics._
import code.model._
import code.model.dataAccess.AuthUser
import code.scope.Scope
import code.usercustomerlinks.UserCustomerLink
import code.users.Users
import code.util.Helper.{MdcLoggable, ObpS, SILENCE_IS_GOLDEN}
import code.util.{Helper, JsonSchemaUtil}
import code.views.system.AccountAccess
import code.views.{MapperViews, Views}
import code.webuiprops.MappedWebUiPropsProvider.getWebUiPropsValue
import com.github.dwickern.macros.NameOf.{nameOf, nameOfType}
import com.openbankproject.commons.ExecutionContext.Implicits.global
import com.openbankproject.commons.model._
import com.openbankproject.commons.model.enums.StrongCustomerAuthentication.SCA
import com.openbankproject.commons.model.enums.{ContentParam, PemCertificateRole, StrongCustomerAuthentication}
import com.openbankproject.commons.util.Functions.Implicits._
import com.openbankproject.commons.util._
import javassist.expr.{ExprEditor, MethodCall}
import javassist.{CannotCompileException, ClassPool, LoaderClassPath}
import net.liftweb.actor.LAFuture
import net.liftweb.common._
import net.liftweb.http._
import net.liftweb.http.js.JE.JsRaw
import net.liftweb.http.provider.HTTPParam
import net.liftweb.http.rest.RestContinuation
import net.liftweb.json
import net.liftweb.json.JsonAST.{JField, JNothing, JObject, JString, JValue}
import net.liftweb.json.JsonParser.ParseException
import net.liftweb.json._
import net.liftweb.mapper.By
import net.liftweb.util.Helpers._
import net.liftweb.util._
import org.apache.commons.io.IOUtils
import org.apache.commons.lang3.StringUtils
import org.http4s.HttpRoutes
import java.io.InputStream
import java.net.URLDecoder
import java.security.AccessControlException
import java.text.{ParsePosition, SimpleDateFormat}
import java.util.concurrent.ConcurrentHashMap
import java.util.regex.Pattern
import java.util.{Calendar, Date, Locale, UUID}
import scala.collection.immutable.{List, Nil}
import scala.collection.mutable
import scala.collection.mutable.{ArrayBuffer, ListBuffer}
import scala.concurrent.{Await, Future}
import scala.concurrent.duration.Duration
import scala.io.BufferedSource
import scala.language.{implicitConversions, reflectiveCalls}
import scala.util.control.Breaks.{break, breakable}
import scala.xml.{Elem, XML}
object APIUtil extends MdcLoggable with CustomJsonFormats{
/**
* Deobfuscate a Jetty-style OBF: password string.
* Replaces org.eclipse.jetty.util.security.Password.deobfuscate
* to eliminate the Jetty dependency.
*/
def deobfuscateJettyPassword(s: String): String = {
val stripped = if (s.startsWith("OBF:")) s.substring(4) else s
val b = new Array[Byte](stripped.length / 2)
var l = 0
var i = 0
while (i < stripped.length) {
val x = stripped.substring(i, i + 4)
val i0 = Integer.parseInt(x, 36)
val i1 = i0 / 256
val i2 = i0 % 256
b(l) = ((i1 + i2 - 254) / 2).toByte
l += 1
i += 4
}
new String(b, 0, l)
}
val DateWithYear = "yyyy"
val DateWithMonth = "yyyy-MM"
val DateWithDay = "yyyy-MM-dd"
val DateWithDay2 = "yyyyMMdd"
val DateWithDay3 = "dd/MM/yyyy"
val DateWithMinutes = "yyyy-MM-dd'T'HH:mm'Z'"
val DateWithSeconds = "yyyy-MM-dd'T'HH:mm:ss'Z'"
val DateWithMs = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
val DateWithMsAndTimeZoneOffset = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
val DateWithYearFormat = new SimpleDateFormat(DateWithYear)
val DateWithMonthFormat = new SimpleDateFormat(DateWithMonth)
val DateWithDayFormat = new SimpleDateFormat(DateWithDay)
val DateWithSecondsFormat = new SimpleDateFormat(DateWithSeconds)
// If you need UTC Z format, please continue to use DateWithMsFormat. eg: 2025-01-01T01:01:01.000Z
val DateWithMsFormat = new SimpleDateFormat(DateWithMs)
// If you need a format with timezone offset (+0000), please use DateWithMsRollbackFormat, eg: 2025-01-01T01:01:01.000+0000
val DateWithMsRollbackFormat = new SimpleDateFormat(DateWithMsAndTimeZoneOffset)
val rfc7231Date = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.ENGLISH)
val DateWithYearExampleString: String = "1100"
val DateWithMonthExampleString: String = "1100-01"
val DateWithDayExampleString: String = "1100-01-01"
val DateWithSecondsExampleString: String = "1100-01-01T01:01:01Z"
val DateWithMsExampleString: String = "1100-01-01T01:01:01.000Z"
val DateWithMsRollbackExampleString: String = "1100-01-01T01:01:01.000+0000"
// Use a fixed date far into the future (rather than current date/time so that cache keys are more static)
// (Else caching is invalidated by constantly changing date)
val DateWithDayExampleObject = DateWithDayFormat.parse(DateWithDayExampleString)
val DateWithSecondsExampleObject = DateWithSecondsFormat.parse(DateWithSecondsExampleString)
val DateWithMsExampleObject = DateWithMsFormat.parse(DateWithMsExampleString)
val DateWithMsRollbackExampleObject = DateWithMsRollbackFormat.parse(DateWithMsRollbackExampleString)
private def oneYearAgo(toDate: Date): Date = {
val oneYearAgo = Calendar.getInstance
oneYearAgo.setTime(toDate)
oneYearAgo.add(Calendar.YEAR, -1)
oneYearAgo.getTime()
}
def ToDateInFuture = new Date(2100, 0, 1) //Sat Jan 01 00:00:00 CET 4000
def DefaultToDate = new Date()
def oneYearAgoDate = oneYearAgo(DefaultToDate)
val theEpochTime: Date = new Date(0) // Set epoch time. The Unix epoch is 00:00:00 UTC on 1 January 1970.
def formatDate(date : Date) : String = {
CustomJsonFormats.losslessFormats.dateFormat.format(date)
}
def epochTimeString = formatDate(theEpochTime)
def DefaultToDateString = formatDate(DefaultToDate)
implicit def errorToJson(error: ErrorMessage): JValue = Extraction.decompose(error)
val headers = ("Access-Control-Allow-Origin","*") :: Nil
val defaultJValue = Extraction.decompose(EmptyClassJson())
lazy val initPasswd = try {System.getenv("UNLOCK")} catch {case _:Throwable => ""}
import code.api.util.ErrorMessages._
def httpMethod : String =
S.request match {
case Full(r) => r.request.method
case _ => "GET"
}
def hasDirectLoginHeader(authorization: Box[String]): Boolean = hasHeader("DirectLogin", authorization)
def has2021DirectLoginHeader(requestHeaders: List[HTTPParam]): Boolean = requestHeaders.find(_.name.toLowerCase == "DirectLogin".toLowerCase()).isDefined
def hasAuthorizationHeader(requestHeaders: List[HTTPParam]): Boolean = requestHeaders.find(_.name == "Authorization").isDefined
def hasAnOAuthHeader(authorization: Box[String]): Boolean = hasHeader("OAuth", authorization)
/*
The OAuth 2.0 Authorization Framework: Bearer Token
For example, the "bearer" token type defined in [RFC6750] is utilized
by simply including the access token string in the request:
GET /resource/1 HTTP/1.1
Host: example.com
Authorization: Bearer mF_9.B5f-4.1JqM
*/
def hasAnOAuth2Header(authorization: Box[String]): Boolean = hasHeader("Bearer", authorization)
def hasGatewayHeader(authorization: Box[String]) = hasHeader("GatewayLogin", authorization)
/**
* The value `DAuth` is in the KEY
* DAuth:xxxxx
*
* Other types: the `GatewayLogin` is in the VALUE
* Authorization:GatewayLogin token=xxxx
*/
def hasDAuthHeader(requestHeaders: List[HTTPParam]) = requestHeaders.map(_.name).exists(_ ==DAuthHeaderKey)
/**
* Helper function which tells us does an "Authorization" request header field has the Type of an authentication scheme
* @param `type` Type of an authentication scheme
* @param authorization "Authorization" request header field defined by HTTP/1.1 [RFC2617]
* @return True or False i.e. does the "Authorization" request header field has the Type of the authentication scheme
*/
def hasHeader(`type`: String, authorization: Box[String]) : Boolean = {
authorization match {
case Full(a) if a.contains(`type`) => true
case _ => false
}
}
/**
* Purpose of this helper function is to get the Consent-JWT value from a Request Headers.
* @return the Consent-JWT value from a Request Header as a String
*/
def getConsentJWT(requestHeaders: List[HTTPParam]): Option[String] = {
requestHeaders.toSet.filter(_.name == RequestHeader.`Consent-JWT`).toList match {
case x :: Nil => Some(x.values.mkString(", "))
case _ => requestHeaders.toSet.filter(_.name == RequestHeader.`Consent-Id`).toList match {
case x :: Nil => Some(x.values.mkString(", "))
case _ => None
}
}
}
/**
* Purpose of this helper function is to get the Consent-JWT value from a Request Headers.
* @return the Consent-JWT value from a Request Header as a String
*/
def getConsentIdRequestHeaderValue(requestHeaders: List[HTTPParam]): Option[String] = {
requestHeaders.toSet.filter(_.name == RequestHeader.`Consent-Id`).toList match {
case x :: Nil => Some(x.values.mkString(", "))
case _ => None
}
}
/**
* Purpose of this helper function is to get the PSD2-CERT value from a Request Headers.
* @return the PSD2-CERT value from a Request Header as a String
*/
def `getPSD2-CERT`(requestHeaders: List[HTTPParam]): Option[String] = {
requestHeaders.toSet.filter(_.name == RequestHeader.`PSD2-CERT`).toList match {
case x :: Nil => Some(x.values.mkString(", "))
case _ => None
}
}
def getRequestHeader(name: String, requestHeaders: List[HTTPParam]): String = {
requestHeaders.toSet.filter(_.name.toLowerCase == name.toLowerCase).toList match {
case x :: Nil => x.values.mkString(";")
case _ => ""
}
}
def hasConsentJWT(requestHeaders: List[HTTPParam]): Boolean = {
getConsentJWT(requestHeaders).isDefined
}
/**
* Purpose of this helper function is to get the Consent-ID value from a Request Headers.
* This Request Header is related to Berlin Group.
* @return the Consent-ID value from a Request Header as a String
*/
def `getConsent-ID`(requestHeaders: List[HTTPParam]): Option[String] = {
requestHeaders.toSet.filter(_.name == RequestHeader.`Consent-ID`).toList match {
case x :: Nil => Some(x.values.mkString(", "))
case _ => None
}
}
def `hasConsent-ID`(requestHeaders: List[HTTPParam]): Boolean = {
`getConsent-ID`(requestHeaders).isDefined
}
def registeredApplication(consumerKey: String): Boolean = {
Consumers.consumers.vend.getConsumerByConsumerKey(consumerKey) match {
case Full(application) => application.isActive.get
case _ => false
}
}
def registeredApplicationFuture(consumerKey: String): Future[Boolean] = {
Consumers.consumers.vend.getConsumerByConsumerKeyFuture(consumerKey) map {
case Full(c) => c.isActive.get
case _ => false
}
}
/*
Return the git commit. If we can't for some reason (not a git root etc) then log and return ""
*/
lazy val gitCommit : String = {
val commit = try {
val properties = new java.util.Properties()
logger.debug("Before getResourceAsStream git.properties")
val stream = getClass().getClassLoader().getResourceAsStream("git.properties")
try {
properties.load(stream)
logger.debug("Before get Property git.commit.id")
properties.getProperty("git.commit.id", "")
} finally {
stream.close()
}
} catch {
case e : Throwable => {
logger.warn("gitCommit says: Could not return git commit. Does resources/git.properties exist?")
logger.error(s"Exception in gitCommit: $e")
"" // Return empty string
}
}
commit
}
// API info props helpers (keep values centralized)
lazy val hostedByOrganisation: String = getPropsValue("hosted_by.organisation", "TESOBE")
lazy val hostedByEmail: String = getPropsValue("hosted_by.email", "contact@tesobe.com")
lazy val hostedByPhone: String = getPropsValue("hosted_by.phone", "+49 (0)30 8145 3994")
lazy val organisationWebsite: String = getPropsValue("organisation_website", "https://www.tesobe.com")
lazy val hostedAtOrganisation: String = getPropsValue("hosted_at.organisation", "")
lazy val hostedAtOrganisationWebsite: String = getPropsValue("hosted_at.organisation_website", "")
lazy val energySourceOrganisation: String = getPropsValue("energy_source.organisation", "")
lazy val energySourceOrganisationWebsite: String = getPropsValue("energy_source.organisation_website", "")
lazy val resourceDocsRequiresRole: Boolean = getPropsAsBoolValue("resource_docs_requires_role", false)
/**
* Caching of unchanged resources
*
* Another typical use of the ETag header is to cache resources that are unchanged.
* If a user visits a given URL again (that has an ETag set), and it is stale (too old to be considered usable),
* the client will send the value of its ETag along in an If-None-Match header field:
*
* If-None-Match: "33a64df551425fcc55e4d42a148795d9f25f89d4"
*
* The server compares the client's ETag (sent with If-None-Match) with the ETag for its current version of the resource,
* and if both values match (that is, the resource has not changed), the server sends back a 304 Not Modified status,
* without a body, which tells the client that the cached version of the response is still good to use (fresh).
*/
private def checkIfNotMatchHeader(cc: Option[CallContext], httpCode: Int, httpBody: Box[String], headerValue: String): Int = {
val url = cc.map(_.url).getOrElse("")
val hash = HashUtil.calculateETag(url, httpBody)
if (httpCode == 200 && hash == headerValue) 304 else httpCode
}
// The If-Modified-Since request HTTP header makes the request conditional: the server sends back the requested resource,
// with a 200 status, only if it has been last modified after the given date.
// If the resource has not been modified since, the response is a 304 without any body;
// the Last-Modified response header of a previous request contains the date of last modification
private def checkIfModifiedSinceHeader(cc: Option[CallContext], httpVerb: String, httpCode: Int, httpBody: Box[String], headerValue: String): Int = {
def headerValueToMillis(): Long = {
var epochTime = 0L
// Create a DateFormat and set the timezone to GMT.
val df: SimpleDateFormat = new SimpleDateFormat(DateWithSeconds)
// df.setTimeZone(TimeZone.getTimeZone("GMT"))
try { // Convert string into Date, for instance: "2023-05-19T02:31:05Z"
epochTime = df.parse(headerValue).getTime()
} catch {
case e: ParseException => e.printStackTrace
}
epochTime
}
def asyncUpdate(row: MappedETag, hash: String): Future[Boolean] = {
Future { // Async update
row
.LastUpdatedMSSinceEpoch(System.currentTimeMillis)
.ETagValue(hash)
.save
}
}
def asyncCreate(cacheKey: String, hash: String): Future[Boolean] = {
Future { // Async create
tryo(MappedETag.create
.ETagResource(cacheKey)
.ETagValue(hash)
.LastUpdatedMSSinceEpoch(System.currentTimeMillis)
.save) match {
case Full(value) => value
case other =>
logger.debug(s"checkIfModifiedSinceHeader.asyncCreate($cacheKey, $hash)")
logger.debug(other)
false
}
}
}
val url = cc.map(_.url).getOrElse("")
val requestHeaders: List[HTTPParam] =
cc.map(_.requestHeaders.filter(i => i.name == "limit" || i.name == "offset").sortBy(_.name)).getOrElse(Nil)
val hashedRequestPayload = HashUtil.Sha256Hash(url + requestHeaders)
val consumerId = cc.map(i => i.consumer.map(_.consumerId.get).getOrElse("None")).getOrElse("None")
val userId = tryo(cc.map(i => i.userId).toBox).flatten.getOrElse("None")
val correlationId: String = tryo(cc.map(i => i.correlationId).toBox).flatten.getOrElse("None")
val compositeKey =
if(consumerId == "None" && userId == "None") {
"anonymous"
} else {
s"""consumerId${consumerId}::userId${userId}"""
}
val cacheKey = s"""$compositeKey::${hashedRequestPayload}"""
val eTag = HashUtil.calculateETag(url, httpBody)
if(httpVerb.toUpperCase() == "GET" || httpVerb.toUpperCase() == "HEAD") { // If-Modified-Since can only be used with a GET or HEAD
val validETag = MappedETag.find(By(MappedETag.ETagResource, cacheKey)) match {
case Full(row) if row.lastUpdatedMSSinceEpoch < headerValueToMillis() =>
val modified = row.eTagValue != eTag
if(modified) {
asyncUpdate(row, eTag)
false // ETAg is outdated
} else {
true // ETAg is up to date
}
case Empty =>
asyncCreate(cacheKey, eTag)
false // There is no ETAg at all
case _ =>
false // In case of any issue we consider ETAg as outdated
}
if (validETag) // Response has not been changed since our previous call
304
else
httpCode
} else {
httpCode
}
}
private def checkConditionalRequest(cc: Option[CallContext], httpVerb: String, httpCode: Int, httpBody: Box[String]) = {
val requestHeaders: List[HTTPParam] = cc.map(_.requestHeaders).getOrElse(Nil)
requestHeaders.filter(_.name == RequestHeader.`If-None-Match` ).headOption match {
case Some(value) => // Handle the If-None-Match HTTP request header
checkIfNotMatchHeader(cc, httpCode, httpBody, value.values.mkString(""))
case None =>
// When used in combination with If-None-Match, it is ignored, unless the server doesn't support If-None-Match.
// The most common use case is to update a cached entity that has no associated ETag
requestHeaders.filter(_.name == RequestHeader.`If-Modified-Since` ).headOption match {
case Some(value) => // Handle the If-Modified-Since HTTP request header
checkIfModifiedSinceHeader(cc, httpVerb, httpCode, httpBody, value.values.mkString(""))
case None =>
httpCode
}
}
}
private def getHeadersNewStyle(cc: Option[CallContextLight]) = {
CustomResponseHeaders(
getGatewayLoginHeader(cc).list :::
getRequestHeadersBerlinGroup(cc).list :::
getRateLimitHeadersNewStyle(cc).list :::
getPaginationHeadersNewStyle(cc).list :::
getRequestHeadersToMirror(cc).list :::
getRequestHeadersToEcho(cc).list
)
}
private def getRateLimitHeadersNewStyle(cc: Option[CallContextLight]) = {
(cc, RateLimitingUtil.useConsumerLimits) match {
case (Some(x), true) =>
CustomResponseHeaders(
List(
("X-Rate-Limit-Reset", x.xRateLimitReset.toString),
("X-Rate-Limit-Remaining", x.xRateLimitRemaining.toString),
("X-Rate-Limit-Limit", x.xRateLimitLimit.toString)
)
)
case _ =>
CustomResponseHeaders((Nil))
}
}
private def getPaginationHeadersNewStyle(cc: Option[CallContextLight]) = {
cc match {
case Some(x) if x.paginationLimit.isDefined && x.paginationOffset.isDefined =>
CustomResponseHeaders(
List(("Range", s"items=${x.paginationOffset.getOrElse("")}-${x.paginationLimit.getOrElse("")}"))
)
case _ =>
CustomResponseHeaders(Nil)
}
}
private def getSignRequestHeadersNewStyle(cc: Option[CallContext], httpBody: Box[String]): CustomResponseHeaders = {
cc.map { i =>
if(JwsUtil.forceVerifyRequestSignResponse(i.url)) {
val headers = JwsUtil.signResponse(httpBody, i.verb, i.url, "application/json;charset=utf-8")
CustomResponseHeaders(headers.map(h => (h.name, h.values.mkString(", "))))
} else {
CustomResponseHeaders(Nil)
}
}.getOrElse(CustomResponseHeaders(Nil))
}
private def getRequestHeadersNewStyle(cc: Option[CallContext], httpBody: Box[String]): CustomResponseHeaders = {
cc.map { i =>
val hash = HashUtil.calculateETag(i.url, httpBody)
CustomResponseHeaders(
List(
(ResponseHeader.ETag, hash)
// Cache-Control is set per-endpoint via implicit CustomResponseHeaders where appropriate
// (e.g. getApiGlossary sets max-age=3600 for static content)
)
)
}.getOrElse(CustomResponseHeaders(Nil))
}
private def getSignRequestHeadersError(cc: Option[CallContextLight], httpBody: String): CustomResponseHeaders = {
cc.map { i =>
if(JwsUtil.forceVerifyRequestSignResponse(i.url)) {
val headers = JwsUtil.signResponse(Full(httpBody), i.verb, i.url, "application/json;charset=utf-8")
CustomResponseHeaders(headers.map(h => (h.name, h.values.mkString(", "))))
} else {
CustomResponseHeaders(Nil)
}
}.getOrElse(CustomResponseHeaders(Nil))
}
/**
*
*/
def getRequestHeadersToMirror(callContext: Option[CallContextLight]): CustomResponseHeaders = {
val mirrorByProperties = getPropsValue("mirror_request_headers_to_response", "").split(",").toList.map(_.trim)
val mirrorRequestHeadersToResponse: List[String] =
if (callContext.exists(_.url.contains(ConstantsBG.berlinGroupVersion1.urlPrefix))) {
// Berlin Group Specification
RequestHeader.`X-Request-ID` :: mirrorByProperties
} else {
mirrorByProperties
}
callContext match {
case Some(cc) =>
cc.requestHeaders match {
case Nil => CustomResponseHeaders(Nil)
case _ =>
val headers = cc.requestHeaders
.filter(item => mirrorRequestHeadersToResponse.contains(item.name))
.map(item => (item.name, item.values.headOption.getOrElse(""))) // Safe extraction
CustomResponseHeaders(headers)
}
case None =>
CustomResponseHeaders(Nil)
}
}
/**
*
*/
def getRequestHeadersToEcho(callContext: Option[CallContextLight]): CustomResponseHeaders = {
val echoRequestHeaders: Boolean =
getPropsAsBoolValue("echo_request_headers", defaultValue = false)
(callContext, echoRequestHeaders) match {
case (Some(cc), true) =>
CustomResponseHeaders(cc.requestHeaders.map(item => (s"echo_${item.name}", item.values.head)))
case _ =>
CustomResponseHeaders(Nil)
}
}
def getRequestHeadersBerlinGroup(callContext: Option[CallContextLight]): CustomResponseHeaders = {
val aspspScaApproach = getPropsValue("berlin_group_aspsp_sca_approach", defaultValue = "redirect")
logger.debug(s"ConstantsBG.berlinGroupVersion1.urlPrefix: ${ConstantsBG.berlinGroupVersion1.urlPrefix}")
logger.debug(s"callContext.map(_.url): ${callContext.map(_.url)}")
callContext match {
case Some(cc) if cc.url.contains(ConstantsBG.berlinGroupVersion1.urlPrefix) && cc.url.endsWith("/consents") =>
CustomResponseHeaders(List(
(ResponseHeader.`ASPSP-SCA-Approach`, aspspScaApproach)
))
case _ =>
CustomResponseHeaders(Nil)
}
}
/**
*
* @param jwt is a JWT value extracted from GatewayLogin Authorization Header.
* Value None implies that Authorization Header is NOT GatewayLogin
* @return GatewayLogin Custom Response Header
* Example of the Header in Response generated by this function:
* GatewayLogin: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJsb2dpbl91c2VyX25hbWUiOiJON2p1dDhkIiwiaXNfZmlyc3QiOmZhbHNlLCJhcHBfaWQiOiIxMjMiLCJhcHBfbmFtZSI6Ik5hbWUgb2YgQ29uc3VtZXIiLCJ0aW1lc3RhbXAiOiIiLCJjYnNfdG9rZW4iOiI-LD8gICAgICAgICAgODE0MzMwMjAxMDI2MTIiLCJ0ZW1lbm9zX2lkIjoiIn0.saE7W-ydZcwbjxfWx7q6HeQ1q4LMLYZiuYSx7qdP0k8
*/
def getGatewayLoginHeader(jwt: Option[CallContextLight]) = {
jwt match {
case Some(v) =>
v.gatewayLoginResponseHeader match {
case Some(h) =>
val header = (gatewayResponseHeaderName, h)
CustomResponseHeaders(List(header))
case None =>
CustomResponseHeaders(Nil)
}
case None =>
CustomResponseHeaders(Nil)
}
}
/** This function provide a name of parameter used to define different spelling of some words
* E.g. if we provide an URL obp/v2.1.0/users/current/customers?format=ISO20022
* JSON response is changed from "currency":"EUR" to "ccy":"EUR"
*
* @return A name of the parameter
*/
def nameOfSpellingParam(): String = "spelling"
def getSpellingParam(): Box[String] = {
S.request match {
case Full(r) =>
r.header(nameOfSpellingParam()) match {
case Full(h) =>
Full(h)
case _ =>
ObpS.param(nameOfSpellingParam())
}
case _ =>
ObpS.param(nameOfSpellingParam())
}
}
def getHeadersCommonPart() = headers ::: List((ResponseHeader.`Correlation-Id`, getCorrelationId()))
def getHeaders() = getHeadersCommonPart() ::: getGatewayResponseHeader()
case class CustomResponseHeaders(list: List[(String, String)])
//This is used for get the value from props `email_domain_to_space_mappings`
case class EmailDomainToSpaceMapping(
domain: String,
bank_ids: List[String]
)
//This is used for get the value from props `skip_consent_sca_for_consumer_id_pairs`
case class ConsumerIdPair(
grantor_consumer_id: String,
grantee_consumer_id: String
)
case class EmailDomainToEntitlementMapping(
domain: String,
entitlements: List[CreateEntitlementJSON]
)
//Note: changed noContent--> defaultSuccess, because of the Swagger format. (Not support empty in DataType, maybe fix it latter.)
def noContentJsonResponse(implicit headers: CustomResponseHeaders = CustomResponseHeaders(Nil)) : JsonResponse =
JsonResponse(JsRaw(""), getHeaders() ::: headers.list, Nil, 204)
def successJsonResponse(json: JsonAST.JValue, httpCode : Int = 200)(implicit headers: CustomResponseHeaders = CustomResponseHeaders(Nil)) : JsonResponse = {
val cc = ApiSession.updateCallContext(Spelling(getSpellingParam()), None)
val jsonAst = ApiSession.processJson(json, cc)
JsonResponse(jsonAst, getHeaders() ::: headers.list, Nil, httpCode)
}
def createdJsonResponse(json: JsonAST.JValue, httpCode : Int = 201)(implicit headers: CustomResponseHeaders = CustomResponseHeaders(Nil)) : JsonResponse = {
val cc = ApiSession.updateCallContext(Spelling(getSpellingParam()), None)
val jsonAst = ApiSession.processJson(json, cc)
JsonResponse(jsonAst, getHeaders() ::: headers.list, Nil, httpCode)
}
// exclude all values that defined in props "excluded.response.field.values"
val excludedFieldValues = APIUtil.getPropsValue("excluded.response.field.values").map[JArray](it => json.parse(it).asInstanceOf[JArray])
def successJsonResponseNewStyle(cc: Any, callContext: Option[CallContext], httpCode : Int = 200)(implicit headers: CustomResponseHeaders = CustomResponseHeaders(Nil)) : JsonResponse = {
val jsonAst: JValue = {
val partialFunctionName = callContext.map(_.resourceDocument.map(_.partialFunctionName)).flatten.getOrElse("")
if (
nameOf(code.api.v5_1_0.APIMethods510.Implementations5_1_0.getMetrics).equals(partialFunctionName) ||
nameOf(code.api.v5_0_0.APIMethods500.Implementations5_0_0.getMetricsAtBank).equals(partialFunctionName) ||
nameOf(Implementations2_2_0.getConnectorMetrics).equals(partialFunctionName)
) {
ApiSession.processJson(Extraction.decompose(cc)(CustomJsonFormats.losslessFormats), callContext)
} else {
ApiSession.processJson((Extraction.decompose(cc)), callContext)
}
}
val excludeOptionalFieldsParam = getHttpRequestUrlParam(callContext.map(_.url).getOrElse(""),"exclude-optional-fields")
val excludedResponseBehaviour = APIUtil.getPropsAsBoolValue("excluded.response.behaviour", false)
//excludeOptionalFieldsParamValue has top priority, then the excludedResponseBehaviour props.
val jsonValue = excludedFieldValues match {
case Full(JArray(arr:List[JValue])) if (excludeOptionalFieldsParam.equalsIgnoreCase("true") || (excludeOptionalFieldsParam.equalsIgnoreCase("") && excludedResponseBehaviour))=>
JsonUtils.deleteFieldRec(jsonAst)(v => arr.contains(v.value))
case _ => jsonAst
}
callContext match {
case Some(c) if c.httpCode.isDefined && c.httpCode.get == 204 =>
val httpBody = None
val jwsHeaders = getSignRequestHeadersNewStyle(callContext,httpBody).list
val responseHeaders = getRequestHeadersNewStyle(callContext,httpBody).list
JsonResponse(JsRaw(""), getHeaders() ::: headers.list ::: jwsHeaders ::: responseHeaders, Nil, 204)
case Some(c) if c.httpCode.isDefined =>
val httpBody = Full(JsonAST.compactRender(jsonValue))
val jwsHeaders = getSignRequestHeadersNewStyle(callContext,httpBody).list
val responseHeaders = getRequestHeadersNewStyle(callContext,httpBody).list
val code = checkConditionalRequest(callContext, c.verb, c.httpCode.get, httpBody)
if(code == 304)
JsonResponse(JsRaw(""), getHeaders() ::: headers.list ::: jwsHeaders ::: responseHeaders, Nil, code)
else
JsonResponse(jsonValue, getHeaders() ::: headers.list ::: jwsHeaders ::: responseHeaders, Nil, code)
case Some(c) if c.verb.toUpperCase() == "DELETE" =>
val httpBody = None
val jwsHeaders = getSignRequestHeadersNewStyle(callContext,httpBody).list
val responseHeaders = getRequestHeadersNewStyle(callContext,httpBody).list
JsonResponse(JsRaw(""), getHeaders() ::: headers.list ::: jwsHeaders ::: responseHeaders, Nil, 204)
case _ =>
val httpBody = Full(JsonAST.compactRender(jsonValue))
val jwsHeaders = getSignRequestHeadersNewStyle(callContext,httpBody).list
val responseHeaders = getRequestHeadersNewStyle(callContext,httpBody).list
JsonResponse(jsonValue, getHeaders() ::: headers.list ::: jwsHeaders ::: responseHeaders, Nil, httpCode)
}
}
def acceptedJsonResponse(json: JsonAST.JValue, httpCode : Int = 202)(implicit headers: CustomResponseHeaders = CustomResponseHeaders(Nil)) : JsonResponse = {
val cc = ApiSession.updateCallContext(Spelling(getSpellingParam()), None)
val jsonAst = ApiSession.processJson(json, cc)
JsonResponse(jsonAst, getHeaders() ::: headers.list, Nil, httpCode)
}
def errorJsonResponse(message : String = "error", httpCode : Int = 400, callContextLight: Option[CallContextLight] = None)(implicit headers: CustomResponseHeaders = CustomResponseHeaders(Nil)) : JsonResponse = {
def check403(message: String): Boolean = {
message.contains(extractErrorMessageCode(UserHasMissingRoles)) ||
message.contains(extractErrorMessageCode(UserNoPermissionAccessView)) ||
message.contains(extractErrorMessageCode(UserHasMissingRoles)) ||
message.contains(extractErrorMessageCode(UserNotSuperAdminOrMissRole)) ||
message.contains(extractErrorMessageCode(ConsumerHasMissingRoles))
}
def check401(message: String): Boolean = {
message.contains(extractErrorMessageCode(AuthenticatedUserIsRequired))
}
def check408(message: String): Boolean = {
message.contains(extractErrorMessageCode(requestTimeout))
}
val (code, responseHeaders) =
message match {
case msg if check401(msg) =>
val host = Constant.HostName
val headerValue = s"""OAuth realm="$host", Bearer realm="$host", DirectLogin realm="$host""""
val addHeader = List((ResponseHeader.`WWW-Authenticate`, headerValue))
(401, getHeaders() ::: headers.list ::: addHeader)
case msg if check403(msg) =>
(403, getHeaders() ::: headers.list)
case msg if check408(msg) =>
(408, getHeaders() ::: headers.list ::: List((ResponseHeader.Connection, "close")))
case _ =>
(httpCode, getHeaders() ::: headers.list)
}
def composeErrorMessage() = {
val path = callContextLight.map(_.url).getOrElse("")
if (path.contains(ConstantsBG.berlinGroupVersion1.urlPrefix)) {
val path =
if(APIUtil.getPropsAsBoolValue("berlin_group_error_message_show_path", defaultValue = true))
callContextLight.map(_.url)
else
None
val codeText = BerlinGroupError.translateToBerlinGroupError(code.toString, message)
val errorMessagesBG = ErrorMessagesBG(tppMessages = List(ErrorMessageBG(category = "ERROR", code = codeText, path = path, text = message)))
Extraction.decompose(errorMessagesBG)
} else {
Extraction.decompose(ErrorMessage(message = message, code = code))
}
}
val errorMessageAst: json.JValue = composeErrorMessage()
val httpBody = JsonAST.compactRender(errorMessageAst)
val jwsHeaders: CustomResponseHeaders = getSignRequestHeadersError(callContextLight, httpBody)
JsonResponse(errorMessageAst, responseHeaders ::: jwsHeaders.list, Nil, code)
}
def notImplementedJsonResponse(message : String = ErrorMessages.NotImplemented, httpCode : Int = 501)(implicit headers: CustomResponseHeaders = CustomResponseHeaders(Nil)) : JsonResponse =
JsonResponse(Extraction.decompose(ErrorMessage(message = message, code = httpCode)), getHeaders() ::: headers.list, Nil, httpCode)
def oauthHeaderRequiredJsonResponse(implicit headers: CustomResponseHeaders = CustomResponseHeaders(Nil)) : JsonResponse =
JsonResponse(Extraction.decompose(ErrorMessage(message = "Authentication via OAuth is required", code = 400)), getHeaders() ::: headers.list, Nil, 400)
lazy val CurrencyIsoCodeFromXmlFile: Elem = LiftRules.getResource("/media/xml/ISOCurrencyCodes.xml").map{ url =>
val input: InputStream = url.openStream()
val xml = XML.load(input)
if (input != null) input.close()
xml
}.openOrThrowException(s"$UnknownError,ISOCurrencyCodes.xml is missing in OBP server. ")
/** check the currency ISO code from the ISOCurrencyCodes.xml file */
def isValidCurrencyISOCode(currencyCode: String): Boolean = {
// Note: We add BTC bitcoin as XBT (the ISO compliant varient)
val currencyIsoCodeArray = (CurrencyIsoCodeFromXmlFile \"CcyTbl" \ "CcyNtry" \ "Ccy").map(_.text).mkString(" ").split("\\s+") :+ "XBT"
currencyIsoCodeArray.contains(currencyCode)
}
/** Check the id values from GUI, such as ACCOUNT_ID, BANK_ID ... */
def isValidID(id :String):Boolean= {
val regex = """^([A-Za-z0-9\-_.]+)$""".r
id match {
case regex(e) if(e.length<256) => true
case _ => false
}
}
/** enforce the password.
* The rules :
* 1) length is >16 characters without validations but max length <= 512
* 2) or Min 10 characters with mixed numbers + letters + upper+lower case + at least one special character.
* */
def fullPasswordValidation(password: String): Boolean = {
/**
* (?=.*\d) //should contain at least one digit
* (?=.*[a-z]) //should contain at least one lower case
* (?=.*[A-Z]) //should contain at least one upper case
* (?=.*[!\"#$%&'\(\)*+,-./:;<=>?@\\[\\\\]^_\\`{|}~\[\]]) //should contain at least one special character
* ([A-Za-z0-9!\"#$%&'\(\)*+,-./:;<=>?@\\[\\\\]^_\\`{|}~\[\]]{10,16}) //should contain 10 to 16 valid characters
**/
val regex =
"""^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[!\"#$%&'\(\)*+,-./:;<=>?@\\[\\\\]^_\\`{|}~\[\]])([A-Za-z0-9!\"#$%&'\(\)*+,-./:;<=>?@\\[\\\\]^_\\`{|}~\[\]]{10,16})$""".r
// first check `basicPasswordValidation`
if (basicPasswordValidation(password) != SILENCE_IS_GOLDEN) {
return false
}
// 2nd: check the password length between 17 and 512
if (password.length > 16 && password.length <= 512) {
return true
}
// 3rd: check the regular expression
regex.pattern.matcher(password).matches()
}
/** only A-Z, a-z, 0-9,-,_,. =, & and max length <= 2048 */
def basicUriAndQueryStringValidation(urlString: String): Boolean = {
val regex =
"""^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?""".r
val decodeUrlValue = URLDecoder.decode(urlString, "UTF-8").trim()
decodeUrlValue match {
case regex(_*) if (decodeUrlValue.length <= 2048) => true
case _ => false
}
}
/** These three functions check rather than assert. I.e. they are silent if OK and return an error message if not.
* They do not throw an exception on failure thus they are not assertions
*/
/** only A-Z, a-z and max length <= 512 */
def checkMediumAlpha(value:String): String ={
val valueLength = value.length
val regex = """^([A-Za-z]+)$""".r
value match {
case regex(e) if(valueLength <= 512) => SILENCE_IS_GOLDEN
case regex(e) if(valueLength > 512) => ErrorMessages.InvalidValueLength
case _ => ErrorMessages.InvalidValueCharacters
}
}
/** only A-Z, a-z, 0-9 and max length <= 512 */
def basicConsumerKeyValidation(value:String): String ={
val valueLength = value.length
val regex = """^([A-Za-z0-9-]+)$""".r
value match {
case regex(e) if(valueLength <= 512) => SILENCE_IS_GOLDEN
case regex(e) if(valueLength > 512) => ErrorMessages.ConsumerKeyIsToLong
case _ => ErrorMessages.ConsumerKeyIsInvalid
}
}
/** only support en_GB, es_ES at the moment, will support more later*/
def obpLocaleValidation(value:String): String ={
if(value.equalsIgnoreCase("es_Es") || value.equalsIgnoreCase("ro_RO") || value.equalsIgnoreCase("en_GB"))
SILENCE_IS_GOLDEN
else
ErrorMessages.InvalidLocale
}
/** only A-Z, a-z, 0-9, all allowed characters for password and max length <= 512 */
/** also support space now */
def basicPasswordValidation(value:String): String ={
val valueLength = value.length
val regex = """^([A-Za-z0-9!\"#$%&'\(\)*+,-./:;<=>?@\\[\\\\]^_\\`{|}~ \[\]]+)$""".r
if (!regex.pattern.matcher(value).matches()) {
return ErrorMessages.InvalidValueCharacters
}
if (valueLength > 512) {
return ErrorMessages.InvalidValueLength
}
SILENCE_IS_GOLDEN
}
/** only A-Z, a-z, 0-9, -, _, ., @, and max length <= 512 */
def checkMediumString(value:String): String ={
val valueLength = value.length
val regex = """^([A-Za-z0-9\-._@]+)$""".r
value match {
case regex(e) if(valueLength <= 512) => SILENCE_IS_GOLDEN
case regex(e) if(valueLength > 512) => ErrorMessages.InvalidValueLength
case _ => ErrorMessages.InvalidValueCharacters
}
}
/** only A-Z, a-z, 0-9, -, _, ., and max length <= 16. NOTE: This function requires at least ONE character (+ in the regx). If you want to accept zero characters use checkOptionalShortString. */
def checkShortString(value:String): String ={
val valueLength = value.length
val regex = """^([A-Za-z0-9\-._]+)$""".r
value match {
case regex(e) if(valueLength <= 16) => SILENCE_IS_GOLDEN
case regex(e) if(valueLength > 16) => ErrorMessages.InvalidValueLength
case _ => ErrorMessages.InvalidValueCharacters
}
}
/** only A-Z, a-z, 0-9, -, _, ., and max length <= 16, allows empty string */
def checkOptionalShortString(value:String): String ={
val valueLength = value.length
val regex = """^([A-Za-z0-9\-._]*)$""".r
value match {
case regex(e) if(valueLength <= 16) => SILENCE_IS_GOLDEN
case regex(e) if(valueLength > 16) => ErrorMessages.InvalidValueLength
case _ => ErrorMessages.InvalidValueCharacters
}
}
/** only A-Z, a-z, 0-9, -, _, ., and max length <= 36
* OBP APIUtil.generateUUID() length is 36 here.*/
def checkObpId(value:String): String ={
val valueLength = value.length
val regex = """^([A-Za-z0-9\-._]+)$""".r
value match {
case _ if value.isEmpty => SILENCE_IS_GOLDEN
case regex(e) if(valueLength <= 36) => SILENCE_IS_GOLDEN
case regex(e) if(valueLength > 36) => ErrorMessages.InvalidValueLength+" The maximum OBP id length is 36. "
case _ => ErrorMessages.InvalidValueCharacters + " only A-Z, a-z, 0-9, -, _, ., and max length <= 36 "
}
}
/** only A-Z, a-z, 0-9, -, _, ., @, space and max length <= 512 */
def checkUsernameString(value:String): String ={
val valueLength = value.length
val regex = """^([A-Za-z0-9\-._@ ]+)$""".r
value match {
case regex(e) if(valueLength <= 512) => SILENCE_IS_GOLDEN
case regex(e) if(valueLength > 512) => ErrorMessages.InvalidValueLength
case _ => ErrorMessages.InvalidValueCharacters
}
}
def ValueOrOBP(text : String) =
text match {
case t if t == null => "OBP"
case t if t.length > 0 => t
case _ => "OBP"
}
def ValueOrOBPId(text : String, OBPId: String) =
text match {
case t if t == null => OBPId
case t if t.length > 0 => t
case _ => OBPId
}