DB & Route Organization
This commit is contained in:
37
internal/auth/auth.go
Normal file
37
internal/auth/auth.go
Normal file
@@ -0,0 +1,37 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"gorm.io/gorm"
|
||||
"reichard.io/imagini/internal/db"
|
||||
log "github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
func AuthenticateUser(userIdentifier string, userPassword string) bool {
|
||||
// By Username
|
||||
foundUser, err := db.GetUser(db.User{Username: userIdentifier})
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
foundUser, err = db.GetUser(db.User{Email: userIdentifier})
|
||||
}
|
||||
|
||||
// Error Checking
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
log.Warn("[auth] User not found: ", userIdentifier)
|
||||
return false
|
||||
} else if err != nil {
|
||||
log.Error(err)
|
||||
return false
|
||||
}
|
||||
|
||||
log.Info("[auth] Authenticating user: ", foundUser.Username)
|
||||
|
||||
// Determine Type
|
||||
switch foundUser.AuthType {
|
||||
case "Local":
|
||||
return authenticateLocalUser(foundUser, userPassword)
|
||||
case "LDAP":
|
||||
return authenticateLDAPUser(foundUser, userPassword)
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"reichard.io/imagini/internal/db"
|
||||
)
|
||||
|
||||
func authenticateLDAPUser(user db.User, pw string) bool {
|
||||
return false
|
||||
}
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"gorm.io/gorm"
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
log "github.com/sirupsen/logrus"
|
||||
"reichard.io/imagini/internal/db"
|
||||
)
|
||||
|
||||
func authenticateLocalUser(user db.User, pw string) bool {
|
||||
bPassword :=[]byte(pw)
|
||||
err := bcrypt.CompareHashAndPassword([]byte(user.HashedPassword), bPassword)
|
||||
if err == nil {
|
||||
log.Info("[local] Authentication successfull: ", user.Username)
|
||||
return true
|
||||
}
|
||||
log.Warn("[local] Authentication failed: ", user.Username)
|
||||
return false
|
||||
}
|
||||
|
||||
func CreateUser(user db.User, pw string) error {
|
||||
log.Info("[local] Creating user: ", user.Username)
|
||||
_, err := db.GetUser(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 db.CreateUser(user)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user