-
Notifications
You must be signed in to change notification settings - Fork 3
/
session.go
112 lines (87 loc) · 2.53 KB
/
session.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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
//
// Last.Backend LLC CONFIDENTIAL
// __________________
//
// [2014] - [2017] Last.Backend LLC
// All Rights Reserved.
//
// NOTICE: All information contained herein is, and remains
// the property of Last.Backend LLC and its suppliers,
// if any. The intellectual and technical concepts contained
// herein are proprietary to Last.Backend LLC
// and its suppliers and may be covered by Russian Federation and Foreign Patents,
// patents in process, and are protected by trade secret or copyright law.
// Dissemination of this information or reproduction of this material
// is strictly forbidden unless prior written permission is obtained
// from Last.Backend LLC.
//
package types
import (
"errors"
"github.com/dgrijalva/jwt-go"
"time"
)
var (
SecretAccessToken = ""
ErrUnexpectedSigninMethod = errors.New("UNEXPECTED_SIGNIN_METHD")
ErrSessionTokenHasNoEXP = errors.New("NO_EXP_IN_TOKEN")
ErrSessionTokenHasNoJTI = errors.New("NO_JTI_IN_TOKEN")
)
// Generate new Session pointer structure
func NewSession(uid, username, email string) *Session {
return &Session{
Uid: uid,
Username: username,
Email: email,
}
}
type Session struct {
Uid string // session uid
Username string // session username
Email string // session email
}
// Decode - decode token to session object
func (s *Session) Decode(token string) error {
payload, err := jwt.Parse(token, func(payload *jwt.Token) (interface{}, error) {
result := []byte(SecretAccessToken)
err := func(token *jwt.Token) error {
claims := token.Claims.(jwt.MapClaims)
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return ErrUnexpectedSigninMethod
}
if claims["exp"] == nil {
return ErrSessionTokenHasNoEXP
}
if claims["jti"] == nil {
return ErrSessionTokenHasNoJTI
}
return nil
}(payload)
return result, err
})
if err != nil || !payload.Valid {
return err
}
claims := payload.Claims.(jwt.MapClaims)
if _, ok := claims["uid"]; ok {
s.Uid = claims["uid"].(string)
}
if _, ok := claims["em"]; ok {
s.Email = claims["em"].(string)
}
if _, ok := claims["un"]; ok {
s.Username = claims["un"].(string)
}
return nil
}
// Encode - encode session structure to jwt token
func (s *Session) Encode() (string, error) {
context := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
"uid": s.Uid,
"em": s.Email,
"un": s.Username,
"jti": time.Now().Add(time.Hour * 2232).Unix(),
"exp": time.Now().Add(time.Hour * 2232).Unix(),
})
return context.SignedString([]byte(SecretAccessToken))
}