/
v0middleware.go
72 lines (61 loc) · 1.88 KB
/
v0middleware.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
package v0
import (
"context"
"strconv"
"gitlab.com/tonyhb/keepupdated/pkg/api/auth"
"gitlab.com/tonyhb/keepupdated/pkg/api/v0/errors"
"gitlab.com/tonyhb/keepupdated/pkg/types"
"github.com/emicklei/go-restful"
"github.com/opentracing/opentracing-go"
)
// MustAuth is middleware which ensures that a user is authenticated before
// invoking the given handler. Being authenticated means:
//
// - The user has a valid JWT
// - We're able to load the user and the user's account
//
// Typically this should be the first middleware in a chain to authenticated
// endpoints.
//
// This adds a types.User as the "user" value of the context, and a
// types.Account as the "acct" value of the context.
func (v *V0) MustAuth(ctx context.Context, r *restful.Request, w *restful.Response) (context.Context, error) {
idstr, err := auth.ParseJWT(r.Request)
if err != nil {
return ctx, errors.APIError{
Status: 401,
Message: "unable to authenticate",
Detail: err.Error(),
}
}
id, err := strconv.Atoi(idstr)
if err != nil {
return ctx, errors.APIError{
Status: 401,
Message: "unable to authenticate",
Detail: err.Error(),
}
}
// Create a child span from our parent
span, mustAuthCtx := opentracing.StartSpanFromContext(ctx, "mustAuth")
defer span.Finish()
user, err := v.mgr.UserByID(mustAuthCtx, id)
if err != nil {
return ctx, errors.ErrInvalidCredentials
}
acct, err := v.mgr.AccountByID(mustAuthCtx, user.AccountID)
if err != nil {
return ctx, errors.ErrInvalidCredentials
}
// don't store pointers in contexts
ctx = context.WithValue(ctx, "user", *user)
ctx = context.WithValue(ctx, "acct", *acct)
return ctx, nil
}
func (v *V0) AccountIsActive(ctx context.Context, r *restful.Request, w *restful.Response) (context.Context, error) {
acct := ctx.Value("acct").(types.Account)
if !acct.IsActive() {
return ctx, errors.ErrInactiveAccount
}
return ctx, nil
}