-
Notifications
You must be signed in to change notification settings - Fork 0
/
jwt.go
62 lines (56 loc) · 1.82 KB
/
jwt.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
/*
*
* * Copyright (C) 2022 The orange protocol Authors
* * This file is part of The orange library.
* *
* * The Orange is free software: you can redistribute it and/or modify
* * it under the terms of the GNU Lesser General Public License as published by
* * the Free Software Foundation, either version 3 of the License, or
* * (at your option) any later version.
* *
* * The orange is distributed in the hope that it will be useful,
* * but WITHOUT ANY WARRANTY; without even the implied warranty of
* * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* * GNU Lesser General Public License for more details.
* *
* * You should have received a copy of the GNU Lesser General Public License
* * along with The orange. If not, see <http://www.gnu.org/licenses/>.
*
*/
package jwt
import (
"log"
"time"
"github.com/dgrijalva/jwt-go"
)
// secret key being used to sign tokens
var (
SecretKey = []byte("secret")
)
// GenerateToken generates a jwt token and assign a username to it's claims and return it
func GenerateToken(did string) (string, error) {
token := jwt.New(jwt.SigningMethodHS256)
/* Create a map to store our claims */
claims := token.Claims.(jwt.MapClaims)
/* Set token claims */
claims["did"] = did
claims["exp"] = time.Now().Add(time.Hour * 24).Unix()
tokenString, err := token.SignedString(SecretKey)
if err != nil {
log.Fatal("Error in Generating key")
return "", err
}
return tokenString, nil
}
// ParseToken parses a jwt token and returns the username in it's claims
func ParseToken(tokenStr string) (string, error) {
token, err := jwt.Parse(tokenStr, func(token *jwt.Token) (interface{}, error) {
return SecretKey, nil
})
if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
did := claims["did"].(string)
return did, nil
} else {
return "", err
}
}