· 7 years ago · Dec 22, 2017, 08:44 PM
1<template>
2 <form @submit.prevent="handleLogin">
3 <label class="label" v-text="labels.user"></label>
4 <p :class="controlClass">
5 <input
6 :class="inputClass"
7 type="text"
8 :placeholder="userPlaceholder"
9 v-model="login.user"
10 >
11 </p>
12 <label class="label" v-text="labels.password"></label>
13 <p :class="controlClass">
14 <input
15 :class="inputClass"
16 type="password"
17 :placeholder="passwordPlaceholder"
18 v-model="login.password"
19 >
20 </p>
21 <p class="control">
22 <button
23 type="submit"
24 class="button is-primary"
25 v-text="labels.button"
26 :disabled="loading"
27 ></button>
28 </p>
29 </form>
30</template>
31
32<script>
33import axios from 'axios'
34
35export default {
36 name: 'VuePassportLogin',
37
38 props: {
39 labels: {
40 type: Object,
41 default () {
42 return {
43 title: 'Login',
44 user: 'User',
45 password: 'Password',
46 button: 'Login'
47 }
48 }
49 },
50
51 userPlaceholder: String,
52
53 passwordPlaceholder: String,
54
55 controlClass: {
56 type: String,
57 default: 'control'
58 },
59
60 inputClass: {
61 type: String,
62 default: 'input'
63 },
64
65 apiUrl: {
66 type: String,
67 required: true
68 },
69
70 loginRoute: {
71 type: String,
72 default: 'oauth/token'
73 },
74
75 userRoute: {
76 type: String,
77 default: 'api/user'
78 },
79
80 clientId: {
81 type: [Number, String],
82 default: 2
83 },
84
85 secret: {
86 type: String,
87 required: true
88 }
89 },
90 data () {
91 return {
92 loading: false,
93 login: {
94 user: '',
95 password: ''
96 }
97 }
98 },
99 computed: {
100 loginUrl () {
101 return `${this.apiUrl}/${this.loginRoute}`
102 },
103 userUrl () {
104 return `${this.apiUrl}/${this.userRoute}`
105 }
106 },
107 methods: {
108 getHeaders (token) {
109 return {
110 'Accept': 'application/json',
111 'Authorization': `Bearer ${token}`
112 }
113 },
114 handleLogin () {
115 this.loading = true
116 const postData = {
117 grant_type: 'password',
118 client_id: this.clientId,
119 client_secret: this.secret,
120 username: this.login.user,
121 password: this.login.password,
122 scope: ''
123 }
124
125 const authUser = {}
126
127 axios.post(this.loginUrl, postData)
128 .then(response => {
129 authUser.access_token = response.data.access_token
130 authUser.refresh_token = response.data.refresh_token
131
132 const headers = this.getHeaders(authUser.access_token)
133
134 axios.get(this.userUrl, {headers})
135 .then(response => {
136 authUser.data = response.data
137 this.$emit('success', { authUser, headers })
138 this.loading = false
139 })
140 .catch(error => {
141 this.$emit('failed', error)
142 this.loading = false
143 })
144 })
145 .catch(error => {
146 this.$emit('failed', error)
147 this.loading = false
148 })
149 }
150 }
151}
152</script>