Skip to content

feat: add Roblox OAuth provider #420

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

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
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
6 changes: 5 additions & 1 deletion playground/.env.example
Original file line number Diff line number Diff line change
Expand Up @@ -136,4 +136,8 @@ NUXT_OAUTH_SLACK_REDIRECT_URL=
#Heroku
NUXT_OAUTH_HEROKU_CLIENT_ID=
NUXT_OAUTH_HEROKU_CLIENT_SECRET=
NUXT_OAUTH_HEROKU_REDIRECT_URL=
NUXT_OAUTH_HEROKU_REDIRECT_URL=
#Roblox
NUXT_OAUTH_ROBLOX_CLIENT_ID=
NUXT_OAUTH_ROBLOX_CLIENT_SECRET=
NUXT_OAUTH_ROBLOX_REDIRECT_URL=
6 changes: 6 additions & 0 deletions playground/app.vue
Original file line number Diff line number Diff line change
Expand Up @@ -248,6 +248,12 @@ const providers = computed(() =>
disabled: Boolean(user.value?.heroku),
icon: 'i-simple-icons-heroku',
},
{
label: user.value?.roblox || 'Roblox',
to: '/auth/roblox',
disabled: Boolean(user.value?.roblox),
icon: 'i-simple-icons-roblox',
},
].map(p => ({
...p,
prefetch: false,
Expand Down
1 change: 1 addition & 0 deletions playground/auth.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ declare module '#auth-utils' {
salesforce?: string
slack?: string
heroku?: string
roblox?: string
}

interface UserSession {
Expand Down
12 changes: 12 additions & 0 deletions playground/server/routes/auth/roblox.get.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
export default defineOAuthRobloxEventHandler({
async onSuccess(event, { user }) {
await setUserSession(event, {
user: {
roblox: user.username,
},
loggedInAt: Date.now(),
})

return sendRedirect(event, '/')
},
})
7 changes: 7 additions & 0 deletions src/module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -468,5 +468,12 @@ export default defineNuxtModule<ModuleOptions>({
redirectURL: '',
scope: '',
})
// Roblox OAuth
runtimeConfig.oauth.roblox = defu(runtimeConfig.oauth.roblox, {
clientId: '',
clientSecret: '',
redirectURL: '',
scope: '',
})
},
})
262 changes: 262 additions & 0 deletions src/runtime/server/lib/oauth/roblox.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,262 @@
import type { H3Event } from 'h3'
import { eventHandler, getQuery, sendRedirect } from 'h3'
import { withQuery } from 'ufo'
import { defu } from 'defu'
import { handleMissingConfiguration, handleAccessTokenErrorResponse, getOAuthRedirectURL, requestAccessToken } from '../utils'
import { useRuntimeConfig, createError } from '#imports'
import type { OAuthConfig } from '#auth-utils'

export interface OAuthRobloxConfig {
/**
* Roblox OAuth Client ID
* @default process.env.NUXT_OAUTH_ROBLOX_CLIENT_ID
*/
clientId?: string
/**
* Roblox OAuth Client Secret
* @default process.env.NUXT_OAUTH_ROBLOX_CLIENT_SECRET
*/
clientSecret?: string
/**
* Roblox OAuth Scope
* Some scopes and claims listed are only available to official Roblox apps, e.g. email
* @default ['openid', 'profile']
* @see https://apis.roblox.com/oauth/.well-known/openid-configuration
* @example ['openid', 'profile', 'asset:read', 'universe-messaging-service:publish']
*/
scope?: string[]
/**
* Roblox OAuth Authorization URL
* @default 'https://apis.roblox.com/oauth/v1/authorize'
*/
authorizationURL?: string
/**
* Roblox OAuth Token URL
* @default 'https://apis.roblox.com/oauth/v1/token'
*/
tokenURL?: string
/**
* Extra authorization parameters to provide to the authorization URL
* @see https://create.roblox.com/docs/cloud/auth/oauth2-reference#get-v1authorize
*/
authorizationParams?: Record<string, string>
/**
* Redirect URL to allow overriding for situations like prod failing to determine public hostname
* @default process.env.NUXT_OAUTH_ROBLOX_REDIRECT_URL or current URL
*/
redirectURL?: string
}

interface OAuthRobloxUserInfo {
/**
* Roblox unique user ID
*/
sub: string

/**
* Display name (may be identical to username) - can be changed by the user
* Available only with the profile scope
*/
name?: string

/**
* Display name (may be identical to username) - can be changed by the user
* Available only with the profile scope
*/
nickname?: string

/**
* Unique username - can be changed by the user
* Available only with the profile scope
*/
preferred_username?: string

/**
* URL of the Roblox account profile
* Available only with the profile scope
*/
created_at?: string

/**
* Roblox avatar headshot image
* Can be null if the avatar headshot image hasn't yet been generated or has been moderated
* Available only with the profile scope
*/
picture?: string | null
}

export interface OAuthRobloxUser {
/**
* The resource path of the user
* @example "users/123"
*/
path: string;

/**
* The timestamp at which the user was created
* @readonly
* @example "2023-07-05T12:34:56Z"
*/
createTime: string;

/**
* Unique ID that identifies a user in Roblox
* @readonly
* @example "123456"
*/
id: string;

/**
* Unique username for a user in Roblox
* @example "exampleUser"
*/
name: string;

/**
* Display name for the user
* @example "userDefinedName"
*/
displayName: string;

/**
* User-defined information about themselves
* @example "Example User's bio"
*/
about: string;

/**
* Current locale selected by the user as an IETF language code
* @example "en-US"
*/
locale: string;

/**
* Whether the user is a premium user
* @readonly
* @example true
*/
premium: boolean;

/**
* Specifies if the user is identity-verified
* Verification includes, but isn't limited to, non-VoIP phone numbers or government IDs
* Available only with the user.advanced:read scope
* @readonly
* @example true
*/
idVerified: boolean;

/**
* User's social network profiles and visibility.
*/
socialNetworkProfiles: {
/**
* Facebook profile URI.
*/
facebook?: string;

/**
* Twitter profile URI.
*/
twitter?: string;

/**
* YouTube profile URI.
*/
youtube?: string;

/**
* Twitch profile URI.
*/
twitch?: string;

/**
* Guilded profile URI.
*/
guilded?: string;

/**
* Visibility of the social network profiles.
* Available only with the user.social:read scope
* @example "SOCIAL_NETWORK_VISIBILITY_UNSPECIFIED"
*/
visibility:
| "SOCIAL_NETWORK_VISIBILITY_UNSPECIFIED"
| "NO_ONE"
| "FRIENDS"
| "FRIENDS_AND_FOLLOWING"
| "FRIENDS_FOLLOWING_AND_FOLLOWERS"
| "EVERYONE";
};
}

export function defineOAuthRobloxEventHandler({ config, onSuccess, onError }: OAuthConfig<OAuthRobloxConfig>) {
return eventHandler(async (event: H3Event) => {
config = defu(config, useRuntimeConfig(event).oauth?.roblox, {
authorizationURL: 'https://apis.roblox.com/oauth/v1/authorize',
tokenURL: 'https://apis.roblox.com/oauth/v1/token',
authorizationParams: {},
}) as OAuthRobloxConfig

const query = getQuery<{ code?: string, error?: string }>(event)

if (!config.clientId || !config.clientSecret) {
return handleMissingConfiguration(event, 'roblox', ['clientId', 'clientSecret'], onError)
}

if (query.error) {
return handleAccessTokenErrorResponse(event, 'roblox', query, onError)
}

const redirectURL = config.redirectURL || getOAuthRedirectURL(event)

if (!query.code) {
config.scope = config.scope || []

// Redirect to Roblox Oauth page
return sendRedirect(
event,
withQuery(config.authorizationURL as string, {
response_type: 'code',
client_id: config.clientId,
redirect_uri: redirectURL,
scope: config.scope.join(' '),
...config.authorizationParams,
}),
)
}

const tokens = await requestAccessToken(config.tokenURL as string, {
body: {
client_id: config.clientId,
client_secret: config.clientSecret,
grant_type: 'authorization_code',
redirect_uri: redirectURL,
code: query.code,
},
})

if (tokens.error) {
return handleAccessTokenErrorResponse(event, 'roblox', tokens, onError)
}

const accessToken = tokens.access_token
const userInfo: OAuthRobloxUserInfo = await $fetch('https://apis.roblox.com/oauth/userinfo', {
headers: {
'user-agent': 'Nuxt Auth Utils',
'Authorization': `Bearer ${accessToken}`,
},
})

const user: OAuthRobloxUser = await $fetch(`https://apis.roblox.com/cloud/v2/users/${userInfo.sub}`, {
headers: {
'user-agent': 'Nuxt Auth Utils',
'Authorization': `Bearer ${accessToken}`,
},
})

return onSuccess(event, {
tokens,
user,
})
}
2 changes: 1 addition & 1 deletion src/runtime/types/oauth-config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import type { H3Event, H3Error } from 'h3'

export type ATProtoProvider = 'bluesky'

export type OAuthProvider = ATProtoProvider | 'atlassian' | 'auth0' | 'authentik' | 'azureb2c' | 'battledotnet' | 'cognito' | 'discord' | 'dropbox' | 'facebook' | 'gitea' | 'github' | 'gitlab' | 'google' | 'hubspot' | 'instagram' | 'kick' | 'keycloak' | 'line' | 'linear' | 'linkedin' | 'microsoft' | 'paypal' | 'polar' | 'spotify' | 'seznam' | 'steam' | 'strava' | 'tiktok' | 'twitch' | 'vk' | 'workos' | 'x' | 'xsuaa' | 'yandex' | 'zitadel' | 'apple' | 'livechat' | 'salesforce' | 'slack' | 'heroku' | (string & {})
export type OAuthProvider = ATProtoProvider | 'atlassian' | 'auth0' | 'authentik' | 'azureb2c' | 'battledotnet' | 'cognito' | 'discord' | 'dropbox' | 'facebook' | 'gitea' | 'github' | 'gitlab' | 'google' | 'hubspot' | 'instagram' | 'kick' | 'keycloak' | 'line' | 'linear' | 'linkedin' | 'microsoft' | 'paypal' | 'polar' | 'spotify' | 'seznam' | 'steam' | 'strava' | 'tiktok' | 'twitch' | 'vk' | 'workos' | 'x' | 'xsuaa' | 'yandex' | 'zitadel' | 'apple' | 'livechat' | 'salesforce' | 'slack' | 'heroku' | 'roblox' | (string & {})

export type OnError = (event: H3Event, error: H3Error) => Promise<void> | void

Expand Down