JSONP callback doesn't seem to be working - node.js

I've been working with the Firebase Admin SDK for Nodejs in the cloud functions to create custom auth tokens using Spotify and Firebase auth.
I've been trying to use the example given by Google that goes as follows:
exports.token = functions.https.onRequest((req, res) => {
try {
cookieParser()(req, res, () => {
functions.logger.log('Received verification state:', req.cookies.state);
functions.logger.log('Received state:', req.query.state);
if (!req.cookies.state) {
throw new Error('State cookie not set or expired. Maybe you took too long to authorize. Please try again.');
} else if (req.cookies.state !== req.query.state) {
throw new Error('State validation failed');
}
functions.logger.log('Received auth code:', req.query.code);
Spotify.authorizationCodeGrant(req.query.code, (error, data) => {
if (error) {
throw error;
}
functions.logger.log(
'Received Access Token:',
data.body['access_token']
);
Spotify.setAccessToken(data.body['access_token']);
Spotify.getMe(async (error, userResults) => {
if (error) {
throw error;
}
functions.logger.log(
'Auth code exchange result received:',
userResults
);
// We have a Spotify access token and the user identity now.
const accessToken = data.body['access_token'];
const spotifyUserID = userResults.body['id'];
const profilePic = userResults.body['images'][0]['url'];
const userName = userResults.body['display_name'];
const email = userResults.body['email'];
// Create a Firebase account and get the Custom Auth Token.
const firebaseToken = await createFirebaseAccount(spotifyUserID, userName, profilePic, email, accessToken);
// Serve an HTML page that signs the user in and updates the user profile.
res.jsonp({token: firebaseToken});
});
});
});
} catch (error) {
res.jsonp({error: error.toString()});
}
return null;
});
Here's the code from the client for making the request
const loginError = ref(null)
const route = useRoute()
console.log(route.query)
const { code, state, error } = route.query
function tokenReceived(data) {
if (data.token) {
projectAuth.signInWithCustomToken(data.token).then((userCredential) => {
console.log(userCredential)
})
} else {
console.error(data)
document.body.innerText = 'Error in the token Function: ' + data.error
}
}
if (error) {
loginError.value = 'Error back from the Spotify auth page: ' + error
} else if (code) {
// Use JSONP to load the 'token' Firebase Function to exchange the auth code against a Firebase custom token.
const script = document.createElement('script')
script.type = 'text/javascript'
// This is the URL to the HTTP triggered 'token' Firebase Function.
// See https://firebase.google.com/docs/functions.
const tokenFunctionURL =
'http://localhost:5001/pacelist-main/us-central1/token'
script.src =
tokenFunctionURL +
'?code=' +
encodeURIComponent(code) +
'&state=' +
encodeURIComponent(state) +
'&callback=' +
tokenReceived.name
document.head.appendChild(script)
}
const signIn = () => {
// Start the auth flow.
window.location.href =
'http://localhost:5001/pacelist-main/us-central1/redirect'
}
return { loginError, signIn }
Full repository here: https://github.com/firebase/functions-samples/tree/main/spotify-auth
But the jsonp callback doesn't seem to run when it goes back to my site. It should "Serve an HTML page that signs the user in and updates the user profile." and log the user in, but it does nothing. Been stuck on this one for days...

Related

Magento2 Integration Oauth error - An error occurred validating the nonce

