/
token.go
81 lines (68 loc) · 2.42 KB
/
token.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
// Package token provide support for generating and validating JWT tokens.
package token
import (
"context"
"fmt"
"net/http"
"time"
"github.com/dgrijalva/jwt-go"
"github.com/dgrijalva/jwt-go/request"
"github.com/yaptide/app/config"
"github.com/yaptide/app/web/server/middleware"
"gopkg.in/mgo.v2/bson"
)
// Generate generate JWT token for account, signed by key.
// Used claims: "id" -> account.ID (bson.ObjectId),
// "exp" -> exp time (int64).
func Generate(id bson.ObjectId, key []byte) (string, error) {
token := jwt.New(jwt.SigningMethodHS256)
claims := token.Claims.(jwt.MapClaims)
claims["id"] = id
claims["exp"] = time.Now().Add(time.Hour * 24).Unix()
if config.DEVEnv {
claims["exp"] = time.Now().Add(time.Hour * 2400).Unix()
}
tokenString, err := token.SignedString(key)
return tokenString, err
}
// ContextKeyType is type of keys used in context.Context map
// TODO move somewhere else
type ContextKeyType int
// ContextIDKey is key for "id" in context.Context map
const ContextIDKey ContextKeyType = 0
// NewValidationMiddleware create middleware which validate access to next http.Handler.
// Returned middleware call next.Serve.Http(w, r), if token from response is correct.
// Otherwise WriteHeader http.StatusUnauthorized and write proper message to w.
// Token is taken from HTTP header: "X-Auth-Token".
// Token claims are passed by context.Context.
func NewValidationMiddleware(key []byte) middleware.Middleware {
return func(next http.Handler) http.Handler {
handlerFunc := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
var keyFunc jwt.Keyfunc = func(*jwt.Token) (interface{}, error) {
return key, nil
}
token, err := request.ParseFromRequest(r, request.HeaderExtractor{"X-Auth-Token"}, keyFunc)
if err != nil {
w.WriteHeader(http.StatusUnauthorized)
_, _ = fmt.Fprint(w, "Unauthorised access to this resource")
return
}
claims, ok := token.Claims.(jwt.MapClaims)
if token.Valid && ok {
idKey := ContextIDKey
idVal := claims["id"]
ctx := context.WithValue(r.Context(), idKey, idVal)
next.ServeHTTP(w, r.WithContext(ctx))
} else {
w.WriteHeader(http.StatusUnauthorized)
_, _ = fmt.Fprint(w, "Token is not valid")
return
}
})
return handlerFunc
}
}
// ExtractAccountID return AccountID from context.Context.
func ExtractAccountID(r *http.Request) bson.ObjectId {
return bson.ObjectIdHex(r.Context().Value(ContextIDKey).(string))
}