diff --git a/internal/controllers/auth_controller.go b/internal/controllers/auth_controller.go index 2176939..2839062 100644 --- a/internal/controllers/auth_controller.go +++ b/internal/controllers/auth_controller.go @@ -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 } @@ -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 } @@ -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 } @@ -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 } diff --git a/internal/services/auth_service.go b/internal/services/auth_service.go index cd0ed16..f20a3f3 100644 --- a/internal/services/auth_service.go +++ b/internal/services/auth_service.go @@ -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) } @@ -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() @@ -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 @@ -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) @@ -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() @@ -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 } @@ -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) @@ -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 := @@ -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 @@ -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) @@ -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) } diff --git a/internal/services/errors.go b/internal/services/errors.go index 4c0a7bf..120edf5 100644 --- a/internal/services/errors.go +++ b/internal/services/errors.go @@ -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") ) diff --git a/internal/services/user_service.go b/internal/services/user_service.go index 32f41c3..046c76e 100644 --- a/internal/services/user_service.go +++ b/internal/services/user_service.go @@ -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 @@ -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