feat: basic oauth

zio/stable
Anthony Fu 2022-11-15 23:48:23 +08:00
parent 72b13f5265
commit 7ab17001f0
16 changed files with 199 additions and 106 deletions

View File

@ -0,0 +1,12 @@
<script setup lang="ts">
const { currentUser } = useAppStore()
</script>
<template>
<div p4>
<!-- TODO: multiple account switcher -->
<AccountInfo v-if="currentUser?.account" :account="currentUser.account" />
<!-- TODO: dialog for select server -->
<a v-else href="/api/mas.to/login" px2 py1 bg-teal6 text-white m2 rounded>Login</a>
</div>
</template>

View File

@ -1,5 +1,10 @@
import type { MastoClient } from 'masto'
import type { AppStore } from '~~/plugins/store.client'
export function useMasto() {
return inject('masto') as Promise<MastoClient>
}
export function useAppStore() {
return inject('app-store') as AppStore
}

View File

@ -0,0 +1,11 @@
import { DEFAULT_SERVER } from '~/constants'
export function useAppCookies() {
const server = useCookie('nuxtodon-server', { default: () => DEFAULT_SERVER })
const token = useCookie('nuxtodon-token')
return {
server,
token,
}
}

View File

@ -4,3 +4,4 @@ export const HOST_DOMAIN = process.dev
? 'http://localhost:3000'
: 'https://nuxtodon.netlify.app'
export const DEFAULT_SERVER = 'mas.to'

View File

@ -10,7 +10,9 @@
<slot />
</div>
<div>
<slot name="right" />
<slot name="right">
<AccountMe />
</slot>
</div>
</main>
</div>

View File

