diff --git a/static/admin/index.js b/static/admin/index.js index 58a8519d..75eff0ec 100644 --- a/static/admin/index.js +++ b/static/admin/index.js @@ -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; } @@ -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); diff --git a/static/admin/lib/auth-utils.js b/static/admin/lib/auth-utils.js index c0874184..f0aa8187 100644 --- a/static/admin/lib/auth-utils.js +++ b/static/admin/lib/auth-utils.js @@ -12,6 +12,9 @@ var lib_auth = { /* JWT Scheme */ JWT_SCHEME: 'Bearer', + /* Admin profile */ + TOKEN_PROFILE_ADMIN: 'admin', + /* * Retrieves access token from session storage @@ -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 */