Restructure main.go
This commit is contained in:
60
auth.go
Normal file
60
auth.go
Normal file
@@ -0,0 +1,60 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"InfrantrySkillCalculator/models"
|
||||
"fmt"
|
||||
"github.com/gin-gonic/gin"
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
"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 {
|
||||
log.Fatal(err)
|
||||
return "", err
|
||||
}
|
||||
|
||||
var hashedPW string
|
||||
hashedPW, err := hashPassword(user.Password)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
return "", err
|
||||
}
|
||||
|
||||
return hashedPW, 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 AuthRequired() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
session, _ := store.Get(c.Request, LoginSessionName)
|
||||
if auth, ok := session.Values["authenticated"].(bool); !ok || !auth {
|
||||
c.Redirect(http.StatusFound, "/login")
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user