@ -7,12 +7,13 @@
"dev": "nuxi dev",
"start": "node .output/server/index.mjs",
"lint": "eslint .",
"register-apps": "esno ./scripts/registerApps.ts",
"postinstall": "nuxi prepare",
"generate": "nuxi generate"
},
"devDependencies": {
"@antfu/eslint-config": "^0.30.1",
"@iconify-json/carbon": "^1.1.9",
"@iconify-json/carbon": "^1.1.10",
"@iconify-json/logos": "^1.1.18",
"@iconify-json/ri": "^1.1.3",
"@iconify-json/twemoji": "^1.1.5",

View File

@ -1,54 +0,0 @@
<script setup lang="ts">
import { login } from 'masto'
import { DEFAULT_SERVER } from '~/plugins/masto'
const server = useCookie('nuxtodon-server')
const token = useCookie('nuxtodon-token')
async function oauth() {
const client = await login({
url: `https://${server.value || DEFAULT_SERVER}`,
})
const redirectUri = `${location.origin}/api/${server.value || DEFAULT_SERVER}/oauth`
const app = await client.apps.create({
clientName: 'Nuxtodon',
redirectUris: redirectUri,
scopes: 'read write follow push',
})
console.log({ app })
const url = `https://${server.value || DEFAULT_SERVER}/oauth/authorize
?client_id=${app.clientId}
&scope=read+write+follow+push
&redirect_uri=${encodeURIComponent(redirectUri)}
&response_type=code`.replace(/\n/g, '')
const a = document.createElement('a')
a.href = url
a.target = '_blank'
a.click()
}
</script>
<template>
<div p4>
<button @click="oauth()">
OAuth
</button>
<input
v-model="server"
placeholder="Server URL"
bg-transparent text-current
border="~ border" p="x2 y1" w-full
outline-none
>
<input
v-model="token"
placeholder="Token"
bg-transparent text-current
border="~ border" p="x2 y1" w-full
outline-none
>
</div>
</template>

View File

@ -0,0 +1,17 @@
<script setup lang="ts">
const { query } = useRoute()
onMounted(async () => {
const { login } = useAppStore()
await login(query as any)
await nextTick()
await nextTick()
location.pathname = '/'
})
</script>
<template>
<div>
Login...
</div>
</template>

View File

@ -0,0 +1,32 @@
<script setup lang="ts">
const { server, token } = useAppCookies()
async function oauth() {
const a = document.createElement('a')
a.href = `/api/${server.value}/login`
a.target = '_blank'
a.click()
}
</script>
<template>
<div p4>
<button @click="oauth()">
OAuth
</button>
<input
v-model="server"
placeholder="Server URL"
bg-transparent text-current
border="~ border" p="x2 y1" w-full
outline-none
>
<input
v-model="token"
placeholder="Token"
bg-transparent text-current
border="~ border" p="x2 y1" w-full
outline-none
>
</div>
</template>

View File

@ -1,19 +1,11 @@
import { login } from 'masto'
export const DEFAULT_SERVER = 'mas.to'
export default defineNuxtPlugin((nuxt) => {
const server = useCookie('nuxtodon-server')
const token = useCookie('nuxtodon-token')
const { server, token } = useAppCookies()
const masto = login({
url: `https://${server.value || DEFAULT_SERVER}`,
url: `https://${server.value}`,
accessToken: token.value,
})
nuxt.vueApp.provide('masto', masto)
// Reload the page when the token changes
watch(token, () => {
location.reload()
})
})

View File

@ -0,0 +1,47 @@
import { login as loginMasto } from 'masto'
import type { UserLogin } from '~/types'
function createStore() {
const { server, token } = useAppCookies()
const accounts = useLocalStorage<UserLogin[]>('nuxtodon-accounts', [], { deep: true })
const currentIndex = useLocalStorage<number>('nuxtodon-current-user', -1)
const currentUser = computed<UserLogin | undefined>(() => accounts.value[currentIndex.value])
async function login(user: UserLogin) {
const existing = accounts.value.findIndex(u => u.server === user.server && u.token === user.token)
if (existing !== -1) {
if (currentIndex.value === existing)
return null
currentIndex.value = existing
server.value = user.server
token.value = user.token
return true
}
const masto = await loginMasto({
url: `https://${user.server}`,
accessToken: user.token,
})
const me = await masto.accounts.verifyCredentials()
user.account = me
accounts.value.push(user)
currentIndex.value = accounts.value.length
server.value = user.server
token.value = user.token
return true
}
return {
currentUser,
accounts,
login,
}
}
export type AppStore = ReturnType<typeof createStore>
export default defineNuxtPlugin((nuxt) => {
nuxt.vueApp.provide('app-store', createStore())
})

View File

@ -2,7 +2,7 @@ lockfileVersion: 5.4
specifiers:
'@antfu/eslint-config': ^0.30.1
'@iconify-json/carbon': ^1.1.9
'@iconify-json/carbon': ^1.1.10
'@iconify-json/logos': ^1.1.18
'@iconify-json/ri': ^1.1.3
'@iconify-json/twemoji': ^1.1.5
@ -26,7 +26,7 @@ specifiers:
devDependencies:
'@antfu/eslint-config': 0.30.1_rmayb2veg2btbq6mbmnyivgasy
'@iconify-json/carbon': 1.1.9
'@iconify-json/carbon': 1.1.10
'@iconify-json/logos': 1.1.18
'@iconify-json/ri': 1.1.3
'@iconify-json/twemoji': 1.1.5
@ -632,8 +632,8 @@ packages:
resolution: {integrity: sha512-ZnQMnLV4e7hDlUvw8H+U8ASL02SS2Gn6+9Ac3wGGLIe7+je2AeAOxPY+izIPJDfFDb7eDjev0Us8MO1iFRN8hA==}
dev: true
/@iconify-json/carbon/1.1.9:
resolution: {integrity: sha512-O3geRhhnE9dDDC4oT6qwBs7sdc37R9UqftiG7BP8YVDw8OcXv8i95J0ZEkIfdOXFj1Wb6kC/Uu/6VTlAqotVXg==}
/@iconify-json/carbon/1.1.10:
resolution: {integrity: sha512-k3/28wk+2CklUPdKBXWhPHQxquvLGiPYk1s6UWdQYR3YtneHRMuCp+0zc9yNjHYBzoSylMIECO0UPH+SdccguA==}
dependencies:
'@iconify/types': 2.0.0
dev: true

View File

@ -1,7 +1,7 @@
import fs from 'fs-extra'
import type { Client } from 'masto'
import { $fetch } from 'ohmyfetch'
import { APP_NAME } from '~~/constants'
import { APP_NAME } from '~/constants'
import type { AppInfo } from '~/types'
const KNOWN_SERVERS = [
'mastodon.social',
@ -9,26 +9,30 @@ const KNOWN_SERVERS = [
'fosstodon.org',
]
const KNOWN_DOMAINS = [
'http://localhost:3000',
'https://nuxtodon.netlify.app',
]
const filename = 'public/registered-apps.json'
let registeredApps: Record<string, Client> = {}
let registeredApps: Record<string, AppInfo> = {}
if (fs.existsSync(filename))
registeredApps = await fs.readJSON(filename)
for (const server of KNOWN_SERVERS) {
if (registeredApps[server])
continue
const redirect_uris = [
'urn:ietf:wg:oauth:2.0:oob',
...KNOWN_DOMAINS.map(d => `${d}/api/${server}/oauth`),
].join('\n')
if (!registeredApps[server] || registeredApps[server].redirect_uri !== redirect_uris) {
const app = await $fetch(`https://${server}/api/v1/apps`, {
method: 'POST',
body: {
client_name: APP_NAME,
redirect_uris: [
'urn:ietf:wg:oauth:2.0:oob',
'http://localhost:3000/*',
'https://nuxtodon.netlify.app/*',
].join('\n'),
redirect_uris,
scopes: 'read write follow push',
},
})
@ -37,5 +41,6 @@ for (const server of KNOWN_SERVERS) {
console.log(`Registered app for ${server}`)
}
}
await fs.writeJSON(filename, registeredApps, { spaces: 2, EOL: '\n' })

View File

@ -1,29 +1,36 @@
import { getQuery } from 'ufo'
import { stringifyQuery } from 'vue-router'
import { getApp } from '~/server/shared'
import { HOST_DOMAIN } from '~/constants'
export default defineEventHandler(async (event) => {
const server = event.context.params.server
export default defineEventHandler(async ({ context, req, res }) => {
const server = context.params.server
const app = await getApp(server)
if (!app) {
event.res.statusCode = 400
res.statusCode = 400
return `App not registered for server: ${server}`
}
const query = getQuery(event.req.url!)
const query = getQuery(req.url!)
const code = query.code
const res = await $fetch(`https://${server}/oauth/token`, {
const result: any = await $fetch(`https://${server}/oauth/token`, {
method: 'POST',
body: {
client_id: app.client_id,
client_secret: app.client_secret,
redirect_uri: 'urn:ietf:wg:oauth:2.0:oob',
redirect_uri: `${HOST_DOMAIN}/api/${server}/oauth`,
grant_type: 'authorization_code',
code,
scope: 'read write follow push',
},
})
console.log({ res })
res.writeHead(302, {
Location: `${HOST_DOMAIN}/login/callback?${stringifyQuery({ server, token: result.access_token })}`,
})
res.end()
return result
})

View File

@ -1,19 +1,17 @@
import { $fetch } from 'ohmyfetch'
export interface AppInfo {
id: string
name: string
website: string | null
redirect_uri: string
client_id: string
client_secret: string
vapid_key: string
}
import type { AppInfo } from '~/types'
export const registeredApps: Record<string, AppInfo> = {}
const promise = $fetch(process.env.APPS_JSON_URL || 'http://localhost:3000/registered-apps.json')
.then(r => Object.assign(registeredApps, r))
.catch((e) => {
if (process.dev)
console.error('Failed to fetch registered apps,\nyou may need to run `nr register-apps` first')
else
console.error('Failed to fetch registered apps')
console.error(e)
})
export async function getApp(server: string) {
await promise

17
types/index.ts 100644
View File

@ -0,0 +1,17 @@
import type { AccountCredentials } from 'masto'
export interface AppInfo {
id: string
name: string
website: string | null
redirect_uri: string
client_id: string
client_secret: string
vapid_key: string
}
export interface UserLogin {
server: string
token: string
account?: AccountCredentials
}