Spaces:
Paused
Paused
File size: 2,010 Bytes
abc1805 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 | "use server";
import { auth } from "@/auth";
import User from "@/models/User";
import dbConnect from "@/lib/db";
import { generateTwoFactorSecret, verifyTwoFactorToken } from "@/lib/tokens";
export const getTwoFactorStatus = async () => {
const session = await auth();
if (!session?.user?.email) return { error: "Unauthorized" };
await dbConnect();
const user = await User.findOne({ email: session.user.email });
return { isEnabled: user?.isTwoFactorEnabled };
};
export const enableTwoFactor = async () => {
const session = await auth();
if (!session?.user?.email) return { error: "Unauthorized" };
await dbConnect();
const user = await User.findOne({ email: session.user.email });
if (!user) return { error: "User not found" };
const { secret, qrCodeUrl } = await generateTwoFactorSecret(user.email);
user.twoFactorSecret = secret;
await user.save();
return { secret, qrCodeUrl };
};
export const confirmTwoFactor = async (token: string) => {
const session = await auth();
if (!session?.user?.email) return { error: "Unauthorized" };
await dbConnect();
const user = await User.findOne({ email: session.user.email });
if (!user || !user.twoFactorSecret) return { error: "User not found or 2FA not initiated" };
const isValid = verifyTwoFactorToken(token, user.twoFactorSecret);
if (!isValid) return { error: "Invalid token" };
user.isTwoFactorEnabled = true;
await user.save();
return { success: true };
};
export const disableTwoFactor = async () => {
const session = await auth();
if (!session?.user?.email) return { error: "Unauthorized" };
await dbConnect();
const user = await User.findOne({ email: session.user.email });
if (!user) return { error: "User not found" };
user.isTwoFactorEnabled = false;
user.twoFactorSecret = undefined;
await user.save();
return { success: true };
};
|