forked from inrittik/BlogPost
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathauthControllers.ts
More file actions
167 lines (155 loc) · 4.84 KB
/
authControllers.ts
File metadata and controls
167 lines (155 loc) · 4.84 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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
import { Request, Response, NextFunction } from "express";
import httpStatus from "http-status";
import jwt from "jsonwebtoken";
import bcrypt from "bcrypt";
import { UserModel } from "@models";
import { Types } from "mongoose";
const nodemailer = require('nodemailer');
require('dotenv').config();
//creating nodemailer variables
const transporter = nodemailer.createTransport({
host : 'smtp.gmail.com',
port : 465,
secure : true,
service: 'gmail',
auth: {
user: process.env.EMAIL,
pass: process.env.PASSWORD
}
});
var mailOptions = {
from: process.env.EMAIL,
subject: 'Email Verification',
text: '',
to : ''
};
const signup = async (req: Request, res: Response, next: NextFunction) => {
try {
let user;
if(process.env.EMAIL === undefined || process.env.PASSWORD === undefined) {}
else
console.log(process.env.EMAIL + process.env.PASSWORD)
const { email } = req.body;
user = await UserModel.UserSchema.findOne({ email: email });
if (user) {
return res.status(httpStatus.BAD_REQUEST).send({
message: "Email already in use",
});
}
user = await UserModel.UserSchema.create(req.body);
const accessToken = jwt.sign(user.toJSON(), <string>process.env.JWT_SECRET);
mailOptions.to = email;
mailOptions.text = `Click on the link below to verify your email http://localhost:${process.env.PORT}/auth/verifyEmail/${email}/${accessToken}`;
transporter.sendMail(mailOptions, ()=>{});
return res.status(httpStatus.CREATED).json({
user: user,
accessToken: accessToken
});
} catch (err) {
return next(err);
}
};
const login = async (req: Request, res: Response, next: NextFunction) => {
try {
let user;
const { email, password } = req.body;
user = await UserModel.UserSchema.findOne({ email: email });
if (!user) {
return res.status(httpStatus.BAD_REQUEST).json({
message: "User with this email does not exist",
});
}
const match = await bcrypt.compare(password, user.password);
if (!match) {
return res.status(httpStatus.BAD_REQUEST).json({
message: "Password is incorrect",
});
}
const accessToken = jwt.sign(user.toJSON(), <string>process.env.JWT_SECRET);
return res.status(httpStatus.OK).json({
user: user,
accessToken: accessToken,
});
} catch (err) {
return next(err);
}
};
// const logout = async (req: Request, res: Response, next: NextFunction) => {
// }
const resetPassword = async (req: Request, res: Response, next: NextFunction) => {
try {
const { id, resetToken } = req.params;
const user = await UserModel.UserSchema.findById(new Types.ObjectId(id));
if (!user) {
return res.status(httpStatus.NOT_FOUND).json({
message: "User not found. Please try again!"
})
}
const secret = <string>process.env.JWT_SECRET + user._id;
const payload = jwt.verify(resetToken, secret);
if (!payload) {
return res.status(httpStatus.FORBIDDEN).json({
message: "Incorrect token received"
})
}
user.password = req.body.password;
await user.save();
return res.status(httpStatus.OK).json({
user: user,
message: "Password updated successfully"
})
}
catch (err) {
return next(err);
}
}
const forgotPassword = async (req: Request, res: Response, next: NextFunction) => {
try {
const { email } = req.body;
const user = await UserModel.UserSchema.findOne({ email: email });
if (!user) {
return res.status(httpStatus.BAD_REQUEST).json({
message: "User doesn't exist with this email"
})
}
const secret = <string>process.env.JWT_SECRET + user.email;
const resetToken = jwt.sign(user.toJSON(), secret, { expiresIn: '10m' })
return res.status(httpStatus.OK).json({
resetToken: resetToken,
link: `http://localhost:${process.env.PORT}/auth/:${user.email}/resetPassword/:${resetToken}`,
});
}
catch (err) {
return next(err);
}
}
//write a function to verify email
const verifyEmail = async (req: Request, res: Response, next : NextFunction) => {
try {
const { id, verifyToken } = req.params;
console.log(id, verifyToken);
const user = await UserModel.UserSchema.findOne({ email : id });
if (!user) {
return res.status(httpStatus.NOT_FOUND).json({
message: "User not found. Please try again!"
})
}
const secret = <string>process.env.JWT_SECRET;
const payload = jwt.verify(verifyToken, secret);
if (!payload) {
return res.status(httpStatus.FORBIDDEN).json({
message: "Incorrect token received"
})
}
user.verified = true;
await user.save();
return res.status(httpStatus.OK).json({
user: user,
message: "Email verified successfully"
})
}
catch (err) {
return next(err);
}
}
export { signup, login, resetPassword, forgotPassword, verifyEmail};