-
Notifications
You must be signed in to change notification settings - Fork 2
/
auth.go
76 lines (60 loc) · 1.4 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
package wg
import (
"context"
"errors"
"fmt"
"github.com/dgrijalva/jwt-go"
"google.golang.org/grpc/metadata"
)
const (
AUTH_KEY = "wg"
)
var (
InvalidAuthKey = errors.New("Invalid Authentication Key")
InvalidTokenFormatErr = errors.New("Invalid token format")
MissingKeyErr = errors.New("No Authentication Key provided")
)
type Authenticator interface {
AuthenticateContext(context.Context) error
}
type auth struct {
sKey string // Signin Key
aKey string // Auth Key
}
func NewAuthenticator(Skey, AKey string) Authenticator {
return &auth{sKey: Skey, aKey: AKey}
}
func (a *auth) AuthenticateContext(ctx context.Context) error {
md, ok := metadata.FromIncomingContext(ctx)
if !ok {
return MissingKeyErr
}
if len(md["token"]) == 0 {
return MissingKeyErr
}
token := md["token"][0]
if token == "" {
return MissingKeyErr
}
jwtToken, err := jwt.Parse(token, func(token *jwt.Token) (interface{}, error) {
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return ctx, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"])
}
return []byte(a.sKey), nil
})
if err != nil {
return err
}
claims, ok := jwtToken.Claims.(jwt.MapClaims)
if !ok || !jwtToken.Valid {
return InvalidTokenFormatErr
}
authKey, ok := claims[AUTH_KEY].(string)
if !ok {
return InvalidTokenFormatErr
}
if authKey != a.aKey {
return InvalidAuthKey
}
return nil
}