Skip to content

Commit c6fc483

Browse files
committed
Section 10-Authentication And Authorization
1 parent 2779707 commit c6fc483

29 files changed

+1073
-25
lines changed

.gitignore

+1-1
Original file line numberDiff line numberDiff line change
@@ -2,4 +2,4 @@ node_modules/
22

33
config.env
44

5-
uploads/
5+
uploads/``

middlewares/errorMiddleware.js

+14-6
Original file line numberDiff line numberDiff line change
@@ -1,25 +1,33 @@
1-
const sendErrorForDev = (err, res) => {
2-
return res.status(err.statusCode).json({
1+
const ApiError = require('../utils/apiError');
2+
3+
const sendErrorForDev = (err, res) =>
4+
res.status(err.statusCode).json({
35
status: err.status,
46
error: err,
57
message: err.message,
68
stack: err.stack,
79
});
8-
};
910

10-
const sendErrorForProd = (err, res) => {
11-
return res.status(err.statusCode).json({
11+
const sendErrorForProd = (err, res) =>
12+
res.status(err.statusCode).json({
1213
status: err.status,
1314
message: err.message,
1415
});
15-
};
16+
17+
const handleJwtInvalidSignature = () =>
18+
new ApiError('Invalid token, please login again..', 401);
19+
20+
const handleJwtExpired = () =>
21+
new ApiError('Expired token, please login again..', 401);
1622

1723
const globalError = (err, req, res, next) => {
1824
err.statusCode = err.statusCode || 500;
1925
err.status = err.status || 'error';
2026
if (process.env.NODE_ENV === 'development') {
2127
sendErrorForDev(err, res);
2228
} else {
29+
if (err.name === 'JsonWebTokenError') err = handleJwtInvalidSignature();
30+
if (err.name === 'TokenExpiredError') err = handleJwtExpired();
2331
sendErrorForProd(err, res);
2432
}
2533
};

models/userModel.js

+55
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
const mongoose = require('mongoose');
2+
const bcrypt = require('bcryptjs');
3+
4+
const userSchema = new mongoose.Schema(
5+
{
6+
name: {
7+
type: String,
8+
trim: true,
9+
required: [true, 'name required'],
10+
},
11+
slug: {
12+
type: String,
13+
lowercase: true,
14+
},
15+
email: {
16+
type: String,
17+
required: [true, 'email required'],
18+
unique: true,
19+
lowercase: true,
20+
},
21+
phone: String,
22+
profileImg: String,
23+
24+
password: {
25+
type: String,
26+
required: [true, 'password required'],
27+
minlength: [6, 'Too short password'],
28+
},
29+
passwordChangedAt: Date,
30+
passwordResetCode: String,
31+
passwordResetExpires: Date,
32+
passwordResetVerified: Boolean,
33+
role: {
34+
type: String,
35+
enum: ['user', 'manager', 'admin'],
36+
default: 'user',
37+
},
38+
active: {
39+
type: Boolean,
40+
default: true,
41+
},
42+
},
43+
{ timestamps: true }
44+
);
45+
46+
userSchema.pre('save', async function (next) {
47+
if (!this.isModified('password')) return next();
48+
// Hashing user password
49+
this.password = await bcrypt.hash(this.password, 12);
50+
next();
51+
});
52+
53+
const User = mongoose.model('User', userSchema);
54+
55+
module.exports = User;

0 commit comments

Comments
 (0)