-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathadminModel.js
More file actions
100 lines (92 loc) · 2.04 KB
/
adminModel.js
File metadata and controls
100 lines (92 loc) · 2.04 KB
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
import mongoose from "mongoose";
import validator from "validator";
import jwt from "jsonwebtoken";
import bcrypt from "bcryptjs";
import dotenv from "dotenv";
dotenv.config();
const JWT = process.env.JWT;
mongoose.set("strictQuery", true);
const adminSchema = new mongoose.Schema({
type: {
type: String,
default: "admin",
},
name: {
type: String,
required: true,
trim: true,
},
email: {
type: String,
unique: true,
required: true,
trim: true,
validate(value) {
if (!validator.isEmail(value)) {
throw new Error("Enter a valid email address");
}
},
},
password: {
type: String,
trim: true,
minLength: 7,
validate(value) {
if (value.length <= 7) {
throw new Error("Password must be minimum 7 characters long");
}
},
},
role: {
type: String,
default: "_admin",
},
resetToken: String,
expireToken: Date,
tokens: [
{
token: {
type: String,
required: true,
},
},
],
});
adminSchema.methods.toJSON = function () {
const user = this;
const userObject = user.toObject();
delete userObject.password;
delete userObject.tokens;
return userObject;
};
adminSchema.methods.generateAuthToken = async function () {
const user = this;
const token = jwt.sign({ _id: user._id.toString() }, JWT, {
expiresIn: "1h",
});
user.tokens = user.tokens.concat({ token });
await user.save();
return token;
};
adminSchema.statics.findByCredentials = async (email, password) => {
const user = await Admin.findOne({
email,
});
if (!user) {
throw new Error("Invalid Username or Sign up first !!");
}
const isMatch = await bcrypt.compare(password, user.password);
if (!isMatch) {
throw new Error("Invalid Password!");
}
return user;
};
adminSchema.pre("save", async function (next) {
const user = this;
if (user.isModified("password")) {
user.password = await bcrypt.hash(user.password, 8);
}
next();
});
const Admin = mongoose.model("Admin", adminSchema);
export default Admin;