Skip to content

Commit 6ced935

Browse files
committed
OTP methods
1 parent e96ad5b commit 6ced935

File tree

1 file changed

+68
-0
lines changed

1 file changed

+68
-0
lines changed

isis.go

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
package isis
2+
3+
import (
4+
"fmt"
5+
"gorm.io/gorm"
6+
"math/rand"
7+
"time"
8+
)
9+
10+
func Generate(conn *gorm.DB, identifier string, digits int, validity int) (token string, err error) {
11+
token = generatePin(digits)
12+
13+
err = conn.Create(&otp{
14+
Identifier: identifier,
15+
Token: token,
16+
Validity: validity,
17+
Valid: true,
18+
CreatedAt: time.Now(),
19+
UpdatedAt: time.Now(),
20+
}).Error
21+
22+
return
23+
}
24+
25+
func Validate(conn *gorm.DB, identifier string, token string) (validated bool, err error) {
26+
var foundOtp otp
27+
28+
err = conn.Model(otp{}).Where("identifier = ?", identifier).Where("token = ?", token).Find(&foundOtp).Error
29+
30+
if err != nil {
31+
return false, err
32+
}
33+
34+
if foundOtp.Empty() || !foundOtp.Valid {
35+
return false, nil
36+
}
37+
38+
conn.First(&foundOtp)
39+
40+
if foundOtp.Exipired() {
41+
foundOtp.Valid = false
42+
foundOtp.UpdatedAt = time.Now()
43+
conn.Save(&foundOtp)
44+
45+
return false, nil
46+
}
47+
48+
foundOtp.Valid = false
49+
foundOtp.UpdatedAt = time.Now()
50+
conn.Save(&foundOtp)
51+
52+
return true, nil
53+
}
54+
55+
func generatePin(digits int) string {
56+
pin := ""
57+
58+
rand.Seed(time.Now().UnixNano())
59+
min := 0
60+
max := 9
61+
62+
for i := 0; i < digits; i++ {
63+
digit := fmt.Sprintf("%d", rand.Intn(max-min+1)+min)
64+
pin = pin + digit
65+
}
66+
67+
return pin
68+
}

0 commit comments

Comments
 (0)