From fa57f5997fc951f7ad3f37672323a49eddce2c1e Mon Sep 17 00:00:00 2001 From: Frederico Santos Date: Sat, 27 Jul 2024 23:41:44 +0100 Subject: [PATCH] Added support for Discord OAuth2 (#25) * Need a login check * chore: Add Discord OAuth2 authentication endpoint chore: Update dependencies and clean up code chore: Update dependencies, add Discord OAuth2 authentication endpoint, and clean up code chore: Update dependencies, add Google OAuth2 authentication endpoint, and clean up code Code clean up uniqueness on external account id chore: Add Discord and Google OAuth2 authentication endpoints, and update dependencies code review fixes * chore: Update prodHandler to use clienturl flag for Access-Control-Allow-Origin * chore: Refactor FetchDiscordIdByUsername and FetchGoogleIdByUsername to handle null values * chore: Set secure and same-site attributes for session cookie * chore: Set session cookie expiration to 3 months * Update callback URL for Oauth2 client in docker-compose and rogueserver.go * Update callback URL for Oauth2 client in docker-compose and rogueserver.go --------- Co-authored-by: Matthew Olker --- Dockerfile | 1 + api/account/discord.go | 104 ++++++++++++++++++++++++++++++ api/account/google.go | 97 ++++++++++++++++++++++++++++ api/account/info.go | 13 +++- api/account/login.go | 21 ++++-- api/common.go | 3 + api/endpoints.go | 127 +++++++++++++++++++++++++++++++++++-- db/account.go | 94 +++++++++++++++++++++++++++ db/db.go | 6 ++ docker-compose.Example.yml | 2 +- go.mod | 6 +- go.sum | 10 +-- rogueserver.go | 25 +++++++- 13 files changed, 485 insertions(+), 24 deletions(-) create mode 100644 api/account/discord.go create mode 100644 api/account/google.go diff --git a/Dockerfile b/Dockerfile index 8a07093..02777ec 100644 --- a/Dockerfile +++ b/Dockerfile @@ -23,6 +23,7 @@ FROM scratch WORKDIR /app COPY --from=builder /src/rogueserver . +COPY --from=builder /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/ EXPOSE 8001 diff --git a/api/account/discord.go b/api/account/discord.go new file mode 100644 index 0000000..df2e8bb --- /dev/null +++ b/api/account/discord.go @@ -0,0 +1,104 @@ +/* + 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 . +*/ + +package account + +import ( + "encoding/json" + "errors" + "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")}, + "client_secret": {os.Getenv("DISCORD_CLIENT_SECRET")}, + "grant_type": {"authorization_code"}, + "code": {code}, + "redirect_uri": {os.Getenv("DISCORD_CALLBACK_URL")}, + "scope": {"identify"}, + }) + + if err != nil { + return "", err + } + + // extract access_token from token + type TokenResponse struct { + 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 + if access_token == "" { + return "", errors.New("access token is empty") + } + + client := &http.Client{} + req, err := http.NewRequest("GET", "https://discord.com/api/users/@me", nil) + if err != nil { + return "", err + } + + req.Header.Set("Authorization", "Bearer "+access_token) + resp, err := client.Do(req) + if err != nil { + return "", err + } + + defer resp.Body.Close() + + type User struct { + Id string `json:"id"` + } + + var user User + err = json.NewDecoder(resp.Body).Decode(&user) + if err != nil { + return "", err + } + + return user.Id, nil +} diff --git a/api/account/google.go b/api/account/google.go new file mode 100644 index 0000000..1cf2c67 --- /dev/null +++ b/api/account/google.go @@ -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 . +*/ + +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, nil +} + +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_URL")}, + }) + + 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() +} diff --git a/api/account/info.go b/api/account/info.go index d76b58f..6802238 100644 --- a/api/account/info.go +++ b/api/account/info.go @@ -23,12 +23,19 @@ import ( type InfoResponse struct { Username string `json:"username"` + DiscordId string `json:"discordId"` + GoogleId string `json:"googleId"` LastSessionSlot int `json:"lastSessionSlot"` } // /account/info - get account info -func Info(username string, uuid []byte) (InfoResponse, error) { +func Info(username string, discordId string, googleId string, uuid []byte) (InfoResponse, error) { slot, _ := db.GetLatestSessionSaveDataSlot(uuid) - - return InfoResponse{Username: username, LastSessionSlot: slot}, nil + response := InfoResponse{ + Username: username, + LastSessionSlot: slot, + DiscordId: discordId, + GoogleId: googleId, + } + return response, nil } diff --git a/api/account/login.go b/api/account/login.go index 5fc3e9c..f9b6034 100644 --- a/api/account/login.go +++ b/api/account/login.go @@ -55,18 +55,25 @@ func Login(username, password string) (LoginResponse, error) { return response, fmt.Errorf("password doesn't match") } - token := make([]byte, TokenSize) - _, err = rand.Read(token) + response.Token, err = GenerateTokenForUsername(username) + if err != nil { return response, fmt.Errorf("failed to generate token: %s", err) } - err = db.AddAccountSession(username, token) + return response, nil +} + +func GenerateTokenForUsername(username string) (string, error) { + token := make([]byte, TokenSize) + _, err := rand.Read(token) if err != nil { - return response, fmt.Errorf("failed to add account session") + return "", fmt.Errorf("failed to generate token: %s", err) } - response.Token = base64.StdEncoding.EncodeToString(token) - - return response, nil + err = db.AddAccountSession(username, token) + if err != nil { + return "", fmt.Errorf("failed to add account session") + } + return base64.StdEncoding.EncodeToString(token), nil } diff --git a/api/common.go b/api/common.go index 96119f3..7e3c2aa 100644 --- a/api/common.go +++ b/api/common.go @@ -63,6 +63,9 @@ func Init(mux *http.ServeMux) error { mux.HandleFunc("GET /daily/rankings", handleDailyRankings) mux.HandleFunc("GET /daily/rankingpagecount", handleDailyRankingPageCount) + // auth + mux.HandleFunc("/auth/{provider}/callback", handleProviderCallback) + mux.HandleFunc("/auth/{provider}/logout", handleProviderLogout) return nil } diff --git a/api/endpoints.go b/api/endpoints.go index 2eccdd9..1c1ed43 100644 --- a/api/endpoints.go +++ b/api/endpoints.go @@ -19,11 +19,15 @@ package api import ( "database/sql" + "encoding/base64" "encoding/json" "errors" "fmt" "net/http" + "os" "strconv" + "strings" + "time" "github.com/pagefaultgames/rogueserver/api/account" "github.com/pagefaultgames/rogueserver/api/daily" @@ -37,7 +41,6 @@ import ( Handler functions are responsible for checking the validity of this data and returning a result or error. Handlers should not return serialized JSON, instead return the struct itself. */ - // account func handleAccountInfo(w http.ResponseWriter, r *http.Request) { @@ -52,13 +55,25 @@ func handleAccountInfo(w http.ResponseWriter, r *http.Request) { httpError(w, r, err, http.StatusInternalServerError) return } - - response, err := account.Info(username, uuid) + discordId, err := db.FetchDiscordIdByUsername(username) + if err != nil { + if !errors.Is(err, sql.ErrNoRows) { + httpError(w, r, err, http.StatusInternalServerError) + return + } + } + googleId, err := db.FetchGoogleIdByUsername(username) + if err != nil { + if !errors.Is(err, sql.ErrNoRows) { + httpError(w, r, err, http.StatusInternalServerError) + return + } + } + response, err := account.Info(username, discordId, googleId, uuid) if err != nil { httpError(w, r, err, http.StatusInternalServerError) return } - writeJSON(w, r, response) } @@ -543,3 +558,107 @@ func handleDailyRankingPageCount(w http.ResponseWriter, r *http.Request) { w.Write([]byte(strconv.Itoa(count))) } + +// redirect link after authorizing application link +func handleProviderCallback(w http.ResponseWriter, r *http.Request) { + provider := r.PathValue("provider") + state := r.URL.Query().Get("state") + gameUrl := os.Getenv("GAME_URL") + 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 + } + + if err != nil { + httpError(w, r, err, http.StatusInternalServerError) + return + } + + if state != "" { + state = strings.Replace(state, " ", "+", -1) + stateByte, err := base64.StdEncoding.DecodeString(state) + if err != nil { + http.Redirect(w, r, gameUrl, http.StatusSeeOther) + return + } + + userName, err := db.FetchUsernameBySessionToken(stateByte) + if err != nil { + http.Redirect(w, r, gameUrl, http.StatusSeeOther) + return + } + + switch provider { + case "discord": + err = db.AddDiscordIdByUsername(externalAuthId, userName) + case "google": + err = db.AddGoogleIdByUsername(externalAuthId, userName) + } + + if err != nil { + http.Redirect(w, r, gameUrl, http.StatusSeeOther) + return + } + + } else { + var userName string + switch provider { + case "discord": + userName, err = db.FetchUsernameByDiscordId(externalAuthId) + case "google": + userName, err = db.FetchUsernameByGoogleId(externalAuthId) + } + if err != nil { + http.Redirect(w, r, gameUrl, http.StatusSeeOther) + return + } + + sessionToken, err := account.GenerateTokenForUsername(userName) + if err != nil { + http.Redirect(w, r, gameUrl, http.StatusSeeOther) + return + } + + http.SetCookie(w, &http.Cookie{ + Name: "pokerogue_sessionId", + Value: sessionToken, + Path: "/", + Secure: true, + SameSite: http.SameSiteStrictMode, + Domain: "beta.pokerogue.net", + Expires: time.Now().Add(time.Hour * 24 * 30 * 3), // 3 months + }) + } + + defer http.Redirect(w, r, gameUrl, http.StatusSeeOther) +} + +func handleProviderLogout(w http.ResponseWriter, r *http.Request) { + uuid, err := uuidFromRequest(r) + if err != nil { + httpError(w, r, err, http.StatusBadRequest) + return + } + + switch r.PathValue("provider") { + case "discord": + err = db.RemoveDiscordIdByUUID(uuid) + case "google": + err = db.RemoveGoogleIdByUUID(uuid) + default: + http.Error(w, "invalid provider", http.StatusBadRequest) + return + } + if err != nil { + httpError(w, r, err, http.StatusInternalServerError) + return + } + w.WriteHeader(http.StatusOK) +} diff --git a/db/account.go b/db/account.go index 6879c50..d463211 100644 --- a/db/account.go +++ b/db/account.go @@ -50,6 +50,82 @@ func AddAccountSession(username string, token []byte) error { return nil } +func AddDiscordIdByUsername(discordId string, username string) error { + _, err := handle.Exec("UPDATE accounts SET discordId = ? WHERE username = ?", discordId, username) + if err != nil { + return err + } + + return nil +} + +func AddGoogleIdByUsername(googleId string, username string) error { + _, err := handle.Exec("UPDATE accounts SET googleId = ? WHERE username = ?", googleId, username) + if err != nil { + return err + } + + return nil +} + +func FetchUsernameByDiscordId(discordId string) (string, error) { + var username string + err := handle.QueryRow("SELECT username FROM accounts WHERE discordId = ?", discordId).Scan(&username) + if err != nil { + return "", err + } + + return username, nil +} + +func FetchUsernameByGoogleId(googleId string) (string, error) { + var username string + err := handle.QueryRow("SELECT username FROM accounts WHERE googleId = ?", googleId).Scan(&username) + if err != nil { + return "", err + } + + return username, nil +} + +func FetchDiscordIdByUsername(username string) (string, error) { + var discordId sql.NullString + err := handle.QueryRow("SELECT discordId FROM accounts WHERE username = ?", username).Scan(&discordId) + if err != nil { + return "", err + } + + if !discordId.Valid { + return "", nil + } + + return discordId.String, nil +} + +func FetchGoogleIdByUsername(username string) (string, error) { + var googleId sql.NullString + err := handle.QueryRow("SELECT googleId FROM accounts WHERE username = ?", username).Scan(&googleId) + if err != nil { + return "", err + } + + if !googleId.Valid { + return "", nil + } + + return googleId.String, nil +} + +func FetchUsernameBySessionToken(token []byte) (string, error) { + var username string + err := handle.QueryRow("SELECT a.username FROM accounts a JOIN sessions s ON a.uuid = s.uuid WHERE s.token = ?", token).Scan(&username) + if err != nil { + return "", err + } + + return username, nil +} + func UpdateAccountPassword(uuid, key, salt []byte) error { _, err := handle.Exec("UPDATE accounts SET (hash, salt) VALUES (?, ?) WHERE uuid = ?", key, salt, uuid) if err != nil { @@ -238,3 +314,21 @@ func FetchUsernameFromUUID(uuid []byte) (string, error) { return username, nil } + +func RemoveDiscordIdByUUID(uuid []byte) error { + _, err := handle.Exec("UPDATE accounts SET discordId = NULL WHERE uuid = ?", uuid) + if err != nil { + return err + } + + return nil +} + +func RemoveGoogleIdByUUID(uuid []byte) error { + _, err := handle.Exec("UPDATE accounts SET googleId = NULL WHERE uuid = ?", uuid) + if err != nil { + return err + } + + return nil +} diff --git a/db/db.go b/db/db.go index a91a94a..885c3b7 100644 --- a/db/db.go +++ b/db/db.go @@ -97,6 +97,12 @@ func setupDb(tx *sql.Tx) error { // MIGRATION 002 `DROP TABLE accountCompensations`, + + // ---------------------------------- + // MIGRATION 003 + + `ALTER TABLE accounts ADD COLUMN IF NOT EXISTS discordId VARCHAR(32) UNIQUE DEFAULT NULL`, + `ALTER TABLE accounts ADD COLUMN IF NOT EXISTS googleId VARCHAR(32) UNIQUE DEFAULT NULL`, } for _, q := range queries { diff --git a/docker-compose.Example.yml b/docker-compose.Example.yml index f1bcb73..3eee682 100644 --- a/docker-compose.Example.yml +++ b/docker-compose.Example.yml @@ -1,6 +1,6 @@ services: server: - command: --debug --dbaddr db --dbuser pokerogue --dbpass pokerogue --dbname pokeroguedb + command: --debug --dbaddr db --dbuser pokerogue --dbpass pokerogue --dbname pokeroguedb --gameurl http://localhost:8000 --callbackurl http://localhost:8001 image: ghcr.io/pagefaultgames/rogueserver:master restart: unless-stopped depends_on: diff --git a/go.mod b/go.mod index eba1467..81a41a6 100644 --- a/go.mod +++ b/go.mod @@ -5,7 +5,9 @@ go 1.22 require ( github.com/go-sql-driver/mysql v1.7.1 github.com/robfig/cron/v3 v3.0.1 - golang.org/x/crypto v0.16.0 + golang.org/x/crypto v0.22.0 ) -require golang.org/x/sys v0.15.0 // indirect +require github.com/golang-jwt/jwt/v5 v5.2.1 + +require golang.org/x/sys v0.19.0 // indirect diff --git a/go.sum b/go.sum index ee42aae..d6d1862 100644 --- a/go.sum +++ b/go.sum @@ -1,8 +1,10 @@ github.com/go-sql-driver/mysql v1.7.1 h1:lUIinVbN1DY0xBg0eMOzmmtGoHwWBbvnWubQUrtU8EI= github.com/go-sql-driver/mysql v1.7.1/go.mod h1:OXbVy3sEdcQ2Doequ6Z5BW6fXNQTmx+9S1MCJN5yJMI= +github.com/golang-jwt/jwt/v5 v5.2.1 h1:OuVbFODueb089Lh128TAcimifWaLhJwVflnrgM17wHk= +github.com/golang-jwt/jwt/v5 v5.2.1/go.mod h1:pqrtFR0X4osieyHYxtmOUWsAWrfe1Q5UVIyoH402zdk= github.com/robfig/cron/v3 v3.0.1 h1:WdRxkvbJztn8LMz/QEvLN5sBU+xKpSqwwUO1Pjr4qDs= github.com/robfig/cron/v3 v3.0.1/go.mod h1:eQICP3HwyT7UooqI/z+Ov+PtYAWygg1TEWWzGIFLtro= -golang.org/x/crypto v0.16.0 h1:mMMrFzRSCF0GvB7Ne27XVtVAaXLrPmgPC7/v0tkwHaY= -golang.org/x/crypto v0.16.0/go.mod h1:gCAAfMLgwOJRpTjQ2zCCt2OcSfYMTeZVSRtQlPC7Nq4= -golang.org/x/sys v0.15.0 h1:h48lPFYpsTvQJZF4EKyI4aLHaev3CxivZmv7yZig9pc= -golang.org/x/sys v0.15.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= +golang.org/x/crypto v0.22.0 h1:g1v0xeRhjcugydODzvb3mEM9SQ0HGp9s/nh3COQ/C30= +golang.org/x/crypto v0.22.0/go.mod h1:vr6Su+7cTlO45qkww3VDJlzDn0ctJvRgYbC2NvXHt+M= +golang.org/x/sys v0.19.0 h1:q5f1RH2jigJ1MoAWp2KTp3gm5zAGFUTarQZ5U386+4o= +golang.org/x/sys v0.19.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= diff --git a/rogueserver.go b/rogueserver.go index 4b98dff..4242329 100644 --- a/rogueserver.go +++ b/rogueserver.go @@ -44,8 +44,27 @@ func main() { dbaddr := flag.String("dbaddr", "localhost", "database address") dbname := flag.String("dbname", "pokeroguedb", "database name") + discordclientid := flag.String("discordclientid", "dcid", "Discord Oauth2 Client ID") + discordsecretid := flag.String("discordsecretid", "dsid", "Discord Oauth2 Secret ID") + + googleclientid := flag.String("googleclientid", "gcid", "Google Oauth2 Client ID") + googlesecretid := flag.String("googlesecretid", "gsid", "Google Oauth2 Secret ID") + callbackurl := flag.String("callbackurl", "http://localhost:8001/", "Callback URL for Oauth2 Client") + + gameurl := flag.String("gameurl", "https://pokerogue.net", "URL for game server") + flag.Parse() + // set discord client id as env variable + os.Setenv("DISCORD_CLIENT_ID", *discordclientid) + os.Setenv("DISCORD_CLIENT_SECRET", *discordsecretid) + os.Setenv("DISCORD_CALLBACK_URL", *callbackurl+"/auth/discord/callback") + + os.Setenv("GOOGLE_CLIENT_ID", *googleclientid) + os.Setenv("GOOGLE_CLIENT_SECRET", *googlesecretid) + os.Setenv("GOOGLE_CALLBACK_URL", *callbackurl+"/auth/google/callback") + os.Setenv("GAME_URL", *gameurl) + // register gob types gob.Register([]interface{}{}) gob.Register(map[string]interface{}{}) @@ -70,7 +89,7 @@ func main() { } // start web server - handler := prodHandler(mux) + handler := prodHandler(mux, gameurl) if *debug { handler = debugHandler(mux) } @@ -105,11 +124,11 @@ func createListener(proto, addr string) (net.Listener, error) { return listener, nil } -func prodHandler(router *http.ServeMux) http.Handler { +func prodHandler(router *http.ServeMux, clienturl *string) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Access-Control-Allow-Headers", "Authorization, Content-Type") w.Header().Set("Access-Control-Allow-Methods", "OPTIONS, GET, POST") - w.Header().Set("Access-Control-Allow-Origin", "https://pokerogue.net") + w.Header().Set("Access-Control-Allow-Origin", *clienturl) if r.Method == "OPTIONS" { w.WriteHeader(http.StatusOK)