Currently, I am utilizing a jwt token for user registration validation. A unique URL is generated and sent to the user via email, which leads them to the authentication page. On the server side, the token is decoded and I need to transmit this JSON data to Angular on the client side. How can I achieve this by using the token as a query parameter and fetching it with ngResource?
server.js
'use strict';
var express = require('express');
var app = express();
var router = express.Router();
var bodyParser = require('body-parser');
var nodemailer = require('nodemailer');
var jwt = require('jsonwebtoken');
var moment = require('moment');
var port = process.env.PORT || 5000;
app.use(express.static('./src/client/'));
app.use(express.static('./'));
app.use(express.static('./.tmp'));
app.use('/*', express.static('./src/client/index.html'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
// Generating token with expiration time
var expires = moment().add(12, 'hours').valueOf();
var token = jwt.sign({
user: 'userdata',
iat: Math.floor(Date.now() / 1000),
expireIn: expires
}, 'thisismysecretstring');
// Nodemailer sendMail function
app.post('/sendMail', function(req, res) {
var transporter = nodemailer.createTransport('smtp://b204bf8f6ede15:<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="efd8de8dda8cdedbd8dcd7dadd8addaf828e86839b9d8e9fc18680">[email protected]</a>:2525');
var data = req.body;
var mailOptions = {
from: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="88e6e7faedf8e4f1c8e1f0eee1faeda6ebe7e5">[email protected]</a>',
to: data.email,
subject: 'Email sent by ' + data.displayName,
html: '<p>Please click on url below to register</p><br><a href="http://localhost:3000/auth/?token='+token+'">CLICK HERE</a>'
};
transporter.sendMail(mailOptions, function(error, info) {
if (error) {
return console.log(error);
}
console.log('Message sent: ' + info.response);
});
res.json(token);
});
// Decoding token from URL parameter
app.get('/auth', function(req, res) {
var token = req.query.token;
try {
var decoded = jwt.verify(token, 'thisismysecretstring');
if (decoded.exp <= Date.now()) {
res.end('Access token has expired', 400);
}
res.json(decoded);
} catch (err) {
console.log(err);
res.json(err);
}
});
app.listen(port, function () {
console.log('Express app listening on port: ' + port);
console.log(__dirname);
});
token.js
(function() {
'use strict';
angular
.module('xfire.token', ['ngResource'])
.factory('Token', function($resource) {
return $resource('auth/:token', {
token: '@token'
});
});
})();
Example of url format:
http://localhost:3000/auth/?token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyIjoiZ2NmYWJyaSIsImlhdCI6MTQ2ODI0NDI1NCwiZXhwaXJlSW4iOjIxNjAwMDAwfQ.5rs1rlWMTTcap4idG-XOU-UiwbU0YzlnAYjm9Vwz-B0