-
Notifications
You must be signed in to change notification settings - Fork 12
/
auth.go
51 lines (42 loc) · 1.08 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
package main
import (
"errors"
"time"
jwt "github.com/dgrijalva/jwt-go"
)
// AuthService provides authentication service
type AuthService interface {
Auth(string, string) (string, error)
}
type authService struct {
key []byte
clients map[string]string
}
type customClaims struct {
ClientID string `json:"clientId"`
jwt.StandardClaims
}
const expiration = 120
func generateToken(signingKey []byte, clientID string) (string, error) {
claims := customClaims{
clientID,
jwt.StandardClaims{
ExpiresAt: time.Now().Add(time.Second * expiration).Unix(),
IssuedAt: jwt.TimeFunc().Unix(),
},
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
return token.SignedString(signingKey)
}
func (as authService) Auth(clientID string, clientSecret string) (string, error) {
if as.clients[clientID] == clientSecret {
signed, err := generateToken(as.key, clientID)
if err != nil {
return "", errors.New(err.Error())
}
return signed, nil
}
return "", ErrAuth
}
// ErrAuth is returned when credentials are incorrect
var ErrAuth = errors.New("Incorrect credentials")