-
-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathauth.go
45 lines (38 loc) · 1.04 KB
/
auth.go
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
package handlers
import (
"context"
"errors"
"github.com/danielgtaylor/huma/v2"
"github.com/enchant97/note-mark/backend/config"
"github.com/enchant97/note-mark/backend/core"
"github.com/enchant97/note-mark/backend/services"
)
func SetupAuthHandler(api huma.API, appConfig config.AppConfig) {
authHandler := AuthHandler{
AppConfig: appConfig,
}
huma.Post(api, "/api/auth/token", authHandler.PostToken)
}
type PostTokenInput struct {
Body core.AccessTokenRequest
}
type PostTokenOutput struct {
Body core.AccessToken
}
type AuthHandler struct {
services.AuthService
AppConfig config.AppConfig
}
func (h AuthHandler) PostToken(ctx context.Context, input *PostTokenInput) (*PostTokenOutput, error) {
if token, err := h.AuthService.GetAccessToken(h.AppConfig, input.Body.Username, input.Body.Password); err != nil {
if errors.Is(err, services.InvalidCredentialsError) {
return nil, huma.Error401Unauthorized("invalid credentials given")
} else {
return nil, err
}
} else {
return &PostTokenOutput{
Body: token,
}, nil
}
}