-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
attachCurrentUser.ts
30 lines (28 loc) · 938 Bytes
/
attachCurrentUser.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
import { Container } from 'typedi';
import mongoose from 'mongoose';
import { IUser } from '../../interfaces/IUser';
/**
* Attach user to req.user
* @param {*} req Express req Object
* @param {*} res Express res Object
* @param {*} next Express next Function
*/
const attachCurrentUser = async (req, res, next) => {
const Logger = Container.get('logger');
try {
const UserModel = Container.get('userModel') as mongoose.Model<IUser & mongoose.Document>;
const userRecord = await UserModel.findById(req.token._id);
if (!userRecord) {
return res.sendStatus(401);
}
const currentUser = userRecord.toObject();
Reflect.deleteProperty(currentUser, 'password');
Reflect.deleteProperty(currentUser, 'salt');
req.currentUser = currentUser;
return next();
} catch (e) {
Logger.error('🔥 Error attaching user to req: %o', e);
return next(e);
}
};
export default attachCurrentUser;