Simple vanilia JS vite project with ATProto OAuth out of the box
at main 1.9 kB view raw
1import './style.css' 2import { 3 AtprotoDohHandleResolver, 4 atprotoLoopbackClientMetadata, 5 BrowserOAuthClient 6} from '@atproto/oauth-client-browser' 7import {showError, showLoggedInPage, showLoginForm} from "./ui.js"; 8import { Agent } from '@atproto/api' 9import clientMetadataUrl from '/oauth-client-metadata.json?url' 10 11// For localhost development 12const scopes = ['atproto', 'transition:generic'] 13const redirectUri = 'http://127.0.0.1:5173/callback' 14const devClientId = `http://localhost?redirect_uri=${encodeURIComponent(redirectUri)}&scope=${encodeURIComponent(scopes.join(' '))}` 15 16//Can be any dns over http. 17const resolver = new AtprotoDohHandleResolver({dohEndpoint: 'https://cloudflare-dns.com/dns-query'}); 18 19 20const client = await BrowserOAuthClient.load({ 21 handleResolver: resolver, 22 // clientId: `${location.origin}${clientMetadataUrl}` 23 clientId: import.meta.env.VITE_OAUTH_DOMAIN ? `https://${import.meta.env.VITE_OAUTH_DOMAIN}${clientMetadataUrl}` : devClientId 24}) 25 26 27window.oauthClient = client 28 29try { 30 const result = await client.init() 31 //If a result is set and there is a session, the user is authenticated or was a successful callback 32 if (result) { 33 const {session, state} = result 34 if (state != null) { 35 console.log( 36 `${session.sub} was successfully authenticated (state: ${state})`, 37 ) 38 } else { 39 console.log(`${session.sub} was restored (last active session)`) 40 } 41 if (session) { 42 //This is what actually makes authenticated atproto requests 43 window.atpAgent = new Agent(session) 44 //Shows the logged in ui page 45 await showLoggedInPage(session) 46 } 47 } else { 48 //Shows the login form 49 showLoginForm() 50 } 51} 52catch (error) { 53 console.error('OAuth client initialization error:', error) 54 showError(error.message) 55}