Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

validate new user name, email, password in update api #510

Merged
merged 3 commits into from
Jan 12, 2021
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -78,22 +78,38 @@ class UserService(
case Some(user) if user.id != userId => Fail.IncorrectInput(LoginAlreadyUsed).raiseError[ConnectionIO, Boolean]
case Some(user) if user.login == newLogin => false.pure[ConnectionIO]
case _ =>
logger.debug(s"Changing login for user: $userId, to: $newLogin")
userModel.updateLogin(userId, newLogin, newLoginLowerCased).map(_ => true)
for {
_ <- validateLogin(newLogin)
_ = logger.debug(s"Changing login for user: $userId, to: $newLogin")
_ <- userModel.updateLogin(userId, newLogin, newLoginLowerCased)
} yield true
}
}

def validateLogin(newLogin: String) =
UserRegisterValidator
.validateLogin(newLogin)
.fold(msg => Fail.IncorrectInput(msg).raiseError[ConnectionIO, Unit], _ => ().pure[ConnectionIO])

def changeEmail(newEmail: String): ConnectionIO[Boolean] = {
val newEmailLowerCased = newEmail.lowerCased
userModel.findByEmail(newEmailLowerCased).flatMap {
case Some(user) if user.id != userId => Fail.IncorrectInput(EmailAlreadyUsed).raiseError[ConnectionIO, Boolean]
case Some(user) if user.emailLowerCased == newEmailLowerCased => false.pure[ConnectionIO]
case _ =>
logger.debug(s"Changing email for user: $userId, to: $newEmail")
userModel.updateEmail(userId, newEmailLowerCased).map(_ => true)
for {
_ <- validateEmail(newEmailLowerCased)
_ = logger.debug(s"Changing email for user: $userId, to: $newEmail")
_ <- userModel.updateEmail(userId, newEmailLowerCased)
} yield true
}
}

def validateEmail(newEmailLowerCased: String) =
UserRegisterValidator
.validateEmail(newEmailLowerCased)
.fold(msg => Fail.IncorrectInput(msg).raiseError[ConnectionIO, Unit], _ => ().pure[ConnectionIO])

def doChange(newLogin: String, newEmail: String): ConnectionIO[Boolean] = {
for {
loginUpdated <- changeLogin(newLogin)
Expand All @@ -119,6 +135,7 @@ class UserService(
for {
user <- userOrNotFound(userModel.findById(userId))
_ <- verifyPassword(user, currentPassword, validationErrorMsg = "Incorrect current password")
_ <- validatePassword(newPassword)
_ = logger.debug(s"Changing password for user: $userId")
_ <- userModel.updatePassword(userId, User.hashPassword(newPassword))
confirmationEmail = emailTemplates.passwordChangeNotification(user.login)
Expand All @@ -139,6 +156,11 @@ class UserService(
Fail.Unauthorized(validationErrorMsg).raiseError[ConnectionIO, Unit]
}
}

private def validatePassword(password: String) =
UserRegisterValidator
.validatePassword(password)
.fold(msg => Fail.IncorrectInput(msg).raiseError[ConnectionIO, Unit], _ => ().pure[ConnectionIO])
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We've got the .fold(...) in a couple of places now, I'm wondering if there's a way to simplify that. Maybe have a UserValidator instead of UserRegisterValidator which would accept optional login/email/password and validate the ones that are present? Then we could also have a single method which converts the Either into a Task.

}

object UserRegisterValidator {
Expand All @@ -147,20 +169,20 @@ object UserRegisterValidator {

def validate(login: String, email: String, password: String): Either[String, Unit] =
for {
_ <- validLogin(login.trim)
_ <- validEmail(email.trim)
_ <- validPassword(password.trim)
_ <- validateLogin(login.trim)
_ <- validateEmail(email.trim)
_ <- validatePassword(password.trim)
} yield ()

private def validLogin(login: String): Either[String, Unit] =
def validateLogin(login: String): Either[String, Unit] =
if (login.length >= MinLoginLength) ValidationOk else Left("Login is too short!")

private val emailRegex =
"""^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$""".r

private def validEmail(email: String) =
def validateEmail(email: String): Either[String, Unit] =
if (emailRegex.findFirstMatchIn(email).isDefined) ValidationOk else Left("Invalid e-mail format!")

private def validPassword(password: String) =
def validatePassword(password: String): Either[String, Unit] =
if (password.nonEmpty) ValidationOk else Left("Password cannot be empty!")
}
Original file line number Diff line number Diff line change
Expand Up @@ -185,6 +185,22 @@ class UserApiTest extends BaseTest with TestEmbeddedPostgres with Eventually {
loginUser(login, newPassword, None).status shouldBe Status.Unauthorized
}

"/user/changepassword" should "not change the password if the new password is invalid" in {
// given
val RegisteredUser(login, _, password, apiKey) = newRegisteredUsed()
val newPassword = ""

// when
val response1 = changePassword(apiKey, password, newPassword)

// then
response1.status shouldBe Status.BadRequest
response1.shouldDeserializeToError shouldBe "Password cannot be empty!"

loginUser(login, password, None).status shouldBe Status.Ok
loginUser(login, newPassword, None).status shouldBe Status.Unauthorized
}

"/user" should "update the login" in {
// given
val RegisteredUser(login, email, _, apiKey) = newRegisteredUsed()
Expand All @@ -199,6 +215,22 @@ class UserApiTest extends BaseTest with TestEmbeddedPostgres with Eventually {
getUser(apiKey).shouldDeserializeTo[GetUser_OUT].email shouldBe email
}

"/user" should "update the login if the new login is invalid" in {
// given
val RegisteredUser(login, email, _, apiKey) = newRegisteredUsed()
val newLogin = "a"

// when
val response1 = updateUser(apiKey, newLogin, email)

// then
response1.status shouldBe Status.BadRequest
response1.shouldDeserializeToError shouldBe "Login is too short!"

getUser(apiKey).shouldDeserializeTo[GetUser_OUT].login shouldBe login
getUser(apiKey).shouldDeserializeTo[GetUser_OUT].email shouldBe email
}

"/user" should "update the email" in {
// given
val RegisteredUser(login, _, _, apiKey) = newRegisteredUsed()
Expand All @@ -212,4 +244,20 @@ class UserApiTest extends BaseTest with TestEmbeddedPostgres with Eventually {
getUser(apiKey).shouldDeserializeTo[GetUser_OUT].login shouldBe login
getUser(apiKey).shouldDeserializeTo[GetUser_OUT].email shouldBe newEmail
}

"/user" should "not update the email if the new email is invalid" in {
// given
val RegisteredUser(login, email, _, apiKey) = newRegisteredUsed()
val newEmail = "aaa"

// when
val response1 = updateUser(apiKey, login, newEmail)

// then
response1.status shouldBe Status.BadRequest
response1.shouldDeserializeToError shouldBe "Invalid e-mail format!"

getUser(apiKey).shouldDeserializeTo[GetUser_OUT].login shouldBe login
getUser(apiKey).shouldDeserializeTo[GetUser_OUT].email shouldBe email
}
}