Skip to content

Commit

Permalink
Fix error messages
Browse files Browse the repository at this point in the history
Signed-off-by: William <[email protected]>
  • Loading branch information
kwesidev committed Dec 12, 2023
1 parent d666bc6 commit dd90202
Show file tree
Hide file tree
Showing 4 changed files with 48 additions and 48 deletions.
16 changes: 8 additions & 8 deletions internal/controllers/auth_controller.go
Original file line number Diff line number Diff line change
Expand Up @@ -50,10 +50,10 @@ func (authCtrl *AuthController) Login(w http.ResponseWriter, r *http.Request) {
authResult, err = authCtrl.authService.LoginByUsernamePassword(authRequest.Username, authRequest.Password, "", "")

if err != nil {
if errors.Is(err, services.ErrorInvalidUsername) || errors.Is(err, services.ErrorInvalidPassword) || errors.Is(err, services.ErrorAccountNotActive) {
if errors.Is(err, services.ErrInvalidUsername) || errors.Is(err, services.ErrInvalidPassword) || errors.Is(err, services.ErrAccountNotActive) {
utilities.JSONError(w, err.Error(), http.StatusUnauthorized)
} else {
utilities.JSONError(w, services.ErrorServer.Error(), http.StatusInternalServerError)
utilities.JSONError(w, services.ErrServer.Error(), http.StatusInternalServerError)
}
return
}
Expand All @@ -77,10 +77,10 @@ func (authCtrl *AuthController) PasswordlessLogin(w http.ResponseWriter, r *http
var passwordLessAuthResponse *models.PasswordLessAuthResponse
passwordLessAuthResponse, err = authCtrl.authService.PasswordlessLogin(passwordLessAuthRequest.Username, passwordLessAuthRequest.SendMethod, "", "")
if err != nil {
if errors.Is(err, services.ErrorInvalidUsername) || errors.Is(err, services.ErrorInvalidPassword) || errors.Is(err, services.ErrorAccountNotActive) {
if errors.Is(err, services.ErrInvalidUsername) || errors.Is(err, services.ErrInvalidPassword) || errors.Is(err, services.ErrAccountNotActive) {
utilities.JSONError(w, err.Error(), http.StatusUnauthorized)
} else {
utilities.JSONError(w, services.ErrorServer.Error(), http.StatusInternalServerError)
utilities.JSONError(w, services.ErrServer.Error(), http.StatusInternalServerError)
}
return
}
Expand All @@ -107,10 +107,10 @@ func (authCtrl *AuthController) CompletePasswordlessLogin(w http.ResponseWriter,
)
authResult, err = authCtrl.authService.CompletePasswordLessLogin(completePasswordLessLogin.Code, completePasswordLessLogin.RequestId)
if err != nil {
if errors.Is(err, services.ErrorInvalidCode) {
if errors.Is(err, services.ErrInvalidCode) {
utilities.JSONError(w, err.Error(), http.StatusUnauthorized)
} else {
utilities.JSONError(w, services.ErrorServer.Error(), http.StatusInternalServerError)
utilities.JSONError(w, services.ErrServer.Error(), http.StatusInternalServerError)
}
return
}
Expand All @@ -127,10 +127,10 @@ func (authCtrl *AuthController) RefreshToken(w http.ResponseWriter, r *http.Requ
}
refreshResult, err := authCtrl.authService.GenerateRefreshToken(tokenRefreshRequest.RefreshToken, r.RemoteAddr, r.UserAgent())
if err != nil {
if errors.Is(err, services.ErrorInvalidToken) {
if errors.Is(err, services.ErrInvalidToken) {
utilities.JSONError(w, err.Error(), http.StatusUnauthorized)
} else {
utilities.JSONError(w, services.ErrorServer.Error(), http.StatusUnauthorized)
utilities.JSONError(w, services.ErrServer.Error(), http.StatusUnauthorized)
}
return
}
Expand Down
44 changes: 22 additions & 22 deletions internal/services/auth_service.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,15 +41,15 @@ func (authSrv *AuthService) LoginByUsernamePassword(username, password, ipAddres
row.Scan(&userId, &passwordHash)
// Check if username is valid
if userId == 0 {
return nil, ErrorInvalidUsername
return nil, ErrInvalidUsername
}
userDetails := authSrv.userService.Get(userId)
if userDetails.Active == false {
return nil, ErrorAccountNotActive
return nil, ErrAccountNotActive
}
// Validates password
if err = bcrypt.CompareHashAndPassword([]byte(passwordHash), []byte(password)); err != nil {
return nil, ErrorInvalidPassword
return nil, ErrInvalidPassword
}
return authSrv.generateAuthResponse(*userDetails, ipAddress, userAgent)
}
Expand Down Expand Up @@ -82,10 +82,10 @@ func (authSrv *AuthService) generateAuthResponse(userDetails models.User, ipAddr
func (authSrv *AuthService) PasswordlessLogin(username, sendMethod, ipAddress, userAgent string) (*models.PasswordLessAuthResponse, error) {
userDetails := authSrv.userService.GetByUsername(username)
if userDetails == nil {
return nil, ErrorInvalidUsername
return nil, ErrInvalidUsername
}
if userDetails.Active == false {
return nil, ErrorAccountNotActive
return nil, ErrAccountNotActive
}
tx, err := authSrv.db.Begin()
defer tx.Rollback()
Expand Down Expand Up @@ -130,7 +130,7 @@ func (authSrv *AuthService) CompletePasswordLessLogin(code, requestId string) (*
row.Scan(&userId, &ipAddress, &userAgent)
if userId == 0 {
log.Println("Invalid Code or Request Id Invalid")
return nil, ErrorInvalidCode
return nil, ErrInvalidCode
}
userDetails := authSrv.userService.Get(userId)
// Deletes the otp requests
Expand All @@ -154,12 +154,12 @@ func (authSrv *AuthService) GenerateRefreshToken(oldRefreshToken, ipAddress, use
row.Scan(&userId)
if userId == 0 {
log.Println("Refresh Token is not there")
return nil, ErrorInvalidToken
return nil, ErrInvalidToken
}
// Check if account is active before refreshing token
userDetails := authSrv.userService.Get(userId)
if userDetails.Active == false {
return nil, ErrorAccountNotActive
return nil, ErrAccountNotActive
}
roles, _ := authSrv.userService.GetRoles(userId)
tokenExpiry := time.Duration(authSrv.tokenTime)
Expand Down Expand Up @@ -210,11 +210,11 @@ func (authSrv *AuthService) ResetPasswordRequest(username string) (bool, error)
row := authSrv.db.QueryRow("SELECT id FROM users where username = $1 OR email_address = $1 ", username)
if err := row.Scan(&userId); err != nil {
log.Println(err)
return false, ErrorInvalidUsername
return false, ErrInvalidUsername
}
userDetails := authSrv.userService.Get(userId)
if userDetails.Active == false {
return false, ErrorAccountNotActive
return false, ErrAccountNotActive
}
tx, err := authSrv.db.Begin()
defer tx.Rollback()
Expand Down Expand Up @@ -259,28 +259,28 @@ func (authSrv *AuthService) VerifyAndSetNewPassword(code string, password string
row.Scan(&userId)
if userId == 0 {
log.Println("Invalid Code")
return false, ErrorInvalidCode
return false, ErrInvalidCode
}
// update password and delete all refresh tokens
passwordHash, err := bcrypt.GenerateFromPassword([]byte(password), 10)
if err != nil {
return false, ErrorPasswordUpdate
return false, ErrPasswordUpdate
}
if _, err = tx.Exec("UPDATE users SET password = $2 WHERE id = $1", userId, passwordHash); err != nil {
log.Println(err)
return false, ErrorPasswordUpdate
return false, ErrPasswordUpdate
}
if _, err = tx.Exec("DELETE FROM user_refresh_tokens WHERE user_id = $1", userId); err != nil {
log.Println(err)
return false, ErrorPasswordUpdate
return false, ErrPasswordUpdate
}
_, err = tx.Exec("DELETE FROM reset_password_requests WHERE user_id = $1", userId)
if err != nil {
log.Println(err)
return false, ErrorPasswordUpdate
return false, ErrPasswordUpdate
}
if err = tx.Commit(); err != nil {
return false, ErrorInvalidPassword
return false, ErrInvalidPassword
}
return true, nil
}
Expand All @@ -306,7 +306,7 @@ func (authSrv *AuthService) twoFactorRequest(userDetails models.User, ipAddress
`
if _, err = tx.Exec(queryString, userDetails.ID, requestId, ipAddress, randomCodes, userAgent, time.Now().Add(expires)); err != nil {
log.Println(err)
return nil, ErrorTwoFactorRequest
return nil, ErrTwoFactorRequest
}
if err = authSrv.emailService.SendTwoFactorRequest(randomCodes, userDetails); err != nil {
log.Println("Sending Email error", err)
Expand All @@ -328,7 +328,7 @@ func (authSrv *AuthService) generateTokenDetails(userDetails models.User, ipAddr
jwtToken, err := utilities.GenerateJwtToken(userDetails.ID, userDetails.Roles, tokenExpiry)
if err != nil {
log.Println(err)
return nil, ErrorAccessToken
return nil, ErrAccessToken
}
refreshToken := utilities.GenerateOpaqueToken(45)
queryString :=
Expand All @@ -341,7 +341,7 @@ func (authSrv *AuthService) generateTokenDetails(userDetails models.User, ipAddr
// Generate a jwt and refresh token
if _, err = authSrv.db.Exec(queryString, userDetails.ID, refreshToken, ipAddress, userAgent, time.Now().Add(tokenExpiry)); err != nil {
log.Println(err)
return nil, ErrorTokenGeneration
return nil, ErrTokenGeneration
}
authResult.RefreshToken = refreshToken
authResult.Token = jwtToken
Expand All @@ -358,11 +358,11 @@ func (authSrv *AuthService) ValidateTwoFactor(code, requestId string, ipAddress,
row.Scan(&userId)
if userId == 0 {
log.Println("Invalid Code")
return nil, ErrorTwoFactorCode
return nil, ErrTwoFactorCode
}
if _, err := authSrv.db.Exec("DELETE FROM two_factor_requests WHERE code = $1 AND request_id = $2", code, requestId); err != nil {
log.Println(err)
return nil, ErrorTwoFactorCode
return nil, ErrTwoFactorCode
}
userDetails := authSrv.userService.Get(userId)
return authSrv.generateTokenDetails(*userDetails, ipAddress, userAgent)
Expand Down Expand Up @@ -399,7 +399,7 @@ func (authSrv *AuthService) VerifyPassCode(userId int, passCode string) bool {
func (authSrv *AuthService) VerifyTOTP(userId int, passCode, ipAddress, userAgent string) (*models.AuthenticationResponse, error) {
userDetails := authSrv.userService.Get(userId)
if !authSrv.VerifyPassCode(userId, passCode) {
return nil, ErrorPassCode
return nil, ErrPassCode
}
return authSrv.generateTokenDetails(*userDetails, ipAddress, userAgent)
}
32 changes: 16 additions & 16 deletions internal/services/errors.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,20 +3,20 @@ package services
import "errors"

var (
ErrUserNameExists = errors.New("The username exists")
ErrSendingMail = errors.New("Failed sending Email")
ErrorAccountNotActive = errors.New("Account is not Active")
ErrorTokenGeneration = errors.New("Failed to generate Token")
ErrorInvalidToken = errors.New("Token is Invalid")
ErrorAccessToken = errors.New("Failed to Access Token")
ErrorInvalidUsername = errors.New("Invalid Username")
ErrorInvalidPassword = errors.New("Invalid Password")
ErrorRegistration = errors.New("Failed to register ")
ErrorPasswordUpdate = errors.New("Failed to update password")
ErrorTwoFactorCode = errors.New("Failed to Verify Two Factor Code")
ErrorTwoFactorRequest = errors.New("Failed to Send Two Factor Request")
ErrorInvalidCode = errors.New("Code is invalid")
ErrorServer = errors.New("Server Error, Try again later")
ErrorPassCode = errors.New("Invalid Passcode")
ErrStrongPassword = errors.New("Password must be at least 8 characters and must contain special characters")
ErrUserNameExists = errors.New("The username exists")
ErrSendingMail = errors.New("Failed sending Email")
ErrAccountNotActive = errors.New("Account is not Active")
ErrTokenGeneration = errors.New("Failed to generate Token")
ErrInvalidToken = errors.New("Token is Invalid")
ErrAccessToken = errors.New("Failed to Access Token")
ErrInvalidUsername = errors.New("Invalid Username")
ErrInvalidPassword = errors.New("Invalid Password")
ErrRegistration = errors.New("Failed to register ")
ErrPasswordUpdate = errors.New("Failed to update password")
ErrTwoFactorCode = errors.New("Failed to Verify Two Factor Code")
ErrTwoFactorRequest = errors.New("Failed to Send Two Factor Request")
ErrInvalidCode = errors.New("Code is invalid")
ErrServer = errors.New("Server Error, Try again later")
ErrPassCode = errors.New("Invalid Passcode")
ErrStrongPassword = errors.New("Password must be at least 8 characters and must contain special characters")
)
4 changes: 2 additions & 2 deletions internal/services/user_service.go
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,7 @@ func (usrSrv *UserService) Register(userRegistrationRequest models.UserRegistrat
var newUserId int
if err = row.Scan(&newUserId); err != nil {
log.Println(err)
return false, ErrorRegistration
return false, ErrRegistration
}
queryString = `
INSERT
Expand All @@ -143,7 +143,7 @@ func (usrSrv *UserService) Register(userRegistrationRequest models.UserRegistrat
`
if _, err = tx.Exec(queryString, newUserId, "USER"); err != nil {
log.Println(err)
return false, ErrorRegistration
return false, ErrRegistration
}
if err = tx.Commit(); err != nil {
return false, err
Expand Down

0 comments on commit dd90202

Please sign in to comment.