-
Notifications
You must be signed in to change notification settings - Fork 1
/
isis.go
109 lines (80 loc) · 1.92 KB
/
isis.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
package isis
import (
"fmt"
"gorm.io/gorm"
"math/rand"
"time"
)
func SetToken(conn *gorm.DB, identifier string, token string, validity int) (err error) {
var exitingOtpCount int64
var exitingOtp otp
_ = conn.Where("identifier = ?", identifier).First(&exitingOtp).Count(&exitingOtpCount)
if exitingOtpCount > 0 {
err = conn.Delete(&exitingOtp).Error
if err != nil {
return
}
}
err = conn.Create(&otp{
Identifier: identifier,
Token: token,
Validity: validity,
Valid: true,
CreatedAt: time.Now(),
UpdatedAt: time.Now(),
}).Error
return
}
func Generate(conn *gorm.DB, identifier string, digits int, validity int) (token string, err error) {
var exitingOtpCount int64
var exitingOtp otp
_ = conn.Where("identifier = ?", identifier).First(&exitingOtp).Count(&exitingOtpCount)
if exitingOtpCount > 0 {
err = conn.Delete(&exitingOtp).Error
if err != nil {
return
}
}
token = generatePin(digits)
err = conn.Create(&otp{
Identifier: identifier,
Token: token,
Validity: validity,
Valid: true,
CreatedAt: time.Now(),
UpdatedAt: time.Now(),
}).Error
return
}
func Validate(conn *gorm.DB, identifier string, token string) (validated bool, err error) {
var foundOtp otp
err = conn.Model(otp{}).Where("identifier = ?", identifier).Where("token = ?", token).Find(&foundOtp).Error
if err != nil {
return false, err
}
if foundOtp.Empty() || !foundOtp.Valid {
return false, nil
}
conn.First(&foundOtp)
if foundOtp.Exipired() {
foundOtp.Valid = false
foundOtp.UpdatedAt = time.Now()
conn.Save(&foundOtp)
return false, nil
}
foundOtp.Valid = false
foundOtp.UpdatedAt = time.Now()
conn.Save(&foundOtp)
return true, nil
}
func generatePin(digits int) string {
pin := ""
rand.Seed(time.Now().UnixNano())
min := 0
max := 9
for i := 0; i < digits; i++ {
digit := fmt.Sprintf("%d", rand.Intn(max-min+1)+min)
pin = pin + digit
}
return pin
}