Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: spotify oauth #18

Merged
merged 14 commits into from
Sep 20, 2024
Merged
Show file tree
Hide file tree
Changes from 9 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
9 changes: 2 additions & 7 deletions backend/cmd/server/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import (

"platnm/internal/config"
"platnm/internal/service"
"platnm/internal/storage/postgres"

_ "github.com/lib/pq"
"github.com/sethvargo/go-envconfig"
Expand All @@ -19,13 +18,9 @@ func main() {
log.Fatalln("Error processing .env file: ", err)
}

// Connect to database
conn := postgres.ConnectDatabase(config.DbHost, config.DbUser, config.DbPassword, config.DbName, config.DbPort)
app := service.InitApp(service.Params{Conn: conn})
app := service.InitApp(config)

defer conn.Close()

if err := app.Listen(":8080"); err != nil {
if err := app.Listen(":" + config.Application.Port); err != nil {
log.Fatalf("Failed to start server: %v", err)
}
}
6 changes: 5 additions & 1 deletion backend/go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,11 @@ go 1.22.6

require (
github.com/gofiber/fiber/v2 v2.52.5
github.com/gofiber/storage/memory v1.3.4
github.com/jackc/pgx/v5 v5.7.0
github.com/lib/pq v1.10.9
github.com/zmb3/spotify/v2 v2.4.2
golang.org/x/oauth2 v0.23.0
)

require (
Expand All @@ -21,7 +24,8 @@ require (
require (
github.com/andybalholm/brotli v1.0.5 // indirect
github.com/goccy/go-json v0.10.3
github.com/google/uuid v1.5.0 // indirect
github.com/gofiber/storage v1.3.3
github.com/google/uuid v1.5.0
github.com/klauspost/compress v1.17.0 // indirect
github.com/mattn/go-colorable v0.1.13 // indirect
github.com/mattn/go-isatty v0.0.20 // indirect
Expand Down
402 changes: 402 additions & 0 deletions backend/go.sum

Large diffs are not rendered by default.

6 changes: 6 additions & 0 deletions backend/internal/config/application.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
package config

type Application struct {
Port string `env:"PORT, default=8080"` // the port for the server to listen on
LogLevel string `env:"LOG_LEVEL, default=INFO"` // the level of event to log
}
11 changes: 3 additions & 8 deletions backend/internal/config/config.go
Original file line number Diff line number Diff line change
@@ -1,12 +1,7 @@
package config

type Config struct {
DbHost string `env:"DB_HOST, required"` // the database host to connect to
DbPort string `env:"DB_PORT, required"` // the database port to connect to
DbUser string `env:"DB_USER, required"` // the user to connect to the database with
DbPassword string `env:"DB_PASSWORD, required"` // the password to connect to the database with
DbName string `env:"DB_NAME, required"` // the name of the database to connect to

Port string `env:"PORT, default=8080"` // the port for the server to listen on
LogLevel string `env:"LOG_LEVEL, default=INFO"` // the level of event to log
Application Application
DB DB
Spotify Spotify
}
15 changes: 15 additions & 0 deletions backend/internal/config/db.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package config

import "fmt"

type DB struct {
Host string `env:"DB_HOST, required"` // the database host to connect to
Port string `env:"DB_PORT, required"` // the database port to connect to
User string `env:"DB_USER, required"` // the user to connect to the database with
Password string `env:"DB_PASSWORD, required"` // the password to connect to the database with
Name string `env:"DB_NAME, required"` // the name of the database to connect to
}

func (db *DB) Connection() string {
return fmt.Sprintf("host=%s user=%s password=%s dbname=%s port=%s sslmode=require statement_cache_mode=describe pgbouncer=true", db.Host, db.User, db.Password, db.Name, db.Port)
}
5 changes: 5 additions & 0 deletions backend/internal/config/spotify.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
package config

type Spotify struct {
RedirectURI string `env:"SPOTIFY_REDIRECT_URI, required"`
}
8 changes: 8 additions & 0 deletions backend/internal/constants/auth.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
package constants

import "time"


const (
StateExpiresAfter = 5 * time.Minute
)
5 changes: 5 additions & 0 deletions backend/internal/constants/http.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
package constants

const (
HeaderRedirect = "X-Redirect"
)
39 changes: 39 additions & 0 deletions backend/internal/service/handler/spotify/begin.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
package spotify

import (
"net/http"
"platnm/internal/constants"

"github.com/gofiber/fiber/v2"
"github.com/google/uuid"
"golang.org/x/oauth2"
)

func (h *Handler) Begin(c *fiber.Ctx) error {
// uuid as state for now
verifier := oauth2.GenerateVerifier()
challenge := oauth2.S256ChallengeFromVerifier(verifier)
state := uuid.NewString()

url := h.authenticator.AuthURL(state,
oauth2.SetAuthURLParam("code_challenge_method", "S256"),
oauth2.SetAuthURLParam("code_challenge", challenge),
)

sv := stateValue{
verifier: verifier,
challenge: challenge,
}

stateValue, err := sv.MarshalBinary()
if err != nil {
return err
}

if err := h.store.Set(state, stateValue, constants.StateExpiresAfter); err != nil {
return err
}

c.Set(constants.HeaderRedirect, url)
return c.SendStatus(http.StatusFound)
}
42 changes: 42 additions & 0 deletions backend/internal/service/handler/spotify/callback.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
package spotify

import (
"log/slog"
"net/http"
"platnm/internal/constants"

"github.com/gofiber/fiber/v2"
"github.com/gofiber/fiber/v2/middleware/adaptor"
"golang.org/x/oauth2"
)

func (h *Handler) Callback(c *fiber.Ctx) error {
garrettladley marked this conversation as resolved.
Show resolved Hide resolved
state := c.Query("state")

sv, err := h.store.Get(state)
if err != nil {
return err
}

var stateValue stateValue
if err := stateValue.UnmarshalBinary(sv); err != nil {
return err
}

req, err := adaptor.ConvertRequest(c, false)
if err != nil {
return err
}

token, err := h.authenticator.Token(c.Context(), state, req, oauth2.SetAuthURLParam("code_verifier", stateValue.verifier))
if err != nil {
slog.Error("Failed to get token", "error", err)
return c.SendStatus(http.StatusInternalServerError)
}

slog.Info("Access token:", "token", token.AccessToken)
slog.Info("Refresh token:", "token", token.RefreshToken)

c.Set(constants.HeaderRedirect, "http://127.0.0.1:3000")
return c.SendStatus(http.StatusFound)
}
24 changes: 24 additions & 0 deletions backend/internal/service/handler/spotify/handler.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package spotify

import (
"platnm/internal/config"

"github.com/gofiber/storage"
spotifyauth "github.com/zmb3/spotify/v2/auth"
)

type Handler struct {
store storage.Storage
authenticator *spotifyauth.Authenticator
}

func NewHandler(store storage.Storage, config config.Spotify) *Handler {
authenticator := spotifyauth.New(
spotifyauth.WithRedirectURL(config.RedirectURI),
spotifyauth.WithScopes(spotifyauth.ScopeUserReadPrivate),
)
return &Handler{
store: store,
authenticator: authenticator,
}
}
57 changes: 57 additions & 0 deletions backend/internal/service/handler/spotify/state_value.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
package spotify

import (
"errors"
"sync"
)

const (
verifierLen = 43
challengeLen = 43
bufferSize = verifierLen + challengeLen
)

var ErrInvalidStateValueLength = errors.New("invalid state value length")

type stateValue struct {
verifier string
challenge string
}

func (sv *stateValue) MarshalBinary() ([]byte, error) {
buffer := getBuffer()
copy(buffer.data[:verifierLen], sv.verifier)
copy(buffer.data[verifierLen:], sv.challenge)
return buffer.data, nil
}

// UnmarshalBinary decodes the state value from binary data.
// Returns ErrInvalidStateValueLength if the data length is
// not equal to bufferSize.
func (sv *stateValue) UnmarshalBinary(data []byte) error {
if len(data) != bufferSize {
return ErrInvalidStateValueLength
}
sv.verifier = string(data[:verifierLen])
sv.challenge = string(data[verifierLen:])
putBuffer(&buffer{data: data})
return nil
}

type buffer struct {
data []byte
}

var bufferPool = sync.Pool{
New: func() interface{} {
return make([]byte, bufferSize)
},
}

func getBuffer() *buffer {
return bufferPool.Get().(*buffer)
}

func putBuffer(buffer *buffer) {
bufferPool.Put(buffer)
}
27 changes: 17 additions & 10 deletions backend/internal/service/server.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
package service

import (
"net/http"
"platnm/internal/config"
"platnm/internal/errs"
"platnm/internal/service/handler"
"platnm/internal/service/handler/spotify"
"platnm/internal/storage/postgres"

go_json "github.com/goccy/go-json"
Expand All @@ -11,32 +14,36 @@ import (
"github.com/gofiber/fiber/v2/middleware/logger"
"github.com/gofiber/fiber/v2/middleware/recover"
"github.com/gofiber/fiber/v2/middleware/requestid"
"github.com/jackc/pgx/v5/pgxpool"
"github.com/gofiber/storage/memory"
)

type Params struct {
Conn *pgxpool.Pool
}

func InitApp(params Params) *fiber.App {
func InitApp(config config.Config) *fiber.App {
app := setupApp()

setupRoutes(app, params.Conn)
setupRoutes(app, config)

return app
}

func setupRoutes(app *fiber.App, conn *pgxpool.Pool) {
func setupRoutes(app *fiber.App, config config.Config) {
app.Get("/health", func(c *fiber.Ctx) error {
return c.SendStatus(fiber.StatusOK)
return c.SendStatus(http.StatusOK)
})

repository := postgres.NewRepository(conn)
repository := postgres.NewRepository(config.DB)
userHandler := handler.NewUserHandler(repository.User)
app.Route("/users", func(r fiber.Router) {
r.Get("/", userHandler.GetUsers)
r.Get("/:id", userHandler.GetUserById)
})

app.Route("/auth", func(r fiber.Router) {
r.Route("/spotify", func(r fiber.Router) {
h := spotify.NewHandler(memory.New(), config.Spotify)
r.Get("/begin", h.Begin)
r.Get("/callback", h.Callback)
})
})
}

func setupApp() *fiber.App {
Expand Down
12 changes: 6 additions & 6 deletions backend/internal/storage/postgres/storage.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,19 +2,17 @@ package postgres

import (
"context"
"fmt"
"log"
"platnm/internal/config"
"platnm/internal/storage"
user "platnm/internal/storage/postgres/schema"

"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
)

func ConnectDatabase(host, user, password, dbname, port string) *pgxpool.Pool {
connStr := fmt.Sprintf("host=%s user=%s password=%s dbname=%s port=%s sslmode=require statement_cache_mode=describe pgbouncer=true", host, user, password, dbname, port)

dbConfig, err := pgxpool.ParseConfig(connStr)
func ConnectDatabase(config config.DB) *pgxpool.Pool {
dbConfig, err := pgxpool.ParseConfig(config.Connection())
if err != nil {
log.Fatal("Failed to create a config, error: ", err)
}
Expand All @@ -38,7 +36,9 @@ func ConnectDatabase(host, user, password, dbname, port string) *pgxpool.Pool {
return conn
}

func NewRepository(db *pgxpool.Pool) *storage.Repository {
func NewRepository(config config.DB) *storage.Repository {
db := ConnectDatabase(config)

return &storage.Repository{
User: user.NewUserRepository(db),
}
Expand Down
Loading