Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
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
43 changes: 41 additions & 2 deletions internal/handler/admin_handler.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package handler

import (
"errors"
"net/http"

"github.com/gin-gonic/gin"
Expand Down Expand Up @@ -39,8 +40,30 @@ func (h *AdminHandler) GetUsers(c *gin.Context) {
// @Success 200 {object} utils.Response
// @Router /api/admin/users/{id}/lock [post]
func (h *AdminHandler) LockUser(c *gin.Context) {
adminID := c.GetString("userID")
userID := c.Param("id")
// TODO: Implement LockUser in AuthService
ipAddress := c.ClientIP()
userAgent := c.GetHeader("User-Agent")
if err := h.authService.LockUser(userID, adminID, ipAddress, userAgent); err != nil {
switch {
case errors.Is(err, service.ErrUserNotFound):
c.JSON(http.StatusNotFound,
utils.ErrorResponse("User not found", err))
case errors.Is(err, service.ErrSelfLock):
c.JSON(http.StatusBadRequest,
utils.ErrorResponse("Cannot lock your own account", err))
case errors.Is(err, service.ErrAdminLock):
c.JSON(http.StatusForbidden,
utils.ErrorResponse("Admin accounts cannot be locked", err))
case errors.Is(err, service.ErrAlreadyLocked):
c.JSON(http.StatusConflict,
utils.ErrorResponse("Account is already locked", err))
default:
c.JSON(http.StatusInternalServerError,
utils.ErrorResponse("Failed to lock user", err))
}
return
}
c.JSON(http.StatusOK, utils.SuccessResponse("User locked successfully", map[string]string{"userID": userID}))
}

Expand All @@ -52,8 +75,24 @@ func (h *AdminHandler) LockUser(c *gin.Context) {
// @Success 200 {object} utils.Response
// @Router /api/admin/users/{id}/unlock [post]
func (h *AdminHandler) UnlockUser(c *gin.Context) {
adminID := c.GetString("userID")
userID := c.Param("id")
// TODO: Implement UnlockUser in AuthService
ipAddress := c.ClientIP()
userAgent := c.GetHeader("User-Agent")
if err := h.authService.UnlockUser(userID, adminID, ipAddress, userAgent); err != nil {
switch {
case errors.Is(err, service.ErrUserNotFound):
c.JSON(http.StatusNotFound,
utils.ErrorResponse("User not found", err))
case errors.Is(err, service.ErrNotLocked):
c.JSON(http.StatusBadRequest,
utils.ErrorResponse("Account is not locked", err))
default:
c.JSON(http.StatusInternalServerError,
utils.ErrorResponse("Failed to unlock user", err))
}
return
}
c.JSON(http.StatusOK, utils.SuccessResponse("User unlocked successfully", map[string]string{"userID": userID}))
}

Expand Down
184 changes: 184 additions & 0 deletions internal/handler/admin_handler_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,184 @@
package handler_test

import (
"net/http"
"net/http/httptest"
"testing"

"github.com/gin-gonic/gin"
"github.com/roshankumar0036singh/auth-server/internal/handler"

"github.com/roshankumar0036singh/auth-server/internal/config"
"github.com/roshankumar0036singh/auth-server/internal/dto"
"github.com/roshankumar0036singh/auth-server/internal/middleware"
"github.com/roshankumar0036singh/auth-server/internal/repository"
"github.com/roshankumar0036singh/auth-server/internal/service"
"github.com/roshankumar0036singh/auth-server/internal/testutils"

"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)

func setupAdminLockRouter(t *testing.T) (
*gin.Engine,
*service.AuthService,
*service.TokenService,
*repository.UserRepository,
) {
t.Helper()

authSvc, db, mr := testutils.SetupIntegrationTest(t)

t.Cleanup(func() {
mr.Close()
})

userRepo := repository.NewUserRepository(db)

cfg := &config.Config{
JWT: config.JWTConfig{
AccessSecret: "test-access-secret",
RefreshSecret: "test-refresh-secret",
},
}

tokenSvc := service.NewTokenService(cfg)

adminHandler := handler.NewAdminHandler(authSvc)

gin.SetMode(gin.TestMode)

r := gin.New()

admin := r.Group("/api/admin")
admin.Use(middleware.AuthMiddleware(tokenSvc))
admin.Use(middleware.RequireRole("admin"))

admin.POST("/users/:id/lock", adminHandler.LockUser)
admin.POST("/users/:id/unlock", adminHandler.UnlockUser)

return r, authSvc, tokenSvc, userRepo
}

func TestAdminHandler_LockUser_Errors(t *testing.T) {
r, authSvc, tokenSvc, userRepo := setupAdminLockRouter(t)

admin, err := authSvc.Register(&dto.RegisterRequest{
Email: "lock-admin@test.com",
Password: "Password123!",
})
require.NoError(t, err)

require.NoError(t,
userRepo.Update(admin.ID, map[string]interface{}{"role": "admin"}))
admin.Role = "admin"

user, err := authSvc.Register(&dto.RegisterRequest{
Email: "lock-user@test.com",
Password: "Password123!",
})
require.NoError(t, err)

otherAdmin, err := authSvc.Register(&dto.RegisterRequest{
Email: "lock-other-admin@test.com",
Password: "Password123!",
})
require.NoError(t, err)

require.NoError(t,
userRepo.Update(otherAdmin.ID, map[string]interface{}{"role": "admin"}))

// ensure already locked case is valid
require.NoError(t,
authSvc.LockUser(user.ID, admin.ID, "", ""))

token, err := tokenSvc.GenerateAccessToken(admin)
require.NoError(t, err)

tests := []struct {
name string
userID string
status int
}{
{"user not found", "00000000-0000-0000-0000-000000000000", http.StatusNotFound},
{"self lock", admin.ID, http.StatusBadRequest},
{"admin account", otherAdmin.ID, http.StatusForbidden},
{"already locked", user.ID, http.StatusConflict},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
req := httptest.NewRequest(
http.MethodPost,
"/api/admin/users/"+tt.userID+"/lock",
nil,
)
req.Header.Set("Authorization", "Bearer "+token)

w := httptest.NewRecorder()
r.ServeHTTP(w, req)

assert.Equal(t, tt.status, w.Code)
})
}
}

func TestAdminHandler_UnlockUser_Errors(t *testing.T) {
r, authSvc, tokenSvc, userRepo := setupAdminLockRouter(t)

admin, err := authSvc.Register(&dto.RegisterRequest{
Email: "unlock-admin@test.com",
Password: "Password123!",
})
require.NoError(t, err)

require.NoError(t,
userRepo.Update(admin.ID, map[string]interface{}{"role": "admin"}))
admin.Role = "admin"

// user 1: will be NOT locked
unlockedUser, err := authSvc.Register(&dto.RegisterRequest{
Email: "unlock-user@test.com",
Password: "Password123!",
})
require.NoError(t, err)

// user 2: will be locked
lockedUser, err := authSvc.Register(&dto.RegisterRequest{
Email: "unlock-user-locked@test.com",
Password: "Password123!",
})
require.NoError(t, err)

require.NoError(t,
authSvc.LockUser(lockedUser.ID, admin.ID, "", ""),
)

token, err := tokenSvc.GenerateAccessToken(admin)
require.NoError(t, err)

tests := []struct {
name string
userID string
status int
}{
{"user not found", "00000000-0000-0000-0000-000000000000", http.StatusNotFound},
{"not locked", unlockedUser.ID, http.StatusBadRequest},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
req := httptest.NewRequest(
http.MethodPost,
"/api/admin/users/"+tt.userID+"/unlock",
nil,
)
req.Header.Set("Authorization", "Bearer "+token)

w := httptest.NewRecorder()
r.ServeHTTP(w, req)

assert.Equal(t, tt.status, w.Code)
})
}
}
5 changes: 5 additions & 0 deletions internal/models/user.go
Original file line number Diff line number Diff line change
Expand Up @@ -77,3 +77,8 @@ func (u *User) ToPublic() *PublicUser {
LastLoginAt: u.LastLoginAt,
}
}

