/* * Copyright (C) 2023 Jonni Liljamo * * This file is licensed under AGPL-3.0-or-later, see NOTICE and LICENSE for * more information. */ package middlewares import ( "context" "log" "net/http" "tixe/db" "tixe/types" "tixe/util" "github.com/gin-contrib/sessions" "github.com/gin-gonic/gin" ) func IsAuthenticated(c *gin.Context) { if sessions.Default(c).Get("profile") == nil { c.Redirect(http.StatusSeeOther, "/login") c.Abort() } else { // Here, we verify if the user actually exists. Bla bla forgery, bla bla, // but mainly this was an issue on the demo. session := sessions.Default(c) user := session.Get("user").(types.User) var exists bool err := db.PgPool.QueryRow(context.Background(), "SELECT EXISTS(SELECT 1 FROM users WHERE id = $1)", user.Id).Scan(&exists) if err != nil || !exists { c.Redirect(http.StatusSeeOther, "/login") c.Abort() session.Clear() if err := session.Save(); err != nil { errStr := "Failed to save session" log.Printf("[tixe/auth] ERROR: %s: %v", errStr, err) util.RenderError(c, "session error", errStr, nil) return } } c.Next() } } func CanLogin(c *gin.Context) { if sessions.Default(c).Get("profile") != nil { // Don't allow the login page if logged in c.Redirect(http.StatusSeeOther, "/") } else { c.Next() } }