Skip to content

Commit

Permalink
Check authentication with admin key
Browse files Browse the repository at this point in the history
  • Loading branch information
kenshin-samourai committed Jul 9, 2019
1 parent 7dd4af9 commit 1379a70
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 8 deletions.
20 changes: 12 additions & 8 deletions static/admin/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ function login() {

// Checks input fields
if (!apiKey) {
lib_msg.displayErrors('API key is mandatory');
lib_msg.displayErrors('Admin key is mandatory');
return;
}

Expand All @@ -20,13 +20,17 @@ function login() {
function (result) {
const auth = result['authorizations'];
const accessToken = auth['access_token'];
lib_auth.setAccessToken(accessToken);
const refreshToken = auth['refresh_token'];
lib_auth.setRefreshToken(refreshToken);
sessionStorage.setItem('activeTab', '');
lib_msg.displayInfo('Successfully connected to your backend');
// Redirection to default page
lib_cmn.goToDefaultPage();
if (lib_auth.isAdmin(accessToken)) {
lib_auth.setAccessToken(accessToken);
const refreshToken = auth['refresh_token'];
lib_auth.setRefreshToken(refreshToken);
sessionStorage.setItem('activeTab', '');
lib_msg.displayInfo('Successfully connected to your backend');
// Redirection to default page
lib_cmn.goToDefaultPage();
} else {
lib_msg.displayErrors('You must sign in with the admin key');
}
},
function (jqxhr) {
let msg = lib_msg.extractJqxhrErrorMsg(jqxhr);
Expand Down
33 changes: 33 additions & 0 deletions static/admin/lib/auth-utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,9 @@ var lib_auth = {
/* JWT Scheme */
JWT_SCHEME: 'Bearer',

/* Admin profile */
TOKEN_PROFILE_ADMIN: 'admin',


/*
* Retrieves access token from session storage
Expand Down Expand Up @@ -87,6 +90,36 @@ var lib_auth = {
return (token && (token != 'null')) ? true : false;
},

/*
* Extract the payload of an access token
* in json format
*/
getPayloadAccessToken: function(token) {
if (!token)
token = this.getAccessToken();

if (!token)
return null;

try {
const payloadBase64 = token.split('.')[1];
const payloadUtf8 = atob(payloadBase64);
return JSON.parse(payloadUtf8);
} catch {
return null;
}
},

/*
* Check if user has admin profile
*/
isAdmin: function(token) {
const payload = this.getPayloadAccessToken(token);
if (!payload)
return false;
return (('prf' in payload) && (payload['prf'] == this.TOKEN_PROFILE_ADMIN));
},

/*
* Local logout
*/
Expand Down

0 comments on commit 1379a70

Please sign in to comment.