|
| 1 | +import settings from './settings'; |
| 2 | +import api from './api'; |
| 3 | +import messages from './text'; |
| 4 | + |
| 5 | +const LOGIN_PATH = '/admin/login'; |
| 6 | +const HOME_PATH = '/admin/'; |
| 7 | + |
| 8 | +const getParameterByName = (name, url) => { |
| 9 | + if (!url) url = window.location.href; |
| 10 | + name = name.replace(/[\[\]]/g, '\\$&'); |
| 11 | + var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)'), |
| 12 | + results = regex.exec(url); |
| 13 | + if (!results) return null; |
| 14 | + if (!results[2]) return ''; |
| 15 | + return decodeURIComponent(results[2].replace(/\+/g, ' ')); |
| 16 | +}; |
| 17 | + |
| 18 | +export const validateCurrentToken = () => { |
| 19 | + if (location.pathname !== LOGIN_PATH) { |
| 20 | + if (!isCurrentTokenValid()) { |
| 21 | + location.replace(LOGIN_PATH); |
| 22 | + } |
| 23 | + } |
| 24 | +}; |
| 25 | + |
| 26 | +export const checkTokenFromUrl = () => { |
| 27 | + if (location.pathname === LOGIN_PATH) { |
| 28 | + const token = getParameterByName('token'); |
| 29 | + if (token && token !== '') { |
| 30 | + const tokenData = parseJWT(token); |
| 31 | + |
| 32 | + if (tokenData) { |
| 33 | + const expiration_date = tokenData.exp * 1000; |
| 34 | + if (expiration_date > Date.now()) { |
| 35 | + saveToken({ token, email: tokenData.email, expiration_date }); |
| 36 | + location.replace(HOME_PATH); |
| 37 | + } else { |
| 38 | + alert(messages.tokenExpired); |
| 39 | + } |
| 40 | + } else { |
| 41 | + alert(messages.tokenInvalid); |
| 42 | + } |
| 43 | + } else { |
| 44 | + if (isCurrentTokenValid()) { |
| 45 | + location.replace(HOME_PATH); |
| 46 | + } |
| 47 | + } |
| 48 | + } |
| 49 | +}; |
| 50 | + |
| 51 | +const parseJWT = jwt => { |
| 52 | + try { |
| 53 | + const payload = jwt.split('.')[1]; |
| 54 | + const tokenData = JSON.parse(atob(payload)); |
| 55 | + return tokenData; |
| 56 | + } catch (e) { |
| 57 | + return null; |
| 58 | + } |
| 59 | +}; |
| 60 | + |
| 61 | +const saveToken = data => { |
| 62 | + localStorage.setItem('dashboard_token', data.token); |
| 63 | + localStorage.setItem('dashboard_email', data.email); |
| 64 | + localStorage.setItem('dashboard_exp', data.expiration_date); |
| 65 | +}; |
| 66 | + |
| 67 | +const isCurrentTokenValid = () => { |
| 68 | + const expiration_date = localStorage.getItem('dashboard_exp'); |
| 69 | + return ( |
| 70 | + localStorage.getItem('dashboard_token') && |
| 71 | + expiration_date && |
| 72 | + expiration_date > Date.now() |
| 73 | + ); |
| 74 | +}; |
| 75 | + |
| 76 | +export const removeToken = () => { |
| 77 | + localStorage.removeItem('dashboard_token'); |
| 78 | + localStorage.removeItem('dashboard_email'); |
| 79 | + localStorage.removeItem('dashboard_exp'); |
| 80 | + localStorage.removeItem('webstore_token'); |
| 81 | + localStorage.removeItem('webstore_email'); |
| 82 | + localStorage.removeItem('webstore_exp'); |
| 83 | + location.replace(LOGIN_PATH); |
| 84 | +}; |
0 commit comments