You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

58 lines
1.3 KiB

5 years ago
5 years ago
5 years ago
4 years ago
5 years ago
5 years ago
5 years ago
5 years ago
  1. export const state = () => ({
  2. username: null,
  3. id: null,
  4. isAuthenticated: false
  5. })
  6. export const mutations = {
  7. setUsername(state, username) {
  8. state.username = username
  9. },
  10. setUserId(state, userId) {
  11. state.id = userId
  12. },
  13. clearUsername(state) {
  14. state.username = null
  15. },
  16. setAuthenticated(state, isAuthenticated) {
  17. state.isAuthenticated = isAuthenticated
  18. }
  19. }
  20. export const getters = {
  21. isAuthenticated(state) {
  22. return state.isAuthenticated
  23. },
  24. getUsername(state) {
  25. return state.username
  26. },
  27. getUserId(state) {
  28. return state.id
  29. }
  30. }
  31. export const actions = {
  32. async authenticateUser({ commit }, authData) {
  33. try {
  34. await this.$services.auth.login(authData.username, authData.password)
  35. commit('setAuthenticated', true)
  36. } catch(error) {
  37. throw new Error('The credential is invalid')
  38. }
  39. },
  40. async initAuth({ commit }) {
  41. try {
  42. const user = await this.$services.user.getMyProfile()
  43. commit('setAuthenticated', true)
  44. commit('setUsername', user.username)
  45. commit('setUserId', user.id)
  46. } catch {
  47. commit('setAuthenticated', false)
  48. }
  49. },
  50. async logout({ commit }) {
  51. await this.$services.auth.logout()
  52. commit('setAuthenticated', false)
  53. commit('clearUsername')
  54. }
  55. }