index.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. import Vue from 'vue';
  2. import axios from 'axios';
  3. const cookieparser = process.server ? require('cookieparser') : null;
  4. export const state = () => ({
  5. loggedIn: false,
  6. user: null,
  7. token: null,
  8. config: null
  9. });
  10. /* eslint-disable no-shadow */
  11. export const mutations = {
  12. loggedIn(state, payload) {
  13. state.loggedIn = payload;
  14. },
  15. user(state, payload) {
  16. if (!payload) {
  17. state.user = {};
  18. localStorage.removeItem('lolisafe-user');
  19. return;
  20. }
  21. localStorage.setItem('lolisafe-user', JSON.stringify(payload));
  22. state.user = payload;
  23. },
  24. token(state, payload) {
  25. if (!payload) {
  26. localStorage.removeItem('lolisafe-token');
  27. state.token = null;
  28. return;
  29. }
  30. localStorage.setItem('lolisafe-token', payload);
  31. setAuthorizationHeader(payload);
  32. state.token = payload;
  33. },
  34. config(state, payload) {
  35. state.config = payload;
  36. }
  37. };
  38. export const actions = {
  39. async nuxtServerInit({ commit }, { req }) {
  40. commit('config', {
  41. version: process.env.npm_package_version,
  42. URL: process.env.DOMAIN,
  43. baseURL: `${process.env.DOMAIN}${process.env.ROUTE_PREFIX}`,
  44. serviceName: process.env.SERVICE_NAME,
  45. maxFileSize: parseInt(process.env.MAX_SIZE, 10),
  46. chunkSize: parseInt(process.env.CHUNK_SIZE, 10),
  47. maxLinksPerAlbum: parseInt(process.env.MAX_LINKS_PER_ALBUM, 10),
  48. publicMode: process.env.PUBLIC_MODE == 'true' ? true : false,
  49. enableAccounts: process.env.USER_ACCOUNTS == 'true' ? true : false
  50. });
  51. let token = null;
  52. if (req.headers.cookie) {
  53. try {
  54. token = cookieparser.parse(req.headers.cookie).token;
  55. commit('loggedIn', true);
  56. commit('token', token);
  57. const res = await axios.get(`${this.config.baseURL}/verify`);
  58. if (!res || !res.data.user);
  59. commit('user', res.data.user);
  60. } catch (error) {
  61. // TODO: Deactivate this on production
  62. console.error(error);
  63. }
  64. }
  65. commit('token', token);
  66. if (!token) {
  67. commit('user', null);
  68. commit('loggedIn', false);
  69. }
  70. }
  71. };
  72. const setAuthorizationHeader = payload => {
  73. Vue.axios.defaults.headers.common.Authorization = payload ? `Bearer ${payload}` : '';
  74. };