I am trying to activate Magento2, version 2.4.4, integration with expressjs backend.
The callback url is being hit and the data is being stored in the db. Then upon hitting the identity url, the pop up of login for app to be integrated is opened and user logs in.
Following the oauth process as defined at https://devdocs.magento.com/guides/v2.4/get-started/authentication/gs-authentication-oauth.html#pre-auth-token on making the POST request to /oauth/token/request I'm getting the following error -
oauth_problem=An+error+occurred+validating+the+nonce
I cannot figure out the source of this error, please help me fix this as I've been stuck at it since many days.
Following are one of the values calculated for the header Authorization and the post body -
Authorization: 'OAuth oauth_consumer_key=kxw5v6vwr4rm77cn2pxmqxdzdhhkor58, oauth_nonce=Fi9KRqgAmSX7sf32YpCTdPQ15FIY-LyY, oauth_signature=OTUzNWU4ZDViMzljZmM1NTM2MDNiMGQxOTUyMmRmMGRiMjdkZDZmNzY5ZTIxZTZkNGM1MzMzMmRkN2U5ZjcxNQ%3D%3D, oauth_signature_method=HMAC-SHA256, oauth_timestamp=1652694701394, oauth_version=1.0'
POST BODY -
{
oauth_consumer_key: 'kxw5v6vwr4rm77cn2pxmqxdzdhhkor58',
oauth_nonce: 'Fi9KRqgAmSX7sf32YpCTdPQ15FIY-LyY',
oauth_signature: 'OTUzNWU4ZDViMzljZmM1NTM2MDNiMGQxOTUyMmRmMGRiMjdkZDZmNzY5ZTIxZTZkNGM1MzMzMmRkN2U5ZjcxNQ%3D%3D',
oauth_signature_method: 'HMAC-SHA256',
oauth_timestamp: '1652694701394',
oauth_version: '1.0'
}
Following is callback url route code -
router.post('/magento-integration/callback', callbackHandler);
async function callbackHandler(req, res) {
const [{store_base_url, oauth_verifier, oauth_consumer_key, oauth_consumer_secret}] = [req.body];
try {
await saveOAuthCredentials({
store_base_url,
oauth_verifier,
oauth_consumer_key,
oauth_consumer_secret
});
return ApiResponse(res, 200);
} catch (err) {
// TODO: check err and set precise value of response status code and err msg
console.error(err.message)
return ApiResponse(res, 500, {message: err});
}
}
Following is the code for the controller of identity url route -
async function appLogin(req, res) {
// code to validate user
// ......
// Magento2 OAuth token exchange initiation
// Magento2 initiates the token exchange process by requesting the /login endpoint and sends
// url encoded query string params oauth_consumer_key and success_call_back which the front end sends in
// the body, against key queryParams, of the request it makes to /appLogin endpoint of sx-sellerapi.
const {oauth_consumer_key, success_call_back} = req.body.queryParams req.body.queryParams : [{}];
if(oauth_consumer_key && success_call_back){
try{
await runMagentoOAuthKeyX(sellerInfo.id, oauth_consumer_key);
res.redirect(success_call_back);
return;
} catch(err) {
return ApiResponse(res, 400, {message: err})
}
}
// rest of the code for usual login
}
Code for runMagentoOAuthKeyX
async function runMagentoOAuthKeyX(sellerId, oauthConsumerKey) {
try {
const oauthCred = await magentoModel.checkOAuthConsumerKeyExists(oauthConsumerKey, sellerId);
// isNonEmptyObject checks if arg passed is of type Object and has keys
if (isNonEmptyObject(oauthCred)) {
oauthCred.oauth_consumer_key = oauthConsumerKey;
oauthCred.url = `${oauthCred.store_base_url}${OAUTH_TOKEN_ENDPOINTS.request}`;
let requestTokenData;
try{
requestTokenData = await getToken(oauthCred, OAUTH_TOKEN_TYPE.requestToken);
} catch(err){
throw err
}
return Promise.all([
magentoModel.updateOAuthCred(oauthConsumerKey, requestTokenData, OAUTH_TOKEN_TYPE.requestToken),
getToken({...oauthCred, ...requestTokenData,
...{url: `${oauthCred.store_base_url}${OAUTH_TOKEN_ENDPOINTS.access}`}}, OAUTH_TOKEN_TYPE.accessToken)
])
.then(async ([_, accessTokenData]) =>
magentoModel.updateOAuthCred(oauthConsumerKey, accessTokenData, OAUTH_TOKEN_TYPE.accessToken)
)
.catch(err => {
throw err;
});
} else {
throw new Error(`OAuthConsumer key passed is unknown ${oauthConsumerKey}`);
}
} catch (err) {
// TODO: add logging
throw err;
}
Code for getToken()
async function getToken(tokenData, tokenType) {
const {url} = tokenData
const [authHeader, body] = await getAuthHeaderAndBody(tokenData, tokenType);
return axios.post(
url,
body,
{
headers: {
Authorization: authHeader
}
})
.catch(err => {
console.error(err.response.data);
throw err;
});
}
Code for getAuthHeaderAndBody
async function getAuthHeaderAndBody(tokenData, tokenType) {
const oauth_nonce = await genOAuthNonce();
const oauth_timestamp = Date.now();
const {
oauth_consumer_key,
oauth_consumer_secret,
oauth_signature_method,
url,
oauth_token,
oauth_token_secret,
oauth_verifier
} = tokenData;
const tokenList = ['access', 'webAPI'];
const oauthSignature = genOAuthSignature(url, {
oauth_consumer_key,
oauth_consumer_secret,
oauth_signature_method,
oauth_nonce,
oauth_timestamp,
oauth_version: OAUTH_VERSION,
oauth_token: tokenList.includes(tokenType) ? oauth_token : null,
oauth_token_secret: tokenList.includes(tokenType) ? oauth_token_secret : null,
oauth_verifier: OAUTH_TOKEN_TYPE.accessToken === tokenType ? oauth_verifier : null
});
const validParams = Object.entries({
oauth_consumer_key,
oauth_signature_method,
oauth_signature: oauthSignature,
oauth_nonce,
oauth_timestamp,
oauth_version: OAUTH_VERSION,
oauth_token: tokenList.includes(tokenType) ? oauth_token : null,
oauth_verifier: OAUTH_TOKEN_TYPE.accessToken == tokenType ? oauth_verifier : null
})
.filter(([_, val]) => val !== null)
.sort((a, b) => a[0] < b[0] ? -1 : 0);
const authHeaderValue = validParams
.map(([key, val]) => `${encodeURIComponent(key)}=${encodeURIComponent(val)}`)
.join(', ');
const authHeaderStart = [OAUTH_TOKEN_TYPE.requestToken, OAUTH_TOKEN_TYPE.accessToken].includes(tokenType) ? 'OAuth' : 'Bearer';
const authHeader = `${authHeaderStart} ${authHeaderValue}`;
return [authHeader, Object.fromEntries(validParams)];
}
Code for genOAuthNonce -
async function genOAuthNonce() {
const charset = '0123456789ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvwxyz-._~';
const buff = Buffer.alloc(32);
const result = [];
return new Promise((resolve, reject) => crypto.randomFill(buff, (err, buff) => {
if(err){
reject(err);
}
buff.forEach(c => result.push(charset[c % charset.length]));
resolve(result.join(''));
}));
}
Code for genOAuthSignature
function genOAuthSignature(baseUrl, params, method = 'POST') {
const keysNotInSignature = ['oauth_consumer_secret', 'oauth_token_secret'];
const signatureString = Object.entries(params)
.filter(([key, val]) => val
!= null && !keysNotInSignature.includes(key))
.sort((item1, item2) => item1[0] < item2[0 ] ? -1 : 0)
.map(([key, val]) => `${key}=${val}`)
.join(AUTH_HEADER_DELIMITER);
const baseString = [
encodeURIComponent(method.toUpperCase()),
encodeURIComponent(baseUrl),
encodeURIComponent(signatureString)
].join(AUTH_HEADER_DELIMITER);
const {oauth_consumer_secret, oauth_token_secret} = params;
let signKey = `${encodeURIComponent(oauth_consumer_secret)}${AUTH_HEADER_DELIMITER}`
signKey += oauth_token_secret ? `${encodeURIComponent(oauth_token_secret)}` : '';
const hmac = createHmac('sha256', signKey);
return Buffer.from(hmac.update(baseString).digest('hex')).toString('base64');
}
Found the bugs in the code for invalid Nonce. The issue was with timestamp as I was using Date.now() which returns UTC timestamp in ms whereas magento2 oauth requires it to be in seconds. Also found and fixed the bug in evaluating the signature for oauth token exchange.
In function getAuthHeaderAndBody -
async function getAuthHeaderAndBody(tokenData, tokenType) {
const oauth_nonce = await genOAuthNonce();
// changed below from Date.now() as timestamp must be in seconds.
const oauth_timestamp = parseInt(Date.now() / 1000);
// ... rest of the code
}
In genOAuthSignature
function genOAuthSignature(baseUrl, params, method = 'POST') {
// preceding code
// last line is changed by looking at Magento2 code for validating the signature
return createHmac('sha256', signKey)
.update(baseString, 'binary')
.digest()
.toString('base64');
}

Firebase Cloud Function Volley Post request returning Unexpected response code 500

Im trying to call a Clound function using a Volley POST request but it is returning error Unexpected response code 500. What this code does is basically request a Token string from the user and then reformat it with new info and then return the new token to the user.
Here is the Java code
RequestQueue mRequestQueue = Volley.newRequestQueue(this);
StringRequest mCloudRequest = new StringRequest(Request.Method.POST,
"my_function_url_from_firebase", new Response.Listener<String>() {
#Override
public void onResponse(String response) {
signInToFirebaseWithCustomToken(response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}){
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("id_token", huaweiAccount.getIdToken());
params.put("uid", uid);
params.put("name", huaweiAccount.displayName);
if (huaweiAccount.email != null) {
params.put("email", huaweiAccount.email);
} else {
params.put("email", "");
}
params.put("photoURL", "");
return params;
}
};
And here is the index.js file.
const app = express();
const bodyParser = require('body-parser');
const PORT = process.env.PORT || 5000;
const functions = require('firebase-functions');
// Firebase Admin SDK
const admin = require('firebase-admin');
const serviceAccount = require('./serviceAccountKey.json');
// For make network calls
const request = require('request-promise');
// Initialize Firebase Admin
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
databaseURL: 'my_firebase_server_url',
});
// Initialize Express and create endpoint
app
.use(bodyParser.json()) // Parse json in request body
.use(bodyParser.urlencoded({
extended: true,
}))
.post('/createCustomToken', (req, res) => {
if (req.body.id_token === undefined) {
// idToken is not find
const ret = {
error_message: 'id_token not found',
};
return res.status(400).send(ret);
}
// Verify idToken
// Create new user on Firebase if user doesn't exist
// Generate custom auth token
// Return client
return verifyHuaweiToken(req.body)
.then((customAuthToken) => {
const ret = {
firebase_token: customAuthToken,
};
return res.status(200).send(ret);
}).catch((err) => {
return res.status(400).send(err);
});
})
.listen(PORT, () => console.log(`Listening on ${ PORT }`));
// Verify idToken on Huawei Server
function verifyHuaweiToken(body) {
return request({
method: 'GET',
uri: 'https://oauth-login.cloud.huawei.com/oauth2/v3/tokeninfo?id_token=' + body.id_token,
json: true,
}).then((response) => {
// Token invalid. Throw an error and stop process
if (response.error !== undefined) {
return Promise.reject(new Error('Something went wrong'));
}
// Get user
return getFirebaseUser(body);
}).then((userRecord) => {
// After user created on Firebase, create new custom token based on user uid
return admin.auth().createCustomToken(userRecord.uid);
}).then((token) => {
// Return token to client
return token;
});
}
function getFirebaseUser(body) {
const firebaseUid = 'huawei_' + body.uid;
// Find user by user uid
return admin.auth().getUser(firebaseUid).then(function(userRecord) {
return userRecord;
}).catch((error) => {
// If user is not exist on Firebase, create new one
if (error.code === 'auth/user-not-found') {
return admin.auth().createUser({
uid: firebaseUid,
displayName: body.name,
photoURL: body.picture,
email: body.email,
});
}
return Promise.reject(error);
});
}
exports.app = functions.https.onRequest(app);
Does anyone know what is wrong with my backend code? or is it the user side code the one causing the problem?
Please help me. Im not a Backend expert.
a simple example in firebase functions to create custom token would be like this one:
const functions = require('firebase-functions');
const firebaseAdmin = require('firebase-admin');
const express = require('express');
const app = express();
firebaseAdmin.initializeApp({
serviceAccountId: 'SERVICE-ACCOUNT_EMAIL',
databaseURL: 'https://PTOJECT-id.firebaseio.com'
});
app.post('/token', async (req, res) => {
try {
const token = await firebaseAdmin.auth().createCustomToken(req.body.userUID);
res.status(200).send(token)
} catch (error) {
res.status(500).send("something went wrong")
}
});
module.exports.app = functions.https.onRequest(app);
make sure that your service account has at least the iam.serviceAccounts.signBlob permission which is included in the role roles/iam.serviceAccountTokenCreator

