Skip to content

Instantly share code, notes, and snippets.

@otraore
Last active October 23, 2023 18:47
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save otraore/4b3120aa70e1c1aa33ba78e886bb54f3 to your computer and use it in GitHub Desktop.
Save otraore/4b3120aa70e1c1aa33ba78e886bb54f3 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"})
}
@techagentng
Copy link

This code helped me greatly. Thank u

@otraore
Copy link
Author

otraore commented Feb 26, 2022

Glad it helped you out!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment