// Only Logic code included - modify according to your project
// do basic things create app.js & create routes, controller and models folder and add files respectively IndexRouter.js , IndexController.js & IndexModel.js
// IndexRouter.js (only logic code added here)
router.post("/register",(req,res)=>{
IndexController.registerUser(req.body).then((result)=>{
var token = result.token; // this token is added from result coming from IndexController
sendEmail(req.body.email,req.body.password,token);
res.render("register",{"output":"User register successfully..."});
//res.status(201).send({ message : "User Logged In"})
}).catch((err)=>{
res.render("register",{"output":err});
//console.log(err);
});
});
=====================
//IndexController.js start
class IndexController {
registerUser(userDetails,cb) {
return new Promise((resolve,reject)=>{
IndexModel.fetchUsers({}).then((result)=>{
var l=result.length;
var _id=(l==0)?1:result[l-1]._id+1;
var token = crypto.randomBytes(32).toString("hex"); // random key to add in link
userDetails={...userDetails,"_id":_id,"status":0,"role":"user","info":Date(),"token":token}
IndexModel.registerUserModel(userDetails).then((result)=>{
resolve(result);
}).catch((err)=>{
reject(err);
});
}).catch((err)=>{
reject(err);
});
})
}
}
=============================================================
//connection.js // for database creation and connectivity
import mongoose from 'mongoose'; // to connect with Mongo database we use mongoose module
const url="mongodb://localhost:27017/vasu1" // here vasu1 is database name ,
mongoose.set('strictQuery',true) // new updated version of mongoose require this query
mongoose.connect(url);
console.log("Successfully connected to mongodb database....");
===================================================================
//IndexModel.js start
//Create your own RegisterSchema and import it
class IndexModel
{
registerUserModel(userDetails) {
return new Promise((resolve,reject)=>{
var obj = new RegisterSchemaModel(userDetails);
obj.setPassword(userDetails.password);
obj.save((err,result)=>{
err ? reject(err) : resolve(result) ;
});
});
}
}
===============================================================
// user will get email like this
// your token will be seen like this in database
as well you can see status is 0 in database , it means user can not login until status will be 1 , and we are going to get update this status 0 to 1 via link by user.
now we have to add this token to our link which will be sent to user on registration . on the time of registration a automatic email sent to user's email (You Can See MY previous Post ). so we have to add only token in it. you can see above in IndexRouter.js coding we have passed token as argument also.
sendEmail(req.body.email,req.body.password,token);
=======================================================================
// go to EmailAPI.js in routes folder
import nodemailer from 'nodemailer';
var sendMail=(email,password,token)=>{
process.env.NODE_TLS_REJECT_UNAUTHORIZED='0'
var transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: 'vasubirla@gmail.com', // through which you want to send to verification mails
pass: 'mtvrqzmxlarnrkl' // create your own temporary password in google security setting
}
});
var mailOptions = {
from: 'vasubirla@gmail.com',
to: email,
subject: 'Verification Mail MyApp',
html: "<h1>Welcome To MyApp</h1><p>you have successfully register to our app , your login credentials are attached below</p><h3>Email : "+email+"</h3><h3>Password : "+password+"</h1>"+"</h3><br><h2>Click on the link below to verify your account</h2>http://localhost:3000/verifyUser/"+email+'/'+token
};
transporter.sendMail(mailOptions, function(error, info){
if (error) {
console.log(error);
} else {
console.log('Email sent: ' + info.response);
}
});
}
export default sendMail; // export this function to use in IndexRouter.js at the time or registration
=======================================================================
Now We have sent Email with unique link successfully - now we have to get update status value 0 to 1 in database when user click on that unique link sent to his email .
// IndexRouter.js
//here email & token is parameter added to link localhost:3000/verifyuser/vasubirla.com/(here we have to add token value)
//Whenever User will click on link - email value will be set in /:email parameter and token value will be set in /:token parameter .
router.get("/verifyuser/:email/:token",(req,res)=>{
console.log(req.params);
IndexController.verifyUser(req.params).then((result)=>{
res.render("verifyuser",{"output":"User Verified successfully...","output1":""});
console.log(result);
}).catch((err)=>{
res.render("verifyuser",{"output1":"Failed to Verify User","output":""});
console.log(err);
});
});
==================================
//IndexController.js
import IndexModel from '../models/IndexModel.js';
class IndexController {
verifyUser(tokenDetails)
{
return new Promise((resolve,reject)=>{
IndexModel.verifyUser(tokenDetails).then((result)=>{
resolve(result);
}).catch((err)=>{
reject(err);
});
});
}
}
=====================================================================
// IndexModel.js ........
import './connection.js'; // we already created above
import RegisterSchemaModel from '../schema/RegisterSchema.js'; // open my previous post to find coding of Register schema
class IndexModel{
verifyUser(tokenDetails)
{
return new Promise((resolve,reject)=>{
RegisterSchemaModel.update({"token":tokenDetails.token},{"status":1},(err,result)=>{
err ? reject(err) : resolve(result);
});
})
}
}
=====================================================================
Now user's status is 1 in data base so he can login now.
if you have any doubts send Email at vasubirla@gmail.com
Thanks
Comments
Post a Comment