Skip to content

Commit

Permalink
chore: Update dependencies, add Google OAuth2 authentication endpoint…
Browse files Browse the repository at this point in the history
…, and clean up code
  • Loading branch information
f-fsantos committed Jun 5, 2024
1 parent e19a67b commit 6e129a9
Show file tree
Hide file tree
Showing 10 changed files with 176 additions and 102 deletions.
40 changes: 30 additions & 10 deletions api/account/discord.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,12 +20,28 @@ package account
import (
"encoding/json"
"errors"
"log"
"net/http"
"net/url"
"os"
)

func HandleDiscordCallback(w http.ResponseWriter, r *http.Request) (string, error) {
code := r.URL.Query().Get("code")
gameUrl := os.Getenv("GAME_URL")
if code == "" {
defer http.Redirect(w, r, gameUrl, http.StatusSeeOther)
return "", errors.New("code is empty")
}

discordId, err := RetrieveDiscordId(code)
if err != nil {
defer http.Redirect(w, r, gameUrl, http.StatusSeeOther)
return "", err
}

return discordId, nil
}

func RetrieveDiscordId(code string) (string, error) {
token, err := http.PostForm("https://discord.com/api/oauth2/token", url.Values{
"client_id": {os.Getenv("DISCORD_CLIENT_ID")},
Expand All @@ -37,23 +53,25 @@ func RetrieveDiscordId(code string) (string, error) {
})

if err != nil {
log.Println("error getting token:", err)
return "", err
}
log.Println("token: ", token)

// extract access_token from token
type TokenResponse struct {
AccessToken string `json:"access_token"`
AccessToken string `json:"access_token"`
TokenType string `json:"token_type"`
ExpiresIn int `json:"expires_in"`
Scope string `json:"scope"`
RefreshToken string `json:"refresh_token"`
}

var tokenResponse TokenResponse
err = json.NewDecoder(token.Body).Decode(&tokenResponse)
if err != nil {
return "", err
}
access_token := tokenResponse.AccessToken
log.Printf("access_token: %s", access_token)

access_token := tokenResponse.AccessToken
if access_token == "" {
err = errors.New("access token is empty")
return "", err
Expand All @@ -62,24 +80,26 @@ func RetrieveDiscordId(code string) (string, error) {
client := &http.Client{}
req, err := http.NewRequest("GET", "https://discord.com/api/users/@me", nil)
if err != nil {
log.Println("error creating request:", err)
return "", err
}

req.Header.Set("Authorization", "Bearer "+access_token)
resp, err := client.Do(req)
if err != nil {
log.Println("error getting user info:", err)
return "", err
}

defer resp.Body.Close()

type User struct {
Id string `json:"id"`
}

var user User
err = json.NewDecoder(resp.Body).Decode(&user)

log.Println("user", user.Id)
if err != nil {
return "", err
}

return user.Id, nil
}
97 changes: 97 additions & 0 deletions api/account/google.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
/*
Copyright (C) 2024 Pagefault Games
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/

package account

import (
"encoding/json"
"errors"
"net/http"
"net/url"
"os"

"github.com/golang-jwt/jwt/v5"
)

func HandleGoogleCallback(w http.ResponseWriter, r *http.Request) (string, error) {
code := r.URL.Query().Get("code")
gameUrl := os.Getenv("GAME_URL")
if code == "" {
defer http.Redirect(w, r, gameUrl, http.StatusSeeOther)
return "", errors.New("code is empty")
}

googleId, err := RetrieveGoogleId(code)
if err != nil {
defer http.Redirect(w, r, gameUrl, http.StatusSeeOther)
return "", err
}

return googleId, err
}

func RetrieveGoogleId(code string) (string, error) {
token, err := http.PostForm("httpS://oauth2.googleapis.com/token", url.Values{
"client_id": {os.Getenv("GOOGLE_CLIENT_ID")},
"client_secret": {os.Getenv("GOOGLE_CLIENT_SECRET")},
"code": {code},
"grant_type": {"authorization_code"},
"redirect_uri": {os.Getenv("GOOGLE_CALLBACK_URI")},
})

if err != nil {
return "", err
}
defer token.Body.Close()
type TokenResponse struct {
AccessToken string `json:"access_token"`
TokenType string `json:"token_type"`
ExpiresIn int `json:"expires_in"`
IdToken string `json:"id_token"`
RefreshToken string `json:"refresh_token"`
Scope string `json:"scope"`
}
var tokenResponse TokenResponse
err = json.NewDecoder(token.Body).Decode(&tokenResponse)
if err != nil {
return "", err
}

userId, err := parseJWTWithoutValidation(tokenResponse.IdToken)
if err != nil {
return "", err
}

return userId, nil
}

func parseJWTWithoutValidation(idToken string) (string, error) {
parser := jwt.NewParser()

// Use ParseUnverified to parse the token without validation
parsedJwt, _, err := parser.ParseUnverified(idToken, jwt.MapClaims{})
if err != nil {
return "", err
}

claims, ok := parsedJwt.Claims.(jwt.MapClaims)
if !ok {
return "", errors.New("invalid token claims")
}

return claims.GetSubject()
}
30 changes: 0 additions & 30 deletions api/auth.go

This file was deleted.

40 changes: 25 additions & 15 deletions api/endpoints.go
Original file line number Diff line number Diff line change
Expand Up @@ -835,57 +835,67 @@ func handleDailyRankingPageCount(w http.ResponseWriter, r *http.Request) {

// redirect link after authorizing application link
func handleProviderCallback(w http.ResponseWriter, r *http.Request) {

code := r.URL.Query().Get("code")
provider := r.PathValue("provider")
state := r.URL.Query().Get("state")
gameUrl := os.Getenv("GAME_URL")
if code == "" {
defer http.Redirect(w, r, gameUrl, http.StatusSeeOther)
var externalAuthId string
var err error
switch provider {
case "discord":
externalAuthId, err = account.HandleDiscordCallback(w, r)
case "google":
externalAuthId, err = account.HandleGoogleCallback(w, r)
default:
http.Error(w, "invalid provider", http.StatusBadRequest)
return
}

var userName string
user, err := account.RetrieveDiscordId(code)
if err != nil {
defer http.Redirect(w, r, gameUrl, http.StatusSeeOther)
httpError(w, r, err, http.StatusInternalServerError)
return
}

if state != "" {
// replace whitespace for +
state = strings.Replace(state, " ", "+", -1)
stateByte, err := base64.StdEncoding.DecodeString(state)
if err != nil {
defer http.Redirect(w, r, gameUrl, http.StatusSeeOther)
return
}
userName, err = db.FetchUsernameBySessionToken(stateByte)

userName, err := db.FetchUsernameBySessionToken(stateByte)
if err != nil {
defer http.Redirect(w, r, gameUrl, http.StatusSeeOther)
return
}
err = db.AddDiscordAuthByUsername(user, userName)

err = db.AddExternalAuthByUsername(externalAuthId, userName)
if err != nil {
defer http.Redirect(w, r, gameUrl, http.StatusSeeOther)
return
}

} else {
userName, err = db.FetchUsernameByDiscordId(user)
userName, err := db.FetchUsernameByExternalAuth(externalAuthId)
if err != nil {
defer http.Redirect(w, r, gameUrl, http.StatusSeeOther)
return
}

cookieToken, err := account.GenerateTokenForUsername(userName)
sessionToken, err := account.GenerateTokenForUsername(userName)
if err != nil {
defer http.Redirect(w, r, gameUrl, http.StatusSeeOther)
return
}
cookie := http.Cookie{Name: "pokerogue_sessionId", Value: string(cookieToken), Path: "/"}
http.SetCookie(w, &cookie)

http.SetCookie(w, &http.Cookie{
Name: "pokerogue_sessionId",
Value: sessionToken,
Path: "/",
})
}
defer http.Redirect(w, r, gameUrl, http.StatusSeeOther)

defer http.Redirect(w, r, gameUrl, http.StatusSeeOther)
}

func handleProviderLogout(w http.ResponseWriter, r *http.Request) {

Check failure on line 901 in api/endpoints.go

View workflow job for this annotation

GitHub Actions / Build (linux)

Error return value of `db.RemoveDiscordAuthByUUID` is not checked (errcheck)

Check failure on line 901 in api/endpoints.go

View workflow job for this annotation

GitHub Actions / Build (windows)

Error return value of `db.RemoveDiscordAuthByUUID` is not checked (errcheck)
Expand Down
8 changes: 4 additions & 4 deletions db/account.go
Original file line number Diff line number Diff line change
Expand Up @@ -50,18 +50,18 @@ func AddAccountSession(username string, token []byte) error {
return nil
}

func AddDiscordAuthByUsername(discordId string, username string) error {
_, err := handle.Exec("UPDATE accounts SET discordId = ? WHERE username = ?", discordId, username)
func AddExternalAuthByUsername(externalAuth string, username string) error {
_, err := handle.Exec("INSERT INTO accountIntegrations (uuid, externalAccountId) SELECT a.uuid, ? FROM accounts a WHERE a.username = ?", externalAuth, username)
if err != nil {
return err
}

return nil
}

func FetchUsernameByDiscordId(discordId string) (string, error) {
func FetchUsernameByExternalAuth(externalAuth string) (string, error) {
var username string
err := handle.QueryRow("SELECT username FROM accounts WHERE discordId = ?", discordId).Scan(&username)
err := handle.QueryRow("SELECT a.username FROM accounts a JOIN accountIntegrations ai ON a.uuid = ai.uuid WHERE ai.externalAccountId = ?", externalAuth).Scan(&username)
if err != nil {
return "", err
}
Expand Down
6 changes: 4 additions & 2 deletions db/db.go
Original file line number Diff line number Diff line change
Expand Up @@ -95,8 +95,10 @@ func setupDb(tx *sql.Tx) error {

// ----------------------------------
// MIGRATION 002
`ALTER TABLE accounts ADD COLUMN IF NOT EXISTS discordId VARCHAR(32) DEFAULT NULL`,
`CREATE INDEX IF NOT EXISTS accountsByDiscordId ON accounts (discordId)`,

`CREATE TABLE IF NOT EXISTS accountIntegrations (uuid BINARY(16) NOT NULL, externalAccountId VARCHAR(32) NOT NULL, PRIMARY KEY (uuid, externalAccountId), FOREIGN KEY (uuid) REFERENCES accounts (uuid) ON DELETE CASCADE ON UPDATE CASCADE)`,
`CREATE INDEX IF NOT EXISTS accountIntegrationsByExternalAccountId ON accountIntegrations (externalAccountId)`,
`CREATE INDEX IF NOT EXISTS accountIntegrationsByUuid ON accountIntegrations (uuid)`,
}

for _, q := range queries {
Expand Down
2 changes: 1 addition & 1 deletion docker-compose.Example.yml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
services:
server:
command: --debug --dbaddr db --dbuser pokerogue --dbpass pokerogue --dbname pokeroguedb --gameurl http://localhost:8000 --discordcallbackuri http://localhost:8001
command: --debug --dbaddr db --dbuser pokerogue --dbpass pokerogue --dbname pokeroguedb --gameurl http://localhost:8000 --callbackuri http://localhost:8001
image: ghcr.io/pagefaultgames/rogueserver:master
restart: unless-stopped
depends_on:
Expand Down
13 changes: 2 additions & 11 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -8,15 +8,6 @@ require (
golang.org/x/crypto v0.22.0
)

require (
github.com/gorilla/context v1.1.1 // indirect
github.com/gorilla/mux v1.6.2 // indirect
github.com/gorilla/securecookie v1.1.2 // indirect
golang.org/x/oauth2 v0.20.0 // indirect
)
require github.com/golang-jwt/jwt/v5 v5.2.1

require (
github.com/gorilla/sessions v1.2.2
github.com/markbates/goth v1.79.0
golang.org/x/sys v0.19.0 // indirect
)
require golang.org/x/sys v0.19.0 // indirect
Loading

0 comments on commit 6e129a9

Please sign in to comment.