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

39 lines
1.1 KiB
Go
Raw Normal View History

2021-01-10 00:44:02 +00:00
package auth
import (
"errors"
"gorm.io/gorm"
"golang.org/x/crypto/bcrypt"
log "github.com/sirupsen/logrus"
2021-01-12 04:48:32 +00:00
"reichard.io/imagini/internal/query"
"reichard.io/imagini/internal/models"
2021-01-10 00:44:02 +00:00
)
2021-01-12 04:48:32 +00:00
func authenticateLocalUser(user models.User, pw string) bool {
2021-01-10 00:44:02 +00:00
bPassword :=[]byte(pw)
err := bcrypt.CompareHashAndPassword([]byte(user.HashedPassword), bPassword)
if err == nil {
2021-01-12 04:48:32 +00:00
log.Info("[auth] Authentication successfull: ", user.Username)
2021-01-10 00:44:02 +00:00
return true
}
2021-01-12 04:48:32 +00:00
log.Warn("[auth] Authentication failed: ", user.Username)
2021-01-10 00:44:02 +00:00
return false
}
2021-01-12 04:48:32 +00:00
func CreateUser(db *gorm.DB, user models.User, pw string) error {
log.Info("[auth] Creating user: ", user.Username)
_, err := query.User(db, user)
2021-01-10 00:44:02 +00:00
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)
2021-01-12 04:48:32 +00:00
return query.CreateUser(db, user)
2021-01-10 00:44:02 +00:00
}