{"size": 1629, "ext": "js", "max_stars_repo_path": "lib/mongodb-models/users.js", "max_stars_repo_name": "davidwieler/passport-next", "max_stars_repo_stars_event_min_datetime": "2020-03-19T21:03:32.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-13T05:25:30.000Z", "max_issues_repo_path": "lib/mongodb-models/users.js", "max_issues_repo_name": "davidwieler/passport-next", "max_issues_repo_issues_event_min_datetime": "2021-03-10T07:02:39.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-14T07:41:06.000Z", "max_forks_repo_path": "lib/mongodb-models/users.js", "max_forks_repo_name": "davidwieler/passport-next", "max_forks_repo_forks_event_min_datetime": "2020-04-13T05:25:33.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-13T05:25:33.000Z"}
{"max_stars_count": 2, "max_issues_count": 4, "max_forks_count": 1, "avg_line_length": 25.8571428571, "max_line_length": 131, "alphanum_fraction": 0.6955187231}
import mongoose from 'mongoose';
import bcrypt from 'bcryptjs';

const Schema = mongoose.Schema;

// Our user schema.
// Password is set to select:false,
// so it won't return in any find statements by default.
const UserSchema = new Schema({
	name: String,
	email: String,
	password: { type: String, select: false },
	github: {
		id: String,
		username: String,
		avatar: String
	}
});

// Export the user model.
// On startup, the Mongoose model will be created and returned.
// Any additional times the model is required, it'll return the already created
// schema. If we don't do this, Next will error with a Mongoose error due to it
// trying to recreate the schema.
export const User = mongoose.models.User || mongoose.model('User', UserSchema);

export const findUserByEmail = async ({ email, includePassword = false, upsert = false, upsertData = {} }) => {
	let user = null;

	if (upsert) {
		user = await User.findOneAndUpdate({ email: email }, { $set: upsertData }, { upsert: true, useFindAndModify: false, new: true });
	} else {
		user = await User.findOne({ email }, { password: includePassword });
	}

	return user;
};

export const comparePassword = async (password, userPassword) => {
	const compare = await bcrypt.compare(password, userPassword);

	return compare;
};

export const createUser = async ({ email, password }) => {
	if (!email || !password) {
		return;
	}

	const salt = await bcrypt.genSalt(10);
	const hash = await bcrypt.hash(password, salt);

	const userDetails = {
		email,
		password: hash
	};

	const newUser = User(userDetails);
	const saveUser = await newUser.save();

	return saveUser;
};
