scsusers/2fa.go

67 lines
1.1 KiB
Go
Raw Normal View History

package scsusers
import (
"crypto/rand"
"errors"
"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-09-26 20:45:19 +00:00
email, ok := u.Get("email")
if !ok {
return errors.New("send2fa: no email")
}
2023-09-26 20:45:19 +00:00
firstname, ok := u.Get("firstname")
if !ok {
return errors.New("send2fa: no firstname")
}
2023-09-26 20:45:19 +00:00
lastname, ok := u.Get("lastname")
if !ok {
return errors.New("send2fa: no lastname")
}
2023-09-26 20:45:19 +00:00
fullname := fmt.Sprintf("%s %s", firstname, lastname)
return Send2faEmail(email, fullname, code)
}