-
Notifications
You must be signed in to change notification settings - Fork 0
/
security.go
59 lines (46 loc) · 1.07 KB
/
security.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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
package security
import (
"context"
"database/sql"
"errors"
"github.com/gaydin/journey/admin/generated"
"github.com/gaydin/journey/authentication"
"github.com/gaydin/journey/store"
)
func New(db store.Database) *Handler {
return &Handler{
db: db,
}
}
type Handler struct {
db store.Database
}
type AuthError struct {
generated.Unauthorized
m string
}
func (ae *AuthError) Error() string {
return ae.m
}
func (sh *Handler) HandleCookieAuth(ctx context.Context, _ string, t generated.CookieAuth) (context.Context, error) {
userName := authentication.GetUserNameString(t.APIKey)
if userName == "" {
return nil, &AuthError{m: "not logged in"}
}
user, err := sh.db.RetrieveUserByName(ctx, userName)
switch {
case errors.Is(err, sql.ErrNoRows):
return nil, errors.New("unknown user")
case err != nil:
return nil, err
}
return context.WithValue(ctx, contextUserIDKey{}, user.Id), nil
}
type contextUserIDKey struct{}
func GetUserID(ctx context.Context) int64 {
userName, ok := ctx.Value(contextUserIDKey{}).(int64)
if !ok {
return 0
}
return userName
}