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.UserResponse) 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) 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*1, "", "", false, true) c.JSON(http.StatusOK, gin.H{}) } func (rc *UserController) LoginHandler(c *gin.Context) { username := c.PostForm("username") password := c.PostForm("password") tokenString, err := services.Users.Login(username, password) if err != nil { data := gin.H{ "error": "Login Failed. Wrong username or Password!", } c.HTML(http.StatusOK, "login.html", data) return } c.SetCookie("Authorization", tokenString.GetAccessToken(), 3600*24, "", "", false, true) //set this so that CreateSessionData works //otherwise header would not be generated correctly user, _ := services.Users.GetByName(c, username) c.Set("user", user) // send it back //c.SetSameSite(http.SameSiteLaxMode) 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)) }