Skip to content

armgit / dub

Public Imported from GitHub
0

The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.

lock account wip

Kiran K193218336c44
diff --git a/apps/web/app/api/user/set-password/route.ts b/apps/web/app/api/user/set-password/route.ts
index c4f69be0d6..ac3d012c56 100644
--- a/apps/web/app/api/user/set-password/route.ts
+++ b/apps/web/app/api/user/set-password/route.ts
@@ -1,6 +1,6 @@
import { DubApiError } from "@/lib/api/errors";
import { withSession } from "@/lib/auth";
-import { PASSWORD_RESET_TOKEN_EXPIRY } from "@/lib/auth/password";
+import { PASSWORD_RESET_TOKEN_EXPIRY } from "@/lib/auth/constants";
import { prisma } from "@/lib/prisma";
import { randomBytes } from "crypto";
import { sendEmail } from "emails";
diff --git a/apps/web/app/app.dub.co/(auth)/login/signin-email-password.tsx b/apps/web/app/app.dub.co/(auth)/login/signin-email-password.tsx
index 0456eee9ba..37075b9705 100644
--- a/apps/web/app/app.dub.co/(auth)/login/signin-email-password.tsx
+++ b/apps/web/app/app.dub.co/(auth)/login/signin-email-password.tsx
@@ -11,6 +11,8 @@ import { toast } from "sonner";
const errorCodes = {
"no-credentials": "Please provide an email and password.",
"invalid-credentials": "Email or password is incorrect.",
+ "exceeded-login-attempts":
+ "Account has been locked due to too many login attempts. Please contact support to unlock your account.",
};
export const SignInWithEmailPassword = () => {
@@ -19,6 +21,7 @@ export const SignInWithEmailPassword = () => {
const {
register,
+ resetField,
handleSubmit,
formState: { isLoading, isSubmitting },
} = useForm<z.infer<typeof signInSchema>>({
@@ -38,6 +41,7 @@ export const SignInWithEmailPassword = () => {
}
if (!response.ok && response.error) {
+ resetField("password");
throw new Error(errorCodes[response.error]);
}
diff --git a/apps/web/lib/auth/constants.ts b/apps/web/lib/auth/constants.ts
new file mode 100644
index 0000000000..9218a9c057
--- /dev/null
+++ b/apps/web/lib/auth/constants.ts
@@ -0,0 +1,5 @@
+export const PASSWORD_RESET_TOKEN_EXPIRY = 1 * 60 * 60; // 1 hour
+
+export const ACCOUN_LOCK_DURATION = 24 * 60 * 60; // 24 hours
+
+export const MAX_LOGIN_ATTEMPTS = 10;
diff --git a/apps/web/lib/auth/lock-account.ts b/apps/web/lib/auth/lock-account.ts
new file mode 100644
index 0000000000..f7ee4e3e86
--- /dev/null
+++ b/apps/web/lib/auth/lock-account.ts
@@ -0,0 +1,63 @@
+import { prisma } from "@/lib/prisma";
+import { User } from "@prisma/client";
+import { ACCOUN_LOCK_DURATION, MAX_LOGIN_ATTEMPTS } from "./constants";
+
+export const incrementLoginAttempts = async (
+ user: Pick<User, "id" | "email">,
+) => {
+ const { invalidLoginAttempts, lockedUntil } = await prisma.user.update({
+ where: { id: user.id },
+ data: {
+ invalidLoginAttempts: {
+ increment: 1,
+ },
+ },
+ select: {
+ lockedUntil: true,
+ invalidLoginAttempts: true,
+ },
+ });
+
+ if (!lockedUntil && invalidLoginAttempts >= MAX_LOGIN_ATTEMPTS) {
+ await prisma.user.update({
+ where: { id: user.id },
+ data: {
+ lockedUntil: new Date(Date.now() + ACCOUN_LOCK_DURATION * 1000),
+ },
+ });
+
+ // TODO:
+ // Send email to user that their account has been locked
+ }
+
+ return {
+ invalidLoginAttempts,
+ lockedUntil,
+ };
+};
+
+export const resetLoginAttempts = async (userId: string) => {
+ await prisma.user.update({
+ where: { id: userId },
+ data: {
+ invalidLoginAttempts: 0,
+ },
+ });
+};
+
+export const isAccountLocked = async (userId: string) => {
+ const { lockedUntil } = await prisma.user.findUniqueOrThrow({
+ where: { id: userId },
+ select: {
+ lockedUntil: true,
+ },
+ });
+
+ return lockedUntil && lockedUntil > new Date();
+};
+
+export const exceededLoginAttemptsThreshold = (
+ user: Pick<User, "invalidLoginAttempts">,
+) => {
+ return user.invalidLoginAttempts >= MAX_LOGIN_ATTEMPTS;
+};
diff --git a/apps/web/lib/auth/options.ts b/apps/web/lib/auth/options.ts
index 4b9d323040..502d5fa02b 100644
--- a/apps/web/lib/auth/options.ts
+++ b/apps/web/lib/auth/options.ts
@@ -17,6 +17,11 @@ import { dub } from "../dub";
import { subscribe } from "../flodesk";
import { isStored, storage } from "../storage";
import { UserProps } from "../types";
+import {
+ exceededLoginAttemptsThreshold,
+ incrementLoginAttempts,
+ resetLoginAttempts,
+} from "./lock-account";
import { validatePassword } from "./password";
const VERCEL_DEPLOYMENT = !!process.env.VERCEL_URL;
@@ -195,6 +200,7 @@ export const authOptions: NextAuthOptions = {
name: true,
email: true,
image: true,
+ invalidLoginAttempts: true,
},
});
@@ -202,15 +208,29 @@ export const authOptions: NextAuthOptions = {
throw new Error("invalid-credentials");
}
+ if (exceededLoginAttemptsThreshold(user)) {
+ throw new Error("exceeded-login-attempts");
+ }
+
const passwordMatch = await validatePassword({
password,
passwordHash: user.passwordHash,
});
if (!passwordMatch) {
- throw new Error("invalid-credentials");
+ const exceededLoginAttempts = exceededLoginAttemptsThreshold(
+ await incrementLoginAttempts(user),
+ );
+
+ if (exceededLoginAttempts) {
+ throw new Error("exceeded-login-attempts");
+ } else {
+ throw new Error("invalid-credentials");
+ }
}
+ await resetLoginAttempts(user.id);
+
return {
id: user.id,
name: user.name,
diff --git a/apps/web/lib/auth/password.ts b/apps/web/lib/auth/password.ts
index 4d108643af..bb26ba8ec1 100644
--- a/apps/web/lib/auth/password.ts
+++ b/apps/web/lib/auth/password.ts
@@ -14,4 +14,21 @@ export async function validatePassword({
return await compare(password, passwordHash);
}
-export const PASSWORD_RESET_TOKEN_EXPIRY = 1 * 60 * 60; // 1 hour
+export const meetsPasswordRequirements = (password: string) => {
+ // Check if the password is at least 8 characters long
+ if (password.length < 8) {
+ return false;
+ }
+
+ // Check if the password contains at least one uppercase and one lowercase letter
+ if (!/[A-Z]/.test(password) || !/[a-z]/.test(password)) {
+ return false;
+ }
+
+ // Check if the password contains at least one digit
+ if (!/\d+/.test(password)) {
+ return false;
+ }
+
+ return true;
+};
diff --git a/apps/web/lib/zod/schemas/auth.ts b/apps/web/lib/zod/schemas/auth.ts
index 339955e34f..7db4bd31e3 100644
--- a/apps/web/lib/zod/schemas/auth.ts
+++ b/apps/web/lib/zod/schemas/auth.ts
@@ -14,4 +14,4 @@ export const updatePasswordSchema = z.object({
export const signInSchema = z.object({
email: z.string().email().min(1),
password: z.string().min(1),
-});
+});
\ No newline at end of file
diff --git a/apps/web/prisma/schema.prisma b/apps/web/prisma/schema.prisma
index 11a85c12ea..b693970bea 100644
--- a/apps/web/prisma/schema.prisma
+++ b/apps/web/prisma/schema.prisma
@@ -13,13 +13,15 @@ generator client {
}
model User {
- id String @id @default(cuid())
- name String?
- email String? @unique
- emailVerified DateTime?
- image String?
- isMachine Boolean @default(false)
- passwordHash String?
+ id String @id @default(cuid())
+ name String?
+ email String? @unique
+ emailVerified DateTime?
+ image String?
+ isMachine Boolean @default(false)
+ passwordHash String?
+ invalidLoginAttempts Int @default(0)
+ lockedUntil DateTime?
accounts Account[]
sessions Session[]