Skip to content

Commit

Permalink
feat: add linear provider
Browse files Browse the repository at this point in the history
* feat: add linear provider

* chore: remove duplicate note

* chore: use email

---------

Co-authored-by: Sébastien Chopin <[email protected]>
  • Loading branch information
blqke and atinux authored Oct 7, 2024
1 parent 2719753 commit c1291cd
Show file tree
Hide file tree
Showing 8 changed files with 167 additions and 2 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -215,6 +215,7 @@ It can also be set using environment variables:
- Google
- Instagram
- Keycloak
- Linear
- LinkedIn
- Microsoft
- PayPal
Expand Down
5 changes: 4 additions & 1 deletion playground/.env.example
Original file line number Diff line number Diff line change
Expand Up @@ -73,4 +73,7 @@ NUXT_OAUTH_DROPBOX_CLIENT_ID=
NUXT_OAUTH_DROPBOX_CLIENT_SECRET=
# Polar
NUXT_OAUTH_POLAR_CLIENT_ID=
NUXT_OAUTH_POLAR_CLIENT_SECRET=
NUXT_OAUTH_POLAR_CLIENT_SECRET=
# Linear
NUXT_OAUTH_LINEAR_CLIENT_ID=
NUXT_OAUTH_LINEAR_CLIENT_SECRET=
6 changes: 6 additions & 0 deletions playground/app.vue
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,12 @@ const providers = computed(() =>
disabled: Boolean(user.value?.gitlab),
icon: 'i-simple-icons-gitlab',
},
{
label: user.value?.linear || 'Linear',
to: '/auth/linear',
disabled: Boolean(user.value?.linear),
icon: 'i-simple-icons-linear',
},
{
label: user.value?.linkedin || 'LinkedIn',
to: '/auth/linkedin',
Expand Down
1 change: 1 addition & 0 deletions playground/auth.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ declare module '#auth-utils' {
discord?: string
battledotnet?: string
keycloak?: string
linear?: string
linkedin?: string
cognito?: string
facebook?: string
Expand Down
12 changes: 12 additions & 0 deletions playground/server/routes/auth/linear.get.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
export default defineOAuthLinearEventHandler({
async onSuccess(event, { user }) {
await setUserSession(event, {
user: {
linear: user.email,
},
loggedInAt: Date.now(),
})

return sendRedirect(event, '/')
},
})
6 changes: 6 additions & 0 deletions src/module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -214,6 +214,12 @@ export default defineNuxtModule<ModuleOptions>({
realm: '',
redirectURL: '',
})
// Linear OAuth
runtimeConfig.oauth.linear = defu(runtimeConfig.oauth.linear, {
clientId: '',
clientSecret: '',
redirectURL: '',
})
// LinkedIn OAuth
runtimeConfig.oauth.linkedin = defu(runtimeConfig.oauth.linkedin, {
clientId: '',
Expand Down
136 changes: 136 additions & 0 deletions src/runtime/server/lib/oauth/linear.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,136 @@
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 OAuthLinearConfig {
/**
* Linear OAuth Client ID
* @default process.env.NUXT_OAUTH_LINEAR_CLIENT_ID
*/
clientId?: string
/**
* Linear OAuth Client Secret
* @default process.env.NUXT_OAUTH_LINEAR_CLIENT_SECRET
*/
clientSecret?: string
/**
* Linear OAuth Scope
* @default ['read']
* @see https://developers.linear.app/docs/oauth/authentication#scopes
* @example ['read', 'write', 'issues:create', 'comments:create', 'timeSchedule:write', 'admin']
*/
scope?: string[]
/**
* Linear OAuth Authorization URL
* @default 'https://linear.app/oauth/authorize'
*/
authorizationURL?: string
/**
* Linear OAuth Token URL
* @default 'https://api.linear.app/oauth/token'
*/
tokenURL?: string
/**
* Extra authorization parameters to provide to the authorization URL
* @see https://developers.linear.app/docs/oauth/authentication#id-2.-redirect-user-access-requests-to-linear
*/
authorizationParams?: Record<string, string>
/**
* Redirect URL to allow overriding for situations like prod failing to determine public hostname
* @default process.env.NUXT_OAUTH_LINEAR_REDIRECT_URL or current URL
*/
redirectURL?: string
}

export function defineOAuthLinearEventHandler({ config, onSuccess, onError }: OAuthConfig<OAuthLinearConfig>) {
return eventHandler(async (event: H3Event) => {
config = defu(config, useRuntimeConfig(event).oauth?.linear, {
authorizationURL: 'https://linear.app/oauth/authorize',
tokenURL: 'https://api.linear.app/oauth/token',
authorizationParams: {},
}) as OAuthLinearConfig

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

if (query.error) {
const error = createError({
statusCode: 401,
message: `Linear login failed: ${query.error || 'Unknown error'}`,
data: query,
})
if (!onError) throw error
return onError(event, error)
}

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

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

if (!query.code) {
config.scope = config.scope || ['read']
// Redirect to Linear 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, {
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: {
grant_type: 'authorization_code',
client_id: config.clientId,
client_secret: config.clientSecret,
redirect_uri: redirectURL,
code: query.code,
},
})

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

const accessToken = tokens.access_token
// TODO: improve typing
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const user: any = await $fetch('https://api.linear.app/graphql', {
method: 'POST',
headers: {
'Authorization': `Bearer ${accessToken}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({
query: '{ viewer { id name email } }',
}),
})

if (!user.data || !user.data.viewer) {
const error = createError({
statusCode: 500,
message: 'Could not get Linear user',
data: tokens,
})
if (!onError) throw error
return onError(event, error)
}

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

export type OAuthProvider = 'auth0' | 'battledotnet' | 'cognito' | 'discord' | 'dropbox' | 'facebook' | 'github' | 'gitlab' | 'google' | 'instagram' | 'keycloak' | 'linkedin' | 'microsoft' | 'paypal' | 'polar' | 'spotify' | 'steam' | 'tiktok' | 'twitch' | 'vk' | 'x' | 'xsuaa' | 'yandex' | (string & {})
export type OAuthProvider = 'auth0' | 'battledotnet' | 'cognito' | 'discord' | 'dropbox' | 'facebook' | 'github' | 'gitlab' | 'google' | 'instagram' | 'keycloak' | 'linear' | 'linkedin' | 'microsoft' | 'paypal' | 'polar' | 'spotify' | 'steam' | 'tiktok' | 'twitch' | 'vk' | 'x' | 'xsuaa' | 'yandex' | (string & {})

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

Expand Down

0 comments on commit c1291cd

Please sign in to comment.