2023-09-26 20:45:19 +00:00
|
|
|
package scsusers
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"log"
|
2023-10-06 23:06:54 +00:00
|
|
|
"strconv"
|
|
|
|
"time"
|
2023-09-26 20:45:19 +00:00
|
|
|
|
|
|
|
"golang.org/x/crypto/bcrypt"
|
|
|
|
)
|
|
|
|
|
|
|
|
func Login(username, password string) bool {
|
|
|
|
u, ok := Get(username)
|
|
|
|
if !ok {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
if bcrypt.CompareHashAndPassword([]byte(u.Password), []byte(password)) != nil {
|
2023-10-06 23:06:54 +00:00
|
|
|
rc, ok := u.Get("recoverycode")
|
2023-10-07 14:20:01 +00:00
|
|
|
if !ok {
|
|
|
|
log.Println("No recovery code")
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
log.Printf("Checking against recovery code %s", rc)
|
2023-10-07 14:21:55 +00:00
|
|
|
if bcrypt.CompareHashAndPassword([]byte(rc), []byte(password)) != nil {
|
2023-10-06 23:06:54 +00:00
|
|
|
log.Printf("scsusers.Login: Failed password for " + username)
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
tmp, ok := u.Get("recoverytime")
|
|
|
|
if !ok {
|
|
|
|
log.Printf("scsusers.Login: recoverytime missing " + username)
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
rt, _ := strconv.ParseInt(tmp, 10, 64)
|
|
|
|
if time.Now().Unix() > rt {
|
|
|
|
log.Printf("scsusers.Login: recovery time expired")
|
|
|
|
return false
|
|
|
|
}
|
2023-10-07 14:42:06 +00:00
|
|
|
u.SetPassword([]byte(rc))
|
2023-10-07 13:55:21 +00:00
|
|
|
u.Delete("recoverycode")
|
2023-10-06 23:06:54 +00:00
|
|
|
u.Delete("recoverytime")
|
2023-09-26 20:45:19 +00:00
|
|
|
}
|
|
|
|
log.Printf("User %s logged in\n", username)
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
|
2023-10-07 14:42:06 +00:00
|
|
|
func (u *UserData) SetPassword(newcrypt []byte) bool {
|
2023-10-09 15:42:54 +00:00
|
|
|
q := fmt.Sprintf("update %s_users set password=? where id=? limit 1", c.TablePrefix)
|
2023-10-07 14:42:06 +00:00
|
|
|
_, err := c.db.Exec(q, newcrypt, u.UserID)
|
|
|
|
if err != nil {
|
2023-10-09 15:39:00 +00:00
|
|
|
log.Printf("scsusers.SetPassword: update failed for %s: %s\n", u.Username, err.Error())
|
2023-10-07 14:42:06 +00:00
|
|
|
return false
|
|
|
|
}
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
|
2023-09-26 20:45:19 +00:00
|
|
|
func (u *UserData) ChangePassword(oldpass, newpass string) bool {
|
|
|
|
if bcrypt.CompareHashAndPassword([]byte(u.Password), []byte(oldpass)) != nil {
|
|
|
|
log.Printf("scsusers.ChangePassword: Failed password for %s\n", u.Username)
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
newcrypt, err := bcrypt.GenerateFromPassword([]byte(newpass), 10)
|
|
|
|
if err != nil {
|
|
|
|
log.Printf("scsusers.ChangePassword: generate: %s", err.Error())
|
|
|
|
return false
|
|
|
|
}
|
2023-10-07 14:42:06 +00:00
|
|
|
return u.SetPassword(newcrypt)
|
2023-09-26 20:45:19 +00:00
|
|
|
}
|