Skip to content

Commit

Permalink
chore: Update dependencies, add Discord OAuth2 authentication endpoin…
Browse files Browse the repository at this point in the history
…t, and clean up code
  • Loading branch information
f-fsantos committed Jun 1, 2024
1 parent 704149a commit e19a67b
Show file tree
Hide file tree
Showing 11 changed files with 197 additions and 104 deletions.
1 change: 1 addition & 0 deletions Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
85 changes: 85 additions & 0 deletions api/account/discord.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
/*
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"
"log"
"net/http"
"net/url"
"os"
)

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_URI")},
"scope": {"identify"},
})

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"`
}

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)

if access_token == "" {
err = errors.New("access token is empty")
return "", err
}

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)

return user.Id, nil
}
21 changes: 14 additions & 7 deletions api/account/login.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
2 changes: 0 additions & 2 deletions api/common.go
Original file line number Diff line number Diff line change
Expand Up @@ -70,9 +70,7 @@ func Init(mux *http.ServeMux) error {
mux.HandleFunc("GET /daily/rankingpagecount", handleDailyRankingPageCount)

// auth
mux.HandleFunc("/auth/{provider}", handleProviderAuth)
mux.HandleFunc("/auth/{provider}/callback", handleProviderCallback)
mux.HandleFunc("/auth/{provider}/link", handleProviderLink)
mux.HandleFunc("/auth/{provider}/logout", handleProviderLogout)
return nil
}
Expand Down
95 changes: 52 additions & 43 deletions api/endpoints.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,14 +19,15 @@ package api

import (
"database/sql"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"log"
"net/http"
"os"
"strconv"
"strings"

"github.com/markbates/goth/gothic"
"github.com/pagefaultgames/rogueserver/api/account"
"github.com/pagefaultgames/rogueserver/api/daily"
"github.com/pagefaultgames/rogueserver/api/savedata"
Expand Down Expand Up @@ -832,60 +833,68 @@ func handleDailyRankingPageCount(w http.ResponseWriter, r *http.Request) {
_, _ = w.Write([]byte(strconv.Itoa(count)))
}

func handleProviderAuth(w http.ResponseWriter, r *http.Request) {
defer http.Redirect(w, r, "https://discord.com/oauth2/authorize?client_id=1246478260985139362&response_type=code&redirect_uri=http%3A%2F%2Flocalhost%3A8001%2Fauth%2Fdiscord%2Fcallback&scope=identify", http.StatusSeeOther)
}

// redirect link after authorizing application link
func handleProviderCallback(w http.ResponseWriter, r *http.Request) {
gothic.GetProviderName = func(r *http.Request) (string, error) { return r.PathValue("provider"), nil }

// called again with code after authorization
code := r.URL.Query().Get("code")
if code != "" {
userId, err := db.FetchDiscordIdByUsername(user)
if err != nil {
log.Println("error fetching Discord ID by username")
return
}
log.Println("user", userId)
defer http.Redirect(w, r, "http://localhost:8000", http.StatusSeeOther)
state := r.URL.Query().Get("state")
gameUrl := os.Getenv("GAME_URL")
if code == "" {
defer http.Redirect(w, r, gameUrl, http.StatusSeeOther)
return
}

gothUser, err := gothic.CompleteUserAuth(w, r)
var userName string
user, err := account.RetrieveDiscordId(code)
if err != nil {
log.Println("callback err", w, r)
defer http.Redirect(w, r, gameUrl, http.StatusSeeOther)
return
} else {
log.Println("gothUser:", gothUser)
// err := db.AddDiscordAuthByUsername(gothUser.UserID, user)
// if err != nil {
// log.Println("error adding Discord Auth to database")
// return
// }
}
log.Println("user", gothUser.UserID)
}

func handleProviderLink(w http.ResponseWriter, r *http.Request) {
gothic.GetProviderName = func(r *http.Request) (string, error) { return r.PathValue("provider"), nil }
username := r.URL.Query().Get("username")
// username recorded prior to authorization
if username != "" {
user = username
}
// try to get the user without re-authenticating
if gothUser, err := gothic.CompleteUserAuth(w, r); err == nil {
log.Print("gothUser:", gothUser.Name)

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)
if err != nil {
defer http.Redirect(w, r, gameUrl, http.StatusSeeOther)
return
}
err = db.AddDiscordAuthByUsername(user, userName)
if err != nil {
defer http.Redirect(w, r, gameUrl, http.StatusSeeOther)
return
}
} else {
gothic.BeginAuthHandler(w, r)
userName, err = db.FetchUsernameByDiscordId(user)
if err != nil {
defer http.Redirect(w, r, gameUrl, http.StatusSeeOther)
return
}

cookieToken, 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)
}
defer http.Redirect(w, r, gameUrl, http.StatusSeeOther)

}

func handleProviderLogout(w http.ResponseWriter, r *http.Request) {
gothic.GetProviderName = func(r *http.Request) (string, error) { return r.PathValue("provider"), nil }
gothic.Logout(w, r)
w.Header().Set("Location", "/")
w.WriteHeader(http.StatusTemporaryRedirect)
uuid, err := uuidFromRequest(r)
if err != nil {
httpError(w, r, err, http.StatusBadRequest)
return
}

db.RemoveDiscordAuthByUUID(uuid)
w.WriteHeader(http.StatusOK)
}
31 changes: 25 additions & 6 deletions db/account.go
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ func AddAccountSession(username string, token []byte) error {
return nil
}

func AddDiscordAuthByUsername(discordId []byte, username string) error {
func AddDiscordAuthByUsername(discordId string, username string) error {
_, err := handle.Exec("UPDATE accounts SET discordId = ? WHERE username = ?", discordId, username)
if err != nil {
return err
Expand All @@ -59,14 +59,24 @@ func AddDiscordAuthByUsername(discordId []byte, username string) error {
return nil
}

func FetchDiscordIdByUsername(username string) ([]byte, error) {
var discordId []byte
err := handle.QueryRow("SELECT discordId FROM accounts WHERE username = ?", username).Scan(&discordId)
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 nil, err
return "", err
}

return discordId, nil
return username, 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 {
Expand Down Expand Up @@ -285,6 +295,15 @@ func RemoveSessionFromToken(token []byte) error {
return nil
}

func RemoveDiscordAuthByUUID(uuid []byte) error {
_, err := handle.Exec("UPDATE accounts SET discordId = NULL WHERE uuid = ?", uuid)
if err != nil {
return err
}

return nil
}

func FetchUsernameFromUUID(uuid []byte) (string, error) {
var username string
err := handle.QueryRow("SELECT username FROM accounts WHERE uuid = ?", uuid).Scan(&username)
Expand Down
5 changes: 5 additions & 0 deletions db/db.go
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,11 @@ func setupDb(tx *sql.Tx) error {

`ALTER TABLE sessions DROP COLUMN IF EXISTS active`,
`CREATE TABLE IF NOT EXISTS activeClientSessions (uuid BINARY(16) NOT NULL PRIMARY KEY, clientSessionId VARCHAR(32) NOT NULL, FOREIGN KEY (uuid) REFERENCES accounts (uuid) ON DELETE CASCADE ON UPDATE CASCADE)`,

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

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
command: --debug --dbaddr db --dbuser pokerogue --dbpass pokerogue --dbname pokeroguedb --gameurl http://localhost:8000 --discordcallbackuri http://localhost:8001
image: ghcr.io/pagefaultgames/rogueserver:master
restart: unless-stopped
depends_on:
Expand Down
5 changes: 1 addition & 4 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,10 @@ require (
)

require (
github.com/golang/protobuf v1.5.3 // indirect
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.17.0 // indirect
google.golang.org/appengine v1.6.8 // indirect
google.golang.org/protobuf v1.32.0 // indirect
golang.org/x/oauth2 v0.20.0 // indirect
)

require (
Expand Down
Loading

0 comments on commit e19a67b

Please sign in to comment.