Cantilever-Labs/controllers/auth.js

449 lines
15 KiB
JavaScript
Raw Normal View History

2021-05-09 04:31:53 -07:00
const bcrypt = require("bcryptjs");
const User = require("../models/User");
const Student = require("../models/Student");
const jwt = require("jsonwebtoken");
2021-04-01 06:38:27 -07:00
const JWT_secret = "Cantileverlabs";
const messagebird = require("messagebird")("llVKD53ve6QRpbCKOHzWBADaS", null, [
"ENABLE_CONVERSATIONSAPI_WHATSAPP_SANDBOX",
]);
2021-05-12 03:44:03 -07:00
const nodemailer = require("nodemailer");
const smtpTransport = require("nodemailer-smtp-transport");
// -------------------------------------------- mail transporter -----------------------------------------
var transport = nodemailer.createTransport(
smtpTransport({
host: "email-smtp.us-east-1.amazonaws.com", //`${process.env.HOST}`
port: 465,
auth: {
user: "AKIA2G7743RRTZMVXE3X", //`${process.env.EMAIL}`
pass: "BJSjV3jArJfsnk1LhFc/hUmisEyEtbLNGgrRbv0noh8c", //`${process.env.PASS}`
},
})
);
// -------------------------------------------- mail transporter -----------------------------------------
2021-03-26 06:29:27 -07:00
2021-05-09 04:31:53 -07:00
module.exports.Protected = async (req, res, next) => {
res.send("Hello User");
};
module.exports.postSignup = async (req, res, next) => {
try {
//we need firstName , lastName , email , password as input
let firstName = req.body.firstName || " ";
let lastName = req.body.lastName || " ";
const { sending_company_email, email, password, subject, _html } = req.body;
2021-05-09 04:31:53 -07:00
let user = await User.findOne({ email: email });
if (user) {
res.json({
message: "User already exist",
type: "error",
});
} else {
const email_otp = Math.floor(100000 + Math.random() * 900000);
console.log("otp", email_otp);
2021-05-09 04:31:53 -07:00
const hashedPass = await bcrypt.hash(password, 12);
user = new User({
firstName: firstName,
lastName: lastName,
email: email,
password: hashedPass,
isAdmin: false,
email_otp,
2021-05-09 04:31:53 -07:00
});
user = await user.save();
await Student.deleteOne({ user: user._id });
let student = new Student({
user: user._id,
});
student = await student.save();
user.student = student._id;
await user.save();
const message = {
from: `${sending_company_email}`, // Sender address
to: `${email}`, // List of recipients
subject: `${subject}`, // Subject line
html: `${_html}`, // design html for email message.
};
transport.sendMail(message, function (err, info) {
if (err) {
console.log(err);
} else {
console.log(info);
}
});
2021-05-09 04:31:53 -07:00
res.json({
message: "OTP has sent to the Email",
2021-05-09 04:31:53 -07:00
type: "success",
});
2021-03-26 06:29:27 -07:00
}
2021-05-09 04:31:53 -07:00
} catch (err) {
console.log(err);
}
};
2021-03-26 06:29:27 -07:00
module.exports.verfiyemail = async (req, res, next) => {
const { email, otp } = req.body;
try {
let user = await User.findOne({ email: email });
if (user) {
const isMatched = await (user.email_otp == otp ? true : false);
if (isMatched) {
if (!user.isVerified) {
user.isVerified = true;
await user.save();
res.json({
message: "User Verified, Please Login",
});
} else {
res.json({
message: "User Already Verified, Please Login",
});
}
} else {
res.json({
message: "OTP Doesn't Matched!",
type: "error",
});
}
} else {
res.json({
message: "No user with this email exists",
type: "error",
});
}
} catch {
(err) => {
console.log(err);
};
}
};
2021-05-09 04:31:53 -07:00
module.exports.postSignin = async (req, res, next) => {
try {
//we need email and password as input
let email = req.body.email;
let password = req.body.password;
let user = await User.findOne({ email: email });
if (user) {
const isMatched = await bcrypt.compare(password, user.password);
if (isMatched) {
const token = jwt.sign({ _id: user._id }, JWT_secret);
res.json({
token: token,
});
} else {
res.json({
message: "email and password doesn't match",
type: "error",
});
}
} else {
res.json({
message: "No user with this email exists",
type: "error",
});
}
} catch (err) {
console.log(err);
}
};
2021-03-26 06:29:27 -07:00
2021-05-12 04:00:38 -07:00
// Phone verification Starts.
// -----------------------------------------------------------------------------------------------
2021-05-09 04:31:53 -07:00
module.exports.sendOTP = (req, res, next) => {
//uNNYosMopvvCW9RTR1tRWJmYC test
//llVKD53ve6QRpbCKOHzWBADaS live
const { phoneNumber } = req.body;
2021-05-09 04:31:53 -07:00
try {
if (!phoneNumber) {
res.status(422).json({ message: "Please Add All Required Fields" });
return;
} else {
messagebird.verify.create(
phoneNumber,
2021-03-26 06:29:27 -07:00
{
2021-05-09 04:31:53 -07:00
template: "Your verification code is %token",
},
function (err, response) {
if (err) {
console.log(err);
res.status(422).json({ message: err.errors[0].description });
} else {
console.log(response);
res.json({ id: response.id });
}
2021-03-26 06:29:27 -07:00
}
2021-05-09 04:31:53 -07:00
);
2021-03-26 06:29:27 -07:00
}
2021-05-09 04:31:53 -07:00
} catch (err) {
console.log(err);
}
};
module.exports.getOTP = (req, res, next) => {
try {
2021-05-12 04:00:38 -07:00
const { id, otp } = req.body;
messagebird.verify.verify(id, otp, function (err, response) {
2021-05-09 04:31:53 -07:00
if (err) {
console.log({ error: err.errors[0].description, id: id });
res.json({ error: err.errors[0].description, id: id });
} else {
console.log(response);
res.json({ message: "Code Verified" });
}
});
} catch (err) {
console.log(err);
}
};
2021-05-12 04:00:38 -07:00
// Phone verification End.
// -----------------------------------------------------------------------------------------------
// -----------------------------------------------------------------------------------------------
// Forgot password Starts
2021-05-12 04:00:38 -07:00
2021-05-11 07:25:34 -07:00
module.exports.forgotpassword = async (req, res, next) => {
const { email, link, sending_company_email, subject } = req.body;
2021-05-12 04:00:38 -07:00
//link = https://cantileverlabs.herokuapp.com/resetpassword/:id/:token
2021-05-12 02:16:11 -07:00
try {
await User.findOne({ email }).then((user) => {
if (!user) {
2021-05-11 07:25:34 -07:00
res.status(404).json({ error: "User not found with this Email" });
return;
} else {
const payload = {
2021-05-12 02:16:11 -07:00
email: user.email,
_id: user._id,
2021-05-11 07:25:34 -07:00
};
2021-05-12 02:16:11 -07:00
const secret = JWT_secret + user.password;
2021-05-11 07:25:34 -07:00
const token = jwt.sign(payload, secret, { expiresIn: "10m" });
2021-05-12 02:16:11 -07:00
User.findByIdAndUpdate(user._id, {
$set: { passwordResetToken: token },
})
.then((data) => {
const reset_link = `${link}/${user._id}/${token}`;
2021-05-12 03:44:03 -07:00
const message = {
from: `${sending_company_email}`, // Sender address
to: `${user.email}`, // List of recipients
subject: `${subject}`, // Subject line
html: `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta
name="viewport"
content="width=device-width, initial-scale=1.0 shrink-to-fit=no"
/>
<title>Forgot password</title>
<link
rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css"
/>
<link rel="stylesheet" href="./reset.css" />
<link
href="https://fonts.googleapis.com/css?family=Poppins"
rel="stylesheet"
/>
<link rel="preconnect" href="https://fonts.gstatic.com" />
<link
href="https://fonts.googleapis.com/css2?family=Poppins:wght@500;600;700;800&display=swap"
rel="stylesheet"
/>
<style>
body {
font-size: 16px;
font-family: Poppins;
letter-spacing: 0.02em;
}
.gray-reset-J {
background-color: #f2f7fb;
}
.reset-J h2 {
font-weight: 600;
}
.reset-J p {
font-weight: lighter;
font-size: 20px;
}
.reset-J button {
background-color: #ffc600;
color: white;
font-weight: 600;
font-size: 19px;
width: 340px;
border-radius: 10px 10px 10px 10px;
}
.reset-logo-J img {
width: 79px;
height: 79px;
}
.reset-logo1-J img {
width: 200px;
height: 50px;
}
.reset-logo2-J img {
width: 17px;
height: 17px;
}
.reset-light-J p {
font-size: 15px;
}
.light-copyright-J {
font-weight: lighter;
color: #6d6d6d;
}
.bold-copyright-J {
font-weight: 700;
color: #6d6d6d;
}
@media (max-width: 410px) {
.reset-J button {
width: 240px;
background-color: #ffc600;
color: white;
font-weight: 600;
font-size: 19px;
border-radius: 10px 10px 10px 10px;
}
}
</style>
</head>
<body>
<div class="container justify-content-center">
<div class="row justify-content-center">
<div
class="
m-5
px-5
py-4
gray-reset-J
col-xl-6 col-lg-6 col-md-8 col-sm-11 col-12
"
>
<div class="my-3 reset-logo-J">
<img src="./images/certificate design-11.png" alt="" />
</div>
<div class="reset-J">
<div class="my-4">
<h2 style="text-align: center">Hello</h2>
</div>
<p>
We got a request to reset your Password. No need to worry you can
reset your Password by clicking the Reset Button.
</p>
<a href=${reset_link}> <button class="btn p-3 my-3">Reset Password</button></a>
<div class="my-3">
<p>
Facing any other issue write us at
<a href="#">info@cantileverlabs.com</a>
</p>
</div>
<div class="my-4 reset-logo1-J">
<img src="./images/Rectangle 1048.png" alt="" />
</div>
<div class="reset-light-J">
<p>Privacy Policy | Terms of Use | Contact us</p>
</div>
</div>
<div class="reset-logo2-J my-5">
<img src="./images/Icon material-copyright.png" alt="" />
<span class="light-copyright-J"
>copyright
<span class="bold-copyright-J">2018 Cantilever Labs</span></span
>
</div>
</div>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
</body>
</html>
`, // design html for email message.
2021-05-12 03:44:03 -07:00
};
transport.sendMail(message, function (err, info) {
if (err) {
console.log(err);
} else {
console.log(info);
}
});
2021-05-12 02:16:11 -07:00
res.status(200).json({
message: "Link is Active for 10 mins",
2021-05-12 02:16:11 -07:00
reset_link,
});
})
.catch((err) => {
console.log(err);
});
2021-05-11 07:25:34 -07:00
}
});
2021-05-12 02:16:11 -07:00
} catch {
(error) => {
console.log("Error from forgot pass", error);
};
}
2021-05-11 07:25:34 -07:00
};
module.exports.resetpassword = async (req, res, next) => {
const { _id, token } = req.params;
const { password } = req.body;
2021-05-12 02:16:11 -07:00
try {
let user = await User.findById({ _id });
if (!user) {
res.json({ error: "User not Found or WrongId" });
return;
} else {
const secret = JWT_secret + user.password;
const user_token = user.passwordResetToken;
2021-05-11 07:25:34 -07:00
const payload = jwt.verify(token, secret);
2021-05-12 02:16:11 -07:00
const hashedPass = await bcrypt.hash(password, 12);
2021-05-11 07:25:34 -07:00
if (token == user_token) {
2021-05-12 02:16:11 -07:00
user.password = hashedPass;
await user
.save()
.then((ok) => {
2021-05-11 07:25:34 -07:00
res.json({ message: "Password Updated!" });
})
.catch((err) => {
2021-05-12 02:16:11 -07:00
console.log("Error in save", err);
2021-05-11 07:25:34 -07:00
});
} else {
2021-05-12 02:16:11 -07:00
res.status(422).json({ error: "Either Token not found or Expired!" });
return;
2021-05-11 07:25:34 -07:00
}
}
2021-05-12 02:16:11 -07:00
} catch {
(err) => {
console.log("error from try catch resetpass", err);
};
}
2021-05-11 07:25:34 -07:00
};
2021-04-01 06:38:27 -07:00
// Forgot password Ends
2021-05-12 04:00:38 -07:00
// -----------------------------------------------------------------------------------------------
2021-05-09 04:31:53 -07:00
module.exports.checkProtected = (req, res, next) => {
console.log(req.user);
res.json({
message: "Protected",
user: req.user,
});
};