Files
InfantrySkillCalculator/pages.go

111 lines
2.9 KiB
Go

package main
import (
"InfantrySkillCalculator/controllers"
"InfantrySkillCalculator/utils"
"github.com/gin-gonic/gin"
"net/http"
"session"
)
func mainPage(c *gin.Context) {
username, ok := session.GetUsername(c)
if !ok {
username = ""
}
data := map[string]interface{}{
"UserRole": controllers.GetUserRoleByCtx(c),
"Username": username,
}
err := utils.MainPageTemplates.Execute(c.Writer, data)
if err != nil {
utils.Logger.Fatalf("[MAIN] Error while executing template: %s", err.Error())
}
}
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 {
utils.Logger.Fatalf("[LOGIN] Error while executing template: %s", err.Error())
}
}
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!"})
utils.Logger.Warnf("[LOGIN] User %s tried to login with invalid credentials", username)
return
}
if err := session.SetLoginSession(username, c); err != nil {
c.JSON(http.StatusInternalServerError, nil)
utils.Logger.Errorf("[LOGIN] Error while setting login session: %s", err.Error())
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)
utils.Logger.Errorf("[LOGOUT] Error while invalidating session: %s", err.Error())
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 {
utils.Logger.Fatalf("[REGISTER] Error while executing template: %s", err.Error())
}
}
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!"})
utils.Logger.Warnf("[REGISTER] User %s tried to register with invalid code %s", username, code)
return
}
hashedPassword, err := hashPassword(password)
if err != nil {
c.HTML(http.StatusOK, "login_error.html", gin.H{"message": "Fehler beim Registrieren!"})
utils.Logger.Errorf("[REGISTER] Error while hashing password: %s", err.Error())
return
}
controllers.CreateUser(username, hashedPassword, true, code)
if err := session.SetLoginSession(username, c); err != nil {
c.JSON(http.StatusInternalServerError, nil)
utils.Logger.Errorf("[REGISTER] Error while setting login session: %s", err.Error())
return
}
c.Header("HX-Redirect", "/")
c.String(http.StatusOK, "")
}