Skip to content

Instantly share code, notes, and snippets.

@encryptblockr
Forked from otraore/session_auth_gin.go
Created October 18, 2021 07:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save encryptblockr/130edd6f4be6971958f6c2864528a74f to your computer and use it in GitHub Desktop.
Save encryptblockr/130edd6f4be6971958f6c2864528a74f to your computer and use it in GitHub Desktop.
package main
import (
"github.com/gin-gonic/contrib/sessions"
"github.com/gin-gonic/gin"
"log"
"net/http"
"strings"
)
func main() {
r := gin.Default()
store := sessions.NewCookieStore([]byte("secret"))
r.Use(sessions.Sessions("mysession", store))
r.POST("/login", login)
r.GET("/logout", logout)
private := r.Group("/private")
{
private.GET("/", private)
private.GET("/two", private2)
}
private.Use(AuthRequired())
r.Run(":8080")
}
func AuthRequired() gin.HandlerFunc {
return func(c *gin.Context) {
session := sessions.Default(c)
user := session.Get("user")
if user == nil {
// You'd normally redirect to login page
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid session token"})
} else {
// Continue down the chain to handler etc
c.Next()
}
}
}
func login(c *gin.Context) {
session := sessions.Default(c)
username := c.PostForm("username")
password := c.PostForm("password")
if strings.Trim(username, " ") == "" || strings.Trim(password, " ") == "" {
c.JSON(http.StatusUnauthorized, gin.H{"error": "Parameters can't be empty"})
return
}
if username == "hello" && password == "itsme" {
session.Set("user", username) //In real world usage you'd set this to the users ID
err := session.Save()
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to generate session token"})
} else {
c.JSON(http.StatusOK, gin.H{"message": "Successfully authenticated user"})
}
} else {
c.JSON(http.StatusUnauthorized, gin.H{"error": "Authentication failed"})
}
}
func logout(c *gin.Context) {
session := sessions.Default(c)
user := session.Get("user")
if user == nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid session token"})
} else {
log.Println(user)
session.Delete("user")
session.Save()
c.JSON(http.StatusOK, gin.H{"message": "Successfully logged out"})
}
}
func private(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"hello": user})
}
func private2(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"hello": "Logged in user"})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment