Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

not working #3

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
167 changes: 141 additions & 26 deletions package-lock.json

Large diffs are not rendered by default.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@
},
"devDependencies": {
"@types/node": "^20",
"@types/nodemailer": "^6.4.15",
"@types/react": "^18",
"@types/react-dom": "^18",
"eslint": "^8",
Expand Down
14 changes: 14 additions & 0 deletions prisma/schema.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ model User {
googleId String? @unique
avatarUrl String?
bio String?
emailVerified Boolean @default(false)
sessions Session[]
posts Post[]
following Follow[] @relation("Following")
Expand All @@ -33,12 +34,25 @@ model User {
comments Comment[]
receivedNotifications Notification[] @relation("Recipient")
issuedNotifications Notification[] @relation("Issuer")
emailVerificationCodes EmailVerificationCode[]

createdAt DateTime @default(now())

@@map("users")
}

model EmailVerificationCode {
id String @id @default(cuid())
code String
userId String
email String
expiresAt DateTime
user User @relation(fields: [userId], references: [id], onDelete: Cascade)

@@map("email_verification_codes")
}


model Session {
id String @id
userId String
Expand Down
13 changes: 8 additions & 5 deletions src/app/(auth)/signup/actions.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
//actions.ts
"use server";

import { lucia } from "@/auth";
Expand All @@ -9,10 +8,10 @@ import { generateIdFromEntropySize } from "lucia";
import { isRedirectError } from "next/dist/client/components/redirect";
import { cookies } from "next/headers";
import { redirect } from "next/navigation";
import { sendVerificationCode } from "@/lib/mailer";
import { generateEmailVerificationCode } from "@/lib/generateEmailVerificationCode";

export async function signUp(
credentials: SignUpValues,
): Promise<{ error: string }> {
export async function signUp(credentials: SignUpValues): Promise<{ error: string }> {
try {
const { username, email, password } = signUpSchema.parse(credentials);

Expand Down Expand Up @@ -62,9 +61,13 @@ export async function signUp(
displayName: username,
email,
passwordHash,
emailVerified: false,
},
});

const verificationCode = await generateEmailVerificationCode(userId, email);
await sendVerificationCode(email, verificationCode);

const session = await lucia.createSession(userId, {});
const sessionCookie = lucia.createSessionCookie(session.id);
cookies().set(
Expand All @@ -76,7 +79,7 @@ export async function signUp(
return redirect("/");
} catch (error) {
if (isRedirectError(error)) throw error;
console.error(error);
console.error("Sign up error: ", error);
return {
error: "Something went wrong. Please try again.",
};
Expand Down
39 changes: 39 additions & 0 deletions src/app/(auth)/vertification/VerifyEmailForm.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
"use client";

import { useState, useTransition } from "react";
import { useForm } from "react-hook-form";
import { Input } from "@/components/ui/input";
import LoadingButton from "@/components/LoadingButton";

export default function VerifyEmailForm() {
const [error, setError] = useState<string>();
const [isPending, startTransition] = useTransition();
const form = useForm<{ code: string }>({
defaultValues: { code: "" },
});

async function onSubmit({ code }: { code: string }) {
setError(undefined);
startTransition(async () => {
const res = await fetch("/api/verify-email", {
method: "POST",
body: JSON.stringify({ code }),
headers: {
"Content-Type": "application/json",
},
});
const { success, error } = await res.json();
if (!success) setError(error);
});
}

return (
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-3">
{error && <p className="text-center text-destructive">{error}</p>}
<Input {...form.register("code")} placeholder="Verification Code" />
<LoadingButton loading={isPending} type="submit" className="w-full">
Verify Email
</LoadingButton>
</form>
);
}
18 changes: 18 additions & 0 deletions src/app/api/verification/verify-email.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { NextApiRequest, NextApiResponse } from "next";
import { verifyEmailVerificationCode } from "@/lib/email-verification";

export default async function handler(req: NextApiRequest, res: NextApiResponse) {
const { code, userId } = req.body;

try {
const success = await verifyEmailVerificationCode(userId, code);
if (success) {
res.status(200).json({ success: true });
} else {
res.status(400).json({ success: false, error: "Invalid or expired verification code" });
}
} catch (error) {
console.error("Verification error: ", error);
res.status(500).json({ success: false, error: "Internal server error" });
}
}
27 changes: 27 additions & 0 deletions src/lib/email-verification.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import prisma from "@/lib/prisma";
import { isWithinExpirationDate } from "oslo";

export async function verifyEmailVerificationCode(userId: string, code: string): Promise<boolean> {
const verificationCode = await prisma.emailVerificationCode.findFirst({
where: { userId }
});

if (!verificationCode || verificationCode.code !== code) {
return false;
}

if (!isWithinExpirationDate(verificationCode.expiresAt)) {
return false;
}

await prisma.emailVerificationCode.delete({
where: { id: verificationCode.id }
});

await prisma.user.update({
where: { id: userId },
data: { emailVerified: true }
});

return true;
}
23 changes: 23 additions & 0 deletions src/lib/generateEmailVerificationCode.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { PrismaClient } from '@prisma/client';
import { TimeSpan, createDate } from "oslo";
import { generateRandomString, alphabet } from "oslo/crypto";

const prisma = new PrismaClient();

export async function generateEmailVerificationCode(userId: string, email: string): Promise<string> {
await prisma.emailVerificationCode.deleteMany({
where: { userId }
});

const code = generateRandomString(6, alphabet("0-9")); // Adjusted length
await prisma.emailVerificationCode.create({
data: {
userId,
email,
code,
expiresAt: createDate(new TimeSpan(15, "m")) // 15 minutes
}
});

return code;
}
26 changes: 26 additions & 0 deletions src/lib/mailer.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
// lib/mailer.ts
import nodemailer from "nodemailer";

const transporter = nodemailer.createTransport({
host: 'smtp.office365.com', // Outlook SMTP server
port: 587, // SMTP port
secure: false, // Use TLS
auth: {
user: process.env.OUTLOOK_USER, // Your Outlook email address
pass: process.env.OUTLOOK_PASS, // Your Outlook password
},
tls: {
ciphers: 'SSLv3'
}
});

export async function sendVerificationCode(email: string, code: string) {
const mailOptions = {
from: process.env.OUTLOOK_USER,
to: email,
subject: 'Email Verification Code',
text: `Your email verification code is ${code}`,
};

await transporter.sendMail(mailOptions);
}
67 changes: 67 additions & 0 deletions src/nodemailer.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
declare module 'nodemailer' {
import * as Transport from 'nodemailer/lib/mailer';
import SMTPTransport from 'nodemailer/lib/smtp-transport';

export function createTransport(options: SMTPTransport.Options): Transport;

export interface SentMessageInfo {
envelope: { from: string; to: string[] };
messageId: string;
accepted: string[];
rejected: string[];
pending: string[];
response: string;
}

export namespace createTestAccount {
function createTestAccount(callback: (err: Error | null, testAccount: TestAccount) => void): void;
function createTestAccount(): Promise<TestAccount>;
}

export interface TestAccount {
user: string;
pass: string;
smtp: SMTPTransport.Options;
imap: any;
pop3: any;
web: string;
}

export interface Transporter<SentMessageInfo = any> {
sendMail(mailOptions: SendMailOptions, callback: (err: Error | null, info: SentMessageInfo) => void): void;
sendMail(mailOptions: SendMailOptions): Promise<SentMessageInfo>;
verify(callback: (err: Error | null, success: true) => void): void;
verify(): Promise<true>;
}

export interface SendMailOptions {
from?: string | Address;
to?: string | Address | Array<string | Address>;
cc?: string | Address | Array<string | Address>;
bcc?: string | Address | Array<string | Address>;
subject?: string;
text?: string;
html?: string | Buffer | Readable;
attachments?: Attachment[];
[key: string]: any;
}

export interface Address {
name: string;
address: string;
}

export interface Attachment {
filename?: string;
content?: string | Buffer | Readable;
path?: string | Url;
href?: string;
contentType?: string;
encoding?: string;
contentDisposition?: string;
cid?: string;
raw?: string | Buffer | Readable;
[key: string]: any;
}
}

1 change: 1 addition & 0 deletions tsconfig.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
{
"compilerOptions": {
"target": "ES2017",
"typeRoots": ["./node_modules/@types", "./types"],
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
Expand Down