Files
portal/controllers/userController.go
2026-06-22 11:38:29 +02:00

142 lines
2.9 KiB
Go

package controllers
import (
"fmt"
"net/http"
"github.com/gin-gonic/gin"
"git.dynamicdiscord.de/malobeo/portal/openapi"
"git.dynamicdiscord.de/malobeo/portal/services"
)
type UserController struct{}
func NewUserController() UserController {
return UserController{}
}
func CreateSessionData(c *gin.Context, extra any) gin.H {
user, exists := c.Get("user")
userImpl, _ := user.(openapi.UserDB)
return gin.H{
"loggedIn": exists,
"isAdmin": userImpl.IsAdmin,
"data": extra,
}
}
func (rc *UserController) Logout(c *gin.Context) {
c.SetCookie("Authorization", "", -1, "", "", false, true)
c.HTML(http.StatusOK, "index.html", gin.H{})
}
//func (uc *UserController) Register(c *gin.Context) {
// //Get the email/passwd off req body
// var body struct {
// Name string
// Email string
// Password string
// }
//
// err := c.Bind(&body)
//
// if err != nil {
// c.JSON(http.StatusBadRequest, gin.H{
// "error": "Failed to read body",
// })
//
// return
// }
//
// _, err = services.Users.Register(body.Name, body.Email, body.Password, false)
//
// if err != nil {
// fmt.Println("Error: ", err)
// c.JSON(http.StatusBadRequest, gin.H{
// "error": "Failed to create user",
// })
//
// return
// }
//
// //respond
// c.JSON(http.StatusOK, gin.H{})
//}
func (uc *UserController) Login(c *gin.Context) {
//Get the email/passwd off req body
var body struct {
Username string
Password string
}
err := c.Bind(&body)
fmt.Println(body)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"error": "Login Failed",
})
return
}
tokenString, err := services.Users.Login(body.Username, body.Password)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"error": "Login Failed",
})
return
}
// send it back
c.SetSameSite(http.SameSiteLaxMode)
c.SetCookie("Authorization", tokenString.GetAccessToken(), 3600*24, "", "", false, true)
c.JSON(http.StatusOK, gin.H{})
}
func (rc *UserController) LoginHandler(c *gin.Context) {
email := c.PostForm("username")
password := c.PostForm("password")
tokenString, err := services.Users.Login(email, password)
if err != nil {
data := gin.H{
"error": "Login Failed. Wrong Email or Password!",
}
c.HTML(http.StatusOK, "login.html", data)
return
}
//set this so that CreateSessionData works
//otherwise header would not be generated correctly
//user, _ := repositories.Users.GetByEmail(email)
//c.Set("user", user)
// send it back
//c.SetSameSite(http.SameSiteLaxMode)
c.SetCookie("Authorization", tokenString.GetAccessToken(), 3600*24, "", "", false, true)
c.HTML(http.StatusOK, "login.html", CreateSessionData(c, gin.H{}))
}
func (rc *UserController) LoginView(c *gin.Context) {
//if already logged in
_, exists := c.Get("user")
if exists {
c.HTML(http.StatusOK, "index.html", CreateSessionData(c, gin.H{}))
return
}
data := gin.H{
"error": "",
}
c.HTML(http.StatusOK, "login.html", CreateSessionData(c, data))
}