feat: complete admin invite and user creation and recovery flows
This commit is contained in:
@@ -0,0 +1,40 @@
|
||||
import { and, eq, sql } from 'drizzle-orm';
|
||||
import { providers } from '~~/drizzle/schema';
|
||||
import { db } from '~~/server/lib/db';
|
||||
|
||||
/**
|
||||
* Tells the recovery page whether a link still works and what using it will
|
||||
* do: set the first password of a new account, or replace a forgotten one. Public on purpose: whoever opens it cannot sign in, that is the point.
|
||||
*/
|
||||
export default defineEventHandler(async (event) => {
|
||||
const link = await findRecoveryLink(getRouterParam(event, 'token')!);
|
||||
|
||||
if (!link) {
|
||||
return { valid: false as const };
|
||||
}
|
||||
|
||||
// an account that never had a password is being set up, not recovered
|
||||
if (!await hasPassword(link.userId)) {
|
||||
return {
|
||||
valid: true as const,
|
||||
newAccount: true as const,
|
||||
email: link.email,
|
||||
name: link.name,
|
||||
};
|
||||
}
|
||||
|
||||
const withKey = await db
|
||||
.select({ name: providers.name })
|
||||
.from(providers)
|
||||
.where(and(eq(providers.userId, link.userId), sql`coalesce(${providers.config}->>'apiKey', '') <> ''`));
|
||||
|
||||
return {
|
||||
valid: true as const,
|
||||
newAccount: false as const,
|
||||
email: link.email,
|
||||
// the providers whose saved key is lost when the link is used
|
||||
keyProviders: withKey.map(p => p.name),
|
||||
resetSecurity: link.resetSecurity,
|
||||
twoFactorEnabled: !!link.twoFactorEnabled,
|
||||
};
|
||||
});
|
||||
@@ -0,0 +1,95 @@
|
||||
import { and, eq, gt, sql } from 'drizzle-orm';
|
||||
import * as z from 'zod';
|
||||
import { providers, recoveryLinks, sessions, twoFactors, users } from '~~/drizzle/schema';
|
||||
import { auth } from '~~/lib/auth';
|
||||
import { db } from '~~/server/lib/db';
|
||||
|
||||
/**
|
||||
* Sets a password with a one-time link.
|
||||
*
|
||||
* For an account an admin just created this is its first password, and there
|
||||
* is nothing else to do. For a forgotten password it is a recovery:
|
||||
*
|
||||
* The saved API keys are encrypted with a key derived from the old password.
|
||||
* Nobody has that password anymore, so the keys can never be read again and
|
||||
* are deleted here. Chats, agents, files and everything else stay.
|
||||
*/
|
||||
export default defineEventHandler(async (event) => {
|
||||
const result = await readValidatedBody(event, (body) =>
|
||||
z
|
||||
.object({
|
||||
password: z.string().min(8).max(128),
|
||||
})
|
||||
.safeParse(body),
|
||||
);
|
||||
|
||||
if (!result.success) {
|
||||
throw createError({
|
||||
statusCode: 400,
|
||||
message: result.error.issues[0]!.message,
|
||||
data: {
|
||||
code: 'INVALID_BODY',
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
const tokenHash = hashRecoveryToken(getRouterParam(event, 'token')!);
|
||||
const { password } = result.data;
|
||||
|
||||
const { password: hasher, internalAdapter } = await auth.$context;
|
||||
const passwordHash = await hasher.hash(password);
|
||||
|
||||
const recovered = await db.transaction(async (tx) => {
|
||||
// deleting the link is what makes it work once: of two requests with
|
||||
// the same link only one gets a row back
|
||||
const [link] = await tx.delete(recoveryLinks)
|
||||
.where(and(eq(recoveryLinks.tokenHash, tokenHash), gt(recoveryLinks.expiresAt, new Date())))
|
||||
.returning({ userId: recoveryLinks.userId, resetSecurity: recoveryLinks.resetSecurity });
|
||||
|
||||
if (!link) return null;
|
||||
|
||||
// if either of these fails the link comes back with the rest of the
|
||||
// transaction
|
||||
if (!await hasPassword(link.userId)) {
|
||||
await internalAdapter.linkAccount({
|
||||
providerId: 'credential',
|
||||
accountId: link.userId,
|
||||
password: passwordHash,
|
||||
userId: link.userId,
|
||||
});
|
||||
|
||||
return 'created';
|
||||
}
|
||||
|
||||
await internalAdapter.updatePassword(link.userId, passwordHash);
|
||||
|
||||
// A provider without its key can't be used, so it is switched off
|
||||
// until the key is entered again. The provider and its models stay.
|
||||
await tx.update(providers)
|
||||
.set({
|
||||
config: sql`${providers.config} - 'apiKey'`,
|
||||
enabled: false,
|
||||
})
|
||||
.where(and(eq(providers.userId, link.userId), sql`coalesce(${providers.config}->>'apiKey', '') <> ''`));
|
||||
|
||||
if (link.resetSecurity) {
|
||||
await tx.delete(twoFactors).where(eq(twoFactors.userId, link.userId));
|
||||
await tx.update(users).set({ twoFactorEnabled: false }).where(eq(users.id, link.userId));
|
||||
await tx.delete(sessions).where(eq(sessions.userId, link.userId));
|
||||
}
|
||||
|
||||
return 'recovered';
|
||||
});
|
||||
|
||||
if (recovered === null) {
|
||||
throw createError({
|
||||
statusCode: 410,
|
||||
statusMessage: 'This recovery link is not valid anymore',
|
||||
data: {
|
||||
code: 'RECOVERY_LINK_INVALID',
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
return { newAccount: recovered === 'created' };
|
||||
});
|
||||
Reference in New Issue
Block a user