func (u *User) IsLocked() bool {
return u.LockedUntil != nil &&
time.Now().Before(*u.LockedUntil)
}
36 changes: 36 additions & 0 deletions internal/repository/user_repository.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package repository

import (
"errors"
"time"

"github.com/roshankumar0036singh/auth-server/internal/models"
"gorm.io/gorm"
Expand Down Expand Up @@ -76,3 +77,38 @@ func (r *UserRepository) EmailExists(email string) (bool, error) {
err := r.db.Model(&models.User{}).Where("email = ?", email).Count(&count).Error
return count > 0, err
}

func (r *UserRepository) LockUser(userID string, lockedUntil time.Time) error {
result := r.db.Model(&models.User{}).
Where("id = ?", userID).
Update("locked_until", lockedUntil)

if result.Error != nil {
return result.Error
}

if result.RowsAffected == 0 {
return ErrUserNotFound
}

return nil
}

func (r *UserRepository) UnlockUser(userID string) error {
result := r.db.Model(&models.User{}).
Where("id = ?", userID).
Updates(map[string]interface{}{
"locked_until": nil,
"failed_login_attempts": 0,
})

if result.Error != nil {
return result.Error
}

if result.RowsAffected == 0 {
return ErrUserNotFound
}

return nil
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
1 change: 1 addition & 0 deletions internal/routes/routes.go
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ func SetupRoutes(router *gin.Engine, db *gorm.DB, redisClient *redis.Client, cfg
auditService,
mfaService,
cfg,
db,
)

// OAuth Provider service
Expand Down
Loading
Loading