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 <matthew.olker@gmail.com>
pull/47/merge
Frederico Santos 5 months ago committed by GitHub
parent 4cac6b6ce8
commit fa57f5997f
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

@ -23,6 +23,7 @@ FROM scratch
WORKDIR /app WORKDIR /app
COPY --from=builder /src/rogueserver . COPY --from=builder /src/rogueserver .
COPY --from=builder /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/
EXPOSE 8001 EXPOSE 8001

@ -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 <http://www.gnu.org/licenses/>.
*/
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
}

@ -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, 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()
}

@ -23,12 +23,19 @@ import (
type InfoResponse struct { type InfoResponse struct {
Username string `json:"username"` Username string `json:"username"`
DiscordId string `json:"discordId"`
GoogleId string `json:"googleId"`
LastSessionSlot int `json:"lastSessionSlot"` LastSessionSlot int `json:"lastSessionSlot"`
} }
// /account/info - get account info // /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) slot, _ := db.GetLatestSessionSaveDataSlot(uuid)
response := InfoResponse{
return InfoResponse{Username: username, LastSessionSlot: slot}, nil Username: username,
LastSessionSlot: slot,
DiscordId: discordId,
GoogleId: googleId,
}
return response, nil
} }

@ -55,18 +55,25 @@ func Login(username, password string) (LoginResponse, error) {
return response, fmt.Errorf("password doesn't match") return response, fmt.Errorf("password doesn't match")
} }
token := make([]byte, TokenSize) response.Token, err = GenerateTokenForUsername(username)
_, err = rand.Read(token)
if err != nil { if err != nil {
return response, fmt.Errorf("failed to generate token: %s", err) 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 { 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) err = db.AddAccountSession(username, token)
if err != nil {
return response, nil return "", fmt.Errorf("failed to add account session")
}
return base64.StdEncoding.EncodeToString(token), nil
} }

@ -63,6 +63,9 @@ func Init(mux *http.ServeMux) error {
mux.HandleFunc("GET /daily/rankings", handleDailyRankings) mux.HandleFunc("GET /daily/rankings", handleDailyRankings)
mux.HandleFunc("GET /daily/rankingpagecount", handleDailyRankingPageCount) mux.HandleFunc("GET /daily/rankingpagecount", handleDailyRankingPageCount)
// auth
mux.HandleFunc("/auth/{provider}/callback", handleProviderCallback)
mux.HandleFunc("/auth/{provider}/logout", handleProviderLogout)
return nil return nil
} }

@ -19,11 +19,15 @@ package api
import ( import (
"database/sql" "database/sql"
"encoding/base64"
"encoding/json" "encoding/json"
"errors" "errors"
"fmt" "fmt"
"net/http" "net/http"
"os"
"strconv" "strconv"
"strings"
"time"
"github.com/pagefaultgames/rogueserver/api/account" "github.com/pagefaultgames/rogueserver/api/account"
"github.com/pagefaultgames/rogueserver/api/daily" "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. 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. Handlers should not return serialized JSON, instead return the struct itself.
*/ */
// account // account
func handleAccountInfo(w http.ResponseWriter, r *http.Request) { 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) httpError(w, r, err, http.StatusInternalServerError)
return return
} }
discordId, err := db.FetchDiscordIdByUsername(username)
response, err := account.Info(username, uuid) 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 { if err != nil {
httpError(w, r, err, http.StatusInternalServerError) httpError(w, r, err, http.StatusInternalServerError)
return return
} }
writeJSON(w, r, response) writeJSON(w, r, response)
} }
@ -543,3 +558,107 @@ func handleDailyRankingPageCount(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(strconv.Itoa(count))) 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)
}

@ -50,6 +50,82 @@ func AddAccountSession(username string, token []byte) error {
return nil 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 { func UpdateAccountPassword(uuid, key, salt []byte) error {
_, err := handle.Exec("UPDATE accounts SET (hash, salt) VALUES (?, ?) WHERE uuid = ?", key, salt, uuid) _, err := handle.Exec("UPDATE accounts SET (hash, salt) VALUES (?, ?) WHERE uuid = ?", key, salt, uuid)
if err != nil { if err != nil {
@ -238,3 +314,21 @@ func FetchUsernameFromUUID(uuid []byte) (string, error) {
return username, nil 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
}

@ -97,6 +97,12 @@ func setupDb(tx *sql.Tx) error {
// MIGRATION 002 // MIGRATION 002
`DROP TABLE accountCompensations`, `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 { for _, q := range queries {

@ -1,6 +1,6 @@
services: services:
server: 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 image: ghcr.io/pagefaultgames/rogueserver:master
restart: unless-stopped restart: unless-stopped
depends_on: depends_on:

@ -5,7 +5,9 @@ go 1.22
require ( require (
github.com/go-sql-driver/mysql v1.7.1 github.com/go-sql-driver/mysql v1.7.1
github.com/robfig/cron/v3 v3.0.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

@ -1,8 +1,10 @@
github.com/go-sql-driver/mysql v1.7.1 h1:lUIinVbN1DY0xBg0eMOzmmtGoHwWBbvnWubQUrtU8EI= 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/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 h1:WdRxkvbJztn8LMz/QEvLN5sBU+xKpSqwwUO1Pjr4qDs=
github.com/robfig/cron/v3 v3.0.1/go.mod h1:eQICP3HwyT7UooqI/z+Ov+PtYAWygg1TEWWzGIFLtro= 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.22.0 h1:g1v0xeRhjcugydODzvb3mEM9SQ0HGp9s/nh3COQ/C30=
golang.org/x/crypto v0.16.0/go.mod h1:gCAAfMLgwOJRpTjQ2zCCt2OcSfYMTeZVSRtQlPC7Nq4= golang.org/x/crypto v0.22.0/go.mod h1:vr6Su+7cTlO45qkww3VDJlzDn0ctJvRgYbC2NvXHt+M=
golang.org/x/sys v0.15.0 h1:h48lPFYpsTvQJZF4EKyI4aLHaev3CxivZmv7yZig9pc= golang.org/x/sys v0.19.0 h1:q5f1RH2jigJ1MoAWp2KTp3gm5zAGFUTarQZ5U386+4o=
golang.org/x/sys v0.15.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= golang.org/x/sys v0.19.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=

@ -44,8 +44,27 @@ func main() {
dbaddr := flag.String("dbaddr", "localhost", "database address") dbaddr := flag.String("dbaddr", "localhost", "database address")
dbname := flag.String("dbname", "pokeroguedb", "database name") 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() 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 // register gob types
gob.Register([]interface{}{}) gob.Register([]interface{}{})
gob.Register(map[string]interface{}{}) gob.Register(map[string]interface{}{})
@ -70,7 +89,7 @@ func main() {
} }
// start web server // start web server
handler := prodHandler(mux) handler := prodHandler(mux, gameurl)
if *debug { if *debug {
handler = debugHandler(mux) handler = debugHandler(mux)
} }
@ -105,11 +124,11 @@ func createListener(proto, addr string) (net.Listener, error) {
return listener, nil 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) { 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-Headers", "Authorization, Content-Type")
w.Header().Set("Access-Control-Allow-Methods", "OPTIONS, GET, POST") 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" { if r.Method == "OPTIONS" {
w.WriteHeader(http.StatusOK) w.WriteHeader(http.StatusOK)

Loading…
Cancel
Save