mirror of
https://github.com/vercel/next.js.git
synced 2026-09-20 02:25:18 +08:00
3675453eac
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 <engzerjun@gmail.com> Co-authored-by: Jiwon Choi <devjiwonchoi@gmail.com>
46 lines
1.4 KiB
JavaScript
46 lines
1.4 KiB
JavaScript
import crypto from "crypto";
|
|
|
|
/**
|
|
* User methods. The example doesn't contain a DB, but for real applications you must use a
|
|
* db here, such as MongoDB, Fauna, SQL, etc.
|
|
*/
|
|
|
|
const users = [];
|
|
|
|
export async function createUser({ username, password }) {
|
|
// 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,
|
|
hash,
|
|
salt,
|
|
};
|
|
|
|
// This is an in memory store for users, there is no data persistence without a proper DB
|
|
users.push(user);
|
|
|
|
return { username, createdAt: Date.now() };
|
|
}
|
|
|
|
// Here you should lookup for the user in your DB
|
|
export async function findUser({ username }) {
|
|
// This is an in memory store for users, there is no data persistence without a proper DB
|
|
return users.find((user) => user.username === username);
|
|
}
|
|
|
|
// Compare the password of an already fetched user (using `findUser`) 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;
|
|
}
|