在服务器端管理用户名密码的代码示例:

import * as bcrypt from 'bcryptjs'; import { User } from './user.model';

export class UserService { private users: User[] = [];

async createUser(username: string, password: string): Promise { const hashedPassword = await bcrypt.hash(password, 12); const newUser = new User(username, hashedPassword); this.users.push(newUser); return newUser; }

async login(username: string, password: string): Promise { const user = this.users.find((u) => u.username === username); if (!user) { throw new Error('User not found'); } const isValidPassword = await bcrypt.compare(password, user.password); if (!isValidPassword) { throw new Error('Invalid password'); } return user; } }

export class User { constructor(public username: string, public password: string) {} }

在上面的代码中,我们使用了bcryptjs库来对用户密码进行哈希和比较。首先,我们在createUser方法中使用bcrypt.hash方法对密码进行哈希,并创建一个新的User对象并将其添加到users数组中。在login方法中,我们查找与给定用户名匹配的用户,然后使用bcrypt.compare方法比较给定密码和用户的哈希密码。如果密码匹配,则返回用户对象;否则,抛出“Invalid password”错误。

写一段在服务器端管理用户名密码的代码TypeScript

原文地址: https://www.cveoy.top/t/topic/m1J 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录