Last active
October 23, 2023 18:47
-
-
Save otraore/4b3120aa70e1c1aa33ba78e886bb54f3 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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
This code helped me greatly. Thank u