-
-
Notifications
You must be signed in to change notification settings - Fork 191
Expand file tree
/
Copy pathauth.go
More file actions
290 lines (250 loc) · 8.7 KB
/
auth.go
File metadata and controls
290 lines (250 loc) · 8.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
package handlers
import (
"context"
"errors"
"net/http"
"time"
"github.com/danielgtaylor/huma/v2"
"github.com/getarcaneapp/arcane/backend/internal/common"
humamw "github.com/getarcaneapp/arcane/backend/internal/huma/middleware"
"github.com/getarcaneapp/arcane/backend/internal/services"
"github.com/getarcaneapp/arcane/backend/pkg/utils/cookie"
"github.com/getarcaneapp/arcane/backend/pkg/utils/mapper"
"github.com/getarcaneapp/arcane/types/auth"
"github.com/getarcaneapp/arcane/types/base"
"github.com/getarcaneapp/arcane/types/user"
)
type AuthHandler struct {
userService *services.UserService
authService *services.AuthService
oidcService *services.OidcService
}
// --- Huma Input/Output Wrappers ---
// These wrap the types from the types package for Huma's input/output handling.
type LoginInput struct {
Body auth.Login
}
type LoginOutput struct {
SetCookie string `header:"Set-Cookie" doc:"Session cookie"`
Body base.ApiResponse[auth.LoginResponse]
}
type LogoutOutput struct {
SetCookie string `header:"Set-Cookie" doc:"Cleared session cookie"`
Body base.ApiResponse[base.MessageResponse]
}
type RefreshTokenInput struct {
Body auth.Refresh
}
type RefreshTokenOutput struct {
SetCookie string `header:"Set-Cookie" doc:"Updated session cookie"`
Body base.ApiResponse[auth.TokenRefreshResponse]
}
type ChangePasswordInput struct {
Body auth.PasswordChange
}
type ChangePasswordOutput struct {
Body base.ApiResponse[base.MessageResponse]
}
type GetCurrentUserOutput struct {
Body base.ApiResponse[user.User]
}
// RegisterAuth registers authentication routes using Huma.
func RegisterAuth(api huma.API, userService *services.UserService, authService *services.AuthService, oidcService *services.OidcService) {
h := &AuthHandler{
userService: userService,
authService: authService,
oidcService: oidcService,
}
huma.Register(api, huma.Operation{
OperationID: "login",
Method: http.MethodPost,
Path: "/auth/login",
Summary: "Login",
Description: "Authenticate a user with username and password",
Tags: []string{"Auth"},
Security: []map[string][]string{},
}, h.Login)
huma.Register(api, huma.Operation{
OperationID: "logout",
Method: http.MethodPost,
Path: "/auth/logout",
Summary: "Logout",
Description: "Clear authentication session",
Tags: []string{"Auth"},
Security: []map[string][]string{},
}, h.Logout)
huma.Register(api, huma.Operation{
OperationID: "get-current-user",
Method: http.MethodGet,
Path: "/auth/me",
Summary: "Get current user",
Description: "Get the currently authenticated user's information",
Tags: []string{"Auth"},
Security: []map[string][]string{
{"BearerAuth": {}},
{"ApiKeyAuth": {}},
},
}, h.GetCurrentUser)
huma.Register(api, huma.Operation{
OperationID: "refresh-token",
Method: http.MethodPost,
Path: "/auth/refresh",
Summary: "Refresh token",
Description: "Obtain a new access token using a refresh token",
Tags: []string{"Auth"},
Security: []map[string][]string{},
}, h.RefreshToken)
huma.Register(api, huma.Operation{
OperationID: "change-password",
Method: http.MethodPost,
Path: "/auth/password",
Summary: "Change password",
Description: "Change the current user's password",
Tags: []string{"Auth"},
Security: []map[string][]string{
{"BearerAuth": {}},
{"ApiKeyAuth": {}},
},
}, h.ChangePassword)
}
// Login authenticates a user and returns tokens.
func (h *AuthHandler) Login(ctx context.Context, input *LoginInput) (*LoginOutput, error) {
if h.authService == nil {
return nil, huma.Error500InternalServerError("service not available")
}
localAuthEnabled, err := h.authService.IsLocalAuthEnabled(ctx)
if err != nil {
return nil, huma.Error500InternalServerError((&common.AuthSettingsCheckError{Err: err}).Error())
}
if !localAuthEnabled {
return nil, huma.Error400BadRequest((&common.LocalAuthDisabledError{}).Error())
}
userModel, tokenPair, err := h.authService.Login(ctx, input.Body.Username, input.Body.Password)
if err != nil {
switch {
case errors.Is(err, services.ErrInvalidCredentials):
return nil, huma.Error401Unauthorized((&common.InvalidCredentialsError{}).Error())
case errors.Is(err, services.ErrLocalAuthDisabled):
return nil, huma.Error400BadRequest((&common.LocalAuthDisabledError{}).Error())
default:
return nil, huma.Error500InternalServerError((&common.AuthFailedError{Err: err}).Error())
}
}
var userResp user.User
if mapErr := mapper.MapStruct(userModel, &userResp); mapErr != nil {
return nil, huma.Error500InternalServerError((&common.UserMappingError{Err: mapErr}).Error())
}
maxAge := max(int(time.Until(tokenPair.ExpiresAt).Seconds()), 0)
maxAge += 60
return &LoginOutput{
SetCookie: cookie.BuildTokenCookieString(maxAge, tokenPair.AccessToken),
Body: base.ApiResponse[auth.LoginResponse]{
Success: true,
Data: auth.LoginResponse{
Token: tokenPair.AccessToken,
RefreshToken: tokenPair.RefreshToken,
ExpiresAt: tokenPair.ExpiresAt,
User: userResp,
},
},
}, nil
}
// Logout clears the authentication session.
func (h *AuthHandler) Logout(ctx context.Context, input *struct{}) (*LogoutOutput, error) {
if h.authService != nil {
if userModel, exists := humamw.GetCurrentUserFromContext(ctx); exists {
h.authService.LogLogout(ctx, userModel)
}
}
return &LogoutOutput{
SetCookie: cookie.BuildClearTokenCookieString(),
Body: base.ApiResponse[base.MessageResponse]{
Success: true,
Data: base.MessageResponse{
Message: "Logged out successfully",
},
},
}, nil
}
// GetCurrentUser returns the currently authenticated user's information.
func (h *AuthHandler) GetCurrentUser(ctx context.Context, input *struct{}) (*GetCurrentUserOutput, error) {
if h.userService == nil {
return nil, huma.Error500InternalServerError("service not available")
}
userID, exists := humamw.GetUserIDFromContext(ctx)
if !exists {
return nil, huma.Error401Unauthorized((&common.NotAuthenticatedError{}).Error())
}
userModel, err := h.userService.GetUser(ctx, userID)
if err != nil {
return nil, huma.Error500InternalServerError((&common.UserRetrievalError{Err: err}).Error())
}
var out user.User
if mapErr := mapper.MapStruct(userModel, &out); mapErr != nil {
return nil, huma.Error500InternalServerError((&common.UserMappingError{Err: mapErr}).Error())
}
return &GetCurrentUserOutput{
Body: base.ApiResponse[user.User]{
Success: true,
Data: out,
},
}, nil
}
// RefreshToken obtains a new access token using a refresh token.
func (h *AuthHandler) RefreshToken(ctx context.Context, input *RefreshTokenInput) (*RefreshTokenOutput, error) {
if h.authService == nil {
return nil, huma.Error500InternalServerError("service not available")
}
tokenPair, err := h.authService.RefreshToken(ctx, input.Body.RefreshToken)
if err != nil {
switch {
case errors.Is(err, services.ErrInvalidToken), errors.Is(err, services.ErrExpiredToken):
return nil, huma.Error401Unauthorized((&common.InvalidTokenError{}).Error())
default:
return nil, huma.Error500InternalServerError((&common.TokenRefreshError{Err: err}).Error())
}
}
maxAge := max(int(time.Until(tokenPair.ExpiresAt).Seconds()), 0)
maxAge += 60
return &RefreshTokenOutput{
SetCookie: cookie.BuildTokenCookieString(maxAge, tokenPair.AccessToken),
Body: base.ApiResponse[auth.TokenRefreshResponse]{
Success: true,
Data: auth.TokenRefreshResponse{
Token: tokenPair.AccessToken,
RefreshToken: tokenPair.RefreshToken,
ExpiresAt: tokenPair.ExpiresAt,
},
},
}, nil
}
// ChangePassword changes the current user's password.
func (h *AuthHandler) ChangePassword(ctx context.Context, input *ChangePasswordInput) (*ChangePasswordOutput, error) {
if h.authService == nil {
return nil, huma.Error500InternalServerError("service not available")
}
userModel, exists := humamw.GetCurrentUserFromContext(ctx)
if !exists {
return nil, huma.Error401Unauthorized((&common.NotAuthenticatedError{}).Error())
}
if input.Body.CurrentPassword == "" {
return nil, huma.Error400BadRequest((&common.PasswordRequiredError{}).Error())
}
err := h.authService.ChangePassword(ctx, userModel.ID, input.Body.CurrentPassword, input.Body.NewPassword)
if err != nil {
switch {
case errors.Is(err, services.ErrInvalidCredentials):
return nil, huma.Error401Unauthorized((&common.IncorrectPasswordError{}).Error())
default:
return nil, huma.Error500InternalServerError((&common.PasswordChangeError{Err: err}).Error())
}
}
return &ChangePasswordOutput{
Body: base.ApiResponse[base.MessageResponse]{
Success: true,
Data: base.MessageResponse{
Message: "Password changed successfully",
},
},
}, nil
}