DEVELOPMENT ENVIRONMENT

~liljamo/tixe

587179c2f07f6dde69d0a2bc867ecf10efdd28ce — Jonni Liljamo 1 year, 1 month ago 52cbe7f 0.1.3
fix: verify users existence in IsAuthenticated
1 files changed, 26 insertions(+), 1 deletions(-)

M middlewares/auth.go
M middlewares/auth.go => middlewares/auth.go +26 -1
@@ 7,7 7,12 @@
package middlewares

import (
	"context"
	"log"
	"net/http"
	"tixe/db"
	"tixe/types"
	"tixe/util"

	"github.com/gin-contrib/sessions"
	"github.com/gin-gonic/gin"


@@ 15,10 20,30 @@ import (

func IsAuthenticated(c *gin.Context) {
	if sessions.Default(c).Get("profile") == nil {
		// TODO: This should probably be validated somehow... DB lookup or something.
		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()
	}
}