package cookies import ( "net/http" "git.ctdo.de/ctdo/machinelock-manager/config" "git.ctdo.de/ctdo/machinelock-manager/templates" "github.com/gin-contrib/sessions" "github.com/gin-contrib/sessions/cookie" "github.com/gin-gonic/gin" uuid "github.com/satori/go.uuid" ) func Init(r *gin.Engine) { var secret []byte if config.CookieSecret != "" { secret = []byte(config.CookieSecret) } else { secret = uuid.NewV4().Bytes() } store := cookie.NewStore(secret) session := sessions.Sessions("machinelock", store) r.Use(session) } func SetAuth(c *gin.Context, status bool) { session := sessions.Default(c) if status { session.Set("auth", "ok") // logged in and in correct group to have access for this } else { session.Set("auth", "nok") // logged in but not in correct group to access this aka forbidden } session.Options(sessions.Options{ MaxAge: 3600 * 24 * 7, // 7 tage Path: "/", }) session.Save() } func Logout(c *gin.Context) { session := sessions.Default(c) session.Clear() } func CheckAuth(c *gin.Context) { session := sessions.Default(c) if session.Get("auth") == nil { c.Redirect(http.StatusFound, "/auth") // redirect to login c.Abort() return } if session.Get("auth") == "nok" { templates.Templates.ExecuteTemplate(c.Writer, "forbidden", gin.H{}) c.Abort() return } if session.Get("auth") != "ok" { c.Next() return } }