/
home
/
infinitibizsol
/
.trash
/
controllers.8
/
File Upload :
llllll
Current File: /home/infinitibizsol/.trash/controllers.8/auth.js
import db from "../model/index"; import bcrypt from "bcrypt"; import { failedResponse } from "../utils/responseFormat"; import catchAsync from "../utils/catchAsync"; import AppError from "../utils/apiError"; import { jwtService } from "../utils/jwtService"; const login = catchAsync(async (req, res, next) => { const { email, password } = req.body; if (!email || !password) { return next(new AppError("Invalid credentials", 401)); } const user = await db.User.findOne({ email: email.toLowerCase() }); if (!user) { return next(new AppError("Invalid credentials", 401)); } const passwordMatch = await bcrypt.compare(password, user.password); if (!passwordMatch) { return next(new AppError("Invalid credentials", 401)); } const token = await jwtService.signToken({ _id: user._id, role: user.role }); res.setHeader("Authorization", token); res.status(200).json({ token: token, user, message: "Login successfully" }); }); const authenticate = catchAsync(async (req, res, next) => { const user = await db.User.findOne({ _id: req.user._id }); if (!user) { return next(new AppError("No user found.", 401)); } const token = await jwtService.signToken({ _id: user._id, role: user.role }); // Create a JWT token res.setHeader("Authorization", token); res.status(200).json({ token: token, user, message: "success" }); }); const restrictTo = (...roles) => { // roles are : admin, agent return (req, res, next) => { if (!roles.includes(req.user.role)) { return failedResponse({ res, error: "You are not allowed!" }); } next(); }; }; export default { login, authenticate, restrictTo };
Copyright ©2k19 -
Hexid
|
Tex7ure