const methods = { /** * Hide Modal * @param {String} Modal ID * */ hideModal: function (id) { $(id).modal('hide'); }, /** * Check if Login * * @return {Boolean} isLogin */ isLogin: function () { if (!localStorage['Access Token']) { return false; } if (this.isSessionExpired()) { this.clearSession(); return false; } return true; }, isSessionExpired: function () { var expiresAt = localStorage.getItem('token_expires_at'); if (!expiresAt) { return false; } return Date.now() >= new Date(expiresAt).getTime(); }, clearSession: function () { localStorage.removeItem('Access Token'); localStorage.removeItem('token_expires_at'); localStorage.removeItem('admin_role'); localStorage.removeItem('admin_session'); localStorage.removeItem('is_impersonating'); delete axios.defaults.headers.common['Authorization']; }, persistLoginSession: function (token, expiresAt, options) { options = options || {}; var bearer = token.indexOf('Bearer ') === 0 ? token : 'Bearer ' + token; localStorage['Access Token'] = bearer; if (expiresAt) { localStorage.setItem('token_expires_at', expiresAt); } else { localStorage.removeItem('token_expires_at'); } if (options.adminRole !== undefined && options.adminRole !== null) { localStorage.setItem('admin_role', String(options.adminRole)); } if (options.adminSession) { localStorage.setItem('admin_session', '1'); } if (options.clearAdminSession) { localStorage.removeItem('admin_role'); localStorage.removeItem('admin_session'); } this.setAuthorization(); }, handleUnauthorized: function (router) { var isAdminPath = window.location.pathname.indexOf('/admin') === 0; this.clearSession(); if (!router || !router.currentRoute) { window.location.href = isAdminPath ? '/admin/login' : '/login'; return; } var routeName = router.currentRoute.name; if (routeName === 'Voter Login' || routeName === 'Admin Login') { return; } router.replace({ name: isAdminPath ? 'Admin Login' : 'Voter Login' }); }, /** * True when the browser session is for the admin portal (not a voter-only token). */ isAdminPortalSession: function () { return localStorage.getItem('admin_role') != null || localStorage.getItem('admin_session') === '1'; }, /** * Route name to open for the current admin session (role 3 is restricted to kehadiran). */ getAdminEntryRoute: function () { if (localStorage.getItem('admin_role') === '3') { return { name: 'Kehadiran Calon' }; } return { name: 'Admin Home' }; }, /** * Log a messages * @param {String} Message * */ log: function (message) { if (config.debug) console.log(message); }, /** * Show an alert message * @param {String} message to be Shown * @param {String} type of message (info|error|loading|success) * @param {Boolean} if message will be closed imediately (true|false) * @return {Notify} */ notify: function (message, label = 'info', progress) { let delay = 5000; let type = 'info'; let icon = 'fa fa-info'; switch (label) { case 'error': type = 'danger'; icon = 'fa fa-warning'; break; case 'loading': delay = 0; icon = 'fa fa-refresh fa-spin'; break; case 'success': type = 'success'; icon = 'fa fa-check'; break; case 'progress': $.notifyClose(); delay = 0; message = `
`; icon = 'fa fa-refresh fa-spin'; break; } return $.notify({ message: message, icon: icon }, { type: type, delay: delay, placement: { from: 'top', align: 'center' } }); }, /** * Set Authorization for all outgoing request * */ setAuthorization: function () { axios.defaults.headers.common['Authorization'] = localStorage['Access Token']; $.ajaxSetup({ headers: { 'Authorization': localStorage['Access Token'] } }); }, /** * Set the title of the webpage * @param {String} Title * */ setTitle: function (title) { $('title').text(title); }, /** * Get the error Message * @param {String} Data * @param {Int} Response Status * @return {String} Error Message */ getErrorMessage: function (data, status) { var message = ''; switch (status) { case 200: message = data.message; break; case 422: // Laravel validation errors are usually: // { message: "...", errors: { field: ["..."] } } // but some endpoints may return { status, message }. data = typeof data == 'string' ? JSON.parse(data) : data; if (!data) { message = 'Sila semak semula input anda.'; break; } if (data.errors && typeof data.errors === 'object') { for (var field in data.errors) { var arr = data.errors[field]; if (Array.isArray(arr)) { arr.forEach(function (y) { message += y + '
'; }); } else if (typeof arr === 'string') { message += arr + '
'; } } break; } if (typeof data.message === 'string') { message = data.message; break; } // Fallback: if it's a plain object, join any string/array values if (typeof data === 'object') { for (var i in data) { var v = data[i]; if (Array.isArray(v)) { v.forEach(function (y) { message += y + '
'; }); } else if (typeof v === 'string') { message += v + '
'; } } } break; case 401: message = 'Sila log masuk terlebih dahulu.'; break; default: message = 'Ralat telah berlaku.'; break; } return message; }, /** * Show the modal * @param {String} Modal ID * */ showModal: function (id) { $(id).modal('show'); }, /** * Show result from an http request * @param {Response} response * @param {Type} responseType (error|success) * @param {library} Library used (ajax|axios) Default : axios */ showResult: function (response, type, library = 'axios') { this.log(response); var isSuccess = data => data.status == 'success'; if (library == 'axios') { if (type == 'success') { if (isSuccess(response.data)) { this.notify(response.data.message, 'success'); return true; } else { this.notify(response.data.message, 'error'); } } else { var status = response.response ? response.response.status : 500; var message = this.getErrorMessage(response.response.data, status); this.notify(message, 'error'); return status; } } else if (library == 'ajax') { if (type == 'success') { if (isSuccess(response)) { this.notify(response.message, 'success'); return true; } else { this.notify(response.message, 'error'); } } else if (type == 'error') { var status = response.status; var message = this.getErrorMessage(response.responseText, status); this.notify(message, 'error'); return status; } } } } const data = { baseURL: config.baseURL, API: config.API, storageURL: config.storageURL, elections: [], election: {}, user: {}, positions: [], position: {}, partylists: [], partylist: {}, voters: {}, voter: {}, nominees: [], nominee: {}, admins: [], information: {}, result: [], results: [], last_update: new Date() } export default { data: function () { return { util: methods, data: data } } } export { methods };