From 2aabad6f077faff558632b840f6bb53a296ef420 Mon Sep 17 00:00:00 2001 From: Achim Rohn Date: Mon, 6 Apr 2026 16:10:43 +0200 Subject: [PATCH] Save credentials for google in the database --- authentication/google/http/google_auth.go | 11 ++++++++--- starter/google/database.go | 20 ++++++++++++++++++++ 2 files changed, 28 insertions(+), 3 deletions(-) diff --git a/authentication/google/http/google_auth.go b/authentication/google/http/google_auth.go index 48a3683..6608a80 100644 --- a/authentication/google/http/google_auth.go +++ b/authentication/google/http/google_auth.go @@ -5,12 +5,13 @@ import ( "crypto/rand" "encoding/base64" "encoding/json" - . "git.gorlug.de/code/ersteller" - "git.gorlug.de/code/ersteller/authentication" "io/ioutil" "net/http" "time" + . "git.gorlug.de/code/ersteller" + "git.gorlug.de/code/ersteller/authentication" + "github.com/gorilla/sessions" "golang.org/x/oauth2" @@ -39,6 +40,7 @@ type GoogleAuth struct { type Database interface { GetUserIdByEmail(ctx context.Context, email string) (int, error) CreateUser(ctx context.Context, email string) (int, error) + SaveCredentials(ctx context.Context, userId int, token *oauth2.Token) error } type Environment struct { @@ -180,7 +182,10 @@ func (g *GoogleAuth) getUserDataFromGoogle(code string) (GoogleUserData, error) func (g *GoogleAuth) SaveCredentials(userId int, token *oauth2.Token) error { Debug("saving google credentials for user ", userId) - // For now, we'll just log this - in a real implementation you'd save to database + err := g.db.SaveCredentials(context.Background(), userId, token) + if err != nil { + return err + } Debug("saved credentials for user", userId) return nil } diff --git a/starter/google/database.go b/starter/google/database.go index 4c5b1f3..aae2089 100644 --- a/starter/google/database.go +++ b/starter/google/database.go @@ -2,10 +2,14 @@ package google import ( "context" + "git.gorlug.de/code/ersteller" google_http "git.gorlug.de/code/ersteller/authentication/google/http" "git.gorlug.de/code/ersteller/starter/ent" + "git.gorlug.de/code/ersteller/starter/ent/googleauth" + "git.gorlug.de/code/ersteller/starter/ent/schema" "git.gorlug.de/code/ersteller/starter/ent/user" + "golang.org/x/oauth2" ) type Database struct { @@ -30,3 +34,19 @@ func (d *Database) CreateUser(ctx context.Context, email string) (int, error) { } return newUser.ID, nil } + +func (d *Database) SaveCredentials(ctx context.Context, userId int, token *oauth2.Token) error { + existing, err := d.db.GoogleAuth.Query().Where(googleauth.HasUserWith(user.ID(userId))).Only(ctx) + if err == nil { + _, err = existing.Update().SetCredentials(schema.Credentials{Token: *token}).Save(ctx) + return err + } + if !ent.IsNotFound(err) { + return err + } + _, err = d.db.GoogleAuth.Create(). + SetUserID(userId). + SetCredentials(schema.Credentials{Token: *token}). + Save(ctx) + return err +}