diff options
| author | Arda Serdar Pektezol <1669855+pektezol@users.noreply.github.com> | 2023-08-26 08:53:24 +0300 |
|---|---|---|
| committer | Arda Serdar Pektezol <1669855+pektezol@users.noreply.github.com> | 2023-08-26 08:53:24 +0300 |
| commit | f1b7589b2936335957a6a1da1eea3d66233ad0ce (patch) | |
| tree | 1975af217c190f5dbdb23b96015cef45206302d4 /backend/handlers/login.go | |
| parent | docs: profile improvement swagger (#51) (diff) | |
| download | lphub-f1b7589b2936335957a6a1da1eea3d66233ad0ce.tar.gz lphub-f1b7589b2936335957a6a1da1eea3d66233ad0ce.tar.bz2 lphub-f1b7589b2936335957a6a1da1eea3d66233ad0ce.zip | |
refactor: reorganizing packages
Former-commit-id: 99410223654c2a5ffc15fdab6ec3e921b5410cba
Diffstat (limited to 'backend/handlers/login.go')
| -rw-r--r-- | backend/handlers/login.go | 166 |
1 files changed, 166 insertions, 0 deletions
diff --git a/backend/handlers/login.go b/backend/handlers/login.go new file mode 100644 index 0000000..4b151c2 --- /dev/null +++ b/backend/handlers/login.go | |||
| @@ -0,0 +1,166 @@ | |||
| 1 | package handlers | ||
| 2 | |||
| 3 | import ( | ||
| 4 | "encoding/json" | ||
| 5 | "fmt" | ||
| 6 | "io" | ||
| 7 | "net/http" | ||
| 8 | "os" | ||
| 9 | "time" | ||
| 10 | |||
| 11 | "github.com/gin-gonic/gin" | ||
| 12 | "github.com/golang-jwt/jwt/v4" | ||
| 13 | "github.com/pektezol/leastportalshub/backend/database" | ||
| 14 | "github.com/pektezol/leastportalshub/backend/models" | ||
| 15 | "github.com/solovev/steam_go" | ||
| 16 | ) | ||
| 17 | |||
| 18 | type LoginResponse struct { | ||
| 19 | Token string `json:"token"` | ||
| 20 | } | ||
| 21 | |||
| 22 | // Login | ||
| 23 | // | ||
| 24 | // @Description Get (redirect) login page for Steam auth. | ||
| 25 | // @Tags login | ||
| 26 | // @Accept json | ||
| 27 | // @Produce json | ||
| 28 | // @Success 200 {object} models.Response{data=LoginResponse} | ||
| 29 | // @Failure 400 {object} models.Response | ||
| 30 | // @Router /login [get] | ||
| 31 | func Login(c *gin.Context) { | ||
| 32 | openID := steam_go.NewOpenId(c.Request) | ||
| 33 | switch openID.Mode() { | ||
| 34 | case "": | ||
| 35 | c.Redirect(http.StatusMovedPermanently, openID.AuthUrl()) | ||
| 36 | case "cancel": | ||
| 37 | c.Redirect(http.StatusMovedPermanently, "/") | ||
| 38 | default: | ||
| 39 | steamID, err := openID.ValidateAndGetId() | ||
| 40 | if err != nil { | ||
| 41 | c.JSON(http.StatusBadRequest, models.ErrorResponse(err.Error())) | ||
| 42 | return | ||
| 43 | } | ||
| 44 | // Create user if new | ||
| 45 | var checkSteamID int64 | ||
| 46 | database.DB.QueryRow("SELECT steam_id FROM users WHERE steam_id = $1", steamID).Scan(&checkSteamID) | ||
| 47 | // User does not exist | ||
| 48 | if checkSteamID == 0 { | ||
| 49 | user, err := GetPlayerSummaries(steamID, os.Getenv("API_KEY")) | ||
| 50 | if err != nil { | ||
| 51 | c.JSON(http.StatusBadRequest, models.ErrorResponse(err.Error())) | ||
| 52 | return | ||
| 53 | } | ||
| 54 | // Empty country code check | ||
| 55 | if user.LocCountryCode == "" { | ||
| 56 | user.LocCountryCode = "XX" | ||
| 57 | } | ||
| 58 | // Insert new user to database | ||
| 59 | database.DB.Exec(`INSERT INTO users (steam_id, user_name, avatar_link, country_code) | ||
| 60 | VALUES ($1, $2, $3, $4)`, steamID, user.PersonaName, user.AvatarFull, user.LocCountryCode) | ||
| 61 | } | ||
| 62 | moderator := false | ||
| 63 | rows, _ := database.DB.Query("SELECT title_name FROM titles t INNER JOIN user_titles ut ON t.id=ut.title_id WHERE ut.user_id = $1", steamID) | ||
| 64 | for rows.Next() { | ||
| 65 | var title string | ||
| 66 | rows.Scan(&title) | ||
| 67 | if title == "Moderator" { | ||
| 68 | moderator = true | ||
| 69 | } | ||
| 70 | } | ||
| 71 | // Generate JWT token | ||
| 72 | token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{ | ||
| 73 | "sub": steamID, | ||
| 74 | "exp": time.Now().Add(time.Hour * 24 * 30).Unix(), | ||
| 75 | "mod": moderator, | ||
| 76 | }) | ||
| 77 | // Sign and get the complete encoded token as a string using the secret | ||
| 78 | tokenString, err := token.SignedString([]byte(os.Getenv("SECRET_KEY"))) | ||
| 79 | if err != nil { | ||
| 80 | c.JSON(http.StatusBadRequest, models.ErrorResponse("Failed to generate token.")) | ||
| 81 | return | ||
| 82 | } | ||
| 83 | c.SetCookie("token", tokenString, 3600*24*30, "/", "", true, true) | ||
| 84 | c.Redirect(http.StatusTemporaryRedirect, "/") | ||
| 85 | // c.JSON(http.StatusOK, models.Response{ | ||
| 86 | // Success: true, | ||
| 87 | // Message: "Successfully generated token.", | ||
| 88 | // Data: LoginResponse{ | ||
| 89 | // Token: tokenString, | ||
| 90 | // }, | ||
| 91 | // }) | ||
| 92 | return | ||
| 93 | } | ||
| 94 | } | ||
| 95 | |||
| 96 | // GET Token | ||
| 97 | // | ||
| 98 | // @Description Gets the token cookie value from the user. | ||
| 99 | // @Tags auth | ||
| 100 | // @Produce json | ||
| 101 | // | ||
| 102 | // @Success 200 {object} models.Response{data=LoginResponse} | ||
| 103 | // @Failure 404 {object} models.Response | ||
| 104 | // @Router /token [get] | ||
| 105 | func GetCookie(c *gin.Context) { | ||
| 106 | cookie, err := c.Cookie("token") | ||
| 107 | if err != nil { | ||
| 108 | c.JSON(http.StatusNotFound, models.ErrorResponse("No token cookie found.")) | ||
| 109 | return | ||
| 110 | } | ||
| 111 | c.JSON(http.StatusOK, models.Response{ | ||
| 112 | Success: true, | ||
| 113 | Message: "Token cookie successfully retrieved.", | ||
| 114 | Data: LoginResponse{ | ||
| 115 | Token: cookie, | ||
| 116 | }, | ||
| 117 | }) | ||
| 118 | } | ||
| 119 | |||
| 120 | // DELETE Token | ||
| 121 | // | ||
| 122 | // @Description Deletes the token cookie from the user. | ||
| 123 | // @Tags auth | ||
| 124 | // @Produce json | ||
| 125 | // | ||
| 126 | // @Success 200 {object} models.Response{data=LoginResponse} | ||
| 127 | // @Failure 404 {object} models.Response | ||
| 128 | // @Router /token [delete] | ||
| 129 | func DeleteCookie(c *gin.Context) { | ||
| 130 | cookie, err := c.Cookie("token") | ||
| 131 | if err != nil { | ||
| 132 | c.JSON(http.StatusNotFound, models.ErrorResponse("No token cookie found.")) | ||
| 133 | return | ||
| 134 | } | ||
| 135 | c.SetCookie("token", "", -1, "/", "", true, true) | ||
| 136 | c.JSON(http.StatusOK, models.Response{ | ||
| 137 | Success: true, | ||
| 138 | Message: "Token cookie successfully deleted.", | ||
| 139 | Data: LoginResponse{ | ||
| 140 | Token: cookie, | ||
| 141 | }, | ||
| 142 | }) | ||
| 143 | } | ||
| 144 | |||
| 145 | func GetPlayerSummaries(steamId, apiKey string) (*models.PlayerSummaries, error) { | ||
| 146 | url := fmt.Sprintf("http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v2/?key=%s&steamids=%s", apiKey, steamId) | ||
| 147 | resp, err := http.Get(url) | ||
| 148 | if err != nil { | ||
| 149 | return nil, err | ||
| 150 | } | ||
| 151 | body, err := io.ReadAll(resp.Body) | ||
| 152 | if err != nil { | ||
| 153 | return nil, err | ||
| 154 | } | ||
| 155 | |||
| 156 | type Result struct { | ||
| 157 | Response struct { | ||
| 158 | Players []models.PlayerSummaries `json:"players"` | ||
| 159 | } `json:"response"` | ||
| 160 | } | ||
| 161 | var data Result | ||
| 162 | if err := json.Unmarshal(body, &data); err != nil { | ||
| 163 | return nil, err | ||
| 164 | } | ||
| 165 | return &data.Response.Players[0], err | ||
| 166 | } | ||