-
Notifications
You must be signed in to change notification settings - Fork 0
/
auth.go
64 lines (54 loc) · 1.85 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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package mid
import (
"context"
"errors"
"net/http"
"github.com/aleury/service/business/web/auth"
v1 "github.com/aleury/service/business/web/v1"
"github.com/aleury/service/foundation/web"
"github.com/google/uuid"
)
// Set of error variables for handling user group errors.
var (
ErrInvalidID = errors.New("ID is not in its proper form")
)
// Authenticate validates a JWT from the `Authorization` header.
func Authenticate(a *auth.Auth) web.Middleware {
return func(handler web.Handler) web.Handler {
return func(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
claims, err := a.Authenticate(ctx, r.Header.Get("authorization"))
if err != nil {
return auth.NewAuthError("authenticate: failed: %s", err)
}
ctx = auth.SetClaims(ctx, claims)
return handler(ctx, w, r)
}
}
}
// Authorize validates that an authenticated user has at least one role from a
// specified list. This method constructs the actual function that is used.
func Authorize(a *auth.Auth, rule string) web.Middleware {
return func(handler web.Handler) web.Handler {
return func(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
claims := auth.GetClaims(ctx)
if claims.Subject == "" {
return auth.NewAuthError("authorize: you are not authorized for that action, no claims.")
}
// I will use a zero valued user id if it doesn't exist.
var userID uuid.UUID
id := web.Param(r, "user_id")
if id != "" {
var err error
userID, err = uuid.Parse(id)
if err != nil {
return v1.NewRequestError(ErrInvalidID, http.StatusBadRequest)
}
ctx = auth.SetUserID(ctx, userID)
}
if err := a.Authorize(ctx, claims, rule); err != nil {
return auth.NewAuthError("authorize: you are not authorized for that action: claims[%v] rule[%v]: %s", claims.Roles, rule, err)
}
return handler(ctx, w, r)
}
}
}