scsusers/2fa.go

62 lines
1.0 KiB
Go
Raw Normal View History

package scsusers
import (
"crypto/rand"
"fmt"
"math/big"
2023-09-26 20:45:19 +00:00
"strconv"
"time"
)
func generate2fa() string {
num, err := rand.Int(rand.Reader, big.NewInt(999999))
if err != nil {
return "918273"
}
return fmt.Sprintf("%06d", num)
}
func Validate2FA(u *UserData, challenge string) bool {
2023-09-26 20:45:19 +00:00
defer func() {
u.Delete("2fa")
u.Delete("2faexpires")
}()
v, ok := u.Get("2fa")
2023-09-26 20:45:19 +00:00
if !ok {
return false
}
exp, ok := u.Get("2faexpires")
if !ok {
return false
}
tmp, err := strconv.ParseInt(exp, 10, 64)
if err != nil {
return false
}
if int64(time.Now().Unix()) > tmp {
return false
}
return ok && v == challenge
}
func Send2FA(u *UserData) error {
code := generate2fa()
u.Set("2fa", code)
u.Set("2faexpires", fmt.Sprintf("%d", time.Now().Add(15*time.Minute).Unix()))
2023-10-09 15:29:07 +00:00
firstname, ok := u.Get("firstname")
if !ok {
firstname = ""
}
lastname, ok := u.Get("lastname")
if !ok {
lastname = ""
}
2023-09-26 20:45:19 +00:00
fullname := fmt.Sprintf("%s %s", firstname, lastname)
2023-10-07 14:23:51 +00:00
return Send2faEmail(u.Username, fullname, code)
}