json-object-editor
Version:
JOE the Json Object Editor | Platform Edition
121 lines (103 loc) • 4.19 kB
JavaScript
var jwtDecode = require('jwt-decode');
// var request = require("request");
//var got = require('got');
function Auth(){
var self = this;
this.default = function(data,req,res){
try{
var payload = {
params:req.params,
data:data
}
}catch(e){
return {errors:'plugin error: '+e,failedat:'plugin'};
}
return payload;
};
this.login = async function(data,req,res){
// Use got to exchange the Google authorization_code for tokens.
// We POST form-encoded params to the current Google OAuth token endpoint.
const gotMod = await import('got');
const got = gotMod.default || gotMod;
var originalUrl = data.state||'';
console.log(originalUrl);
const tokenUrl = 'https://oauth2.googleapis.com/token';
const options = {
method: 'POST',
// Google expects application/x-www-form-urlencoded body, not querystring.
form: {
grant_type: 'authorization_code',
code: data.code,
redirect_uri: `${JOE.webconfig.authorization.host}/API/plugin/auth/login`,
client_id: JOE.webconfig.authorization.client_id,
client_secret: JOE.webconfig.authorization.client_secret
},
headers: {
'cache-control': 'no-cache',
Accept: 'application/json'
},
responseType: 'json',
https: {
rejectUnauthorized: false
}
};
got(tokenUrl, options)
.then(response => {
const body = response.body || {};
// if (error){
// res.send(error);
// return;
// }
if (body.error){
// Bubble up Google's error payload so it's easier to diagnose
console.error('[auth.login] Google token error payload:', body);
res.status(400).send(body);
return;
}
//res.send(body);
//get creds
var id_token = body.id_token;
var access_token = body.access_token;
var user = {};
var idTokenInfo = jwtDecode(id_token);
//var accessTokenInfo = jwtDecode(access_token);
//user.username = accessTokenInfo.username.toLowerCase();
user.email = idTokenInfo.email.toLowerCase();
var users = (JOE.Data && JOE.Data.user) || [];
var User = users.where({email:user.email})[0]||false;
if(User){
//req.cookies._j_user && req.cookies._j_token
res.cookie('_j_user',User.name);
res.cookie('_j_token',User.token);
}else{
var finalUrl = originalUrl+(originalUrl.indexOf('?') == -1?'?':'&')+'noSSO=true'
res.redirect(finalUrl);
return;
}
//redirect to home or gotoUrl
res.redirect(originalUrl || `/JOE/${User.apps[0]}`);
})
.catch(error => {
// Log structured info so we can see status + body from Google
const status = error.response && error.response.statusCode;
const body = error.response && error.response.body;
console.error('[auth.login] HTTPError from Google token endpoint:', {
status,
body,
message: error.message
});
res.status(status || 500).send(body || {
error: 'oauth_token_error',
message: error.message
});
});
return({use_callback:true});
}
this.html = function(data,req,res){
return JSON.stringify(self.default(data,req),'','\t\r\n <br/>');
}
this.protected = [];
this.async = {login:true}
return self;
}
module.exports = new Auth();