Skip to content
Open
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
40 changes: 27 additions & 13 deletions src/runtime/server/lib/oauth/spotify.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,14 +21,9 @@ export interface OAuthSpotifyConfig {
* Spotify OAuth Scope
* @default []
* @see https://developer.spotify.com/documentation/web-api/concepts/scopes
* @example ['user-read-email']
* @example ['playlist-read-private']
*/
scope?: string[]
/**
* Require email from user, adds the ['user-read-email'] scope if not present
* @default false
*/
emailRequired?: boolean

/**
* Spotify OAuth Authorization URL
Expand All @@ -55,7 +50,31 @@ export interface OAuthSpotifyConfig {
redirectURL?: string
}

export function defineOAuthSpotifyEventHandler({ config, onSuccess, onError }: OAuthConfig<OAuthSpotifyConfig>) {
interface SpotifyUser {
display_name: string
external_urls: {
spotify: string
}
href: string
id: string
images: {
url: string
height: number
width: number
}[]
type: string
uri: string
}

interface SpotifyTokens {
access_token: string
token_type: string
scope: string
expires_in: number
refresh_token: string
}

export function defineOAuthSpotifyEventHandler({ config, onSuccess, onError }: OAuthConfig<OAuthSpotifyConfig, { user: SpotifyUser, tokens: SpotifyTokens }>) {
return eventHandler(async (event: H3Event) => {
config = defu(config, useRuntimeConfig(event).oauth?.spotify, {
authorizationURL: 'https://accounts.spotify.com/authorize',
Expand All @@ -72,9 +91,6 @@ export function defineOAuthSpotifyEventHandler({ config, onSuccess, onError }: O

if (!query.code) {
config.scope = config.scope || []
if (config.emailRequired && !config.scope.includes('user-read-email')) {
config.scope.push('user-read-email')
}
// Redirect to Spotify Oauth page
return sendRedirect(
event,
Expand Down Expand Up @@ -106,9 +122,7 @@ export function defineOAuthSpotifyEventHandler({ config, onSuccess, onError }: O

const accessToken = tokens.access_token

// TODO: improve typing
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const user: any = await $fetch('https://api.spotify.com/v1/me', {
const user = await $fetch<SpotifyUser>('https://api.spotify.com/v1/me', {
headers: {
Authorization: `Bearer ${accessToken}`,
},
Expand Down
Loading