Skip to content

Commit

Permalink
Merge pull request #2265 from constantine2nd/develop
Browse files Browse the repository at this point in the history
New Style
  • Loading branch information
simonredfern authored Sep 13, 2023
2 parents accc477 + 0929819 commit 04c837e
Show file tree
Hide file tree
Showing 11 changed files with 235 additions and 135 deletions.
2 changes: 1 addition & 1 deletion obp-api/src/main/resources/props/sample.props.template
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,7 @@ read_authentication_type_validation_requires_role=false
## Define endpoint timeouts in miliseconds
short_endpoint_timeout = 1000
medium_endpoint_timeout = 7000
long_endpoint_timeout = 60000
long_endpoint_timeout = 55000

##Added Props property_name_prefix, default is OBP_. This adds the prefix only for the system environment property name, eg: db.driver --> OBP_db.driver
#system_environment_property_name_prefix=OBP_
Expand Down
2 changes: 1 addition & 1 deletion obp-api/src/main/scala/code/api/constant/constant.scala
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ object Constant extends MdcLoggable {

final val shortEndpointTimeoutInMillis = APIUtil.getPropsAsLongValue(nameOfProperty = "short_endpoint_timeout", 1L * 1000L)
final val mediumEndpointTimeoutInMillis = APIUtil.getPropsAsLongValue(nameOfProperty = "medium_endpoint_timeout", 7L * 1000L)
final val longEndpointTimeoutInMillis = APIUtil.getPropsAsLongValue(nameOfProperty = "long_endpoint_timeout", 60L * 1000L)
final val longEndpointTimeoutInMillis = APIUtil.getPropsAsLongValue(nameOfProperty = "long_endpoint_timeout", 55L * 1000L)

final val h2DatabaseDefaultUrlValue = "jdbc:h2:mem:OBPTest_H2_v2.1.214;NON_KEYWORDS=VALUE;DB_CLOSE_DELAY=10"

Expand Down
3 changes: 3 additions & 0 deletions obp-api/src/main/scala/code/api/util/ErrorMessages.scala
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,9 @@ object ErrorMessages {

val ScaMethodNotDefined = "OBP-10030: Strong customer authentication method is not defined at this instance."

val createFxCurrencyIssue = "OBP-10050: Cannot create FX currency. "




// Authentication / Authorisation / User messages (OBP-20XXX)
Expand Down
22 changes: 22 additions & 0 deletions obp-api/src/main/scala/code/api/util/NewStyle.scala
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,14 @@ object NewStyle extends MdcLoggable{
x => fullBoxOrException(x ~> APIFailureNewStyle(BranchNotFoundByBranchId, 400, callContext.map(_.toLight)))
} map { unboxFull(_) }
}

def createOrUpdateBranch(branch: BranchT, callContext: Option[CallContext]): Future[BranchT] = {
Future {
Connector.connector.vend.createOrUpdateBranch(branch)
} map {
unboxFullOrFail(_, callContext, ErrorMessages.CountNotSaveOrUpdateResource + " Branch", 400)
}
}

/**
* delete a branch, just set isDeleted field to true, marks it is deleted
Expand Down Expand Up @@ -2222,6 +2230,20 @@ object NewStyle extends MdcLoggable{
unboxFullOrFail(_, callContext, FXCurrencyCodeCombinationsNotSupported)
}

def createOrUpdateFXRate(bankId: String,
fromCurrencyCode: String,
toCurrencyCode: String,
conversionValue: Double,
inverseConversionValue: Double,
effectiveDate: Date,
callContext: Option[CallContext]
): Future[FXRate] =
Future(
Connector.connector.vend.createOrUpdateFXRate(bankId, fromCurrencyCode, toCurrencyCode, conversionValue, inverseConversionValue, effectiveDate)
) map {
unboxFullOrFail(_, callContext, createFxCurrencyIssue)
}

def createMeeting(
bankId: BankId,
staffUser: User,
Expand Down
150 changes: 96 additions & 54 deletions obp-api/src/main/scala/code/api/v1_2_1/APIMethods121.scala

Large diffs are not rendered by default.

11 changes: 6 additions & 5 deletions obp-api/src/main/scala/code/api/v1_4_0/APIMethods140.scala
Original file line number Diff line number Diff line change
Expand Up @@ -110,20 +110,21 @@ trait APIMethods140 extends MdcLoggable with APIMethods130 with APIMethods121{
emptyObjectJson,
customerMessagesJson,
List(UserNotLoggedIn, UnknownError),
List(apiTagMessage, apiTagCustomer, apiTagOldStyle))
List(apiTagMessage, apiTagCustomer))

lazy val getCustomersMessages : OBPEndpoint = {
case "banks" :: BankId(bankId) :: "customer" :: "messages" :: Nil JsonGet _ => {
cc =>{
cc => {
implicit val ec = EndpointContext(Some(cc))
for {
u <- cc.user ?~! ErrorMessages.UserNotLoggedIn
(bank, callContext ) <- BankX(bankId, Some(cc)) ?~! {ErrorMessages.BankNotFound}
(Full(u), callContext) <- authenticatedAccess(cc)
(_, callContext) <- NewStyle.function.getBank(bankId, callContext)
//au <- ResourceUser.find(By(ResourceUser.id, u.apiId))
//role <- au.isCustomerMessageAdmin ~> APIFailure("User does not have sufficient permissions", 401)
} yield {
val messages = CustomerMessages.customerMessageProvider.vend.getMessages(u, bankId)
val json = JSONFactory1_4_0.createCustomerMessagesJson(messages)
successJsonResponse(Extraction.decompose(json))
(json, HttpCode.`200`(callContext))
}
}
}
Expand Down
50 changes: 26 additions & 24 deletions obp-api/src/main/scala/code/api/v2_0_0/APIMethods200.scala
Original file line number Diff line number Diff line change
Expand Up @@ -1232,7 +1232,7 @@ trait APIMethods200 {
emptyObjectJson,
transactionTypesJsonV200,
List(BankNotFound, UnknownError),
List(apiTagBank, apiTagPSD2AIS, apiTagPsd2, apiTagOldStyle)
List(apiTagBank, apiTagPSD2AIS, apiTagPsd2)
)

lazy val getTransactionTypes : OBPEndpoint = {
Expand Down Expand Up @@ -1532,41 +1532,43 @@ trait APIMethods200 {
createUserJson,
userJsonV200,
List(UserNotLoggedIn, InvalidJsonFormat, InvalidStrongPasswordFormat ,"Error occurred during user creation.", "User with the same username already exists." , UnknownError),
List(apiTagUser, apiTagOnboarding, apiTagOldStyle))
List(apiTagUser, apiTagOnboarding))

lazy val createUser: OBPEndpoint = {
case "users" :: Nil JsonPost json -> _ => {
cc =>
cc => implicit val ec = EndpointContext(Some(cc))
for {
postedData <- tryo {json.extract[CreateUserJson]} ?~! ErrorMessages.InvalidJsonFormat
_ <- tryo(assert(fullPasswordValidation(postedData.password))) ?~! ErrorMessages.InvalidStrongPasswordFormat
} yield {
if (AuthUser.find(By(AuthUser.username, postedData.username)).isEmpty) {
val userCreated = AuthUser.create
postedData <- NewStyle.function.tryons(ErrorMessages.InvalidJsonFormat, 400, cc.callContext) {
json.extract[CreateUserJson]
}
_ <- Helper.booleanToFuture(ErrorMessages.InvalidStrongPasswordFormat, 400, cc.callContext) {
fullPasswordValidation(postedData.password)
}
_ <- Helper.booleanToFuture("User with the same username already exists.", 409, cc.callContext) {
AuthUser.find(By(AuthUser.username, postedData.username)).isEmpty
}
userCreated <- Future {
AuthUser.create
.firstName(postedData.first_name)
.lastName(postedData.last_name)
.username(postedData.username)
.email(postedData.email)
.password(postedData.password)
.validated(APIUtil.getPropsAsBoolValue("user_account_validated", false))
if(userCreated.validate.size > 0){
Full(errorJsonResponse(userCreated.validate.map(_.msg).mkString(";")))
}
else
{
userCreated.saveMe()
if (userCreated.saved_?) {
AuthUser.grantDefaultEntitlementsToAuthUser(userCreated)
val json = JSONFactory200.createUserJSONfromAuthUser(userCreated)
successJsonResponse(Extraction.decompose(json), 201)
}
else
Full(errorJsonResponse("Error occurred during user creation."))
}
}
else {
Full(errorJsonResponse("User with the same username already exists.", 409))
_ <- Helper.booleanToFuture(userCreated.validate.map(_.msg).mkString(";"), 400, cc.callContext) {
userCreated.validate.size == 0
}
savedUser <- NewStyle.function.tryons(ErrorMessages.InvalidJsonFormat, 400, cc.callContext) {
userCreated.saveMe()
}
_ <- Helper.booleanToFuture("Error occurred during user creation.", 400, cc.callContext) {
userCreated.saved_?
}
} yield {
AuthUser.grantDefaultEntitlementsToAuthUser(savedUser)
val json = JSONFactory200.createUserJSONfromAuthUser(userCreated)
(json, HttpCode.`201`(cc.callContext))
}
}
}
Expand Down
53 changes: 34 additions & 19 deletions obp-api/src/main/scala/code/api/v2_2_0/APIMethods220.scala
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
package code.api.v2_2_0

import java.util.Date

import code.api.ResourceDocs1_4_0.SwaggerDefinitionsJSON._
import code.api.util.APIUtil._
import code.api.util.ApiRole.{canCreateBranch, _}
import code.api.util.ApiTag._
import code.api.util.ErrorMessages.{BankAccountNotFound, _}
import code.api.util.FutureUtil.EndpointContext
import code.api.util.NewStyle.HttpCode
import code.api.util.{ErrorMessages, _}
import code.api.v1_2_1.{CreateViewJsonV121, UpdateViewJsonV121}
Expand Down Expand Up @@ -97,7 +99,7 @@ trait APIMethods220 {
lazy val getViewsForBankAccount : OBPEndpoint = {
//get the available views on an bank account
case "banks" :: BankId(bankId) :: "accounts" :: AccountId(accountId) :: "views" :: Nil JsonGet _ => {
cc =>
cc => implicit val ec = EndpointContext(Some(cc))
for {
(Full(u), callContext) <- authenticatedAccess(cc)
(account, callContext) <- NewStyle.function.checkBankAccountExists(bankId, accountId, callContext)
Expand Down Expand Up @@ -278,7 +280,7 @@ trait APIMethods220 {

lazy val getCurrentFxRate: OBPEndpoint = {
case "banks" :: BankId(bankId) :: "fx" :: fromCurrencyCode :: toCurrencyCode :: Nil JsonGet _ => {
cc =>
cc => implicit val ec = EndpointContext(Some(cc))
for {
(_, callContext) <- getCurrentFxRateIsPublic match {
case false => authenticatedAccess(cc)
Expand Down Expand Up @@ -326,7 +328,7 @@ trait APIMethods220 {

lazy val getExplictCounterpartiesForAccount : OBPEndpoint = {
case "banks" :: BankId(bankId) :: "accounts" :: AccountId(accountId) :: ViewId(viewId) :: "counterparties" :: Nil JsonGet req => {
cc =>
cc => implicit val ec = EndpointContext(Some(cc))
for {
(Full(u), callContext) <- authenticatedAccess(cc)
(account, callContext) <- NewStyle.function.checkBankAccountExists(bankId, accountId, callContext)
Expand Down Expand Up @@ -376,7 +378,7 @@ trait APIMethods220 {

lazy val getExplictCounterpartyById : OBPEndpoint = {
case "banks" :: BankId(bankId) :: "accounts" :: AccountId(accountId) :: ViewId(viewId) :: "counterparties" :: CounterpartyId(counterpartyId) :: Nil JsonGet req => {
cc =>
cc => implicit val ec = EndpointContext(Some(cc))
for {
(Full(u), callContext) <- authenticatedAccess(cc)
(account, callContext) <- NewStyle.function.checkBankAccountExists(bankId, accountId, callContext)
Expand Down Expand Up @@ -416,6 +418,7 @@ trait APIMethods220 {
lazy val getMessageDocs: OBPEndpoint = {
case "message-docs" :: connector :: Nil JsonGet _ => {
cc => {
implicit val ec = EndpointContext(Some(cc))
for {
connectorObject <- Future(tryo{Connector.getConnectorInstance(connector)}) map { i =>
val msg = "$InvalidConnector Current Input is $connector. It should be eg: kafka_vSept2018..."
Expand Down Expand Up @@ -694,33 +697,44 @@ trait APIMethods220 {
UserHasMissingRoles,
UnknownError
),
List(apiTagFx, apiTagOldStyle),
List(apiTagFx),
Some(List(canCreateFxRate, canCreateFxRateAtAnyBank))
)



lazy val createFx: OBPEndpoint = {
case "banks" :: BankId(bankId) :: "fx" :: Nil JsonPut json -> _ => {
cc =>
cc => implicit val ec = EndpointContext(Some(cc))
for {
u <- cc.user ?~!ErrorMessages.UserNotLoggedIn
(bank, callContext) <- BankX(bankId, Some(cc)) ?~! BankNotFound
_ <- NewStyle.function.hasAllEntitlements(bank.bankId.value, u.userId, createFxEntitlementsRequiredForSpecificBank, createFxEntitlementsRequiredForAnyBank, callContext)
fx <- tryo {json.extract[FXRateJsonV220]} ?~! ErrorMessages.InvalidJsonFormat
_ <- booleanToBox(APIUtil.isValidCurrencyISOCode(fx.from_currency_code),InvalidISOCurrencyCode+s"Current from_currency_code is ${fx.from_currency_code}")
_ <- booleanToBox(APIUtil.isValidCurrencyISOCode(fx.to_currency_code),InvalidISOCurrencyCode+s"Current to_currency_code is ${fx.to_currency_code}")
success <- Connector.connector.vend.createOrUpdateFXRate(
(Full(u), callContext) <- authenticatedAccess(cc)
(bank, callContext) <- NewStyle.function.getBank(bankId, callContext)
_ <- Future {
NewStyle.function.hasAllEntitlements(
bank.bankId.value,
u.userId,
createFxEntitlementsRequiredForSpecificBank,
createFxEntitlementsRequiredForAnyBank,
callContext
)
}
fx <- NewStyle.function.tryons(ErrorMessages.InvalidJsonFormat, 400, callContext) {
json.extract[FXRateJsonV220]
}
_ <- NewStyle.function.isValidCurrencyISOCode(fx.from_currency_code, callContext)
_ <- NewStyle.function.isValidCurrencyISOCode(fx.to_currency_code, callContext)
fxRate <- NewStyle.function.createOrUpdateFXRate(
bankId = fx.bank_id,
fromCurrencyCode = fx.from_currency_code,
toCurrencyCode = fx.to_currency_code,
conversionValue = fx.conversion_value,
inverseConversionValue = fx.inverse_conversion_value,
effectiveDate = fx.effective_date
effectiveDate = fx.effective_date,
callContext
)
} yield {
val json = JSONFactory220.createFXRateJSON(success)
createdJsonResponse(Extraction.decompose(json))
val viewJSON = JSONFactory220.createFXRateJSON(fxRate)
(viewJSON, HttpCode.`201`(callContext))
}
}
}
Expand Down Expand Up @@ -774,6 +788,7 @@ trait APIMethods220 {
// Create a new account
case "banks" :: BankId(bankId) :: "accounts" :: AccountId(accountId) :: Nil JsonPut json -> _ => {
cc =>{
implicit val ec = EndpointContext(Some(cc))
for {
(Full(u), callContext) <- authenticatedAccess(cc)
failMsg = s"$InvalidJsonFormat The Json body should be the $CreateAccountJSONV220 "
Expand Down Expand Up @@ -865,7 +880,7 @@ trait APIMethods220 {

lazy val config: OBPEndpoint = {
case "config" :: Nil JsonGet _ =>
cc =>
cc => implicit val ec = EndpointContext(Some(cc))
for {
(Full(u), callContext) <- authenticatedAccess(cc)
_ <- NewStyle.function.hasEntitlement("", u.userId, ApiRole.canGetConfig, callContext)
Expand Down Expand Up @@ -923,7 +938,7 @@ trait APIMethods220 {

lazy val getConnectorMetrics : OBPEndpoint = {
case "management" :: "connector" :: "metrics" :: Nil JsonGet _ => {
cc =>
cc => implicit val ec = EndpointContext(Some(cc))
for {
(Full(u), callContext) <- authenticatedAccess(cc)
_ <- NewStyle.function.hasEntitlement("", u.userId, ApiRole.canGetConnectorMetrics, callContext)
Expand Down Expand Up @@ -1113,7 +1128,7 @@ trait APIMethods220 {

lazy val createCounterparty: OBPEndpoint = {
case "banks" :: BankId(bankId) :: "accounts" :: AccountId(accountId) :: ViewId(viewId) :: "counterparties" :: Nil JsonPost json -> _ => {
cc =>
cc => implicit val ec = EndpointContext(Some(cc))
for {
(Full(u), callContext) <- authenticatedAccess(cc)
_ <- Helper.booleanToFuture(InvalidAccountIdFormat, cc=callContext) {isValidID(accountId.value)}
Expand Down
28 changes: 18 additions & 10 deletions obp-api/src/main/scala/code/api/v3_0_0/APIMethods300.scala
Original file line number Diff line number Diff line change
Expand Up @@ -1084,24 +1084,32 @@ trait APIMethods300 {
InsufficientAuthorisationToCreateBranch,
UnknownError
),
List(apiTagBranch, apiTagOldStyle),
List(apiTagBranch),
Some(List(canCreateBranch, canCreateBranchAtAnyBank))
)

lazy val createBranch: OBPEndpoint = {
case "banks" :: BankId(bankId) :: "branches" :: Nil JsonPost json -> _ => {
cc =>
cc => implicit val ec = EndpointContext(Some(cc))
for {
u <- cc.user ?~!ErrorMessages.UserNotLoggedIn
(bank, _) <- BankX(bankId, Some(cc)) ?~! BankNotFound
_ <- NewStyle.function.hasAllEntitlements(bank.bankId.value, u.userId, canCreateBranch::Nil, canCreateBranchAtAnyBank::Nil, cc.callContext)
branchJsonV300 <- tryo {json.extract[BranchJsonV300]} ?~! {ErrorMessages.InvalidJsonFormat + " BranchJsonV300"}
_ <- booleanToBox(branchJsonV300.bank_id == bank.bankId.value, "BANK_ID has to be the same in the URL and Body")
branch <- transformToBranchFromV300(branchJsonV300) ?~! {ErrorMessages.CouldNotTransformJsonToInternalModel + " Branch"}
success: BranchT <- Connector.connector.vend.createOrUpdateBranch(branch) ?~! {ErrorMessages.CountNotSaveOrUpdateResource + " Branch"}
(Full(u), callContext) <- authenticatedAccess(cc)
(bank, callContext) <- NewStyle.function.getBank(bankId, callContext)
_ <- Future(
NewStyle.function.hasAllEntitlements(bank.bankId.value, u.userId, canCreateBranch::Nil, canCreateBranchAtAnyBank::Nil, cc.callContext)
)
branchJsonV300 <- NewStyle.function.tryons(failMsg = InvalidJsonFormat + " BranchJsonV300", 400, callContext) {
json.extract[BranchJsonV300]
}
_ <- Helper.booleanToFuture(failMsg = "BANK_ID has to be the same in the URL and Body", 400, callContext) {
branchJsonV300.bank_id == bank.bankId.value
}
branch <- NewStyle.function.tryons(CouldNotTransformJsonToInternalModel + " Branch", 400, cc.callContext) {
transformToBranch(branchJsonV300)
}
success: BranchT <- NewStyle.function.createOrUpdateBranch(branch, callContext)
} yield {
val json = JSONFactory300.createBranchJsonV300(success)
createdJsonResponse(Extraction.decompose(json), 201)
(json, HttpCode.`201`(callContext))
}
}
}
Expand Down
Loading

0 comments on commit 04c837e

Please sign in to comment.