Save credentials for google in the database

This commit is contained in:
Achim Rohn
2026-04-06 16:10:43 +02:00
parent d3c1cad6f2
commit 2aabad6f07
2 changed files with 28 additions and 3 deletions
+8 -3
View File
@@ -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
}
+20
View File
@@ -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
}