39 lines
1.1 KiB
Go
39 lines
1.1 KiB
Go
package auth
|
|
|
|
import (
|
|
"errors"
|
|
"gorm.io/gorm"
|
|
"golang.org/x/crypto/bcrypt"
|
|
log "github.com/sirupsen/logrus"
|
|
"reichard.io/imagini/internal/query"
|
|
"reichard.io/imagini/internal/models"
|
|
)
|
|
|
|
func authenticateLocalUser(user models.User, pw string) bool {
|
|
bPassword :=[]byte(pw)
|
|
err := bcrypt.CompareHashAndPassword([]byte(user.HashedPassword), bPassword)
|
|
if err == nil {
|
|
log.Info("[auth] Authentication successfull: ", user.Username)
|
|
return true
|
|
}
|
|
log.Warn("[auth] Authentication failed: ", user.Username)
|
|
return false
|
|
}
|
|
|
|
func CreateUser(db *gorm.DB, user models.User, pw string) error {
|
|
log.Info("[auth] Creating user: ", user.Username)
|
|
_, err := query.User(db, user)
|
|
if !errors.Is(err, gorm.ErrRecordNotFound) {
|
|
log.Warn("[auth] User already exists: ", user.Username)
|
|
return errors.New("User already exists")
|
|
}
|
|
|
|
hashedPassword, err := bcrypt.GenerateFromPassword([]byte(pw), bcrypt.DefaultCost)
|
|
if err != nil {
|
|
log.Error(err)
|
|
return err
|
|
}
|
|
user.HashedPassword = string(hashedPassword)
|
|
return query.CreateUser(db, user)
|
|
}
|