how to refresh token on google oauth2 using firebase functions?

I developed an integration using Google Oauth2 inside firebase functions to access Google Sheets API. The integration works correctly but I'm having problems to make sure the refresh token is running correctly. The function stops working after the first token expires.
when this happens the following error occur:
Function execution started
Error: No refresh token is set.
at OAuth2Client.refreshTokenNoCache (/workspace/node_modules/googleapis-common/node_modules/google-auth-library/build/src/auth/oauth2client.js:161:19)
at OAuth2Client.refreshToken (/workspace/node_modules/googleapis-common/node_modules/google-auth-library/build/src/auth/oauth2client.js:142:25)
at OAuth2Client.getRequestMetadataAsync (/workspace/node_modules/googleapis-common/node_modules/google-auth-library/build/src/auth/oauth2client.js:256:28)
at OAuth2Client.requestAsync (/workspace/node_modules/googleapis-common/node_modules/google-auth-library/build/src/auth/oauth2client.js:329:34)
at OAuth2Client.request (/workspace/node_modules/googleapis-common/node_modules/google-auth-library/build/src/auth/oauth2client.js:323:25)
at createAPIRequestAsync (/workspace/node_modules/googleapis-common/build/src/apirequest.js:292:27)
at Object.createAPIRequest (/workspace/node_modules/googleapis-common/build/src/apirequest.js:43:9)
at Resource$Spreadsheets$Values.update (/workspace/node_modules/googleapis/build/src/apis/sheets/v4.js:601:37)
at exports.loadStripeData.functions.runWith.https.onRequest (/workspace/index.js:176:32)
at process._tickCallback (internal/process/next_tick.js:68:7)
I want to make sure the token refresh correctly and get stored on Firestore.
What am I doing wrong?
index.js:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
const {google} = require('googleapis');
const sheets = google.sheets('v4');
admin.initializeApp();
const CLIENT_ID = 'CLIENT_ID';
const CLIENT_SECRET = 'CLIENT_SECRETT';
const REDIRECT_URL = 'https://us-central1-MY-PROJECT.cloudfunctions.net/oauth2callback';
const SCOPES = ['https://www.googleapis.com/auth/spreadsheets'];
oauth2Client.on('tokens', (tokens) => {
if (tokens.refresh_token) {
try {
admin.firestore()
.collection('oauth2')
.doc('google')
.set({
tokens: tokens.refresh_token,
});
} catch (error) {
console.error(JSON.stringify(error));
}
}
});
/*asks user permission to access his spreadsheets*/
exports.authenticate = functions.https.onRequest((req, res) => {
const authorizeUrl = oauth2Client.generateAuthUrl({
access_type: 'offline',
scope: SCOPES.join(','),
});
res.send(`<html>click here: ${authorizeUrl}</html>`)
});
/*callback function for when the user finishes authenticating*/
exports.oauth2callback = functions.https.onRequest(async(req, res) => {
const code = req.query.code.toString() || '';
try {
await admin.firestore()
.collection('oauth2')
.doc('google')
.set({
code: decodeURIComponent(code)
});
} catch(error) {
res.send(JSON.stringify(error))
}
res.send('auth successfully. You can close this tab');
});
/* get token from Firestone to execute function*/
async function oauth2Auth() {
const doc = await admin.firestore()
.collection('oauth2')
.doc('google')
.get();
const credentials = doc.data();
if (credentials.code !== undefined) {
const response = await oauth2Client.getToken(credentials.code);
credentials.tokens = response.tokens;
delete credentials.code;
try {
await admin.firestore()
.collection('oauth2')
.doc('google')
.set({
tokens: credentials.tokens,
})
} catch (error) {
console.error(error);
}
}
oauth2Client.setCredentials(credentials.tokens);
}
/*function that requires google sheets api*/
exports.mainFunction = functions.https.onRequest(async(req, res) => {
oauth2Auth();
//do main function
});
Finally discovered the problem!
You only get the refreshing token in the first time you ask for authorization. So if you're don't save it correctly you have to ask permission again.
To solve it:
when redirecting the user to the authorization URL add the following parameters to have sure you get the refreshing token:
access_type=offline&prompt=consent
to save the refreshing token:
oauth2Client.on('tokens', async(tokens:any) => {
if (tokens.refresh_token) {
try {
const authorization = await oauth2Client.getToken(tokens.refresh_token);
await admin.firestore()
.collection('collectionName')
.doc(docId)
.update({
token: authorization.tokens
})
} catch (error) {
console.error(JSON.stringify(error));
}
}
});

