Last active
June 23, 2022 09:35
-
-
Save RaheemJnr/b9017f52e2f21748a99d180fb8671d08 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Authentication controller | |
[authDao] was created earlier, an interface that we use to communicate with our database | |
[jwt controller] a class for user authentication | |
[encryptor] an helper method for enrypting password string | |
* */ | |
class AuthController( | |
private val authDao: AuthDao, | |
private val jwt: JwtController, | |
private val encryptor: (String) -> String | |
) { | |
//register user | |
fun register(username: String, email: String, userType: String, password: String): AuthResponse { | |
return try { | |
validateRCredentials(username,email,password) | |
if (!authDao.isEmailTaken(email)) { | |
throw BadRequestException("Email already taken! Input another email") | |
} | |
val user = authDao.registerUser(username, email, userType, encryptor(password)) | |
AuthResponse.success(jwt.generateToken(user.id), "Registration successful") | |
} catch (BRE: BadRequestException) { | |
AuthResponse.failed(BRE.message) | |
} catch (UAE: UnauthorizedActivityException) { | |
AuthResponse.unauthorized(UAE.message) | |
} | |
} | |
fun validateRCredentials( | |
username: String, | |
email: String, | |
password: String, | |
) { | |
val message = when { | |
(username.isBlank() or password.isBlank()) -> "Username or password should not be blank" | |
(email.isBlank()) -> "Email cannot not be blank" | |
(username.length !in (4..30)) -> "Username should be of min 4 and max 30 character in length" | |
(password.length !in (8..50)) -> "Password should be of min 8 and max 50 character in length" | |
else -> return | |
} | |
throw BadRequestException(message) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment