2020-06-10 05:46:11 +02:00
|
|
|
import crypto from "crypto";
|
2020-06-12 04:29:26 +02:00
|
|
|
import { v4 as uuidv4 } from "uuid";
|
2020-06-10 05:46:11 +02:00
|
|
|
|
|
|
|
/**
|
|
|
|
* 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({ email, 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: uuidv4(),
|
|
|
|
createdAt: Date.now(),
|
|
|
|
email,
|
|
|
|
hash,
|
|
|
|
salt,
|
|
|
|
};
|
|
|
|
|
|
|
|
// This is an in memory store for users, there is no data persistence without a proper DB
|
|
|
|
users.push(user);
|
|
|
|
|
|
|
|
return user;
|
|
|
|
}
|
|
|
|
|
|
|
|
// Here you should lookup for the user in your DB
|
|
|
|
export async function findUser({ email }) {
|
|
|
|
// This is an in memory store for users, there is no data persistence without a proper DB
|
|
|
|
return users.find((user) => user.email === email);
|
|
|
|
}
|
|
|
|
|
|
|
|
// Compare the password of an already fetched user (using `findUser`) and compare the
|
|
|
|
// password for a potential match
|
|
|
|
export async function validatePassword(user, inputPassword) {
|
2020-06-15 14:39:12 +02:00
|
|
|
const inputHash = crypto
|
|
|
|
.pbkdf2Sync(inputPassword, user.salt, 1000, 64, "sha512")
|
2020-06-10 05:46:11 +02:00
|
|
|
.toString("hex");
|
2020-06-15 14:39:12 +02:00
|
|
|
const passwordsMatch = user.hash === inputHash;
|
2020-06-10 05:46:11 +02:00
|
|
|
return passwordsMatch;
|
|
|
|
}
|