getting error UnhandledPromiseRejectionWarning: Error: Can't set headers after they are sent. in express js api

I am working on express js api with jwtr,when i run the api it gives me error:
UnhandledPromiseRejectionWarning: Error: Can't set headers after they
are sent.
can anyone please help me why i am getting this error, here i have added my code, can anyone please look in it, and help me to resolve this issue,
const requireAuthentication = async(req, res, next) => {
try {
const token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiIxUWpuTDBhd2lTIiwiaWF0IjoxNTY5OTQwMjgyfQ.1xwX2OULW4RjKW4Ok13mwlJE8k95u-d0o7T6k5U9tjs'; //req.headers['vrc-access-token'];
if (!token) return res.status(401).send('Failed to authenticate token.');
let verify_token_data = await jwtr.verify(token, secret);
if(typeof verify_token_data.jti != 'undefined') {
req.body.username = verify_token_data.username;
req.body.organization = verify_token_data.organization;
req.body.userId = verify_token_data.id;
req.body.organizationId = verify_token_data.organizationId;
console.log("sdsd234");
// create a new token
const newToken = await jwtr.sign({
username: verify_token_data.username,
organization: verify_token_data.organization,
id: verify_token_data.id,
organizationId: verify_token_data.organizationId
}, config['token-secret']);
console.log(newToken);
req.refreshToken = newToken;
console.log('sdfdf');
return await next();
} else {
return res.status(401).send('Failed to authenticate token.');
}
} catch (error) {
return res.status(401).send(error.message);
}
};
i have had this issue before and it happens because you have already send the response back to the server and it reaches a code which sends a response again.
i think that the issue is when you do
return await next()
what you should do is:
next()
const requireAuthentication = async(req, res, next) => {
try {
const token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiIxUWpuTDBhd2lTIiwiaWF0IjoxNTY5OTQwMjgyfQ.1xwX2OULW4RjKW4Ok13mwlJE8k95u-d0o7T6k5U9tjs'; //req.headers['vrc-access-token'];
if (!token) return res.status(401).send('Failed to authenticate token.');
let verify_token_data = await jwtr.verify(token, secret);
if(typeof verify_token_data.jti != 'undefined') {
req.body.username = verify_token_data.username;
req.body.organization = verify_token_data.organization;
req.body.userId = verify_token_data.id;
req.body.organizationId = verify_token_data.organizationId;
// create a new token
const newToken = await jwtr.sign({
username: verify_token_data.username,
organization: verify_token_data.organization,
id: verify_token_data.id,
organizationId: verify_token_data.organizationId
}, config['token-secret']);
console.log(newToken);
req.refreshToken = newToken;
next();
} else {
return res.status(401).send('Failed to authenticate token.');
}
} catch (error) {
return res.status(401).send(error.message);
}
};

