mirror of
https://github.com/hanzoai/next.js.git
synced 2026-10-30 14:46:38 +00:00
Starting from Node.js v14.17.0 and v15.6.0, we can use Node.js's `randomUUID` function in the crypto module to generate version 4 UUID. Since Next.js requires Node 18 or newer, we can replace `uuid` dependency with `crypto.randomUUID`. Reference: https://nodejs.org/docs/latest-v18.x/api/crypto.html#cryptorandomuuidoptions Signed-off-by: Eng Zer Jun <[email protected]> Co-authored-by: Jiwon Choi <[email protected]>
60 lines
1.9 KiB
JavaScript
60 lines
1.9 KiB
JavaScript
import crypto from "crypto";
|
|
|
|
export function getAllUsers(req) {
|
|
// For demo purpose only. You are not likely to have to return all users.
|
|
return req.session.users;
|
|
}
|
|
|
|
export function createUser(req, { username, password, name }) {
|
|
// Here you should create the user and save the salt and hashed password (some dbs may have
|
|
// authentication methods that will do it for you so you don't have to worry about it):
|
|
const salt = crypto.randomBytes(16).toString("hex");
|
|
const hash = crypto
|
|
.pbkdf2Sync(password, salt, 1000, 64, "sha512")
|
|
.toString("hex");
|
|
const user = {
|
|
id: crypto.randomUUID(),
|
|
createdAt: Date.now(),
|
|
username,
|
|
name,
|
|
hash,
|
|
salt,
|
|
};
|
|
|
|
// Here you should insert the user into the database
|
|
// await db.createUser(user)
|
|
req.session.users.push(user);
|
|
}
|
|
|
|
export function findUserByUsername(req, username) {
|
|
// Here you find the user based on id/username in the database
|
|
// const user = await db.findUserById(id)
|
|
return req.session.users.find((user) => user.username === username);
|
|
}
|
|
|
|
export function updateUserByUsername(req, username, update) {
|
|
// Here you update the user based on id/username in the database
|
|
// const user = await db.updateUserById(id, update)
|
|
const user = req.session.users.find((u) => u.username === username);
|
|
Object.assign(user, update);
|
|
return user;
|
|
}
|
|
|
|
export function deleteUser(req, username) {
|
|
// Here you should delete the user in the database
|
|
// await db.deleteUser(req.user)
|
|
req.session.users = req.session.users.filter(
|
|
(user) => user.username !== req.user.username,
|
|
);
|
|
}
|
|
|
|
// Compare the password of an already fetched user (using `findUserByUsername`) and compare the
|
|
// password for a potential match
|
|
export function validatePassword(user, inputPassword) {
|
|
const inputHash = crypto
|
|
.pbkdf2Sync(inputPassword, user.salt, 1000, 64, "sha512")
|
|
.toString("hex");
|
|
const passwordsMatch = user.hash === inputHash;
|
|
return passwordsMatch;
|
|
}
|