aboutsummaryrefslogtreecommitdiff
path: root/src/site/store/auth.js
blob: 73976d6f62a20d1923984e48f6f96ba544e747e0 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
/* eslint-disable no-shadow */
// only used so I could keep the convention of naming the first param as "state" in mutations
const getDefaultState = () => ({
	loggedIn: false,
	isLoading: false,
	user: null,
	token: null
});

export const state = getDefaultState;

export const getters = {
	isLoggedIn: state => state.loggedIn,
	getApiKey: state => state.user?.apiKey
};

export const actions = {
	async verify({ commit, dispatch }) {
		try {
			const response = await this.$axios.$get('verify');
			commit('loginSuccess', response);
		} catch (e) {
			dispatch('alert/set', { text: e.message, error: true }, { root: true });
		}
	},
	async login({ commit, dispatch }, { username, password }) {
		commit('loginRequest');

		try {
			const data = await this.$axios.$post(`auth/login`, { username, password });
			this.$axios.setToken(data.token, 'Bearer');

			commit('setToken', data.token);
			commit('loginSuccess', { token: data.token, user: data.user });
		} catch (e) {
			dispatch('alert/set', { text: e.message, error: true }, { root: true });
		}
	},
	async fetchCurrentUser({ commit, dispatch }) {
		try {
			const data = await this.$axios.$get(`users/me`);
			commit('setUser', data.user);
		} catch (e) {
			dispatch('alert/set', { text: e.message, error: true }, { root: true });
		}
	},
	async changePassword({ dispatch }, { password, newPassword }) {
		try {
			const response = await this.$axios.$post(`user/password/change`, {
				password,
				newPassword
			});

			return response;
		} catch (e) {
			dispatch('alert/set', { text: e.message, error: true }, { root: true });
		}
	},
	async requestAPIKey({ commit, dispatch }) {
		try {
			const response = await this.$axios.$post(`user/apikey/change`);
			commit('setApiKey', response.apiKey);

			return response;
		} catch (e) {
			dispatch('alert/set', { text: e.message, error: true }, { root: true });
		}
	},
	logout({ commit }) {
		commit('logout');
	}
};

export const mutations = {
	setToken(state, token) {
		state.token = token;
	},
	setApiKey(state, apiKey) {
		state.user.apiKey = apiKey;
	},
	setUser(state, user) {
		state.user = user;
	},
	loginRequest(state) {
		state.isLoading = true;
	},
	loginSuccess(state, { user }) {
		this.$cookies.set('token', state.token);
		state.user = user;
		state.loggedIn = true;
		state.isLoading = false;
	},
	logout(state) {
		this.$cookies.remove('token');
		// reset state to default
		Object.assign(state, getDefaultState());
	}
};