How to implement jwt verify token in node js

I tried to implement jwt token generation in node js.I got jwt token but how to validate token using node js crud operation.but I got token jwt verfiy code using callback function.without call back function used to implement async/awit function implement.
index.js
router.post('/', async (req, res) => {
(async function() {
try {
await client.connect();
console.log("Connected correctly to server");
const db = client.db('olc_prod_db');
//Validation
const { error } = validate.validate(req.body);
if (error)
{
return res.status(400).send(error.details[0].message);
}
else
{
const check_login = req.body
const r = await db.collection('UserRegistration').find().toArray();
r.forEach(element => {
if(element['username'] == check_login['username'])
{
const token = get_token.validate(req.body)
res.send({"token ":token})
}
else
{
return res.send(401,"Un Authorized");
}
});
}
client.close();
} catch(err) {
console.log(err.stack);
}
})();
});
authtoken.js
var jwt = require('jsonwebtoken')
function get_token(userdata)
{
var accessToken = jwt.sign(userdata, 'secretkey', {
//Set the expiration
expiresIn: 3600 //we are setting the expiration time of 1 hr.
});
//send the response to the caller with the accesstoken and data
console.log('Authentication is done successfully.....');
return accessToken
}
exports.validate = get_token;
const jwt = require('jsonwebtoken')
const config = require('../../config/default')
function verifyjwt(req,res,next){
const token = req.headers['authorization']
if(!token) return res.status(401).json('Unauthorize user')
try{
const decoded = jwt.verify(token,config.secret);
req.user = decoded
next()
}catch(e){
res.status(400).json('Token not valid')
}
}
module.exports = verifyjwt
const CONST = require('../../config')
exports.validJWTNeeded = (req, res, next) => {
if (req.headers['authorization']) {
try {
let authorization = req.headers['authorization'].split(' ');
if (authorization[0] !== 'Bearer') {
return res.status(401).send('invalid request'); //invalid request
} else {
req.jwt = jwt.verify(authorization[1], CONST.SECRET);
return next();
}
} catch (err) {
return res.status(403).send(); //invalid token
}
} else {
return res.status(401).send('invalid request');
}
}

Resources