-
Notifications
You must be signed in to change notification settings - Fork 485
/
http.go
84 lines (66 loc) · 2.01 KB
/
http.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
83
84
package auth
import (
"context"
"net/http"
"strings"
"firebase.google.com/go/v4/auth"
commonerrors "github.com/ThreeDotsLabs/wild-workouts-go-ddd-example/internal/common/errors"
"github.com/ThreeDotsLabs/wild-workouts-go-ddd-example/internal/common/server/httperr"
)
type FirebaseHttpMiddleware struct {
AuthClient *auth.Client
}
func (a FirebaseHttpMiddleware) Middleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
bearerToken := a.tokenFromHeader(r)
if bearerToken == "" {
httperr.Unauthorised("empty-bearer-token", nil, w, r)
return
}
token, err := a.AuthClient.VerifyIDToken(ctx, bearerToken)
if err != nil {
httperr.Unauthorised("unable-to-verify-jwt", err, w, r)
return
}
// it's always a good idea to use custom type as context value (in this case ctxKey)
// because nobody from the outside of the package will be able to override/read this value
ctx = context.WithValue(ctx, userContextKey, User{
UUID: token.UID,
Email: token.Claims["email"].(string),
Role: token.Claims["role"].(string),
DisplayName: token.Claims["name"].(string),
})
r = r.WithContext(ctx)
next.ServeHTTP(w, r)
})
}
func (a FirebaseHttpMiddleware) tokenFromHeader(r *http.Request) string {
headerValue := r.Header.Get("Authorization")
if len(headerValue) > 7 && strings.ToLower(headerValue[0:6]) == "bearer" {
return headerValue[7:]
}
return ""
}
type User struct {
UUID string
Email string
Role string
DisplayName string
}
type ctxKey int
const (
userContextKey ctxKey = iota
)
var (
// if we expect that the user of the function may be interested with concrete error,
// it's a good idea to provide variable with this error
NoUserInContextError = commonerrors.NewAuthorizationError("no user in context", "no-user-found")
)
func UserFromCtx(ctx context.Context) (User, error) {
u, ok := ctx.Value(userContextKey).(User)
if ok {
return u, nil
}
return User{}, NoUserInContextError
}