user auth backend

PHOTO EMBED

Sun Jul 23 2023 09:22:52 GMT+0000 (Coordinated Universal Time)

Saved by @nelson22

SERVER.JS

const express = require('express');
require('dotenv').config();
const mongoose = require('mongoose');

const app = express();
app.use(express.json());

const userRoutes = require('./routes/user');

mongoose.connect(process.env.MONGO_URI)
 .then(() => {
    app.listen(process.env.PORT, () => {
        console.log('listening on port', process.env.PORT);
    })
 })
 .catch(err => {console.log(err)})

app.use('/api/user', userRoutes)

----------------------------------------------------------

USER.JS

const express = require('express');

const router = express.Router();

const {loginUser, signUpUser} = require('../controllers/userController');

// sign in route
router.post('/login', loginUser)

// sign up route
router.post('/signup', signUpUser)

module.exports = router

----------------------------------------------------------

USERCONTROLLER.JS

const User = require('../models/userModel');
const jwt = require('jsonwebtoken');

const createToken = (_id) => {
    return jwt.sign({_id}, process.env.SECRET, {expiresIn: '2d'})
}

// login user
const loginUser = async (req, res) => {
    const {email, password} = req.body;

    try{
        const user = await User.login(email, password);
        // create a token
        const token = createToken(user._id);

        res.status(200).json({email, token});
    } catch(err){
        res.status(400).json({error: err.message});
    }
}

// signup user
const signUpUser = async (req, res) => {
    const {email, password} = req.body

    try{
        const user = await User.signup(email, password);
        // create a token
        const token = createToken(user._id);
        
        res.status(200).json({email, token})
    }catch(err){
        res.status(400).json({error: err.message})
    }
}

module.exports = {loginUser, signUpUser}

----------------------------------------------------------

USERMODEL.JS

const mongoose = require('mongoose');
const bcrypt = require('bcrypt');

const Schema = mongoose.Schema;

const userSchema = new Schema({
    email: {
        type: String,
        required: true,
        unique: true
    },
    password: {
        type: String,
        required: true,
    }
})

// static signup method
userSchema.statics.signup = async function(email, password){
    const exists = await this.findOne({email})
    if(exists){
        throw Error("Email already exists")
    }
    
    // salt are random strings which gets attached to the password so that hackers cannot crack with password match, 
    const salt = await bcrypt.genSalt(10)
    const hash = await bcrypt.hash(password, salt);

    const user = this.create({email, password: hash});
    return user
}

// static login method
userSchema.statics.login = async function(email, password){
    const user = await this.findOne({email});

    if(!user || !password){
        throw Error("All fields are compulsary");
    }

    if(!user){
        throw Error("User doesent exists");
    }

    const match = await bcrypt.compare(password, user.password);

    if(!match){
        throw Error("Password is incorrect");
    }

    return user
}

module.exports = mongoose.model('User', userSchema)
content_copyCOPY