Skip to content

Commit

Permalink
TRELLO-2572 : Fix tests
Browse files Browse the repository at this point in the history
  • Loading branch information
ssedoudbgouv committed Nov 10, 2024
1 parent bec348d commit 6a256dc
Show file tree
Hide file tree
Showing 10 changed files with 48 additions and 38 deletions.
2 changes: 1 addition & 1 deletion app/models/AccessToken.scala
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ object ActivationRequest {

case class InvitationRequest(
email: EmailAddress,
authProvider: AuthProvider
authProvider: Option[AuthProvider]
)
object InvitationRequest {
implicit val InvitationRequestFormat: OFormat[InvitationRequest] = Json.format[InvitationRequest]
Expand Down
5 changes: 2 additions & 3 deletions app/orchestrators/AccessesOrchestrator.scala
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ import config.TokenConfiguration
import controllers.error.AppError._
import io.scalaland.chimney.dsl._
import models.AuthProvider.ProConnect
import models.AuthProvider.SignalConso
import models._
import models.token.AdminOrDgccrfTokenKind
import models.token.AgentAccessToken
Expand Down Expand Up @@ -235,14 +234,14 @@ class AccessesOrchestrator(

def sendDGCCRFInvitation(invitationRequest: InvitationRequest): Future[Unit] =
invitationRequest.authProvider match {
case ProConnect =>
case Some(ProConnect) =>
for {
_ <- userOrchestrator.createProConnectUser(invitationRequest.email, UserRole.DGCCRF)
_ <- mailService.send(
DgccrfAgentInvitation.Email("DGCCRF")(invitationRequest.email, frontRoute.dashboard.welcome)
)
} yield ()
case SignalConso => sendAdminOrAgentInvitation(invitationRequest.email, TokenKind.DGCCRFAccount)
case _ => sendAdminOrAgentInvitation(invitationRequest.email, TokenKind.DGCCRFAccount)
}

def sendDGALInvitation(email: EmailAddress): Future[Unit] =
Expand Down
58 changes: 32 additions & 26 deletions app/orchestrators/AuthOrchestrator.scala
Original file line number Diff line number Diff line change
Expand Up @@ -74,42 +74,48 @@ class AuthOrchestrator(
Future.successful(())
}

def signalConsoLogin(userCredentials: UserCredentials, request: Request[_]): Future[UserSession] = for {
_ <- validateAuthenticationAttempts(userCredentials.login)
user <- getStrictUser(userCredentials.login)
_ = logger.debug(s"Found user (maybe deleted)")
_ <- handleDeletedUser(user, userCredentials)
_ = logger.debug(s"Check last validation email for DGCCRF users")
_ <- validateAgentAccountLastEmailValidation(user)
_ = logger.debug(s"Successful login for user")
_ <- credentialsProvider.authenticate(userCredentials.login, userCredentials.password)
cookie <- authenticator.initSignalConsoCookie(EmailAddress(userCredentials.login), None)(request).liftTo[Future]
_ = logger.debug(s"Successful generated token for user")
userSession = UserSession(cookie, user)
_ <- saveAuthAttempt(userSession)
} yield userSession
def signalConsoLogin(userCredentials: UserCredentials, request: Request[_]): Future[UserSession] = {

val eventualUserSession = for {
_ <- validateAuthenticationAttempts(userCredentials.login)
user <- getStrictUser(userCredentials.login)
_ = logger.debug(s"Found user (maybe deleted)")
_ <- handleDeletedUser(user, userCredentials)
_ = logger.debug(s"Check last validation email for DGCCRF users")
_ <- validateAgentAccountLastEmailValidation(user)
_ = logger.debug(s"Successful login for user")
_ <- credentialsProvider.authenticate(userCredentials.login, userCredentials.password)
cookie <- authenticator.initSignalConsoCookie(EmailAddress(userCredentials.login), None)(request).liftTo[Future]
_ = logger.debug(s"Successful generated token for user")
} yield UserSession(cookie, user)


saveAuthAttemptWithRecovery(userCredentials.login, eventualUserSession)

}

def proConnectLogin(
user: User,
request: Request[_],
proConnectIdToken: String,
proConnectState: String
): Future[UserSession] =
for {
): Future[UserSession] = {
val eventualUserSession =for {
cookie <- authenticator
.initProConnectCookie(user.email, proConnectIdToken, proConnectState)(request)
.liftTo[Future]
_ = logger.debug(s"Successful generated token for user ${user.email.value}")
userSession = UserSession(cookie, user)
_ <- saveAuthAttempt(userSession)
} yield userSession

private def saveAuthAttempt(userSession: UserSession): Future[UserSession] = {
val login = userSession.user.email.value
logger.debug(s"Saving auth attempts for user")
authAttemptRepository
.create(AuthAttempt.build(login, isSuccess = true))
.map(_ => userSession)
} yield UserSession(cookie, user)

saveAuthAttemptWithRecovery(user.email.value, eventualUserSession)
}

private def saveAuthAttemptWithRecovery[T](login: String, eventualSession: Future[T]): Future[T] = {
eventualSession
.flatMap { session =>
logger.debug(s"Saving auth attempts for user")
authAttemptRepository.create(AuthAttempt.build(login, isSuccess = true)).map(_ => session)
}
.recoverWith {
case error: AppError =>
logger.debug(s"Saving failed auth attempt for user")
Expand Down
2 changes: 1 addition & 1 deletion app/services/EmailAddressService.scala
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ object EmailAddressService {
adminEmailRegexp.matches(emailAddress)

def isEmailAcceptableForDgccrfAccount(emailAddress: String): Boolean =
dgccrfEmailRegexp.matches(emailAddress) || true
dgccrfEmailRegexp.matches(emailAddress)

def isEmailAcceptableForDgalAccount(emailAddress: String): Boolean =
dgalEmailRegexp.matches(emailAddress)
Expand Down
5 changes: 3 additions & 2 deletions test/controllers/AccountControllerSpec.scala
Original file line number Diff line number Diff line change
Expand Up @@ -152,7 +152,7 @@ class AccountControllerSpec(implicit ee: ExecutionEnv)

"send an invalid DGCCRF invitation" in {
val request = FakeRequest(POST, routes.AccountController.sendAgentInvitation(UserRole.DGCCRF).toString)
.withJsonBody(Json.obj("email" -> "[email protected]"))
.withJsonBody(Json.obj("email" -> "[email protected]", "authProvider" -> AuthProvider.SignalConso ))
.withAuthCookie(identity.email, components.cookieAuthenticator)

val result = route(app, request).get
Expand All @@ -162,7 +162,7 @@ class AccountControllerSpec(implicit ee: ExecutionEnv)
"send a DGCCRF invitation" in {
val request = FakeRequest(POST, routes.AccountController.sendAgentInvitation(UserRole.DGCCRF).toString)
.withAuthCookie(identity.email, components.cookieAuthenticator)
.withJsonBody(Json.obj("email" -> "[email protected]"))
.withJsonBody(Json.obj("email" -> "[email protected]", "authProvider" -> AuthProvider.SignalConso ))

val result = route(app, request).get
Helpers.status(result) must beEqualTo(200)
Expand All @@ -177,6 +177,7 @@ class AccountControllerSpec(implicit ee: ExecutionEnv)
Helpers.status(result) must beEqualTo(403)
}


"send a DGAL invitation" in {
val request = FakeRequest(POST, routes.AccountController.sendAgentInvitation(UserRole.DGAL).toString)
.withAuthCookie(identity.email, components.cookieAuthenticator)
Expand Down
1 change: 1 addition & 0 deletions test/controllers/AuthControllerSpec.scala
Original file line number Diff line number Diff line change
Expand Up @@ -172,6 +172,7 @@ class AuthControllerSpec(implicit ee: ExecutionEnv)
)

val authAttempts = Await.result(result.map(_._2), Duration.Inf)
println(s"------------------ authAttempts = ${authAttempts} ------------------")
authAttempts.length shouldEqual 1
authAttempts.headOption.map(_.login) shouldEqual Some(login)
authAttempts.headOption.flatMap(_.isSuccess) shouldEqual (Some(false))
Expand Down
4 changes: 2 additions & 2 deletions test/repositories/UserRepositorySpec.scala
Original file line number Diff line number Diff line change
Expand Up @@ -114,8 +114,8 @@ class UserRepositorySpec(implicit ee: ExecutionEnv) extends Specification with A

def e6 = userRepository
.listInactiveAgentsWithSentEmailCount(now.minusMonths(1), now.minusYears(1))
.map(_.map { case (user, count) => (user.id, count) }) must beEqualTo(
List(inactiveDgccrfUser.id -> None, inactiveDgccrfUserWithEmails.id -> Some(2))
.map(_.map { case (user, count) => (user.id, count) }.toSet) must beEqualTo(
List(inactiveDgccrfUserWithEmails.id -> Some(2),inactiveDgccrfUser.id -> None).toSet
).await
def e7 = userRepository
.listInactiveAgentsWithSentEmailCount(now.minusMonths(1), now.minusMonths(2)) must beEmpty[List[
Expand Down
2 changes: 1 addition & 1 deletion test/tasks/account/InactiveAccountTaskSpec.scala
Original file line number Diff line number Diff line change
Expand Up @@ -140,7 +140,7 @@ class InactiveAccountTaskSpec(implicit ee: ExecutionEnv)
)

// Validating user
userList.map(_.id).containsSlice(expectedUsers.map(_.id)) shouldEqual true
userList.map(_.id).toSet shouldEqual(expectedUsers.map(_.id).toSet)
userList.map(_.id).contains(inactiveDGCCRFUser.id) shouldEqual false
deletedUsersList.map(_.id).contains(inactiveDGCCRFUser.id) shouldEqual true

Expand Down
2 changes: 1 addition & 1 deletion test/utils/AuthHelpers.scala
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import play.api.test.FakeRequest
object AuthHelpers {
implicit class FakeRequestOps[A](request: FakeRequest[A]) {
def withAuthCookie(userEmail: EmailAddress, cookieAuthenticator: CookieAuthenticator): FakeRequest[A] = {
val cookie = cookieAuthenticator.init(userEmail, None)(request).toOption.get
val cookie = cookieAuthenticator.initSignalConsoCookie(userEmail, None)(request).toOption.get
request.withCookies(cookie)
}
}
Expand Down
5 changes: 4 additions & 1 deletion test/utils/Fixtures.scala
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package utils

import models.AuthProvider.SignalConso
import models._
import models.barcode.BarcodeProduct
import models.company.Address
Expand Down Expand Up @@ -55,7 +56,9 @@ object Fixtures {
firstName = firstName,
lastName = lastName,
userRole = userRole,
lastEmailValidation = None
lastEmailValidation = None,
authProvider = SignalConso,
authProviderId = None
)

val genFirstName = Gen.oneOf("Alice", "Bob", "Charles", "Danièle", "Émilien", "Fanny", "Gérard")
Expand Down

0 comments on commit 6a256dc

Please sign in to comment.