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
|
package api
import (
"context"
"net/http"
"strings"
"github.com/labstack/echo/v4"
"github.com/nsfisis/iosdc-2024-albatross-backend/auth"
"github.com/nsfisis/iosdc-2024-albatross-backend/db"
)
type ApiHandler struct {
q *db.Queries
}
func NewHandler(queries *db.Queries) *ApiHandler {
return &ApiHandler{
q: queries,
}
}
func (h *ApiHandler) PostApiLogin(ctx context.Context, request PostApiLoginRequestObject) (PostApiLoginResponseObject, error) {
username := request.Body.Username
password := request.Body.Password
userId, err := auth.Login(ctx, h.q, username, password)
if err != nil {
return PostApiLogin401JSONResponse{
Message: "Invalid username or password",
}, echo.NewHTTPError(http.StatusUnauthorized, "Invalid username or password")
}
user, err := h.q.GetUserById(ctx, int32(userId))
if err != nil {
return PostApiLogin401JSONResponse{
Message: "Invalid username or password",
}, echo.NewHTTPError(http.StatusUnauthorized, "Invalid username or password")
}
jwt, err := auth.NewJWT(&user)
if err != nil {
// TODO
return PostApiLogin401JSONResponse{
Message: "Internal Server Error",
}, echo.NewHTTPError(http.StatusInternalServerError, "Internal Server Error")
}
return PostApiLogin200JSONResponse{
Token: jwt,
}, nil
}
func _assertJwtPayloadIsCompatibleWithJWTClaims() {
var c auth.JWTClaims
var p JwtPayload
p.UserId = c.UserID
p.Username = c.Username
p.DisplayName = c.DisplayName
p.IconPath = c.IconPath
p.IsAdmin = c.IsAdmin
_ = p
}
func NewJWTMiddleware() StrictMiddlewareFunc {
return func(handler StrictHandlerFunc, operationID string) StrictHandlerFunc {
if operationID == "PostApiLogin" {
return handler
} else {
return func(c echo.Context, request interface{}) (response interface{}, err error) {
authorization := c.Request().Header.Get("Authorization")
const prefix = "Bearer "
if !strings.HasPrefix(authorization, prefix) {
return nil, echo.NewHTTPError(http.StatusUnauthorized)
}
token := authorization[len(prefix):]
claims, err := auth.ParseJWT(token)
if err != nil {
return nil, echo.NewHTTPError(http.StatusUnauthorized)
}
c.SetRequest(c.Request().WithContext(context.WithValue(c.Request().Context(), "user", claims)))
return handler(c, request)
}
}
}
}
|