forked from leanote/leanote
-
Notifications
You must be signed in to change notification settings - Fork 0
/
TokenService.go
72 lines (57 loc) · 1.55 KB
/
TokenService.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
package service
import (
"gopkg.in/mgo.v2/bson"
"github.com/leanote/leanote/app/db"
"github.com/leanote/leanote/app/info"
. "github.com/leanote/leanote/app/lea"
"time"
)
// token
// 找回密码
// 修改密码
type TokenService struct {
}
// 生成token
func (this *TokenService) NewToken(userId string, email string, tokenType int) string {
token := info.Token{UserId: bson.ObjectIdHex(userId), Token: NewGuidWith(email), CreatedTime: time.Now(), Email: email, Type: tokenType}
if db.Upsert(db.Tokens, bson.M{"_id": token.UserId}, token) {
return token.Token
}
return ""
}
// 删除token
func (this *TokenService) DeleteToken(userId string, tokenType int) bool {
return db.Delete(db.Tokens, bson.M{"_id": bson.ObjectIdHex(userId), "Type": tokenType})
}
func (this *TokenService) GetOverHours(tokenType int) float64 {
if tokenType == info.TokenPwd {
return info.PwdOverHours
} else if tokenType == info.TokenUpdateEmail {
return info.UpdateEmailOverHours
} else {
return info.ActiveEmailOverHours
}
}
// 验证token, 是否存在, 过时?
func (this *TokenService) VerifyToken(token string, tokenType int) (ok bool, msg string, tokenInfo info.Token) {
overHours = this.GetOverHours(tokenType)
ok = false
if token == "" {
msg = "不存在"
return
}
db.GetByQ(db.Tokens, bson.M{"Token": token}, &tokenInfo)
if tokenInfo.UserId == "" {
msg = "不存在"
return
}
// 验证是否过时
now := time.Now()
duration := now.Sub(tokenInfo.CreatedTime)
if duration.Hours() > overHours {
msg = "过期"
return
}
ok = true
return
}