aboutsummaryrefslogtreecommitdiff
path: root/src/site/store/auth.js
blob: 51a79d643a7683451640720d995031f5de280b81 (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
99
100
101
102
103
104
105
106
const getDefaultState = () => ({
	loggedIn: false,
	user: {
		id: null,
		isAdmin: false,
		username: null
	},
	token: null
});

export const state = getDefaultState;

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

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 }, { username, password }) {
		commit('loginRequest');

		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 });
	},
	async register(_, { username, password }) {
		return this.$axios.$post('auth/register', {
			username,
			password
		});
	},
	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 });
		}

		return null;
	},
	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 });
		}

		return null;
	},
	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, { path: '/' });
		state.user = user;
		state.loggedIn = true;
		state.isLoading = false;
	},
	logout(state) {
		this.$cookies.remove('token', { path: '/' });
		// reset state to default
		Object.assign(state, getDefaultState());
	}
};