import { pick } from 'lodash'; import Moment from 'moment-timezone'; import JWT from 'jsonwebtoken'; import { handler as ErrorHandler } from './error'; import User from '../../common/models/user.model'; /** * Load item by id add to req locals. */ exports.load = async (req, res, next) => { try { const id = req.params.id; // console.log(id); const user = await User.get(id); req.locals = req.locals ? req.locals : {}; req.locals.user = user; return next(); } catch (ex) { return ErrorHandler(ex, req, res, next); } }; /** * Load count for filter. */ exports.count = async (req, res, next) => { try { req.totalRecords = await User.totalRecords( req.query ); return next(); } catch (ex) { return ErrorHandler(ex, req, res, next); } }; /** * Load item by id add to req locals. */ exports.checkEmail = async (req, res, next) => { try { const user = await User.findOne({ where: { email: req.body.email } }); if (user) { return res.status(400).json({ message: 'email have aldready exist' }); } return next(); } catch (ex) { return ErrorHandler(ex, req, res, next); } }; exports.loadUser = async (req, res, next) => { try { const user = await User.findOne({ where: { email: req.body.email } }); if (!user) { return res.status(400).json({ message: 'email or password incorrect' }); } req.locals = { user }; return next(); } catch (ex) { return ErrorHandler(ex, req, res, next); } }; exports.checkPassword = async (req, res, next) => { const { user } = req.locals; const isCheck = await user.passwordMatch(req.body.password); if (!isCheck) { return res.status(400).json({ message: 'email or password incorrect' }); } return next(); }; exports.genarateToken = async (req, res, next) => { let user = null; user = pick(req.locals.user, ['name', 'avatar', 'email', 'phone', 'service']); user.id = req.locals.user._id; req.locals = { user }; const inforToken = {}; inforToken.token = JWT.sign(user, process.env.NODE_ENV || 'development', { expiresIn: 60 * 60 }); inforToken.refresToken = JWT.sign(user, process.env.PORT || '3002', { expiresIn: 60 * 60 * 1000 }); inforToken.access_expired_at = Moment.tz(new Date(), 'Asia/Ho_Chi_Minh').unix() + (60 * 60 * 1000); inforToken.expRefreshTime = Moment.tz(new Date(), 'Asia/Ho_Chi_Minh').unix(); req.locals.token = inforToken; return next(); }; // exports.loginFacebook= async (req,res,next)=>{ // } exports.checkCurrentPassword = async (req, res, next) => { const { user } = req.locals; // console.log(user); const isCheck = await User.passwordMatches(user, req.body.current_password); if (!isCheck) { return res.status(400).json({ message: 'Password incorrect'}); } return next(); };