Graphical PDS migrator for AT Protocol
1import { Agent } from "npm:@atproto/api"; 2import { CredentialSession, OauthSession } from "./types.ts"; 3import { 4 getCredentialSession, 5 getCredentialSessionAgent, 6} from "./cred/sessions.ts"; 7import { getOauthSession, getOauthSessionAgent } from "./oauth/sessions.ts"; 8import { IronSession } from "npm:iron-session"; 9 10/** 11 * Get the session for the given request. 12 * @param req - The request object 13 * @param res - The response object 14 * @param isMigration - Whether to get the migration session 15 * @returns The session 16 */ 17export async function getSession( 18 req: Request, 19 res: Response = new Response(), 20 isMigration: boolean = false, 21): Promise<IronSession<OauthSession | CredentialSession>> { 22 if (isMigration) { 23 return await getCredentialSession(req, res, true); 24 } 25 const oauthSession = await getOauthSession(req); 26 const credentialSession = await getCredentialSession(req, res); 27 28 if (oauthSession.did) { 29 console.log("Oauth session found"); 30 return oauthSession; 31 } 32 if (credentialSession.did) { 33 return credentialSession; 34 } 35 36 throw new Error("No session found"); 37} 38 39/** 40 * Get the session agent for the given request. 41 * @param req - The request object 42 * @param res - The response object 43 * @param isMigration - Whether to get the migration session 44 * @returns The session agent 45 */ 46export async function getSessionAgent( 47 req: Request, 48 res: Response = new Response(), 49 isMigration: boolean = false, 50): Promise<Agent | null> { 51 if (isMigration) { 52 return await getCredentialSessionAgent(req, res, isMigration); 53 } 54 55 const oauthAgent = await getOauthSessionAgent(req); 56 const credentialAgent = await getCredentialSessionAgent( 57 req, 58 res, 59 isMigration, 60 ); 61 62 if (oauthAgent) { 63 return oauthAgent; 64 } 65 66 if (credentialAgent) { 67 return credentialAgent; 68 } 69 70 return null; 71} 72 73/** 74 * Destroy all sessions for the given request. 75 * @param req - The request object 76 * @param res - The response object 77 */ 78export async function destroyAllSessions( 79 req: Request, 80 res?: Response, 81): Promise<Response> { 82 const response = res || new Response(); 83 const oauthSession = await getOauthSession(req, response); 84 const credentialSession = await getCredentialSession(req, res); 85 const migrationSession = await getCredentialSession( 86 req, 87 res, 88 true, 89 ); 90 91 if (oauthSession.did) { 92 oauthSession.destroy(); 93 } 94 if (credentialSession.did) { 95 credentialSession.destroy(); 96 } 97 if (migrationSession.did) { 98 console.log("DESTROYING MIGRATION SESSION", migrationSession); 99 migrationSession.destroy(); 100 } else { 101 console.log("MIGRATION SESSION NOT FOUND", migrationSession); 102 } 103 104 return response; 105}