/
auth.go
82 lines (68 loc) · 2.41 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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
package mid
import (
"context"
"errors"
"fmt"
"net/http"
"strings"
"github.com/yosephbuitrago/garagesale/business/auth"
"github.com/yosephbuitrago/garagesale/foundation/web"
"go.opentelemetry.io/otel"
)
// Authenticate validates a JWT from the `Authorization` header.
func Authenticate(a *auth.Auth) web.Middleware {
// This is the actual middleware function to be executed.
m := func(handler web.Handler) web.Handler {
// Create the handler that will be attached in the middleware chain.
h := func(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
tr := otel.GetTracerProvider().Tracer("business.mid.authenticate")
_, span := tr.Start(ctx, "authenticate")
defer span.End()
// Expecting: bearer <token>
authStr := r.Header.Get("authorization")
// Parse the authorization header.
parts := strings.Split(authStr, " ")
if len(parts) != 2 || strings.ToLower(parts[0]) != "bearer" {
err := errors.New("expected authorization header format: bearer <token>")
return web.NewRequestError(err, http.StatusUnauthorized)
}
// Validate the token is signed by us.
claims, err := a.ValidateToken(parts[1])
if err != nil {
return web.NewRequestError(err, http.StatusUnauthorized)
}
// Add claims to the context so they can be retrieved later.
ctx = context.WithValue(ctx, auth.Key, claims)
return handler(ctx, w, r)
}
return h
}
return m
}
// 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(roles ...string) web.Middleware {
// This is the actual middleware function to be executed.
m := func(handler web.Handler) web.Handler {
// Create the handler that will be attached in the middleware chain.
h := func(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
tr := otel.GetTracerProvider().Tracer("business.mid.authorize")
_, span := tr.Start(ctx, "authorize")
defer span.End()
// If the context is missing this value return failure.
claims, ok := ctx.Value(auth.Key).(auth.Claims)
if !ok {
return errors.New("claims missing from context")
}
if !claims.Authorized(roles...) {
return web.NewRequestError(
fmt.Errorf("you are not authorized for that action: claims: %v exp: %v", claims.Roles, roles),
http.StatusForbidden,
)
}
return handler(ctx, w, r)
}
return h
}
return m
}