Path: blob/master/src/packages/next/pages/api/v2/auth/password-strength.ts
2211 views
/*1* This file is part of CoCalc: Copyright © 2020 Sagemath, Inc.2* License: MS-RSL – see LICENSE.md for details3*/45/*6API endpoint for checking password strength during sign-up.7Provides real-time feedback without requiring the large zxcvbn library on the client.89Usage:10POST /api/v2/auth/password-strength11Body: { password: "user-password" }1213Response:14Success: { score: 0-4, help?: "suggestion text" }15Error: { error: "error message" }16*/1718import passwordStrength from "@cocalc/server/auth/password-strength";19import { MAX_PASSWORD_LENGTH, MIN_PASSWORD_LENGTH } from "@cocalc/util/auth";20import { apiRoute, apiRouteOperation } from "lib/api";21import getParams from "lib/api/get-params";22import { z } from "zod";2324const PasswordStrengthInputSchema = z.object({25password: z.string().min(1).max(MAX_PASSWORD_LENGTH),26});2728const PasswordStrengthOutputSchema = z.object({29score: z.number().min(0).max(4),30help: z.string().optional(),31});3233export async function checkPasswordStrength(req, res) {34try {35const { password } = getParams(req);3637if (!password || typeof password !== "string") {38res.status(400).json({ error: "Password is required" });39return;40}4142if (password.length < MIN_PASSWORD_LENGTH) {43res.status(400).json({44error: `Password must be at least ${MIN_PASSWORD_LENGTH} characters long`,45});46return;47}4849if (password.length > MAX_PASSWORD_LENGTH) {50res.status(400).json({51error: `Password must be at most ${MAX_PASSWORD_LENGTH} characters long`,52});53return;54}5556const result = passwordStrength(password);57res.json(result);58} catch (err) {59res.status(500).json({ error: err.message });60}61}6263export default apiRoute({64checkPasswordStrength: apiRouteOperation({65method: "POST",66openApiOperation: {67tags: ["Auth"],68},69})70.input({71contentType: "application/json",72body: PasswordStrengthInputSchema,73})74.outputs([75{76status: 200,77contentType: "application/json",78body: PasswordStrengthOutputSchema,79},80])81.handler(checkPasswordStrength),82});838485