Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -11,3 +11,7 @@ JWT_SECRET=dev-only-change-me
JWT_ACCESS_EXPIRE=1h
JWT_REFRESH_EXPIRE=720h
TMDB_API_TOKEN=
FRONTEND_ORIGIN=http://localhost:5173
GOOGLE_CLIENT_ID=
GOOGLE_CLIENT_SECRET=
GOOGLE_REDIRECT_URL=http://localhost:8080/auth/google/callback
7 changes: 7 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ A collaborative movie list web app for couples and friends to track movies they
- **Backend**: Go 1.24 + Gin framework
- **Database**: MySQL + GORM ORM
- **Authentication**: JWT with refresh token rotation
- **OAuth**: Google OAuth web-server flow
- **Drag & Drop**: @dnd-kit library
- **External APIs**: TMDB (movies, TV shows, watch providers)

Expand Down Expand Up @@ -53,6 +54,9 @@ Services:
The compose setup mounts `./backend` and `./frontend` into their containers, so local source edits are picked up by the development servers. The backend runs `go run .`; restart the backend container after Go code changes if needed. Frontend changes are handled by Vite HMR.

Set `TMDB_API_TOKEN` in `.env` to enable movie search, watch providers, and recommendations.
To enable Google sign-in locally, create a Google OAuth web client with redirect URI
`http://localhost:8080/auth/google/callback`, then set `GOOGLE_CLIENT_ID` and
`GOOGLE_CLIENT_SECRET` in `.env`.

Useful commands:

