You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
63 lines
1.6 KiB
Go
63 lines
1.6 KiB
Go
package auth
|
|
|
|
import (
|
|
"context"
|
|
"net/http"
|
|
|
|
"gitea.ravianand.me/Dan6erbond/listy/core"
|
|
"gitea.ravianand.me/Dan6erbond/listy/internal"
|
|
"gitea.ravianand.me/Dan6erbond/listy/users"
|
|
"github.com/zmb3/spotify/v2"
|
|
)
|
|
|
|
func RegisterRoutes(app *core.App) {
|
|
app.Mux.Get("/auth/oidc/spotify/redirect", Redirect(app))
|
|
app.Mux.Get("/auth/oidc/spotify/callback", Callback(app))
|
|
}
|
|
|
|
func Redirect(app *core.App) func(w http.ResponseWriter, r *http.Request) {
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
|
state, _ := internal.GenerateRandomString(16)
|
|
|
|
session, _ := app.SessionStore.Get(r, "oidc")
|
|
session.Values["state"] = state
|
|
|
|
if err := session.Save(r, w); err != nil {
|
|
http.Error(w, err.Error(), http.StatusInternalServerError)
|
|
return
|
|
}
|
|
|
|
url := app.SpotifyAuth.AuthURL(state)
|
|
http.Redirect(w, r, url, http.StatusSeeOther)
|
|
}
|
|
}
|
|
|
|
func Callback(app *core.App) func(w http.ResponseWriter, r *http.Request) {
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
|
ctx := context.Background()
|
|
|
|
session, _ := app.SessionStore.Get(r, "oidc")
|
|
state, ok := session.Values["state"]
|
|
|
|
if !ok {
|
|
http.Error(w, "No state found", http.StatusInternalServerError)
|
|
return
|
|
}
|
|
|
|
// use the same state string here that you used to generate the URL
|
|
token, err := app.SpotifyAuth.Token(r.Context(), state.(string), r)
|
|
if err != nil {
|
|
http.Error(w, "Couldn't get token", http.StatusNotFound)
|
|
return
|
|
}
|
|
|
|
spotifyClient := spotify.New(app.SpotifyAuth.Client(r.Context(), token))
|
|
|
|
user, _ := spotifyClient.CurrentUser(ctx)
|
|
|
|
users.SaveUserToken(ctx, app, user.ID, token)
|
|
|
|
app.Render.JSON(w, 200, user)
|
|
}
|
|
}
|