Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
sagemathinc
GitHub Repository: sagemathinc/cocalc
Path: blob/master/src/packages/next/pages/api/v2/auth/password-strength.ts
2211 views
1
/*
2
* This file is part of CoCalc: Copyright © 2020 Sagemath, Inc.
3
* License: MS-RSL – see LICENSE.md for details
4
*/
5
6
/*
7
API endpoint for checking password strength during sign-up.
8
Provides real-time feedback without requiring the large zxcvbn library on the client.
9
10
Usage:
11
POST /api/v2/auth/password-strength
12
Body: { password: "user-password" }
13
14
Response:
15
Success: { score: 0-4, help?: "suggestion text" }
16
Error: { error: "error message" }
17
*/
18
19
import passwordStrength from "@cocalc/server/auth/password-strength";
20
import { MAX_PASSWORD_LENGTH, MIN_PASSWORD_LENGTH } from "@cocalc/util/auth";
21
import { apiRoute, apiRouteOperation } from "lib/api";
22
import getParams from "lib/api/get-params";
23
import { z } from "zod";
24
25
const PasswordStrengthInputSchema = z.object({
26
password: z.string().min(1).max(MAX_PASSWORD_LENGTH),
27
});
28
29
const PasswordStrengthOutputSchema = z.object({
30
score: z.number().min(0).max(4),
31
help: z.string().optional(),
32
});
33
34
export async function checkPasswordStrength(req, res) {
35
try {
36
const { password } = getParams(req);
37
38
if (!password || typeof password !== "string") {
39
res.status(400).json({ error: "Password is required" });
40
return;
41
}
42
43
if (password.length < MIN_PASSWORD_LENGTH) {
44
res.status(400).json({
45
error: `Password must be at least ${MIN_PASSWORD_LENGTH} characters long`,
46
});
47
return;
48
}
49
50
if (password.length > MAX_PASSWORD_LENGTH) {
51
res.status(400).json({
52
error: `Password must be at most ${MAX_PASSWORD_LENGTH} characters long`,
53
});
54
return;
55
}
56
57
const result = passwordStrength(password);
58
res.json(result);
59
} catch (err) {
60
res.status(500).json({ error: err.message });
61
}
62
}
63
64
export default apiRoute({
65
checkPasswordStrength: apiRouteOperation({
66
method: "POST",
67
openApiOperation: {
68
tags: ["Auth"],
69
},
70
})
71
.input({
72
contentType: "application/json",
73
body: PasswordStrengthInputSchema,
74
})
75
.outputs([
76
{
77
status: 200,
78
contentType: "application/json",
79
body: PasswordStrengthOutputSchema,
80
},
81
])
82
.handler(checkPasswordStrength),
83
});
84
85