ソースを参照

Logging in and saving token

master
LeneS 5年前
コミット
fafbd1b2a6

+ 10
- 0
src/App.vue ファイルの表示

@@ -21,6 +21,16 @@ export default {
21 21
     NavBar,
22 22
     FooterSection,
23 23
   },
24
+  // created() {
25
+  //   this.$http.interceptors.response.use(undefined, (err) => {
26
+  //     return new Promise(function(resolve, reject) {
27
+  //       if (err.status === 401 && err.config && !err.config.__isRetryRequest) {
28
+  //         this.$store.dispatch(logout);
29
+  //       }
30
+  //       throw err;
31
+  //     });
32
+  //   });
33
+  // },
24 34
   methods: {
25 35
     routerGoTo(goTo) {
26 36
       this.$router.push(goTo);

+ 9
- 0
src/assets/Log.js ファイルの表示

@@ -0,0 +1,9 @@
1
+const items = {
2
+  isLoggedIn() {
3
+    return localStorage.getItem('token') !== undefined;
4
+  },
5
+  getUser() {
6
+    return localStorage.getItem('User');
7
+  },
8
+};
9
+export default items;

+ 7
- 1
src/components/shared/navBar.vue ファイルの表示

@@ -194,7 +194,7 @@
194 194
             >Login</a>
195 195
             <div class="dropdown-menu" aria-labelledby="navbarDropdown">
196 196
               <a class="dropdown-item cursor-pointer" @click="routerGoTo('/user/login')">Login</a>
197
-              <a class="dropdown-item cursor-pointer" @click="routerGoTo('/user/login')">Logout</a>
197
+              <a class="dropdown-item cursor-pointer" @click="routerGoTo('/user/logout')">Logout</a>
198 198
               <a class="dropdown-item cursor-pointer" @click="routerGoTo('/user/register')">Register</a>
199 199
               <a
200 200
                 class="dropdown-item cursor-pointer"
@@ -217,8 +217,14 @@
217 217
   </nav>
218 218
 </template>
219 219
 <script>
220
+import { mapGetters } from 'vuex';
221
+
220 222
 export default {
223
+  computed: {},
224
+
221 225
   methods: {
226
+    ...mapGetters('authentication', ['isLoggedIn']),
227
+
222 228
     routerGoTo(goTo) {
223 229
       console.log(goTo);
224 230
       this.$emit('routerGoTo', goTo);

+ 19
- 0
src/components/user/logOut.vue ファイルの表示

@@ -0,0 +1,19 @@
1
+<script>
2
+import { mapActions } from 'vuex';
3
+
4
+export default {
5
+  computed: {
6
+    isLoggedIn() {
7
+      return this.$store.getters.isLoggedIn;
8
+    },
9
+  },
10
+  methods: {
11
+    ...mapActions('authentication', ['logout']),
12
+    Logout() {
13
+      this.logout('logout').then(() => {
14
+        this.$router.push('/users/login');
15
+      });
16
+    },
17
+  },
18
+};
19
+</script>

+ 14
- 9
src/components/user/loginPage.vue ファイルの表示

@@ -6,6 +6,7 @@
6 6
         <div class="form">
7 7
           <div>
8 8
             <h4>Login</h4>
9
+            <br />
9 10
           </div>
10 11
           <div class="row">
11 12
             <div class="col-md-11" style="margin-bottom: 1em">
@@ -19,6 +20,7 @@
19 20
                     type="text"
20 21
                     name="username"
21 22
                     placeholder="Username"
23
+                    v-model="username"
22 24
                     value
23 25
                   />
24 26
                 </div>
@@ -82,7 +84,9 @@
82 84
 </template>
83 85
 
84 86
 <script>
85
-const axios = require('axios');
87
+import { mapActions, mapState } from 'vuex';
88
+// import axios from 'axios';
89
+// import User from '../../assets/Log';
86 90
 
87 91
 export default {
88 92
   name: 'Login',
@@ -98,18 +102,19 @@ export default {
98 102
       text: '',
99 103
       showPassword: false,
100 104
       password: '',
105
+      email: '',
101 106
     };
102 107
   },
108
+  computed: {
109
+    ...mapState('authentication', ['token', 'status']),
110
+  },
103 111
   methods: {
112
+    ...mapActions('authentication', ['login']),
104 113
     Login() {
105
-      axios
106
-        .post('/api/register/authenticate', {
107
-          username: this.username,
108
-          password: this.password,
109
-        })
110
-        .then(response => console.log(response.data))
111
-        .catch(error => console.log(error.push));
112
-      this.$router.push('/');
114
+      this.login({ username: this.username, password: this.password })
115
+        .then(() => this.router.push('/'))
116
+        .catch(err => console.log(err));
117
+      this.$router.push('/about/us');
113 118
     },
114 119
     togglePassword() {
115 120
       this.showPassword = true;

+ 5
- 0
src/components/user/secure.vue ファイルの表示

@@ -0,0 +1,5 @@
1
+<template>
2
+  <div>
3
+    <h1>This page is protected by auth</h1>
4
+  </div>
5
+</template>

+ 19
- 0
src/main.js ファイルの表示

@@ -1,5 +1,6 @@
1 1
 import Vue from 'vue';
2 2
 import EvaIcons from 'vue-eva-icons';
3
+import axios from 'axios';
3 4
 import App from './App.vue';
4 5
 import router from './router';
5 6
 import store from './store';
@@ -8,6 +9,24 @@ Vue.use(EvaIcons);
8 9
 
9 10
 Vue.config.productionTip = false;
10 11
 
12
+Vue.prototype.$http = axios;
13
+const token = localStorage.getItem('token');
14
+if (token) {
15
+  Vue.prototype.$http.defaults.headers.common.Authorization = token;
16
+}
17
+
18
+router.beforeEach((to, from, next) => {
19
+  if (to.matched.some(record => record.meta.requiresAuth)) {
20
+    if (store.getters.isLoggedIn) {
21
+      next();
22
+      return;
23
+    }
24
+    next('/users/login');
25
+  } else {
26
+    next();
27
+  }
28
+});
29
+
11 30
 Vue.filter('toCurrency', (value) => {
12 31
   if (typeof value !== 'number') {
13 32
     return value;

+ 2
- 0
src/router/index.js ファイルの表示

@@ -1,3 +1,4 @@
1
+/* eslint-disable import/prefer-default-export */
1 2
 import Vue from 'vue';
2 3
 import Router from 'vue-router';
3 4
 
@@ -39,6 +40,7 @@ import PrivacyPolicy from '../components/misc/privacyPolicyPage.vue';
39 40
 
40 41
 import MakeOffer from '../components/processFlow/makeOffer.vue';
41 42
 import Offer from '../components/processFlow/offers.vue';
43
+// import store from '../store';
42 44
 
43 45
 Vue.use(Router);
44 46
 

+ 2
- 0
src/store/index.js ファイルの表示

@@ -16,6 +16,7 @@ import PropertyTypes from './modules/property/propertyTypes';
16 16
 import Register from './modules/user/register';
17 17
 import WeekList from './modules/timeshare/weekList';
18 18
 import Bid from './modules/processFlow/bid';
19
+import Authentication from './modules/user/authentication';
19 20
 
20 21
 Vue.use(Vuex);
21 22
 /* eslint no-param-reassign: ["error", { "props": false }] */
@@ -37,5 +38,6 @@ export default new Vuex.Store({
37 38
     registerAgency: Register,
38 39
     weekList: WeekList,
39 40
     bid: Bid,
41
+    authentication: Authentication,
40 42
   },
41 43
 });

+ 68
- 0
src/store/modules/user/authentication.js ファイルの表示

@@ -0,0 +1,68 @@
1
+import Vue from 'vue';
2
+import Vuex from 'vuex';
3
+import axios from 'axios';
4
+
5
+Vue.use(Vuex);
6
+export default {
7
+  namespaced: true,
8
+  state: {
9
+    status: '123',
10
+    token: localStorage.getItem('token') || '',
11
+    user: {},
12
+  },
13
+  mutations: {
14
+    auth_request(state) {
15
+      state.status = 'loading';
16
+    },
17
+    auth_success(state, token, user) {
18
+      state.status = 'success';
19
+      state.token = token;
20
+      state.user = user;
21
+    },
22
+    auth_error(state) {
23
+      state.status = 'error';
24
+    },
25
+    logout(state) {
26
+      state.status = '';
27
+      state.token = '';
28
+    },
29
+  },
30
+  getters: {
31
+    isLoggenIn: state => !!state.token,
32
+    authStatus: state => state.status,
33
+  },
34
+  actions: {
35
+    login({
36
+      commit,
37
+    }, user) {
38
+      return new Promise((reject) => {
39
+        commit('auth_request');
40
+        axios({
41
+          url: '/api/register/authenticate',
42
+          data: user,
43
+          method: 'POST',
44
+        })
45
+          .then((resp) => {
46
+            console.log(resp.data);
47
+            localStorage.setItem('token', resp.data.token);
48
+            commit('auth_success', resp.data.token, resp.data);
49
+          })
50
+          .catch((err) => {
51
+            commit('auth_error');
52
+            localStorage.removeItem('token');
53
+            reject(err);
54
+          });
55
+      });
56
+    },
57
+    logout({
58
+      commit,
59
+    }) {
60
+      return new Promise(() => {
61
+        commit('logout');
62
+        console.log('What');
63
+        localStorage.removeItem('token');
64
+        delete axios.defaults.headers.common.Authorization;
65
+      });
66
+    },
67
+  },
68
+};

読み込み中…
キャンセル
保存