From 66929b059af90cedce1d25d5fefc7768f8f2843d Mon Sep 17 00:00:00 2001 From: Arda Serdar Pektezol <1669855+pektezol@users.noreply.github.com> Date: Thu, 27 Oct 2022 01:17:14 +0300 Subject: (#2) finished user authentication with steam (probably) --- backend/controllers/controllers.go | 73 ++++++++++++++++++++++++++------------ 1 file changed, 50 insertions(+), 23 deletions(-) (limited to 'backend') diff --git a/backend/controllers/controllers.go b/backend/controllers/controllers.go index 8ce4860..79fc223 100644 --- a/backend/controllers/controllers.go +++ b/backend/controllers/controllers.go @@ -8,6 +8,7 @@ import ( "github.com/gin-contrib/sessions" "github.com/gin-gonic/gin" + "github.com/golang-jwt/jwt/v4" "github.com/pektezol/leastportals/backend/database" "github.com/solovev/steam_go" ) @@ -31,47 +32,73 @@ func Home(c *gin.Context) { } func Login(c *gin.Context) { - opId := steam_go.NewOpenId(c.Request) - switch opId.Mode() { + openID := steam_go.NewOpenId(c.Request) + switch openID.Mode() { case "": - http.Redirect(c.Writer, c.Request, opId.AuthUrl(), 301) + c.Redirect(http.StatusMovedPermanently, openID.AuthUrl()) case "cancel": - c.Writer.Write([]byte("Authorization cancelled")) + c.Redirect(http.StatusMovedPermanently, "/") default: - steamId, err := opId.ValidateAndGetId() + steamID, err := openID.ValidateAndGetId() if err != nil { http.Error(c.Writer, err.Error(), http.StatusInternalServerError) } // Create user if new var checkSteamID int64 - database.DB.QueryRow("SELECT steam_id FROM users WHERE steamid = $1", steamId).Scan(&checkSteamID) - if checkSteamID == 0 { // User does not exist - user, err := steam_go.GetPlayerSummaries(steamId, os.Getenv("API_KEY")) + database.DB.QueryRow("SELECT steam_id FROM users WHERE steamid = $1", steamID).Scan(&checkSteamID) + // User does not exist + if checkSteamID == 0 { + user, err := steam_go.GetPlayerSummaries(steamID, os.Getenv("API_KEY")) if err != nil { log.Panic(err) } + // Insert new user to database database.DB.Exec(`INSERT INTO users (steam_id, username, avatar_link, country_code, created_at, updated_at, user_type) - VALUES ($1, $2, $3, $4, $5, $6, $7)`, steamId, user.PersonaName, user.Avatar, user.LocCountryCode, time.Now().UTC(), time.Now().UTC(), 0) + VALUES ($1, $2, $3, $4, $5, $6, $7)`, steamID, user.PersonaName, user.Avatar, user.LocCountryCode, time.Now().UTC(), time.Now().UTC(), 0) + } + // Update updated_at + database.DB.Exec(`UPDATE users SET updated_at = $1 WHERE steam_id = $2`, time.Now().UTC(), steamID) + // Generate JWT token + token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{ + "sub": steamID, + "exp": time.Now().Add(time.Hour * 24 * 30).Unix(), + }) + // Sign and get the complete encoded token as a string using the secret + tokenString, err := token.SignedString([]byte(os.Getenv("SECRET_KEY"))) + if err != nil { + c.JSON(http.StatusBadRequest, gin.H{ + "error": "failed to create token", + }) + return } - session := sessions.Default(c) - session.Set("id", steamId) - session.Save() - // Do whatever you want with steam id + // Create auth cookie + c.SetSameSite(http.SameSiteLaxMode) + c.SetCookie("auth", tokenString, 3600*24*30, "/", "", true, true) c.Redirect(http.StatusMovedPermanently, "/") - c.Writer.Write([]byte(steamId)) } } func Logout(c *gin.Context) { - session := sessions.Default(c) - if session.Get("id") == nil { - c.JSON(http.StatusBadRequest, "no id, not auth") + // Check if user exists + _, exists := c.Get("user") + if !exists { + c.JSON(http.StatusBadRequest, gin.H{ + "error": "not logged in", + }) } else { - session.Set("id", "") - session.Clear() - session.Options(sessions.Options{Path: "/", MaxAge: -1}) - session.Save() - log.Print("id", session.Get("id")) - c.Redirect(http.StatusPermanentRedirect, "/") + // Set auth cookie to die + tokenString, _ := c.Cookie("auth") + c.SetCookie("auth", tokenString, -1, "/", "", true, true) + c.JSON(http.StatusOK, gin.H{ + "output": "logout success", + }) + //c.Redirect(http.StatusPermanentRedirect, "/") } } + +func Validate(c *gin.Context) { + user, _ := c.Get("user") + c.JSON(http.StatusOK, gin.H{ + "output": user, + }) +} -- cgit v1.2.3