Player cache and project structure refactor.
This commit is contained in:
106
cmd/auth.go
Normal file
106
cmd/auth.go
Normal file
@@ -0,0 +1,106 @@
|
||||
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 == ""
|
||||
}
|
||||
153
cmd/main.go
Normal file
153
cmd/main.go
Normal file
@@ -0,0 +1,153 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"InfantrySkillCalculator/controllers"
|
||||
"InfantrySkillCalculator/models"
|
||||
"InfantrySkillCalculator/utils"
|
||||
"github.com/gin-gonic/gin"
|
||||
_ "github.com/gorilla/sessions"
|
||||
"html/template"
|
||||
"io"
|
||||
"log"
|
||||
"os"
|
||||
)
|
||||
|
||||
func init() {
|
||||
var err error
|
||||
utils.MainPageTemplates, err = template.ParseFiles(
|
||||
"./templates/index.html",
|
||||
"./templates/components/home_clan_bar.html",
|
||||
"./templates/components/opp_clan_bar.html",
|
||||
"./templates/components/home_player_list.html",
|
||||
"./templates/components/opp_player_list.html",
|
||||
"./templates/components/bottom_controls.html",
|
||||
"./templates/modals/delete_clan.html",
|
||||
"./templates/modals/add_clan.html",
|
||||
"./templates/modals/edit_clan.html",
|
||||
"./templates/modals/add_player.html",
|
||||
"./templates/modals/delete_player.html",
|
||||
"./templates/modals/edit_player.html",
|
||||
"./templates/modals/settings.html",
|
||||
"./templates/components/header.html",
|
||||
)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
utils.LoginPageTemplates, err = template.ParseFiles(
|
||||
"./templates/login.html",
|
||||
"./templates/components/header.html",
|
||||
)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
utils.RegisterPageTemplates, err = template.ParseFiles(
|
||||
"./templates/register.html",
|
||||
"./templates/components/header.html",
|
||||
)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
utils.PlayerItemTemplate, err = template.ParseFiles(
|
||||
"./templates/player_list_item.html",
|
||||
)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
controllers.LoadMetrics()
|
||||
}
|
||||
|
||||
func main() {
|
||||
if os.Getenv("GO_ENV") == "production" {
|
||||
gin.SetMode(gin.ReleaseMode)
|
||||
}
|
||||
|
||||
router := gin.New()
|
||||
err := router.SetTrustedProxies([]string{"127.0.0.1"})
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
router.LoadHTMLGlob("templates/**/*")
|
||||
reader := router.Group("/")
|
||||
reader.Use(ReaderAuthRequired())
|
||||
author := router.Group("/")
|
||||
author.Use(AuthorAuthRequired())
|
||||
admin := router.Group("/admin")
|
||||
admin.Use(AdminAuthRequired())
|
||||
|
||||
models.ConnectDatabase()
|
||||
models.ConnectCache(utils.PlayerCacheLifetime)
|
||||
|
||||
var code models.ActivationCode
|
||||
if err := models.DB.First(&code).Error; err != nil {
|
||||
firstCode := utils.GenerateActivationCode()
|
||||
models.DB.Create(&models.ActivationCode{Code: firstCode, UserRole: models.AdminRole})
|
||||
log.Println("Created first activation code with ADMIN role:\n" + firstCode)
|
||||
}
|
||||
|
||||
f, _ := os.OpenFile("isc_rest.log", os.O_RDWR|os.O_APPEND|os.O_CREATE, 0660)
|
||||
utils.GinWriter = io.MultiWriter(f, os.Stdout)
|
||||
router.Use(
|
||||
gin.LoggerWithWriter(utils.GinWriter, "/static"),
|
||||
gin.Recovery(),
|
||||
)
|
||||
reader.Use(
|
||||
gin.LoggerWithWriter(utils.GinWriter),
|
||||
gin.Recovery(),
|
||||
)
|
||||
author.Use(
|
||||
gin.LoggerWithWriter(utils.GinWriter),
|
||||
gin.Recovery(),
|
||||
)
|
||||
admin.Use(
|
||||
gin.LoggerWithWriter(utils.GinWriter),
|
||||
gin.Recovery(),
|
||||
)
|
||||
|
||||
router.Static("/static", "./static")
|
||||
|
||||
router.GET("/login", loginPage)
|
||||
router.POST("/login", loginPost)
|
||||
router.GET("/logout", logout)
|
||||
router.GET("/register", registerPage)
|
||||
router.POST("/register", registerPost)
|
||||
|
||||
reader.GET("/", mainPage)
|
||||
|
||||
reader.GET("/clans", controllers.GetAllClans)
|
||||
reader.GET("/clans_html", controllers.GetAllClansHTML)
|
||||
reader.GET("/clan/:id", controllers.GetClanByID)
|
||||
author.POST("/clan", controllers.AddClan)
|
||||
author.PATCH("/clan/:id", controllers.UpdateClanByID)
|
||||
author.DELETE("/clan/:id", controllers.DeleteClanByID)
|
||||
|
||||
reader.GET("/players", controllers.GetAllPlayers)
|
||||
reader.GET("/players_html", controllers.GetPlayersByClanHTML)
|
||||
reader.GET("/player/:id", controllers.GetPlayerByID)
|
||||
reader.GET("/playerid/:name", controllers.GetPlayerIDByName)
|
||||
author.POST("/player", controllers.AddPlayer)
|
||||
author.PATCH("/player/:id", controllers.UpdatePlayerByID)
|
||||
author.DELETE("/player/:id", controllers.DeletePlayerByID)
|
||||
|
||||
reader.GET("/cache/:player_id", controllers.GetCacheByPlayerID)
|
||||
|
||||
reader.GET("/score/:player_id", controllers.GetScoreByPlayerID)
|
||||
reader.POST("/score/:player_name", controllers.GetScoreByPlayerName)
|
||||
|
||||
reader.GET("/game", controllers.GetGames)
|
||||
reader.GET("/game_html", controllers.GetGamesHTML)
|
||||
|
||||
reader.GET("/settings", controllers.GetSettings)
|
||||
reader.PATCH("/settings", controllers.UpdateSettings)
|
||||
|
||||
admin.DELETE("/clear_cache", controllers.DeleteAllCaches)
|
||||
admin.DELETE("/purge_players", controllers.DeleteAllPlayers)
|
||||
admin.DELETE("/purge_clans", controllers.DeleteAllClans)
|
||||
admin.POST("/create_code", controllers.CreateCode)
|
||||
|
||||
log.Println("Running on 8000...")
|
||||
log.Fatal(router.Run(":8000"))
|
||||
}
|
||||
99
cmd/pages.go
Normal file
99
cmd/pages.go
Normal file
@@ -0,0 +1,99 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"InfantrySkillCalculator/controllers"
|
||||
"InfantrySkillCalculator/utils"
|
||||
"github.com/gin-gonic/gin"
|
||||
"log"
|
||||
"net/http"
|
||||
"session"
|
||||
)
|
||||
|
||||
func mainPage(c *gin.Context) {
|
||||
data := map[string]interface{}{
|
||||
"UserRole": controllers.GetUserRoleByCtx(c),
|
||||
}
|
||||
|
||||
err := utils.MainPageTemplates.Execute(c.Writer, data)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func loginPage(c *gin.Context) {
|
||||
if auth, ok := session.GetAuthenticated(c); ok && auth {
|
||||
c.Redirect(http.StatusFound, "/")
|
||||
return
|
||||
}
|
||||
|
||||
err := utils.LoginPageTemplates.Execute(c.Writer, nil)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func loginPost(c *gin.Context) {
|
||||
username := c.PostForm("username")
|
||||
password := c.PostForm("password")
|
||||
|
||||
if !checkUserCredentials(username, password) {
|
||||
c.HTML(http.StatusOK, "login_error.html", gin.H{"message": "Ungültige Logindaten!"})
|
||||
return
|
||||
}
|
||||
|
||||
if err := session.SetLoginSession(username, c); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, nil)
|
||||
return
|
||||
}
|
||||
|
||||
c.Header("HX-Redirect", "/")
|
||||
c.String(http.StatusOK, "")
|
||||
}
|
||||
|
||||
func logout(c *gin.Context) {
|
||||
if err := session.InvalidateSession(c); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, nil)
|
||||
return
|
||||
}
|
||||
|
||||
c.Redirect(http.StatusFound, "/login")
|
||||
}
|
||||
|
||||
func registerPage(c *gin.Context) {
|
||||
if auth, ok := session.GetAuthenticated(c); ok && auth {
|
||||
c.Redirect(http.StatusFound, "/")
|
||||
return
|
||||
}
|
||||
|
||||
err := utils.RegisterPageTemplates.Execute(c.Writer, nil)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func registerPost(c *gin.Context) {
|
||||
username := c.PostForm("username")
|
||||
password := c.PostForm("password")
|
||||
code := c.PostForm("code")
|
||||
|
||||
if !isValidCode(code) {
|
||||
c.HTML(http.StatusOK, "login_error.html", gin.H{"message": "Ungültiger Aktivierungscode!"})
|
||||
return
|
||||
}
|
||||
|
||||
hashedPassword, err := hashPassword(password)
|
||||
if err != nil {
|
||||
c.HTML(http.StatusOK, "login_error.html", gin.H{"message": "Fehler beim Registrieren!"})
|
||||
return
|
||||
}
|
||||
|
||||
controllers.CreateUser(username, hashedPassword, true, code)
|
||||
|
||||
if err := session.SetLoginSession(username, c); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, nil)
|
||||
return
|
||||
}
|
||||
|
||||
c.Header("HX-Redirect", "/")
|
||||
c.String(http.StatusOK, "")
|
||||
}
|
||||
Reference in New Issue
Block a user