From 4820c7696db3c54959258b1a5b00c77e1246cbd7 Mon Sep 17 00:00:00 2001 From: Arda Serdar Pektezol <1669855+pektezol@users.noreply.github.com> Date: Fri, 6 Jan 2023 23:55:12 +0300 Subject: what the fuck is this mess (#21) --- backend/controllers/controllers.go | 88 ------------------ backend/controllers/demoController.go | 2 +- backend/controllers/homeController.go | 77 ++++++++++++++++ backend/controllers/userController.go | 168 +++++++--------------------------- 4 files changed, 110 insertions(+), 225 deletions(-) delete mode 100644 backend/controllers/controllers.go create mode 100644 backend/controllers/homeController.go (limited to 'backend/controllers') diff --git a/backend/controllers/controllers.go b/backend/controllers/controllers.go deleted file mode 100644 index 5237ccd..0000000 --- a/backend/controllers/controllers.go +++ /dev/null @@ -1,88 +0,0 @@ -package controllers - -import ( - "log" - "net/http" - "os" - "time" - - "github.com/gin-gonic/gin" - "github.com/golang-jwt/jwt/v4" - "github.com/pektezol/leastportals/backend/database" - "github.com/solovev/steam_go" -) - -func Home(c *gin.Context) { - user, exists := c.Get("user") - if !exists { - c.JSON(200, "no id, not auth") - } else { - c.JSON(200, gin.H{ - "output": user, - }) - } -} - -func Login(c *gin.Context) { - openID := steam_go.NewOpenId(c.Request) - switch openID.Mode() { - case "": - c.Redirect(http.StatusMovedPermanently, openID.AuthUrl()) - case "cancel": - c.Redirect(http.StatusMovedPermanently, "/") - default: - 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 steam_id = $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.AvatarFull, 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 - } - // Create auth cookie - c.SetSameSite(http.SameSiteLaxMode) - c.SetCookie("auth", tokenString, 3600*24*30, "/", "", true, true) - c.Redirect(http.StatusMovedPermanently, "/") - } -} - -func Logout(c *gin.Context) { - // Check if user exists - _, exists := c.Get("user") - if !exists { - c.JSON(http.StatusBadRequest, gin.H{ - "error": "not logged in", - }) - } else { - // 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", - }) - } -} diff --git a/backend/controllers/demoController.go b/backend/controllers/demoController.go index fdabbae..85f6ede 100644 --- a/backend/controllers/demoController.go +++ b/backend/controllers/demoController.go @@ -40,7 +40,7 @@ func UploadDemo(c *gin.Context) { }) return }*/ - f, err := os.Open("test.txt") + f, err := os.Open("pgun_2280.dem") if err != nil { panic(fmt.Sprintf("cannot open file: %v", err)) } diff --git a/backend/controllers/homeController.go b/backend/controllers/homeController.go new file mode 100644 index 0000000..8d81eef --- /dev/null +++ b/backend/controllers/homeController.go @@ -0,0 +1,77 @@ +package controllers + +import ( + "net/http" + "os" + "time" + + "github.com/gin-gonic/gin" + "github.com/golang-jwt/jwt/v4" + "github.com/pektezol/leastportals/backend/database" + "github.com/pektezol/leastportals/backend/models" + "github.com/solovev/steam_go" +) + +func Home(c *gin.Context) { + user, exists := c.Get("user") + if !exists { + c.JSON(200, "no id, not auth") + } else { + c.JSON(200, gin.H{ + "output": user, + }) + } +} + +func Login(c *gin.Context) { + openID := steam_go.NewOpenId(c.Request) + switch openID.Mode() { + case "": + c.Redirect(http.StatusMovedPermanently, openID.AuthUrl()) + case "cancel": + c.Redirect(http.StatusMovedPermanently, "/") + default: + steamID, err := openID.ValidateAndGetId() + if err != nil { + c.JSON(http.StatusInternalServerError, models.ErrorResponse(err.Error())) + return + } + // Create user if new + var checkSteamID int64 + err = database.DB.QueryRow("SELECT steam_id FROM users WHERE steam_id = $1", steamID).Scan(&checkSteamID) + if err != nil { + c.JSON(http.StatusInternalServerError, models.ErrorResponse(err.Error())) + return + } + // User does not exist + if checkSteamID == 0 { + user, err := steam_go.GetPlayerSummaries(steamID, os.Getenv("API_KEY")) + if err != nil { + c.JSON(http.StatusInternalServerError, models.ErrorResponse(err.Error())) + return + } + // Insert new user to database + database.DB.Exec(`INSERT INTO users (steam_id, username, avatar_link, country_code) + VALUES ($1, $2, $3, $4)`, steamID, user.PersonaName, user.AvatarFull, user.LocCountryCode) + } + // Generate JWT token + token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{ + "sub": steamID, + "exp": time.Now().Add(time.Hour * 24 * 365).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, models.ErrorResponse("Failed to generate token.")) + return + } + c.JSON(http.StatusOK, models.Response{ + Success: true, + Message: "Successfully generated token.", + Data: models.LoginResponse{ + Token: tokenString, + }, + }) + return + } +} diff --git a/backend/controllers/userController.go b/backend/controllers/userController.go index 87a9427..70a2a34 100644 --- a/backend/controllers/userController.go +++ b/backend/controllers/userController.go @@ -13,161 +13,57 @@ func Profile(c *gin.Context) { // Check if user exists user, exists := c.Get("user") if !exists { - c.JSON(http.StatusUnauthorized, gin.H{ - "code": http.StatusUnauthorized, - "output": gin.H{ - "error": "User not logged in. Could be invalid token.", - }, - }) - return - } else { - user := user.(models.User) - c.JSON(http.StatusOK, gin.H{ - "code": http.StatusOK, - "output": gin.H{ - "avatar": user.AvatarLink, - "country": user.CountryCode, - "types": user.TypeToString(), - "username": user.Username, - }, - "profile": true, - }) - return - } -} - -func FetchUser(c *gin.Context) { - id := c.Param("id") - // Check if id is all numbers and 17 length - match, _ := regexp.MatchString("^[0-9]{17}$", id) - if !match { - c.JSON(http.StatusNotFound, gin.H{ - "code": http.StatusNotFound, - "output": gin.H{ - "error": "User not found.", - }, - }) - return - } - // Check if user exists - var targetUser models.User - database.DB.QueryRow(`SELECT * FROM users WHERE steam_id = $1;`, id).Scan( - &targetUser.SteamID, &targetUser.Username, &targetUser.AvatarLink, &targetUser.CountryCode, - &targetUser.CreatedAt, &targetUser.UpdatedAt, &targetUser.UserType) - if targetUser.SteamID == "" { - // User does not exist - c.JSON(http.StatusNotFound, gin.H{ - "code": http.StatusNotFound, - "output": gin.H{ - "error": "User not found.", - }, - }) + c.JSON(http.StatusUnauthorized, models.ErrorResponse("User not logged in.")) return } - // Target user exists - _, exists := c.Get("user") - if exists { - c.Redirect(http.StatusFound, "/api/v1/profile") - return - } - c.JSON(http.StatusOK, gin.H{ - "code": http.StatusOK, - "output": gin.H{ - "avatar": targetUser.AvatarLink, - "country": targetUser.CountryCode, - "types": targetUser.TypeToString(), - "username": targetUser.Username, + c.JSON(http.StatusOK, models.Response{ + Success: true, + Message: "", + Data: models.ProfileResponse{ + Profile: true, + SteamID: user.(models.User).SteamID, + Username: user.(models.User).Username, + AvatarLink: user.(models.User).AvatarLink, + CountryCode: user.(models.User).CountryCode, }, - "profile": false, }) return } -/*func UpdateUserCountry(c *gin.Context) { +func FetchUser(c *gin.Context) { id := c.Param("id") - cc := c.Param("country") // Check if id is all numbers and 17 length match, _ := regexp.MatchString("^[0-9]{17}$", id) if !match { - c.JSON(http.StatusNotFound, gin.H{ - "code": http.StatusNotFound, - "output": gin.H{ - "error": "User not found.", - }, - }) - return - } - // Check if valid country code length - match, _ = regexp.MatchString("^[A-Z]{2}$", cc) - if !match { - c.JSON(http.StatusNotFound, gin.H{ - "code": http.StatusNotFound, - "output": gin.H{ - "error": "Invalid country code.", - }, - }) + c.JSON(http.StatusNotFound, models.ErrorResponse("User not found.")) return } // Check if user exists - var targetUser models.User - database.DB.QueryRow(`SELECT * FROM users WHERE steam_id = $1;`, id).Scan( - &targetUser.SteamID, &targetUser.Username, &targetUser.AvatarLink, &targetUser.CountryCode, - &targetUser.CreatedAt, &targetUser.UpdatedAt, &targetUser.UserType) - if targetUser.SteamID == "" { + var user models.User + err := database.DB.QueryRow(`SELECT * FROM users WHERE steam_id = $1;`, id).Scan( + &user.SteamID, &user.Username, &user.AvatarLink, &user.CountryCode, + &user.CreatedAt, &user.UpdatedAt) + if user.SteamID == "" { // User does not exist - c.JSON(http.StatusNotFound, gin.H{ - "code": http.StatusNotFound, - "output": gin.H{ - "error": "User not found.", - }, - }) + c.JSON(http.StatusNotFound, models.ErrorResponse("User not found.")) return } - // Target user exists - user, exists := c.Get("user") - if exists { - user := user.(models.User) - if user.SteamID == targetUser.SteamID { - // Can change because it's our own profile - // TODO:Check if country code exists in database // ADD countries TABLE - var existingCC string - database.DB.QueryRow(`SELECT country_code FROM countries WHERE country_code = $1;`, cc).Scan(&existingCC) - if existingCC == "" { - c.JSON(http.StatusNotFound, gin.H{ - "code": http.StatusForbidden, - "output": gin.H{ - "error": "Given country code is not found.", - }, - }) - return - } - // Valid to change - database.DB.Exec(`UPDATE users SET country_code = $1 WHERE steam_id = $2`, cc, user.SteamID) - c.JSON(http.StatusOK, gin.H{ - "code": http.StatusOK, - "output": gin.H{ - "avatar": user.AvatarLink, - "country": user.CountryCode, - "types": user.TypeToString(), - "username": user.Username, - }, - "profile": true, - }) - return - } - c.JSON(http.StatusForbidden, gin.H{ - "code": http.StatusForbidden, - "output": gin.H{ - "error": "Can not change country of another user.", - }, - }) + if err != nil { + c.JSON(http.StatusInternalServerError, models.ErrorResponse(err.Error())) return } - c.JSON(http.StatusUnauthorized, gin.H{ - "code": http.StatusUnauthorized, - "output": gin.H{ - "error": "User not logged in. Could be invalid token.", + // Target user exists + _, exists := c.Get("user") + c.JSON(http.StatusOK, models.Response{ + Success: true, + Message: "", + Data: models.ProfileResponse{ + Profile: exists, + SteamID: user.SteamID, + Username: user.Username, + AvatarLink: user.AvatarLink, + CountryCode: user.CountryCode, }, }) return -}*/ +} -- cgit v1.2.3