authnodejs-mongodb
v2.0.4
Published
The Auth class provides the following methods:
Downloads
8
Maintainers
Readme
Authnodejs-mongodb Description
This Pakage contains code for user registration, login, and logout functionality. The code is implemented using Node.js and MongoDB. Below is a brief description of the code files and their functionalities.
Sample Code
Here is a sample code snippet demonstrating how to use the provided functions:
const { registerUser, loginUser, logoutUser } = require('authnodejs-mongodb');
// Register a new user
exports.registerUser = async (req, res, next) => {
const { email, password, phonenumber, customerShippingAddress, customerBillingAddress } = req.body;
const credentials = { email, password, phonenumber, customerShippingAddress, customerBillingAddress };
await registerUser(req, res, next, User, credentials);
};
// Login user
exports.loginUser = async (req, res, next) => {
await loginUser(req, res, next, User);
};
// Logout user
exports.logoutUser = (req, res, next) => {
logoutUser(req, res, next);
};
Here is Sample Code For Db Model
const mongoose = require('mongoose')
const validator = require('validator')
const bcrypt = require('bcrypt')
const jwt = require('jsonwebtoken')
const crypto = require('crypto')
const userSchema = new mongoose.Schema({
email:{
type: String,
required: [true, 'Please Enter The email'],
unique:true,
validate: [validator.isEmail,"please enter correct email address"]
},
password:{
type:String,
required:[true,"Please enter password"],
maxlength:[20,"password cannot exceed 20 characters"],
select:false,
validate: [validator.isStrongPassword,'Please enter one uppercase one lowercase and min 8 values']
},
})
userSchema.pre('save',async function(next){
if (!this.isModified('password')) {
next();
}
this.password = await bcrypt.hash(this.password,10)
})
userSchema.methods.getJwtToken = function (){
return jwt.sign({ id: this.id }, process.env.JWT_SECRET ,{
expiresIn: process.env.JWT_EXPIRES_TIME
})
}
userSchema.methods.isValidPassword = async function(EnteredPassword){
return bcrypt.compare(EnteredPassword,this.password)
}
let model = mongoose.model('user', userSchema)
module.exports = model
Make sure to replace User
with the appropriate model for user authentication.