This repository has been archived on 2023-11-13. You can view files and clone it, but cannot push or open issues or pull requests.
imagini/internal/auth/local.go
2021-01-11 23:48:32 -05:00

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)
}