2024-05-04 17:06:01 +02:00
|
|
|
package db
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"fmt"
|
2024-05-09 15:02:43 +02:00
|
|
|
"log"
|
2024-05-04 17:06:01 +02:00
|
|
|
|
|
|
|
"code.lila.network/adoralaura/go-urlsh/models"
|
|
|
|
)
|
|
|
|
|
2024-05-09 15:02:43 +02:00
|
|
|
// UserHasMFA checks the DB if given models.User has MFA enabled.
|
|
|
|
// Returns (true, nil) if User has MFA enabled, (false, nil) if not.
|
|
|
|
// (false, error) if a DB error happened
|
2024-05-04 17:06:01 +02:00
|
|
|
func UserHasMFA(user models.User) (bool, error) {
|
|
|
|
numrows, err := models.DB.NewSelect().Model((*models.MFAConfig)(nil)).Where("username = ?", user.UserName).Where("active = ?", true).Count(context.Background())
|
|
|
|
if err != nil {
|
|
|
|
return false, fmt.Errorf("[UserHasMFA] error getting MFA count from database: %q", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
if numrows >= 1 {
|
|
|
|
return true, nil
|
|
|
|
}
|
|
|
|
return false, nil
|
|
|
|
}
|
2024-05-06 15:32:53 +02:00
|
|
|
|
|
|
|
// ScratchCodeUnique checks the database if the generated scratch code
|
|
|
|
// is unique (not in the database yet)
|
|
|
|
func ScratchCodeIsUnique(scratchcode string) bool {
|
|
|
|
var dbitem models.MFAScratchCode
|
|
|
|
numrows, err := models.DB.NewSelect().Model(&dbitem).Where("code = ?", scratchcode).Count(context.Background())
|
|
|
|
if err != nil {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
|
|
|
if numrows != 0 {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
return true
|
|
|
|
}
|
2024-05-09 15:02:43 +02:00
|
|
|
|
|
|
|
// RemoveMFAFromDB removes MFA entries for given models.User from the database.
|
|
|
|
// Returns nil on success, error otherwise.
|
|
|
|
func RemoveMFAFromDB(user models.User) error {
|
|
|
|
hasMfa, err := UserHasMFA(user)
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("[RemoveMFAFromDB] Error removing MFA from DB for user %v: %w", user.UserName, err)
|
|
|
|
}
|
|
|
|
|
|
|
|
if !hasMfa {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
_, err = models.DB.NewDelete().Model((*models.MFAConfig)(nil)).Where("username = ?", user.UserName).Exec(context.Background())
|
|
|
|
if err != nil {
|
|
|
|
log.Println(err.Error())
|
|
|
|
return fmt.Errorf("[RemoveMFAFromDB] Error removing MFA Config from DB for user %v: %w", user.UserName, err)
|
|
|
|
}
|
|
|
|
|
|
|
|
_, err = models.DB.NewDelete().Model((*models.MFAScratchCode)(nil)).Where("username = ?", user.UserName).Exec(context.Background())
|
|
|
|
if err != nil {
|
|
|
|
log.Println(err.Error())
|
|
|
|
return fmt.Errorf("[RemoveMFAFromDB] Error removing MFA scratch codes from DB for user %v: %w", user.UserName, err)
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|