Expand All @@ -78,6 +82,9 @@ DB_DSN=user:password@tcp(localhost:3306)/database_name
JWT_SECRET=your_secret_key
TMDB_API_TOKEN=your_tmdb_api_key
FRONTEND_ORIGIN=http://localhost:5173
GOOGLE_CLIENT_ID=your_google_client_id
GOOGLE_CLIENT_SECRET=your_google_client_secret
GOOGLE_REDIRECT_URL=http://localhost:8080/auth/google/callback
PORT=8080
```

Expand Down
191 changes: 191 additions & 0 deletions backend/controllers/auth_controller.go
Original file line number Diff line number Diff line change
@@ -1,14 +1,24 @@
package controllers

import (
"context"
"crypto/rand"
"encoding/hex"
"encoding/json"
"errors"
"net/http"
"net/url"
"os"
"strconv"
"strings"
"time"

"github.com/8bury/list2gether/middleware"
"github.com/8bury/list2gether/services"
"github.com/gin-gonic/gin"
"github.com/golang-jwt/jwt/v5"
"golang.org/x/oauth2"
"golang.org/x/oauth2/google"
)

type AuthController struct {
Expand All @@ -21,6 +31,8 @@ func NewAuthController(router *gin.Engine, service services.AuthService, authMid
group := router.Group("/auth")
group.POST("/register", c.register)
group.POST("/login", c.login)
group.GET("/google/login", c.googleLogin)
group.GET("/google/callback", c.googleCallback)
group.POST("/refresh", c.refresh)
group.POST("/logout", c.logout)

Expand All @@ -29,6 +41,14 @@ func NewAuthController(router *gin.Engine, service services.AuthService, authMid
return c
}

type googleUserInfo struct {
Sub string `json:"sub"`
Email string `json:"email"`
EmailVerified bool `json:"email_verified"`
Name string `json:"name"`
Picture string `json:"picture"`
}

type registerRequest struct {
Username string `json:"username"`
Email string `json:"email"`
Expand Down Expand Up @@ -61,6 +81,16 @@ func (a *AuthController) register(c *gin.Context) {
}
user, err := a.service.Register(req.Username, req.Email, req.Password)
if err != nil {
if errors.Is(err, services.ErrGoogleLoginRequired) {
c.Header("Cache-Control", "no-store")
c.JSON(http.StatusConflict, gin.H{
"error": err.Error(),
"code": "GOOGLE_LOGIN_REQUIRED",
"details": []string{},
"timestamp": time.Now().UTC().Format(time.RFC3339),
})
return
}
respondValidationError(c, []string{err.Error()})
return
}
Expand Down Expand Up @@ -99,6 +129,102 @@ func (a *AuthController) login(c *gin.Context) {
})
}

func (a *AuthController) googleLogin(c *gin.Context) {
oauthConfig, err := googleOAuthConfig()
if err != nil {
respondOAuthError(c, http.StatusServiceUnavailable, "Google login is not configured")
return
}
state, err := generateOAuthState()
if err != nil {
respondOAuthError(c, http.StatusInternalServerError, "Failed to start Google login")
return
}
http.SetCookie(c.Writer, oauthStateCookie(c, state, 600))
c.Redirect(http.StatusFound, oauthConfig.AuthCodeURL(state, oauth2.AccessTypeOffline))
}

func (a *AuthController) googleCallback(c *gin.Context) {
frontendOrigin := getFrontendOrigin()
callbackURL := frontendOrigin + "/oauth/google/callback"
clearOAuthStateCookie(c)

expectedState, err := c.Cookie("oauth_state")
if err != nil || expectedState == "" || c.Query("state") == "" || c.Query("state") != expectedState {
c.Redirect(http.StatusFound, callbackURL+"#error="+url.QueryEscape("Invalid Google login state"))
return
}
if oauthErr := c.Query("error"); oauthErr != "" {
c.Redirect(http.StatusFound, callbackURL+"#error="+url.QueryEscape(oauthErr))
return
}
code := c.Query("code")
if code == "" {
c.Redirect(http.StatusFound, callbackURL+"#error="+url.QueryEscape("Missing Google authorization code"))
return
}

oauthConfig, err := googleOAuthConfig()
if err != nil {
c.Redirect(http.StatusFound, callbackURL+"#error="+url.QueryEscape("Google login is not configured"))
return
}
ctx, cancel := context.WithTimeout(c.Request.Context(), 10*time.Second)
defer cancel()
token, err := oauthConfig.Exchange(ctx, code)
if err != nil {
c.Redirect(http.StatusFound, callbackURL+"#error="+url.QueryEscape("Could not exchange Google authorization code"))
return
}

client := oauthConfig.Client(ctx, token)
req, err := http.NewRequestWithContext(ctx, http.MethodGet, "https://openidconnect.googleapis.com/v1/userinfo", nil)
if err != nil {
c.Redirect(http.StatusFound, callbackURL+"#error="+url.QueryEscape("Could not fetch Google profile"))
return
}
res, err := client.Do(req)
if err != nil || res == nil {
c.Redirect(http.StatusFound, callbackURL+"#error="+url.QueryEscape("Could not fetch Google profile"))
return
}
defer res.Body.Close()
if res.StatusCode < 200 || res.StatusCode >= 300 {
c.Redirect(http.StatusFound, callbackURL+"#error="+url.QueryEscape("Could not fetch Google profile"))
return
}
var profile googleUserInfo
if err := json.NewDecoder(res.Body).Decode(&profile); err != nil {
c.Redirect(http.StatusFound, callbackURL+"#error="+url.QueryEscape("Could not read Google profile"))
return
}

user, accessToken, refreshToken, expiresIn, accessExp, err := a.service.LoginWithGoogle(services.GoogleProfile{
Subject: profile.Sub,
Email: profile.Email,
EmailVerified: profile.EmailVerified,
Name: profile.Name,
Picture: profile.Picture,
})
if err != nil {
c.Redirect(http.StatusFound, callbackURL+"#error="+url.QueryEscape(err.Error()))
return
}

userJSON, err := json.Marshal(user)
if err != nil {
c.Redirect(http.StatusFound, callbackURL+"#error="+url.QueryEscape("Could not complete Google login"))
return
}
values := url.Values{}
values.Set("access_token", accessToken)
values.Set("refresh_token", refreshToken)
values.Set("expires_in", strconv.FormatInt(expiresIn, 10))
values.Set("access_token_expires_at", strconv.FormatInt(accessExp, 10))
values.Set("user", string(userJSON))
c.Redirect(http.StatusFound, callbackURL+"#"+values.Encode())
}

func (a *AuthController) refresh(c *gin.Context) {
var req refreshRequest
if err := c.ShouldBindJSON(&req); err != nil || req.RefreshToken == "" {
Expand Down Expand Up @@ -215,3 +341,68 @@ func respondTokenInvalid(c *gin.Context) {
"timestamp": time.Now().UTC().Format(time.RFC3339),
})
}

func googleOAuthConfig() (*oauth2.Config, error) {
clientID := strings.TrimSpace(os.Getenv("GOOGLE_CLIENT_ID"))
clientSecret := strings.TrimSpace(os.Getenv("GOOGLE_CLIENT_SECRET"))
redirectURL := strings.TrimSpace(os.Getenv("GOOGLE_REDIRECT_URL"))
if redirectURL == "" {
redirectURL = "http://localhost:8080/auth/google/callback"
}
if clientID == "" || clientSecret == "" {
return nil, os.ErrInvalid
}
return &oauth2.Config{
ClientID: clientID,
ClientSecret: clientSecret,
RedirectURL: redirectURL,
Scopes: []string{"openid", "email", "profile"},
Endpoint: google.Endpoint,
}, nil
}

func generateOAuthState() (string, error) {
buf := make([]byte, 32)
if _, err := rand.Read(buf); err != nil {
return "", err
}
return hex.EncodeToString(buf), nil
}

func oauthStateCookie(c *gin.Context, value string, maxAge int) *http.Cookie {
secure := false
if redirectURL := strings.TrimSpace(os.Getenv("GOOGLE_REDIRECT_URL")); strings.HasPrefix(redirectURL, "https://") {
secure = true
}
return &http.Cookie{
Name: "oauth_state",
Value: value,
Path: "/auth/google",
MaxAge: maxAge,
HttpOnly: true,
Secure: secure,
SameSite: http.SameSiteLaxMode,
}
}

func clearOAuthStateCookie(c *gin.Context) {
http.SetCookie(c.Writer, oauthStateCookie(c, "", -1))
}

func getFrontendOrigin() string {
origin := strings.TrimRight(strings.TrimSpace(os.Getenv("FRONTEND_ORIGIN")), "/")
if origin == "" {
return "http://localhost:5173"
}
return origin
}

func respondOAuthError(c *gin.Context, status int, message string) {
c.Header("Cache-Control", "no-store")
c.JSON(status, gin.H{
"error": message,
"code": "OAUTH_ERROR",
"details": []string{},
"timestamp": time.Now().UTC().Format(time.RFC3339),
})
}
9 changes: 9 additions & 0 deletions backend/daos/mocks/user_dao_mock.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,15 @@ func (m *MockUserDAO) FindByEmail(email string) (*models.User, error) {
return args.Get(0).(*models.User), args.Error(1)
}

// FindByGoogleID mocks the FindByGoogleID method.
func (m *MockUserDAO) FindByGoogleID(googleID string) (*models.User, error) {
args := m.Called(googleID)
if args.Get(0) == nil {
return nil, args.Error(1)
}
return args.Get(0).(*models.User), args.Error(1)
}

// FindByUsername mocks the FindByUsername method.
func (m *MockUserDAO) FindByUsername(username string) (*models.User, error) {
args := m.Called(username)
Expand Down
10 changes: 10 additions & 0 deletions backend/daos/user_dao.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import (
type UserDAO interface {
Create(user *models.User) error
FindByEmail(email string) (*models.User, error)
FindByGoogleID(googleID string) (*models.User, error)
FindByUsername(username string) (*models.User, error)
FindByID(id int64) (*models.User, error)
Update(user *models.User) error
Expand All @@ -36,6 +37,15 @@ func (d *userDAO) FindByEmail(email string) (*models.User, error) {
return &user, err
}

func (d *userDAO) FindByGoogleID(googleID string) (*models.User, error) {
var user models.User
err := d.db.Where("google_id = ?", googleID).First(&user).Error
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, gorm.ErrRecordNotFound
}
return &user, err
}

func (d *userDAO) FindByUsername(username string) (*models.User, error) {
var user models.User
err := d.db.Where("username = ?", username).First(&user).Error
Expand Down
7 changes: 6 additions & 1 deletion backend/go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,12 @@ go 1.24.11

require github.com/gin-gonic/gin v1.10.1

require github.com/golang-jwt/jwt/v5 v5.2.2
require (
github.com/golang-jwt/jwt/v5 v5.2.2
golang.org/x/oauth2 v0.30.0
)

require cloud.google.com/go/compute/metadata v0.3.0 // indirect

require (
github.com/davecgh/go-spew v1.1.1 // indirect
Expand Down
4 changes: 4 additions & 0 deletions backend/go.sum
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
cloud.google.com/go/compute/metadata v0.3.0 h1:Tz+eQXMEqDIKRsmY3cHTL6FVaynIjX2QxYC4trgAKZc=
cloud.google.com/go/compute/metadata v0.3.0/go.mod h1:zFmK7XCadkQkj6TtorcaGlCW1hT1fIilQDwofLpJ20k=
filippo.io/edwards25519 v1.1.0 h1:FNf4tywRC1HmFuKW5xopWpigGjJKiJSV0Cqo0cJWDaA=
filippo.io/edwards25519 v1.1.0/go.mod h1:BxyFTGdWcka3PhytdK4V28tE5sGfRvvvRV7EaN4VDT4=
github.com/bytedance/sonic v1.13.2 h1:8/H1FempDZqC4VqjptGo14QQlJx8VdZJegxs6wwfqpQ=
Expand Down Expand Up @@ -92,6 +94,8 @@ golang.org/x/crypto v0.36.0 h1:AnAEvhDddvBdpY+uR+MyHmuZzzNqXSe/GvuDeob5L34=
golang.org/x/crypto v0.36.0/go.mod h1:Y4J0ReaxCR1IMaabaSMugxJES1EpwhBHhv2bDHklZvc=
golang.org/x/net v0.38.0 h1:vRMAPTMaeGqVhG5QyLJHqNDwecKTomGeqbnfZyKlBI8=
golang.org/x/net v0.38.0/go.mod h1:ivrbrMbzFq5J41QOQh0siUuly180yBYtLp+CKbEaFx8=
golang.org/x/oauth2 v0.30.0 h1:dnDm7JmhM45NNpd8FDDeLhK6FwqbOf4MLCM9zb1BOHI=
golang.org/x/oauth2 v0.30.0/go.mod h1:B++QgG3ZKulg6sRPGD/mqlHQs5rB3Ml9erfeDY7xKlU=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.31.0 h1:ioabZlmFYtWhL+TRYpcnNlLwhyxaM9kWTDEmfnprqik=
golang.org/x/sys v0.31.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=
Expand Down
1 change: 1 addition & 0 deletions backend/models/user.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ type User struct {
Username string `gorm:"uniqueIndex;not null;size:50;column:username" json:"username"`
Email string `gorm:"uniqueIndex;not null;size:255;column:email" json:"email"`
Password string `gorm:"not null;type:text;column:password" json:"-"`
GoogleID *string `gorm:"uniqueIndex;size:255;column:google_id" json:"-"`
AvatarURL *string `gorm:"size:500;column:avatar_url" json:"avatar_url,omitempty"`
CreatedAt time.Time `gorm:"autoCreateTime;column:created_at" json:"created_at"`
UpdatedAt time.Time `gorm:"autoUpdateTime;column:updated_at" json:"updated_at"`
Expand Down
Loading
Loading