forked from qor/auth
-
Notifications
You must be signed in to change notification settings - Fork 1
/
token.go
90 lines (74 loc) · 2.23 KB
/
token.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
package phone
import (
"math/rand"
"reflect"
"strings"
"time"
"github.com/jinzhu/gorm"
"github.com/fahmibaswara/auth"
"github.com/fahmibaswara/auth/auth_identity"
"github.com/fahmibaswara/auth/claims"
"github.com/qor/qor/utils"
)
var ()
// DefaultSendTokenHandler default Token Verification Sender
var DefaultSendTokenHandler = func(phonenumber string, context *auth.Context, tx *gorm.DB) error {
var (
err error
provider, _ = context.Provider.(*Provider)
)
tokenIdentity := reflect.New(utils.ModelType(context.Auth.Config.UserTokenModel)).Interface()
if err = tx.Where(map[string]interface{}{
"identity": phonenumber,
}).FirstOrCreate(tokenIdentity).Error; err != nil {
return auth.ErrInvalidAccount
}
token := generateToken(6)
tx.Model(tokenIdentity).Where("identity = ?", phonenumber).Update(map[string]interface{}{
"token": token,
"validUntil": time.Now().Add(time.Hour * 3),
})
message := strings.NewReplacer(
"{token}", token,
).Replace(provider.Config.TokenMessage)
if err = context.Auth.SMSSender.Send(phonenumber, message); err != nil {
return err
}
return nil
}
// DefaultCheckToken default confirmation handler
var DefaultCheckToken = func(phonenumber string, token string, context *auth.Context, DB *gorm.DB) (*claims.Claims, error) {
var (
authInfo auth_identity.Basic
tokenIdentity auth_identity.AuthToken
provider, _ = context.Provider.(*Provider)
)
if DB.Model(context.Auth.Config.UserTokenModel).Where(map[string]interface{}{
"identity": phonenumber,
"token": token,
}).Scan(&tokenIdentity).RecordNotFound() {
return nil, auth.ErrInvalidAccount
}
now := time.Now()
if now.After(*tokenIdentity.ValidUntil) {
return nil, ErrTokenExpired
}
authInfo.Provider = provider.GetName()
authInfo.UID = phonenumber
if DB.Model(context.Auth.AuthIdentityModel).Where(
map[string]interface{}{
"provider": authInfo.Provider,
"uid": authInfo.UID,
}).Scan(&authInfo).RecordNotFound() {
return nil, auth.ErrInvalidAccount
}
return authInfo.ToClaims(), nil
}
func generateToken(len int) string {
rand.Seed(time.Now().UnixNano())
a := make([]byte, len)
for i := 0; i <= len-1; i++ {
a[i] = byte(48 + rand.Intn(10)) // 48 (ascii) -> 0
}
return string(a)
}