From 6a256dcd54c10217913e41e601cf22ed76df4fc7 Mon Sep 17 00:00:00 2001 From: ssedoudbgouv Date: Sun, 10 Nov 2024 11:46:12 +0100 Subject: [PATCH] TRELLO-2572 : Fix tests --- app/models/AccessToken.scala | 2 +- app/orchestrators/AccessesOrchestrator.scala | 5 +- app/orchestrators/AuthOrchestrator.scala | 58 ++++++++++--------- app/services/EmailAddressService.scala | 2 +- test/controllers/AccountControllerSpec.scala | 5 +- test/controllers/AuthControllerSpec.scala | 1 + test/repositories/UserRepositorySpec.scala | 4 +- .../account/InactiveAccountTaskSpec.scala | 2 +- test/utils/AuthHelpers.scala | 2 +- test/utils/Fixtures.scala | 5 +- 10 files changed, 48 insertions(+), 38 deletions(-) diff --git a/app/models/AccessToken.scala b/app/models/AccessToken.scala index 5d709137a..68af40c9c 100644 --- a/app/models/AccessToken.scala +++ b/app/models/AccessToken.scala @@ -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] diff --git a/app/orchestrators/AccessesOrchestrator.scala b/app/orchestrators/AccessesOrchestrator.scala index a78419335..f34d6763e 100644 --- a/app/orchestrators/AccessesOrchestrator.scala +++ b/app/orchestrators/AccessesOrchestrator.scala @@ -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 @@ -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] = diff --git a/app/orchestrators/AuthOrchestrator.scala b/app/orchestrators/AuthOrchestrator.scala index 7930526bd..d9a08a28d 100644 --- a/app/orchestrators/AuthOrchestrator.scala +++ b/app/orchestrators/AuthOrchestrator.scala @@ -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") diff --git a/app/services/EmailAddressService.scala b/app/services/EmailAddressService.scala index c531472d9..42cf22df7 100644 --- a/app/services/EmailAddressService.scala +++ b/app/services/EmailAddressService.scala @@ -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) diff --git a/test/controllers/AccountControllerSpec.scala b/test/controllers/AccountControllerSpec.scala index 6eda636ef..c11d5828a 100644 --- a/test/controllers/AccountControllerSpec.scala +++ b/test/controllers/AccountControllerSpec.scala @@ -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" -> "user@example.com")) + .withJsonBody(Json.obj("email" -> "user@example.com", "authProvider" -> AuthProvider.SignalConso )) .withAuthCookie(identity.email, components.cookieAuthenticator) val result = route(app, request).get @@ -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" -> "user@dgccrf.gouv.fr")) + .withJsonBody(Json.obj("email" -> "user@dgccrf.gouv.fr", "authProvider" -> AuthProvider.SignalConso )) val result = route(app, request).get Helpers.status(result) must beEqualTo(200) @@ -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) diff --git a/test/controllers/AuthControllerSpec.scala b/test/controllers/AuthControllerSpec.scala index 444845161..e8fae6a9e 100644 --- a/test/controllers/AuthControllerSpec.scala +++ b/test/controllers/AuthControllerSpec.scala @@ -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)) diff --git a/test/repositories/UserRepositorySpec.scala b/test/repositories/UserRepositorySpec.scala index 033cde3ab..65e51b403 100644 --- a/test/repositories/UserRepositorySpec.scala +++ b/test/repositories/UserRepositorySpec.scala @@ -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[ diff --git a/test/tasks/account/InactiveAccountTaskSpec.scala b/test/tasks/account/InactiveAccountTaskSpec.scala index ac886c114..315b88264 100644 --- a/test/tasks/account/InactiveAccountTaskSpec.scala +++ b/test/tasks/account/InactiveAccountTaskSpec.scala @@ -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 diff --git a/test/utils/AuthHelpers.scala b/test/utils/AuthHelpers.scala index bd072985d..4ff39fbb2 100644 --- a/test/utils/AuthHelpers.scala +++ b/test/utils/AuthHelpers.scala @@ -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) } } diff --git a/test/utils/Fixtures.scala b/test/utils/Fixtures.scala index b87f7d90b..64d42b449 100644 --- a/test/utils/Fixtures.scala +++ b/test/utils/Fixtures.scala @@ -1,5 +1,6 @@ package utils +import models.AuthProvider.SignalConso import models._ import models.barcode.BarcodeProduct import models.company.Address @@ -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")