refact: optimize and repair response

This commit is contained in:
pahmiudahgede 2025-02-13 01:47:15 +07:00
parent 79ac7c91da
commit d6cbd62f1b
13 changed files with 73 additions and 89 deletions

View File

@ -28,7 +28,7 @@ func (h *AddressHandler) CreateAddress(c *fiber.Ctx) error {
addressResponse, err := h.AddressService.CreateAddress(c.Locals("userID").(string), requestAddressDTO)
if err != nil {
return utils.GenericErrorResponse(c, fiber.StatusBadRequest, err.Error())
return utils.GenericResponse(c, fiber.StatusBadRequest, err.Error())
}
return utils.CreateResponse(c, addressResponse, "user address created successfully")
@ -39,7 +39,7 @@ func (h *AddressHandler) GetAddressByUserID(c *fiber.Ctx) error {
addresses, err := h.AddressService.GetAddressByUserID(userID)
if err != nil {
return utils.GenericErrorResponse(c, fiber.StatusNotFound, err.Error())
return utils.GenericResponse(c, fiber.StatusNotFound, err.Error())
}
return utils.SuccessResponse(c, addresses, "User addresses fetched successfully")
@ -51,7 +51,7 @@ func (h *AddressHandler) GetAddressByID(c *fiber.Ctx) error {
address, err := h.AddressService.GetAddressByID(userID, addressID)
if err != nil {
return utils.GenericErrorResponse(c, fiber.StatusNotFound, err.Error())
return utils.GenericResponse(c, fiber.StatusNotFound, err.Error())
}
return utils.SuccessResponse(c, address, "Address fetched successfully")
@ -73,7 +73,7 @@ func (h *AddressHandler) UpdateAddress(c *fiber.Ctx) error {
updatedAddress, err := h.AddressService.UpdateAddress(userID, addressID, addressDTO)
if err != nil {
return utils.GenericErrorResponse(c, fiber.StatusNotFound, err.Error())
return utils.GenericResponse(c, fiber.StatusNotFound, err.Error())
}
return utils.SuccessResponse(c, updatedAddress, "User address updated successfully")
@ -85,7 +85,7 @@ func (h *AddressHandler) DeleteAddress(c *fiber.Ctx) error {
err := h.AddressService.DeleteAddress(userID, addressID)
if err != nil {
return utils.GenericErrorResponse(c, fiber.StatusForbidden, err.Error())
return utils.GenericResponse(c, fiber.StatusForbidden, err.Error())
}
return utils.SuccessResponse(c, nil, "Address deleted successfully")

View File

@ -31,12 +31,12 @@ func (h *ArticleHandler) CreateArticle(c *fiber.Ctx) error {
coverImage, err := c.FormFile("coverImage")
if err != nil {
return utils.GenericErrorResponse(c, fiber.StatusBadRequest, "Cover image is required")
return utils.GenericResponse(c, fiber.StatusBadRequest, "Cover image is required")
}
articleResponse, err := h.ArticleService.CreateArticle(request, coverImage)
if err != nil {
return utils.GenericErrorResponse(c, fiber.StatusInternalServerError, err.Error())
return utils.GenericResponse(c, fiber.StatusInternalServerError, err.Error())
}
return utils.SuccessResponse(c, articleResponse, "Article created successfully")
@ -61,7 +61,7 @@ func (h *ArticleHandler) GetAllArticles(c *fiber.Ctx) error {
articles, totalArticles, err = h.ArticleService.GetAllArticles(0, 0)
if err != nil {
return utils.GenericErrorResponse(c, fiber.StatusInternalServerError, "Failed to fetch articles")
return utils.GenericResponse(c, fiber.StatusInternalServerError, "Failed to fetch articles")
}
return utils.NonPaginatedResponse(c, articles, totalArticles, "Articles fetched successfully")
@ -69,7 +69,7 @@ func (h *ArticleHandler) GetAllArticles(c *fiber.Ctx) error {
articles, totalArticles, err = h.ArticleService.GetAllArticles(page, limit)
if err != nil {
return utils.GenericErrorResponse(c, fiber.StatusInternalServerError, "Failed to fetch articles")
return utils.GenericResponse(c, fiber.StatusInternalServerError, "Failed to fetch articles")
}
return utils.PaginatedResponse(c, articles, page, limit, totalArticles, "Articles fetched successfully")
@ -78,12 +78,12 @@ func (h *ArticleHandler) GetAllArticles(c *fiber.Ctx) error {
func (h *ArticleHandler) GetArticleByID(c *fiber.Ctx) error {
id := c.Params("article_id")
if id == "" {
return utils.GenericErrorResponse(c, fiber.StatusBadRequest, "Article ID is required")
return utils.GenericResponse(c, fiber.StatusBadRequest, "Article ID is required")
}
article, err := h.ArticleService.GetArticleByID(id)
if err != nil {
return utils.GenericErrorResponse(c, fiber.StatusNotFound, err.Error())
return utils.GenericResponse(c, fiber.StatusNotFound, err.Error())
}
return utils.SuccessResponse(c, article, "Article fetched successfully")
@ -92,7 +92,7 @@ func (h *ArticleHandler) GetArticleByID(c *fiber.Ctx) error {
func (h *ArticleHandler) UpdateArticle(c *fiber.Ctx) error {
id := c.Params("article_id")
if id == "" {
return utils.GenericErrorResponse(c, fiber.StatusBadRequest, "Article ID is required")
return utils.GenericResponse(c, fiber.StatusBadRequest, "Article ID is required")
}
var request dto.RequestArticleDTO
@ -108,12 +108,12 @@ func (h *ArticleHandler) UpdateArticle(c *fiber.Ctx) error {
coverImage, err := c.FormFile("coverImage")
if err != nil && err.Error() != "no such file" {
return utils.GenericErrorResponse(c, fiber.StatusBadRequest, "Cover image is required")
return utils.GenericResponse(c, fiber.StatusBadRequest, "Cover image is required")
}
articleResponse, err := h.ArticleService.UpdateArticle(id, request, coverImage)
if err != nil {
return utils.GenericErrorResponse(c, fiber.StatusInternalServerError, err.Error())
return utils.GenericResponse(c, fiber.StatusInternalServerError, err.Error())
}
return utils.SuccessResponse(c, articleResponse, "Article updated successfully")

View File

@ -30,7 +30,7 @@ func (h *UserHandler) Login(c *fiber.Ctx) error {
user, err := h.UserService.Login(loginDTO)
if err != nil {
return utils.GenericErrorResponse(c, fiber.StatusUnauthorized, err.Error())
return utils.GenericResponse(c, fiber.StatusUnauthorized, err.Error())
}
return utils.SuccessResponse(c, user, "Login successful")
@ -50,7 +50,7 @@ func (h *UserHandler) Register(c *fiber.Ctx) error {
userResponse, err := h.UserService.Register(registerDTO)
if err != nil {
return utils.GenericErrorResponse(c, fiber.StatusConflict, err.Error())
return utils.GenericResponse(c, fiber.StatusConflict, err.Error())
}
return utils.CreateResponse(c, userResponse, "Registration successful")
@ -60,7 +60,7 @@ func (h *UserHandler) Logout(c *fiber.Ctx) error {
userID, ok := c.Locals("userID").(string)
if !ok || userID == "" {
log.Println("Unauthorized access: User ID not found in session")
return utils.GenericErrorResponse(c, fiber.StatusUnauthorized, "Unauthorized: User session not found")
return utils.GenericResponse(c, fiber.StatusUnauthorized, "Unauthorized: User session not found")
}
err := utils.DeleteSessionData(userID)

View File

@ -18,12 +18,12 @@ func (h *RoleHandler) GetRoles(c *fiber.Ctx) error {
roleID, ok := c.Locals("roleID").(string)
if !ok || roleID != utils.RoleAdministrator {
return utils.GenericErrorResponse(c, fiber.StatusForbidden, "Forbidden: You don't have permission to access this resource")
return utils.GenericResponse(c, fiber.StatusForbidden, "Forbidden: You don't have permission to access this resource")
}
roles, err := h.RoleService.GetRoles()
if err != nil {
return utils.GenericErrorResponse(c, fiber.StatusInternalServerError, err.Error())
return utils.GenericResponse(c, fiber.StatusInternalServerError, err.Error())
}
return utils.SuccessResponse(c, roles, "Roles fetched successfully")
@ -34,12 +34,12 @@ func (h *RoleHandler) GetRoleByID(c *fiber.Ctx) error {
roleIDFromSession, ok := c.Locals("roleID").(string)
if !ok || roleIDFromSession != utils.RoleAdministrator {
return utils.GenericErrorResponse(c, fiber.StatusForbidden, "Forbidden: You don't have permission to access this resource")
return utils.GenericResponse(c, fiber.StatusForbidden, "Forbidden: You don't have permission to access this resource")
}
role, err := h.RoleService.GetRoleByID(roleID)
if err != nil {
return utils.GenericErrorResponse(c, fiber.StatusNotFound, "role id tidak ditemukan")
return utils.GenericResponse(c, fiber.StatusNotFound, "role id tidak ditemukan")
}
return utils.SuccessResponse(c, role, "Role fetched successfully")

View File

@ -19,12 +19,12 @@ func (h *UserProfileHandler) GetUserProfile(c *fiber.Ctx) error {
userID, ok := c.Locals("userID").(string)
if !ok || userID == "" {
return utils.GenericErrorResponse(c, fiber.StatusUnauthorized, "Unauthorized: User session not found")
return utils.GenericResponse(c, fiber.StatusUnauthorized, "Unauthorized: User session not found")
}
userProfile, err := h.UserProfileService.GetUserProfile(userID)
if err != nil {
return utils.GenericErrorResponse(c, fiber.StatusNotFound, err.Error())
return utils.GenericResponse(c, fiber.StatusNotFound, err.Error())
}
return utils.SuccessResponse(c, userProfile, "User profile retrieved successfully")
@ -38,7 +38,7 @@ func (h *UserProfileHandler) UpdateUserProfile(c *fiber.Ctx) error {
userID, ok := c.Locals("userID").(string)
if !ok || userID == "" {
return utils.GenericErrorResponse(c, fiber.StatusUnauthorized, "Unauthorized: User session not found")
return utils.GenericResponse(c, fiber.StatusUnauthorized, "Unauthorized: User session not found")
}
errors, valid := updateData.Validate()
@ -48,7 +48,7 @@ func (h *UserProfileHandler) UpdateUserProfile(c *fiber.Ctx) error {
userResponse, err := h.UserProfileService.UpdateUserProfile(userID, updateData)
if err != nil {
return utils.GenericErrorResponse(c, fiber.StatusConflict, err.Error())
return utils.GenericResponse(c, fiber.StatusConflict, err.Error())
}
return utils.SuccessResponse(c, userResponse, "User profile updated successfully")
@ -62,7 +62,7 @@ func (h *UserProfileHandler) UpdateUserPassword(c *fiber.Ctx) error {
userID, ok := c.Locals("userID").(string)
if !ok || userID == "" {
return utils.GenericErrorResponse(c, fiber.StatusUnauthorized, "Unauthorized: User session not found")
return utils.GenericResponse(c, fiber.StatusUnauthorized, "Unauthorized: User session not found")
}
errors, valid := passwordData.Validate()
@ -70,28 +70,28 @@ func (h *UserProfileHandler) UpdateUserPassword(c *fiber.Ctx) error {
return utils.ValidationErrorResponse(c, errors)
}
userResponse, err := h.UserProfileService.UpdateUserPassword(userID, passwordData)
_, err := h.UserProfileService.UpdateUserPassword(userID, passwordData)
if err != nil {
return utils.GenericErrorResponse(c, fiber.StatusBadRequest, err.Error())
return utils.GenericResponse(c, fiber.StatusBadRequest, err.Error())
}
return utils.SuccessResponse(c, userResponse, "Password updated successfully")
return utils.GenericResponse(c, fiber.StatusOK, "Password updated successfully")
}
func (h *UserProfileHandler) UpdateUserAvatar(c *fiber.Ctx) error {
userID, ok := c.Locals("userID").(string)
if !ok || userID == "" {
return utils.GenericErrorResponse(c, fiber.StatusUnauthorized, "Unauthorized: User session not found")
return utils.GenericResponse(c, fiber.StatusUnauthorized, "Unauthorized: User session not found")
}
file, err := c.FormFile("avatar")
if err != nil {
return utils.GenericErrorResponse(c, fiber.StatusBadRequest, "No avatar file uploaded")
return utils.GenericResponse(c, fiber.StatusBadRequest, "No avatar file uploaded")
}
userResponse, err := h.UserProfileService.UpdateUserAvatar(userID, file)
if err != nil {
return utils.GenericErrorResponse(c, fiber.StatusInternalServerError, err.Error())
return utils.GenericResponse(c, fiber.StatusInternalServerError, err.Error())
}
return utils.SuccessResponse(c, userResponse, "Avatar updated successfully")

View File

@ -28,12 +28,12 @@ func (h *UserPinHandler) VerifyUserPin(c *fiber.Ctx) error {
userID, ok := c.Locals("userID").(string)
if !ok || userID == "" {
return utils.GenericErrorResponse(c, fiber.StatusUnauthorized, "Unauthorized: User session not found")
return utils.GenericResponse(c, fiber.StatusUnauthorized, "Unauthorized: User session not found")
}
_, err := h.UserPinService.VerifyUserPin(requestUserPinDTO.Pin, userID)
if err != nil {
return utils.GenericErrorResponse(c, fiber.StatusUnauthorized, "pin yang anda masukkan salah")
return utils.GenericResponse(c, fiber.StatusUnauthorized, "pin yang anda masukkan salah")
}
return utils.SuccessResponse(c, map[string]string{"data": "pin yang anda masukkan benar"}, "Pin verification successful")
@ -42,16 +42,16 @@ func (h *UserPinHandler) VerifyUserPin(c *fiber.Ctx) error {
func (h *UserPinHandler) CheckPinStatus(c *fiber.Ctx) error {
userID, ok := c.Locals("userID").(string)
if !ok || userID == "" {
return utils.GenericErrorResponse(c, fiber.StatusUnauthorized, "Unauthorized: User session not found")
return utils.GenericResponse(c, fiber.StatusUnauthorized, "Unauthorized: User session not found")
}
status, _, err := h.UserPinService.CheckPinStatus(userID)
if err != nil {
return utils.GenericErrorResponse(c, fiber.StatusInternalServerError, err.Error())
return utils.GenericResponse(c, fiber.StatusInternalServerError, err.Error())
}
if status == "Pin not created" {
return utils.GenericErrorResponse(c, fiber.StatusBadRequest, "pin belum dibuat")
return utils.GenericResponse(c, fiber.StatusBadRequest, "pin belum dibuat")
}
return utils.SuccessResponse(c, map[string]string{"data": "pin sudah dibuat"}, "Pin status retrieved successfully")
@ -72,7 +72,7 @@ func (h *UserPinHandler) CreateUserPin(c *fiber.Ctx) error {
userPinResponse, err := h.UserPinService.CreateUserPin(userID, requestUserPinDTO.Pin)
if err != nil {
return utils.GenericErrorResponse(c, fiber.StatusConflict, err.Error())
return utils.GenericResponse(c, fiber.StatusConflict, err.Error())
}
return utils.CreateResponse(c, userPinResponse, "User pin created successfully")
@ -93,7 +93,7 @@ func (h *UserPinHandler) UpdateUserPin(c *fiber.Ctx) error {
userPinResponse, err := h.UserPinService.UpdateUserPin(userID, requestUserPinDTO.OldPin, requestUserPinDTO.NewPin)
if err != nil {
return utils.GenericErrorResponse(c, fiber.StatusBadRequest, err.Error())
return utils.GenericResponse(c, fiber.StatusBadRequest, err.Error())
}
return utils.SuccessResponse(c, userPinResponse, "User pin updated successfully")

View File

@ -20,7 +20,7 @@ func (h *WilayahIndonesiaHandler) ImportWilayahData(c *fiber.Ctx) error {
err := h.WilayahService.ImportDataFromCSV()
if err != nil {
return utils.GenericErrorResponse(c, fiber.StatusInternalServerError, err.Error())
return utils.GenericResponse(c, fiber.StatusInternalServerError, err.Error())
}
return utils.SuccessResponse(c, fiber.StatusCreated, "Data imported successfully")
@ -39,7 +39,7 @@ func (h *WilayahIndonesiaHandler) GetProvinces(c *fiber.Ctx) error {
provinces, totalProvinces, err := h.WilayahService.GetAllProvinces(page, limit)
if err != nil {
return utils.GenericErrorResponse(c, fiber.StatusInternalServerError, "Failed to fetch provinces")
return utils.GenericResponse(c, fiber.StatusInternalServerError, "Failed to fetch provinces")
}
if page > 0 && limit > 0 {
@ -63,7 +63,7 @@ func (h *WilayahIndonesiaHandler) GetProvinceByID(c *fiber.Ctx) error {
province, totalRegencies, err := h.WilayahService.GetProvinceByID(provinceID, page, limit)
if err != nil {
return utils.GenericErrorResponse(c, fiber.StatusInternalServerError, "Failed to fetch province")
return utils.GenericResponse(c, fiber.StatusInternalServerError, "Failed to fetch province")
}
if page > 0 && limit > 0 {
@ -85,7 +85,7 @@ func (h *WilayahIndonesiaHandler) GetAllRegencies(c *fiber.Ctx) error {
regencies, totalRegencies, err := h.WilayahService.GetAllRegencies(page, limit)
if err != nil {
return utils.GenericErrorResponse(c, fiber.StatusInternalServerError, "Failed to fetch regency")
return utils.GenericResponse(c, fiber.StatusInternalServerError, "Failed to fetch regency")
}
if page > 0 && limit > 0 {
@ -109,7 +109,7 @@ func (h *WilayahIndonesiaHandler) GetRegencyByID(c *fiber.Ctx) error {
regency, totalDistrict, err := h.WilayahService.GetRegencyByID(regencyId, page, limit)
if err != nil {
return utils.GenericErrorResponse(c, fiber.StatusInternalServerError, "Failed to fetch regency")
return utils.GenericResponse(c, fiber.StatusInternalServerError, "Failed to fetch regency")
}
if page > 0 && limit > 0 {
@ -131,7 +131,7 @@ func (h *WilayahIndonesiaHandler) GetAllDistricts(c *fiber.Ctx) error {
districts, totalDistricts, err := h.WilayahService.GetAllDistricts(page, limit)
if err != nil {
return utils.GenericErrorResponse(c, fiber.StatusInternalServerError, "Failed to fetch districts")
return utils.GenericResponse(c, fiber.StatusInternalServerError, "Failed to fetch districts")
}
if page > 0 && limit > 0 {
@ -155,7 +155,7 @@ func (h *WilayahIndonesiaHandler) GetDistrictByID(c *fiber.Ctx) error {
district, totalVillages, err := h.WilayahService.GetDistrictByID(districtId, page, limit)
if err != nil {
return utils.GenericErrorResponse(c, fiber.StatusInternalServerError, "Failed to fetch district")
return utils.GenericResponse(c, fiber.StatusInternalServerError, "Failed to fetch district")
}
if page > 0 && limit > 0 {
@ -177,7 +177,7 @@ func (h *WilayahIndonesiaHandler) GetAllVillages(c *fiber.Ctx) error {
villages, totalVillages, err := h.WilayahService.GetAllVillages(page, limit)
if err != nil {
return utils.GenericErrorResponse(c, fiber.StatusInternalServerError, "Failed to fetch villages")
return utils.GenericResponse(c, fiber.StatusInternalServerError, "Failed to fetch villages")
}
if page > 0 && limit > 0 {
@ -192,7 +192,7 @@ func (h *WilayahIndonesiaHandler) GetVillageByID(c *fiber.Ctx) error {
village, err := h.WilayahService.GetVillageByID(id)
if err != nil {
return utils.GenericErrorResponse(c, fiber.StatusInternalServerError, err.Error())
return utils.GenericResponse(c, fiber.StatusInternalServerError, err.Error())
}
return utils.SuccessResponse(c, village, "Village fetched successfully")

View File

@ -104,11 +104,11 @@ func CheckPasswordHash(password, hashedPassword string) bool {
func (s *userService) Register(user dto.RegisterDTO) (*dto.UserResponseDTO, error) {
if user.Password != user.ConfirmPassword {
return nil, fmt.Errorf("%s: %v", ErrPasswordMismatch, nil)
return nil, fmt.Errorf("%s", ErrPasswordMismatch)
}
if user.RoleID == "" {
return nil, fmt.Errorf("%s: %v", ErrRoleIDRequired, nil)
return nil, fmt.Errorf("%s", ErrRoleIDRequired)
}
role, err := s.RoleRepo.FindByID(user.RoleID)
@ -117,15 +117,15 @@ func (s *userService) Register(user dto.RegisterDTO) (*dto.UserResponseDTO, erro
}
if existingUser, _ := s.UserRepo.FindByUsername(user.Username); existingUser != nil {
return nil, fmt.Errorf("%s: %v", ErrUsernameTaken, nil)
return nil, fmt.Errorf("%s", ErrUsernameTaken)
}
if existingPhone, _ := s.UserRepo.FindByPhoneAndRole(user.Phone, user.RoleID); existingPhone != nil {
return nil, fmt.Errorf("%s: %v", ErrPhoneTaken, nil)
return nil, fmt.Errorf("%s", ErrPhoneTaken)
}
if existingEmail, _ := s.UserRepo.FindByEmailAndRole(user.Email, user.RoleID); existingEmail != nil {
return nil, fmt.Errorf("%s: %v", ErrEmailTaken, nil)
return nil, fmt.Errorf("%s", ErrEmailTaken)
}
hashedPassword, err := bcrypt.GenerateFromPassword([]byte(user.Password), bcrypt.DefaultCost)

View File

@ -19,7 +19,7 @@ import (
type UserProfileService interface {
GetUserProfile(userID string) (*dto.UserResponseDTO, error)
UpdateUserProfile(userID string, updateData dto.UpdateUserDTO) (*dto.UserResponseDTO, error)
UpdateUserPassword(userID string, passwordData dto.UpdatePasswordDTO) (*dto.UserResponseDTO, error)
UpdateUserPassword(userID string, passwordData dto.UpdatePasswordDTO) (string, error)
UpdateUserAvatar(userID string, file *multipart.FileHeader) (*dto.UserResponseDTO, error)
}
@ -148,50 +148,34 @@ func (s *userProfileService) updateEmailIfNeeded(user *model.User, newEmail stri
return nil
}
func (s *userProfileService) UpdateUserPassword(userID string, passwordData dto.UpdatePasswordDTO) (*dto.UserResponseDTO, error) {
func (s *userProfileService) UpdateUserPassword(userID string, passwordData dto.UpdatePasswordDTO) (string, error) {
validationErrors, valid := passwordData.Validate()
if !valid {
return nil, fmt.Errorf("validation failed: %v", validationErrors)
return "", fmt.Errorf("validation failed: %v", validationErrors)
}
user, err := s.UserProfileRepo.FindByID(userID)
if err != nil {
return nil, errors.New("user not found")
return "", errors.New("user not found")
}
if !CheckPasswordHash(passwordData.OldPassword, user.Password) {
return nil, errors.New("old password is incorrect")
return "", errors.New("old password is incorrect")
}
hashedPassword, err := bcrypt.GenerateFromPassword([]byte(passwordData.NewPassword), bcrypt.DefaultCost)
if err != nil {
return nil, fmt.Errorf("failed to hash new password: %v", err)
return "", fmt.Errorf("failed to hash new password: %v", err)
}
user.Password = string(hashedPassword)
err = s.UserProfileRepo.Update(user)
if err != nil {
return nil, fmt.Errorf("failed to update password: %v", err)
return "", fmt.Errorf("failed to update password: %v", err)
}
createdAt, _ := utils.FormatDateToIndonesianFormat(user.CreatedAt)
updatedAt, _ := utils.FormatDateToIndonesianFormat(user.UpdatedAt)
userResponse := &dto.UserResponseDTO{
ID: user.ID,
Username: user.Username,
Name: user.Name,
Phone: user.Phone,
Email: user.Email,
EmailVerified: user.EmailVerified,
RoleName: user.Role.RoleName,
CreatedAt: createdAt,
UpdatedAt: updatedAt,
}
return userResponse, nil
return "Password berhasil diupdate", nil
}
func (s *userProfileService) UpdateUserAvatar(userID string, file *multipart.FileHeader) (*dto.UserResponseDTO, error) {

View File

@ -10,12 +10,12 @@ import (
func APIKeyMiddleware(c *fiber.Ctx) error {
apiKey := c.Get("x-api-key")
if apiKey == "" {
return utils.GenericErrorResponse(c, fiber.StatusUnauthorized, "Unauthorized: API key is required")
return utils.GenericResponse(c, fiber.StatusUnauthorized, "Unauthorized: API key is required")
}
validAPIKey := os.Getenv("API_KEY")
if apiKey != validAPIKey {
return utils.GenericErrorResponse(c, fiber.StatusUnauthorized, "Unauthorized: Invalid API key")
return utils.GenericResponse(c, fiber.StatusUnauthorized, "Unauthorized: Invalid API key")
}
return c.Next()

View File

@ -11,7 +11,7 @@ import (
func AuthMiddleware(c *fiber.Ctx) error {
tokenString := c.Get("Authorization")
if tokenString == "" {
return utils.GenericErrorResponse(c, fiber.StatusUnauthorized, "Unauthorized: No token provided")
return utils.GenericResponse(c, fiber.StatusUnauthorized, "Unauthorized: No token provided")
}
if len(tokenString) > 7 && tokenString[:7] == "Bearer " {
@ -22,29 +22,29 @@ func AuthMiddleware(c *fiber.Ctx) error {
return []byte(os.Getenv("SECRET_KEY")), nil
})
if err != nil || !token.Valid {
return utils.GenericErrorResponse(c, fiber.StatusUnauthorized, "Unauthorized: Invalid token")
return utils.GenericResponse(c, fiber.StatusUnauthorized, "Unauthorized: Invalid token")
}
claims, ok := token.Claims.(jwt.MapClaims)
if !ok || claims["sub"] == nil {
return utils.GenericErrorResponse(c, fiber.StatusUnauthorized, "Unauthorized: Invalid token claims")
return utils.GenericResponse(c, fiber.StatusUnauthorized, "Unauthorized: Invalid token claims")
}
userID := claims["sub"].(string)
if userID == "" {
return utils.GenericErrorResponse(c, fiber.StatusUnauthorized, "Unauthorized: Invalid user session")
return utils.GenericResponse(c, fiber.StatusUnauthorized, "Unauthorized: Invalid user session")
}
sessionKey := "session:" + userID
sessionData, err := utils.GetJSONData(sessionKey)
if err != nil || sessionData == nil {
return utils.GenericErrorResponse(c, fiber.StatusUnauthorized, "Session expired or invalid")
return utils.GenericResponse(c, fiber.StatusUnauthorized, "Session expired or invalid")
}
roleID, roleOK := sessionData["roleID"].(string)
roleName, roleNameOK := sessionData["roleName"].(string)
if !roleOK || !roleNameOK {
return utils.GenericErrorResponse(c, fiber.StatusUnauthorized, "Unauthorized: Invalid session data")
return utils.GenericResponse(c, fiber.StatusUnauthorized, "Unauthorized: Invalid session data")
}
c.Locals("userID", userID)

View File

@ -9,12 +9,12 @@ func RoleMiddleware(allowedRoles ...string) fiber.Handler {
return func(c *fiber.Ctx) error {
if len(allowedRoles) == 0 {
return utils.GenericErrorResponse(c, fiber.StatusForbidden, "Forbidden: No roles specified")
return utils.GenericResponse(c, fiber.StatusForbidden, "Forbidden: No roles specified")
}
roleID, ok := c.Locals("roleID").(string)
if !ok || roleID == "" {
return utils.GenericErrorResponse(c, fiber.StatusUnauthorized, "Unauthorized: Role not found")
return utils.GenericResponse(c, fiber.StatusUnauthorized, "Unauthorized: Role not found")
}
for _, role := range allowedRoles {
@ -23,6 +23,6 @@ func RoleMiddleware(allowedRoles ...string) fiber.Handler {
}
}
return utils.GenericErrorResponse(c, fiber.StatusForbidden, "Access Denied: You don't have permission to access this resource")
return utils.GenericResponse(c, fiber.StatusForbidden, "Access Denied: You don't have permission to access this resource")
}
}

View File

@ -74,7 +74,7 @@ func InternalServerErrorResponse(c *fiber.Ctx, message string) error {
return c.Status(fiber.StatusInternalServerError).JSON(response)
}
func GenericErrorResponse(c *fiber.Ctx, status int, message string) error {
func GenericResponse(c *fiber.Ctx, status int, message string) error {
response := APIResponse{
Meta: MetaData{
Status: status,