|
| 1 | +package controller |
| 2 | + |
| 3 | +import ( |
| 4 | + "errors" |
| 5 | + "net/http" |
| 6 | + "sync" |
| 7 | + "time" |
| 8 | + |
| 9 | + "shadmin/domain" |
| 10 | + "shadmin/internal/constants" |
| 11 | + |
| 12 | + "github.com/gin-gonic/gin" |
| 13 | +) |
| 14 | + |
| 15 | +type DeviceAuthController struct { |
| 16 | + DeviceAuthUsecase domain.DeviceAuthUsecase |
| 17 | + requestLimiter *deviceAuthRateLimiter |
| 18 | + pollLimiter *deviceAuthRateLimiter |
| 19 | + activateLimiter *deviceAuthRateLimiter |
| 20 | +} |
| 21 | + |
| 22 | +func NewDeviceAuthController(deviceAuthUsecase domain.DeviceAuthUsecase) *DeviceAuthController { |
| 23 | + return &DeviceAuthController{ |
| 24 | + DeviceAuthUsecase: deviceAuthUsecase, |
| 25 | + requestLimiter: newDeviceAuthRateLimiter(10, time.Minute), |
| 26 | + pollLimiter: newDeviceAuthRateLimiter(60, time.Minute), |
| 27 | + activateLimiter: newDeviceAuthRateLimiter(20, time.Minute), |
| 28 | + } |
| 29 | +} |
| 30 | + |
| 31 | +// RequestCode godoc |
| 32 | +// @Summary Request device authorization code |
| 33 | +// @Description Create a device authorization session for CLI login |
| 34 | +// @Tags Authentication |
| 35 | +// @Accept json |
| 36 | +// @Produce json |
| 37 | +// @Param request body domain.DeviceCodeRequest true "Device code request" |
| 38 | +// @Success 200 {object} domain.Response{data=domain.DeviceCodeResponse} |
| 39 | +// @Failure 400 {object} domain.Response |
| 40 | +// @Failure 500 {object} domain.Response |
| 41 | +// @Router /auth/device/code [post] |
| 42 | +func (dc *DeviceAuthController) RequestCode(c *gin.Context) { |
| 43 | + if !dc.allow(c, dc.requestLimiter) { |
| 44 | + return |
| 45 | + } |
| 46 | + |
| 47 | + var request domain.DeviceCodeRequest |
| 48 | + if !MustBindJSON(c, &request) { |
| 49 | + return |
| 50 | + } |
| 51 | + |
| 52 | + resp, err := dc.DeviceAuthUsecase.RequestCode(c, request, "/auth/device") |
| 53 | + if err != nil { |
| 54 | + c.JSON(http.StatusInternalServerError, domain.RespError(err.Error())) |
| 55 | + return |
| 56 | + } |
| 57 | + c.JSON(http.StatusOK, domain.RespSuccess(resp)) |
| 58 | +} |
| 59 | + |
| 60 | +// PollToken godoc |
| 61 | +// @Summary Poll device authorization token |
| 62 | +// @Description Poll until user authorizes a device code, then return JWT tokens |
| 63 | +// @Tags Authentication |
| 64 | +// @Accept json |
| 65 | +// @Produce json |
| 66 | +// @Param request body domain.DeviceTokenRequest true "Device token request" |
| 67 | +// @Success 200 {object} domain.Response{data=domain.LoginResponse} |
| 68 | +// @Failure 400 {object} domain.Response |
| 69 | +// @Failure 500 {object} domain.Response |
| 70 | +// @Router /auth/device/token [post] |
| 71 | +func (dc *DeviceAuthController) PollToken(c *gin.Context) { |
| 72 | + if !dc.allow(c, dc.pollLimiter) { |
| 73 | + return |
| 74 | + } |
| 75 | + |
| 76 | + var request domain.DeviceTokenRequest |
| 77 | + if !MustBindJSON(c, &request) { |
| 78 | + return |
| 79 | + } |
| 80 | + |
| 81 | + resp, err := dc.DeviceAuthUsecase.PollToken(c, request) |
| 82 | + if err != nil { |
| 83 | + status := http.StatusBadRequest |
| 84 | + switch { |
| 85 | + case errors.Is(err, domain.ErrDeviceAuthorizationPending), |
| 86 | + errors.Is(err, domain.ErrDeviceSlowDown), |
| 87 | + errors.Is(err, domain.ErrDeviceExpired), |
| 88 | + errors.Is(err, domain.ErrDeviceConsumed), |
| 89 | + errors.Is(err, domain.ErrDeviceAccessDenied), |
| 90 | + errors.Is(err, domain.ErrDeviceInvalidCode): |
| 91 | + status = http.StatusBadRequest |
| 92 | + default: |
| 93 | + status = http.StatusInternalServerError |
| 94 | + } |
| 95 | + c.JSON(status, domain.RespError(err.Error())) |
| 96 | + return |
| 97 | + } |
| 98 | + c.JSON(http.StatusOK, domain.RespSuccess(resp)) |
| 99 | +} |
| 100 | + |
| 101 | +// Activate godoc |
| 102 | +// @Summary Activate device authorization code |
| 103 | +// @Description Authorize a CLI device code using the current web user session |
| 104 | +// @Tags Authentication |
| 105 | +// @Accept json |
| 106 | +// @Produce json |
| 107 | +// @Param request body domain.DeviceActivateRequest true "Device activation request" |
| 108 | +// @Success 200 {object} domain.Response{data=domain.DeviceActivateResponse} |
| 109 | +// @Failure 400 {object} domain.Response |
| 110 | +// @Failure 401 {object} domain.Response |
| 111 | +// @Failure 500 {object} domain.Response |
| 112 | +// @Router /auth/device/activate [post] |
| 113 | +func (dc *DeviceAuthController) Activate(c *gin.Context) { |
| 114 | + if !dc.allow(c, dc.activateLimiter) { |
| 115 | + return |
| 116 | + } |
| 117 | + |
| 118 | + var request domain.DeviceActivateRequest |
| 119 | + if !MustBindJSON(c, &request) { |
| 120 | + return |
| 121 | + } |
| 122 | + |
| 123 | + userIDValue, exists := c.Get(constants.UserID) |
| 124 | + if !exists { |
| 125 | + c.JSON(http.StatusUnauthorized, domain.RespError("Not authorized")) |
| 126 | + return |
| 127 | + } |
| 128 | + userID, ok := userIDValue.(string) |
| 129 | + if !ok || userID == "" { |
| 130 | + c.JSON(http.StatusUnauthorized, domain.RespError("Invalid user context")) |
| 131 | + return |
| 132 | + } |
| 133 | + |
| 134 | + resp, err := dc.DeviceAuthUsecase.Activate(c, userID, request) |
| 135 | + if err != nil { |
| 136 | + status := http.StatusBadRequest |
| 137 | + if !errors.Is(err, domain.ErrDeviceInvalidCode) && |
| 138 | + !errors.Is(err, domain.ErrDeviceExpired) && |
| 139 | + !errors.Is(err, domain.ErrDeviceAccessDenied) { |
| 140 | + status = http.StatusInternalServerError |
| 141 | + } |
| 142 | + c.JSON(status, domain.RespError(err.Error())) |
| 143 | + return |
| 144 | + } |
| 145 | + c.JSON(http.StatusOK, domain.RespSuccess(resp)) |
| 146 | +} |
| 147 | + |
| 148 | +func (dc *DeviceAuthController) allow(c *gin.Context, limiter *deviceAuthRateLimiter) bool { |
| 149 | + if limiter == nil || limiter.Allow(c.ClientIP()) { |
| 150 | + return true |
| 151 | + } |
| 152 | + c.JSON(http.StatusTooManyRequests, domain.RespError("too_many_requests")) |
| 153 | + return false |
| 154 | +} |
| 155 | + |
| 156 | +// Close is kept for callers that manage controller lifecycles. |
| 157 | +func (dc *DeviceAuthController) Close() { |
| 158 | + dc.requestLimiter.close() |
| 159 | + dc.pollLimiter.close() |
| 160 | + dc.activateLimiter.close() |
| 161 | +} |
| 162 | + |
| 163 | +type deviceAuthRateLimiter struct { |
| 164 | + mu sync.Mutex |
| 165 | + limit int |
| 166 | + window time.Duration |
| 167 | + hits map[string]*deviceAuthRateLimitEntry |
| 168 | + lastCleanup time.Time |
| 169 | +} |
| 170 | + |
| 171 | +type deviceAuthRateLimitEntry struct { |
| 172 | + count int |
| 173 | + windowStart time.Time |
| 174 | +} |
| 175 | + |
| 176 | +func newDeviceAuthRateLimiter(limit int, window time.Duration) *deviceAuthRateLimiter { |
| 177 | + l := &deviceAuthRateLimiter{ |
| 178 | + limit: limit, |
| 179 | + window: window, |
| 180 | + hits: make(map[string]*deviceAuthRateLimitEntry), |
| 181 | + lastCleanup: time.Now(), |
| 182 | + } |
| 183 | + return l |
| 184 | +} |
| 185 | + |
| 186 | +func (l *deviceAuthRateLimiter) cleanupExpiredLocked(now time.Time) { |
| 187 | + for key, entry := range l.hits { |
| 188 | + if now.Sub(entry.windowStart) >= l.window { |
| 189 | + delete(l.hits, key) |
| 190 | + } |
| 191 | + } |
| 192 | +} |
| 193 | + |
| 194 | +// close is kept for controller lifecycle compatibility. |
| 195 | +func (l *deviceAuthRateLimiter) close() { |
| 196 | +} |
| 197 | + |
| 198 | +func (l *deviceAuthRateLimiter) Allow(key string) bool { |
| 199 | + if key == "" { |
| 200 | + key = "unknown" |
| 201 | + } |
| 202 | + now := time.Now() |
| 203 | + l.mu.Lock() |
| 204 | + defer l.mu.Unlock() |
| 205 | + if now.Sub(l.lastCleanup) >= l.window { |
| 206 | + l.cleanupExpiredLocked(now) |
| 207 | + l.lastCleanup = now |
| 208 | + } |
| 209 | + |
| 210 | + entry, ok := l.hits[key] |
| 211 | + if !ok || now.Sub(entry.windowStart) >= l.window { |
| 212 | + l.hits[key] = &deviceAuthRateLimitEntry{count: 1, windowStart: now} |
| 213 | + return true |
| 214 | + } |
| 215 | + if entry.count >= l.limit { |
| 216 | + return false |
| 217 | + } |
| 218 | + entry.count++ |
| 219 | + return true |
| 220 | +} |
0 commit comments