User Tools

Site Tools


Gin with session

ginweb.go
/*
 * Copyright 2019 Oleg Borodin  <borodin@unix7.org>
 */
 
package main
 
import (
    "net/http"
    "log"
    "errors"
    "strings"
    "github.com/gin-contrib/sessions"
    "github.com/gin-contrib/sessions/cookie"
    "github.com/gin-gonic/gin"
)
 
func CheckAuthMiddleware(context *gin.Context) {
    session := sessions.Default(context)
    username := session.Get("username")
    if username == nil {
        context.Redirect(http.StatusMovedPermanently, "/login")
        return
    }
    context.Next()
}
 
func userAuth(username string, password string) error {
    if len(strings.TrimSpace(username)) > 0 && len(strings.TrimSpace(username)) > 0 {
        return nil
    }
    return errors.New("username or password mismatch")
}
 
func SessionInitMiddleware(context *gin.Context) {
    session := sessions.Default(context)
    session.Set("dummy", 1)
    session.Save()
    context.Next()
}
 
func main() {
 
    router := gin.Default()
    router.LoadHTMLGlob("./templates/*.html")
    store := cookie.NewStore([]byte("supersecret"))
    router.Use(sessions.Sessions("session", store))
    router.Use(SessionInitMiddleware)
 
    router.GET("/login", func(context *gin.Context) {
        context.HTML(http.StatusOK, "login.html", nil)
    })
 
    router.GET("/logout", func(context *gin.Context) {
        session := sessions.Default(context)
        session.Clear()
        context.Redirect(http.StatusMovedPermanently, "/login")
    })
 
    router.POST("/auth", func(context *gin.Context) {
        type User struct {
            Username string `form:"username" json:"username" binding:"required"`
            Password string `form:"password" json:"password" binding:"required"`
        }
        var user User
        if err := context.ShouldBind(&user); err != nil {
            log.Println("auth error binding")
            context.Redirect(http.StatusMovedPermanently, "/login")
        }
        if err := userAuth(user.Username, user.Password); err == nil {
            session := sessions.Default(context)
            session.Set("username", user.Username)
            session.Save()
            context.Redirect(http.StatusMovedPermanently, "/")
            return
        }
        context.Redirect(http.StatusMovedPermanently, "/login")
    })
 
    authorized := router.Group("/")
    authorized.Use(CheckAuthMiddleware)
    authorized.GET("/", func(context *gin.Context) {
        session := sessions.Default(context)
        session.Set("count", 12)
        session.Save()
        context.HTML(http.StatusOK, "home.html", nil)
    })
 
    router.Static("/assets", "./public/assets/")
    router.Run(":8080")
}

login

after