Files
InfantrySkillCalculator/cmd/auth.go
2024-01-21 18:02:27 +01:00

107 lines
2.4 KiB
Go

package main
import (
"InfantrySkillCalculator/controllers"
"InfantrySkillCalculator/models"
"errors"
"fmt"
"github.com/gin-gonic/gin"
"golang.org/x/crypto/bcrypt"
"gorm.io/gorm"
"internal/session"
"log"
"net/http"
)
func checkUserCredentials(username, password string) bool {
var hashedPassword string
hashedPassword, err := getUserPassword(username)
if err != nil {
return false
}
err = bcrypt.CompareHashAndPassword([]byte(hashedPassword), []byte(password))
return err == nil
}
func getUserPassword(username string) (string, error) {
var user models.User
if err := models.DB.Where("username = ?", username).First(&user).Error; err != nil {
if !errors.Is(err, gorm.ErrRecordNotFound) {
log.Fatal(err)
}
return "", err
}
return user.Password, nil
}
func hashPassword(password string) (string, error) {
hashedPassword, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
if err != nil {
return "", fmt.Errorf("failed to hash password: %w", err)
}
return string(hashedPassword), nil
}
func ReaderAuthRequired() gin.HandlerFunc {
return func(c *gin.Context) {
auth, okAuth := session.GetAuthenticated(c)
username, okUser := session.GetUsername(c)
if !okAuth || !okUser || !auth || !controllers.IsUserEnabled(username) {
redirectToLogin(c)
return
}
c.Next()
}
}
func AuthorAuthRequired() gin.HandlerFunc {
return func(c *gin.Context) {
auth, okAuth := session.GetAuthenticated(c)
username, okUser := session.GetUsername(c)
if !okAuth || !okUser || !auth || !controllers.IsUserEnabled(username) || controllers.GetUserRole(username) == models.ReaderRole {
redirectToLogin(c)
return
}
c.Next()
}
}
func AdminAuthRequired() gin.HandlerFunc {
return func(c *gin.Context) {
auth, okAuth := session.GetAuthenticated(c)
username, okUser := session.GetUsername(c)
if !okAuth || !okUser || !auth || !controllers.IsUserEnabled(username) || !controllers.IsUserAdmin(username) {
redirectToLogin(c)
return
}
c.Next()
}
}
func redirectToLogin(c *gin.Context) {
if err := session.InvalidateSession(c); err != nil {
log.Fatal(err)
}
c.Redirect(http.StatusFound, "/login")
c.Abort()
}
func isValidCode(code string) bool {
var activationCode models.ActivationCode
if err := models.DB.Where("code = ?", code).First(&activationCode).Error; err != nil {
return false
}
return activationCode.Code == code && activationCode.UsedForUsername == ""
}