scsusers/2fa.go

64 lines
1.1 KiB
Go

package scsusers
import (
"crypto/rand"
"fmt"
"log"
"math/big"
"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 {
defer func() {
u.Delete("2fa")
u.Delete("2faexpires")
}()
v, ok := u.Get("2fa")
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()))
firstname, ok := u.Get("firstname")
if !ok {
firstname = ""
}
lastname, ok := u.Get("lastname")
if !ok {
lastname = ""
}
fullname := fmt.Sprintf("%s %s", firstname, lastname)
log.Printf("Sending %s %s %s", u.Username, fullname, code)
return Send2faEmail(u.Username, fullname, code)
}