mirror of
https://github.com/hex248/sprint.git
synced 2026-02-07 18:23:03 +00:00
verification emails and full email setup
This commit is contained in:
@@ -13,4 +13,7 @@ S3_SECRET_ACCESS_KEY=your_secret_access_key
|
||||
S3_BUCKET_NAME=issue
|
||||
|
||||
STRIPE_PUBLISHABLE_KEY=your_stripe_publishable_key
|
||||
STRIPE_SECRET_KEY=your_stripe_secret_key
|
||||
STRIPE_SECRET_KEY=your_stripe_secret_key
|
||||
|
||||
RESEND_API_KEY=re_xxxxxxxxxxxxxxxx
|
||||
EMAIL_FROM=Sprint <support@sprint.ob248.com>
|
||||
28
packages/backend/drizzle/0028_quick_supernaut.sql
Normal file
28
packages/backend/drizzle/0028_quick_supernaut.sql
Normal file
@@ -0,0 +1,28 @@
|
||||
CREATE TABLE "EmailJob" (
|
||||
"id" integer PRIMARY KEY GENERATED ALWAYS AS IDENTITY (sequence name "EmailJob_id_seq" INCREMENT BY 1 MINVALUE 1 MAXVALUE 2147483647 START WITH 1 CACHE 1),
|
||||
"userId" integer NOT NULL,
|
||||
"type" varchar(64) NOT NULL,
|
||||
"scheduledFor" timestamp NOT NULL,
|
||||
"sentAt" timestamp,
|
||||
"failedAt" timestamp,
|
||||
"errorMessage" text,
|
||||
"metadata" json,
|
||||
"createdAt" timestamp DEFAULT now()
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE "EmailVerification" (
|
||||
"id" integer PRIMARY KEY GENERATED ALWAYS AS IDENTITY (sequence name "EmailVerification_id_seq" INCREMENT BY 1 MINVALUE 1 MAXVALUE 2147483647 START WITH 1 CACHE 1),
|
||||
"userId" integer NOT NULL,
|
||||
"code" varchar(6) NOT NULL,
|
||||
"attempts" integer DEFAULT 0 NOT NULL,
|
||||
"maxAttempts" integer DEFAULT 5 NOT NULL,
|
||||
"expiresAt" timestamp NOT NULL,
|
||||
"verifiedAt" timestamp,
|
||||
"createdAt" timestamp DEFAULT now()
|
||||
);
|
||||
--> statement-breakpoint
|
||||
ALTER TABLE "User" ALTER COLUMN "email" SET DATA TYPE varchar(256);--> statement-breakpoint
|
||||
ALTER TABLE "User" ADD COLUMN "emailVerified" boolean DEFAULT false NOT NULL;--> statement-breakpoint
|
||||
ALTER TABLE "User" ADD COLUMN "emailVerifiedAt" timestamp;--> statement-breakpoint
|
||||
ALTER TABLE "EmailJob" ADD CONSTRAINT "EmailJob_userId_User_id_fk" FOREIGN KEY ("userId") REFERENCES "public"."User"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "EmailVerification" ADD CONSTRAINT "EmailVerification_userId_User_id_fk" FOREIGN KEY ("userId") REFERENCES "public"."User"("id") ON DELETE cascade ON UPDATE no action;
|
||||
1354
packages/backend/drizzle/meta/0028_snapshot.json
Normal file
1354
packages/backend/drizzle/meta/0028_snapshot.json
Normal file
File diff suppressed because it is too large
Load Diff
@@ -197,6 +197,13 @@
|
||||
"when": 1769635016079,
|
||||
"tag": "0027_volatile_otto_octavius",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 28,
|
||||
"version": "7",
|
||||
"when": 1769643481882,
|
||||
"tag": "0028_quick_supernaut",
|
||||
"breakpoints": true
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -20,6 +20,8 @@
|
||||
"@types/bun": "latest",
|
||||
"@types/jsonwebtoken": "^9.0.10",
|
||||
"@types/pg": "^8.15.6",
|
||||
"@types/react": "^19.2.10",
|
||||
"@types/react-dom": "^19.2.3",
|
||||
"drizzle-kit": "^0.31.8",
|
||||
"tsx": "^4.21.0"
|
||||
},
|
||||
@@ -27,12 +29,17 @@
|
||||
"typescript": "^5"
|
||||
},
|
||||
"dependencies": {
|
||||
"@react-email/components": "^1.0.6",
|
||||
"@react-email/render": "^2.0.4",
|
||||
"@sprint/shared": "workspace:*",
|
||||
"bcrypt": "^6.0.0",
|
||||
"dotenv": "^17.2.3",
|
||||
"drizzle-orm": "^0.45.0",
|
||||
"jsonwebtoken": "^9.0.3",
|
||||
"pg": "^8.16.3",
|
||||
"react": "^19.2.4",
|
||||
"react-dom": "^19.2.4",
|
||||
"resend": "^6.9.1",
|
||||
"sharp": "^0.34.5",
|
||||
"stripe": "^20.2.0",
|
||||
"zod": "^3.23.8"
|
||||
|
||||
121
packages/backend/src/db/queries/email-verification.ts
Normal file
121
packages/backend/src/db/queries/email-verification.ts
Normal file
@@ -0,0 +1,121 @@
|
||||
import { EmailVerification, type EmailVerificationRecord, User } from "@sprint/shared";
|
||||
import { eq, lt, sql } from "drizzle-orm";
|
||||
import { db } from "../client";
|
||||
|
||||
const CODE_EXPIRY_MINUTES = 15;
|
||||
const MAX_ATTEMPTS = 5;
|
||||
|
||||
export function generateVerificationCode(): string {
|
||||
const bytes = new Uint8Array(4);
|
||||
crypto.getRandomValues(bytes);
|
||||
|
||||
// 6 digit
|
||||
const code = ((bytes[0] ?? 0) * 256 * 256 + (bytes[1] ?? 0) * 256 + (bytes[2] ?? 0)) % 1000000;
|
||||
return code.toString().padStart(6, "0");
|
||||
}
|
||||
|
||||
export async function createVerificationCode(userId: number): Promise<EmailVerificationRecord> {
|
||||
const code = generateVerificationCode();
|
||||
const expiresAt = new Date(Date.now() + CODE_EXPIRY_MINUTES * 60 * 1000);
|
||||
|
||||
// delete existing codes for the user
|
||||
await db.delete(EmailVerification).where(eq(EmailVerification.userId, userId));
|
||||
|
||||
const [verification] = await db
|
||||
.insert(EmailVerification)
|
||||
.values({
|
||||
userId,
|
||||
code,
|
||||
expiresAt,
|
||||
attempts: 0,
|
||||
maxAttempts: MAX_ATTEMPTS,
|
||||
})
|
||||
.returning();
|
||||
|
||||
if (!verification) {
|
||||
throw new Error("Failed to create verification code");
|
||||
}
|
||||
|
||||
return verification;
|
||||
}
|
||||
|
||||
export async function getVerificationByUserId(userId: number): Promise<EmailVerificationRecord | undefined> {
|
||||
const [verification] = await db
|
||||
.select()
|
||||
.from(EmailVerification)
|
||||
.where(eq(EmailVerification.userId, userId));
|
||||
return verification;
|
||||
}
|
||||
|
||||
export async function incrementAttempts(id: number): Promise<void> {
|
||||
await db
|
||||
.update(EmailVerification)
|
||||
.set({
|
||||
attempts: sql`CASE WHEN ${EmailVerification.attempts} IS NULL THEN 1 ELSE ${EmailVerification.attempts} + 1 END`,
|
||||
})
|
||||
.where(eq(EmailVerification.id, id));
|
||||
}
|
||||
|
||||
export async function markAsVerified(id: number): Promise<void> {
|
||||
await db.update(EmailVerification).set({ verifiedAt: new Date() }).where(eq(EmailVerification.id, id));
|
||||
}
|
||||
|
||||
export async function deleteVerification(id: number): Promise<void> {
|
||||
await db.delete(EmailVerification).where(eq(EmailVerification.id, id));
|
||||
}
|
||||
|
||||
export async function deleteUserVerifications(userId: number): Promise<void> {
|
||||
await db.delete(EmailVerification).where(eq(EmailVerification.userId, userId));
|
||||
}
|
||||
|
||||
export async function cleanupExpiredVerifications(): Promise<number> {
|
||||
const result = await db.delete(EmailVerification).where(lt(EmailVerification.expiresAt, new Date()));
|
||||
return result.rowCount ?? 0;
|
||||
}
|
||||
|
||||
export async function verifyCode(
|
||||
userId: number,
|
||||
code: string,
|
||||
): Promise<{ success: boolean; error?: string }> {
|
||||
const verification = await getVerificationByUserId(userId);
|
||||
|
||||
if (!verification) {
|
||||
return { success: false, error: "No verification code found" };
|
||||
}
|
||||
|
||||
if (verification.verifiedAt) {
|
||||
return { success: false, error: "Email already verified" };
|
||||
}
|
||||
|
||||
if (new Date() > verification.expiresAt) {
|
||||
await deleteVerification(verification.id);
|
||||
return { success: false, error: "Verification code expired" };
|
||||
}
|
||||
|
||||
if (verification.attempts >= verification.maxAttempts) {
|
||||
await deleteVerification(verification.id);
|
||||
return { success: false, error: "Too many attempts. Please request a new code." };
|
||||
}
|
||||
|
||||
if (verification.code !== code) {
|
||||
await db
|
||||
.update(EmailVerification)
|
||||
.set({ attempts: verification.attempts + 1 })
|
||||
.where(eq(EmailVerification.id, verification.id));
|
||||
|
||||
const remainingAttempts = verification.maxAttempts - (verification.attempts + 1);
|
||||
return {
|
||||
success: false,
|
||||
error: `Invalid code. ${remainingAttempts} attempts remaining.`,
|
||||
};
|
||||
}
|
||||
|
||||
await db
|
||||
.update(User)
|
||||
.set({ emailVerified: true, emailVerifiedAt: new Date() })
|
||||
.where(eq(User.id, userId));
|
||||
|
||||
await deleteVerification(verification.id);
|
||||
|
||||
return { success: true };
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
export * from "./email-verification";
|
||||
export * from "./issue-comments";
|
||||
export * from "./issues";
|
||||
export * from "./organisations";
|
||||
|
||||
1
packages/backend/src/emails/index.ts
Normal file
1
packages/backend/src/emails/index.ts
Normal file
@@ -0,0 +1 @@
|
||||
export { VerificationCode } from "./templates/VerificationCode";
|
||||
@@ -0,0 +1,3 @@
|
||||
export function VerificationCode({ code }: { code: string }) {
|
||||
return <body>{code}</body>;
|
||||
}
|
||||
@@ -41,6 +41,8 @@ const main = async () => {
|
||||
"/auth/login": withGlobal(routes.authLogin),
|
||||
"/auth/logout": withGlobalAuthed(withAuth(withCSRF(routes.authLogout))),
|
||||
"/auth/me": withGlobalAuthed(withAuth(routes.authMe)),
|
||||
"/auth/verify-email": withGlobalAuthed(withAuth(withCSRF(routes.authVerifyEmail))),
|
||||
"/auth/resend-verification": withGlobalAuthed(withAuth(withCSRF(routes.authResendVerification))),
|
||||
|
||||
"/user/by-username": withGlobalAuthed(withAuth(routes.userByUsername)),
|
||||
"/user/update": withGlobalAuthed(withAuth(withCSRF(routes.userUpdate))),
|
||||
|
||||
54
packages/backend/src/lib/email/service.ts
Normal file
54
packages/backend/src/lib/email/service.ts
Normal file
@@ -0,0 +1,54 @@
|
||||
import { render } from "@react-email/render";
|
||||
import type React from "react";
|
||||
import { Resend } from "resend";
|
||||
|
||||
const resend = new Resend(process.env.RESEND_API_KEY);
|
||||
|
||||
const FROM_EMAIL = process.env.EMAIL_FROM || "Sprint <noreply@sprint.app>";
|
||||
|
||||
export interface SendEmailOptions {
|
||||
to: string;
|
||||
subject: string;
|
||||
template: React.ReactElement;
|
||||
from?: string;
|
||||
}
|
||||
|
||||
export async function sendEmail({ to, subject, template, from }: SendEmailOptions) {
|
||||
const html = await render(template);
|
||||
|
||||
const { data, error } = await resend.emails.send({
|
||||
from: from || FROM_EMAIL,
|
||||
to,
|
||||
subject,
|
||||
html,
|
||||
});
|
||||
|
||||
if (error) {
|
||||
console.error("Failed to send email:", error);
|
||||
throw new Error(`Email send failed: ${error.message}`);
|
||||
}
|
||||
|
||||
return data;
|
||||
}
|
||||
|
||||
export async function sendEmailWithRetry(
|
||||
options: SendEmailOptions,
|
||||
maxRetries = 3,
|
||||
): Promise<ReturnType<typeof sendEmail>> {
|
||||
let lastError: Error | undefined;
|
||||
|
||||
for (let attempt = 1; attempt <= maxRetries; attempt++) {
|
||||
try {
|
||||
return await sendEmail(options);
|
||||
} catch (error) {
|
||||
lastError = error as Error;
|
||||
console.warn(`Email send attempt ${attempt} failed:`, error);
|
||||
|
||||
if (attempt < maxRetries) {
|
||||
await new Promise((resolve) => setTimeout(resolve, 1000 * 2 ** (attempt - 1)));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
throw lastError || new Error("Email send failed after all retries");
|
||||
}
|
||||
@@ -39,6 +39,7 @@ export default async function login(req: BunRequest) {
|
||||
username: user.username,
|
||||
avatarURL: user.avatarURL,
|
||||
iconPreference: user.iconPreference,
|
||||
emailVerified: user.emailVerified,
|
||||
},
|
||||
csrfToken: session.csrfToken,
|
||||
}),
|
||||
|
||||
@@ -13,5 +13,6 @@ export default async function me(req: AuthedRequest) {
|
||||
return Response.json({
|
||||
user: safeUser as Omit<UserRecord, "passwordHash">,
|
||||
csrfToken: req.csrfToken,
|
||||
emailVerified: user.emailVerified,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
import { RegisterRequestSchema } from "@sprint/shared";
|
||||
import type { BunRequest } from "bun";
|
||||
import { buildAuthCookie, generateToken, hashPassword } from "../../auth/utils";
|
||||
import { createSession, createUser, getUserByUsername } from "../../db/queries";
|
||||
import { createSession, createUser, createVerificationCode, getUserByUsername } from "../../db/queries";
|
||||
import { getUserByEmail } from "../../db/queries/users";
|
||||
import { VerificationCode } from "../../emails";
|
||||
import { sendEmailWithRetry } from "../../lib/email/service";
|
||||
import { errorResponse, parseJsonBody } from "../../validation";
|
||||
|
||||
export default async function register(req: BunRequest) {
|
||||
@@ -36,6 +38,19 @@ export default async function register(req: BunRequest) {
|
||||
return errorResponse("failed to create session", "SESSION_ERROR", 500);
|
||||
}
|
||||
|
||||
const verification = await createVerificationCode(user.id);
|
||||
|
||||
try {
|
||||
await sendEmailWithRetry({
|
||||
to: user.email,
|
||||
subject: "Verify your Sprint account",
|
||||
template: VerificationCode({ code: verification.code }),
|
||||
});
|
||||
} catch (error) {
|
||||
console.error("Failed to send verification email:", error);
|
||||
// don't fail registration if email fails - user can resend
|
||||
}
|
||||
|
||||
const token = generateToken(session.id, user.id);
|
||||
|
||||
return new Response(
|
||||
@@ -46,6 +61,7 @@ export default async function register(req: BunRequest) {
|
||||
username: user.username,
|
||||
avatarURL: user.avatarURL,
|
||||
iconPreference: user.iconPreference,
|
||||
emailVerified: user.emailVerified,
|
||||
},
|
||||
csrfToken: session.csrfToken,
|
||||
}),
|
||||
|
||||
69
packages/backend/src/routes/auth/resend-verification.ts
Normal file
69
packages/backend/src/routes/auth/resend-verification.ts
Normal file
@@ -0,0 +1,69 @@
|
||||
import type { BunRequest } from "bun";
|
||||
import type { AuthedRequest } from "../../auth/middleware";
|
||||
import { createVerificationCode } from "../../db/queries";
|
||||
import { getUserById } from "../../db/queries/users";
|
||||
import { VerificationCode } from "../../emails";
|
||||
import { sendEmailWithRetry } from "../../lib/email/service";
|
||||
import { errorResponse } from "../../validation";
|
||||
|
||||
const resendAttempts = new Map<number, number[]>();
|
||||
|
||||
const MAX_RESENDS_PER_HOUR = 3;
|
||||
const HOUR_IN_MS = 60 * 60 * 1000;
|
||||
|
||||
function canResend(userId: number): boolean {
|
||||
const now = Date.now();
|
||||
const attempts = resendAttempts.get(userId) || [];
|
||||
|
||||
const recentAttempts = attempts.filter((time) => now - time < HOUR_IN_MS);
|
||||
|
||||
if (recentAttempts.length >= MAX_RESENDS_PER_HOUR) {
|
||||
return false;
|
||||
}
|
||||
|
||||
recentAttempts.push(now);
|
||||
resendAttempts.set(userId, recentAttempts);
|
||||
return true;
|
||||
}
|
||||
|
||||
export default async function resendVerification(req: BunRequest | AuthedRequest) {
|
||||
if (req.method !== "POST") {
|
||||
return errorResponse("method not allowed", "METHOD_NOT_ALLOWED", 405);
|
||||
}
|
||||
|
||||
const authedReq = req as AuthedRequest;
|
||||
if (!authedReq.userId) {
|
||||
return errorResponse("unauthorized", "UNAUTHORIZED", 401);
|
||||
}
|
||||
|
||||
if (!canResend(authedReq.userId)) {
|
||||
return errorResponse("too many resend attempts. please try again later", "RATE_LIMITED", 429);
|
||||
}
|
||||
|
||||
const user = await getUserById(authedReq.userId);
|
||||
if (!user) {
|
||||
return errorResponse("user not found", "USER_NOT_FOUND", 404);
|
||||
}
|
||||
|
||||
if (user.emailVerified) {
|
||||
return errorResponse("email already verified", "ALREADY_VERIFIED", 400);
|
||||
}
|
||||
|
||||
const verification = await createVerificationCode(user.id);
|
||||
|
||||
try {
|
||||
await sendEmailWithRetry({
|
||||
to: user.email,
|
||||
subject: "Verify your Sprint account",
|
||||
template: VerificationCode({ code: verification.code }),
|
||||
});
|
||||
} catch (error) {
|
||||
console.error("Failed to send verification email:", error);
|
||||
return errorResponse("failed to send verification email", "EMAIL_SEND_FAILED", 500);
|
||||
}
|
||||
|
||||
return new Response(JSON.stringify({ success: true }), {
|
||||
status: 200,
|
||||
headers: { "Content-Type": "application/json" },
|
||||
});
|
||||
}
|
||||
32
packages/backend/src/routes/auth/verify-email.ts
Normal file
32
packages/backend/src/routes/auth/verify-email.ts
Normal file
@@ -0,0 +1,32 @@
|
||||
import { VerifyEmailRequestSchema } from "@sprint/shared";
|
||||
import type { BunRequest } from "bun";
|
||||
import type { AuthedRequest } from "../../auth/middleware";
|
||||
import { verifyCode } from "../../db/queries";
|
||||
import { errorResponse, parseJsonBody } from "../../validation";
|
||||
|
||||
export default async function verifyEmail(req: BunRequest | AuthedRequest) {
|
||||
if (req.method !== "POST") {
|
||||
return errorResponse("method not allowed", "METHOD_NOT_ALLOWED", 405);
|
||||
}
|
||||
|
||||
const authedReq = req as AuthedRequest;
|
||||
if (!authedReq.userId) {
|
||||
return errorResponse("unauthorized", "UNAUTHORIZED", 401);
|
||||
}
|
||||
|
||||
const parsed = await parseJsonBody(req, VerifyEmailRequestSchema);
|
||||
if ("error" in parsed) return parsed.error;
|
||||
|
||||
const { code } = parsed.data;
|
||||
|
||||
const result = await verifyCode(authedReq.userId, code);
|
||||
|
||||
if (!result.success) {
|
||||
return errorResponse(result.error || "verification failed", "VERIFICATION_FAILED", 400);
|
||||
}
|
||||
|
||||
return new Response(JSON.stringify({ success: true }), {
|
||||
status: 200,
|
||||
headers: { "Content-Type": "application/json" },
|
||||
});
|
||||
}
|
||||
@@ -2,6 +2,8 @@ import authLogin from "./auth/login";
|
||||
import authLogout from "./auth/logout";
|
||||
import authMe from "./auth/me";
|
||||
import authRegister from "./auth/register";
|
||||
import authResendVerification from "./auth/resend-verification";
|
||||
import authVerifyEmail from "./auth/verify-email";
|
||||
import issueById from "./issue/by-id";
|
||||
import issueCreate from "./issue/create";
|
||||
import issueDelete from "./issue/delete";
|
||||
@@ -57,6 +59,8 @@ export const routes = {
|
||||
authLogin,
|
||||
authLogout,
|
||||
authMe,
|
||||
authVerifyEmail,
|
||||
authResendVerification,
|
||||
|
||||
userByUsername,
|
||||
userUpdate,
|
||||
|
||||
Reference in New Issue
Block a user