/
wpauthentication.js
128 lines (113 loc) · 2.29 KB
/
wpauthentication.js
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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
import axios from 'axios';
/**
*
*/
export default class WPAuth {
/**
*
* @param {Object} options
*/
constructor (options = {}) {
this.endpoint = options.endpoint || '';
this._token = '';
this._data = {};
this.loggedin = this._restoreToken();
}
/**
*
* @param {*} username
* @param {*} password
* @param {*} callback
*/
async doAuth (username = '', password = '', callback = null) {
const method = 'wp-json/jwt-auth/v1/token';
let url = this.endpoint + (!(this.endpoint.endsWith('/')) ? '/' : '') + method;
console.log(url, username, password);
try {
let response = await axios({
method: 'post',
url: url,
data: { 'username': username, 'password': password },
withCredentials: true,
headers: {
'content-type': 'application/json',
'cache-control': 'no-cache'
}
});
let data = response.data || {};
console.log(response);
if (data.token) {
this._token = data.token;
delete data.token;
}
this._data = data;
console.log('Autenticazione avvenuta con successo');
this.loggedin = true;
this._saveToken();
if (callback instanceof Function) {
callback(this._token, this._data);
}
} catch (err) {
console.error('Autenticazione fallita', err);
this.loggedin = false;
}
}
/**
*
*/
get token () {
return this._token;
}
/**
*
*/
set token (t) {
this._token = t;
}
/**
*
*/
get data () {
return this._data;
}
/**
*
*/
set data (d) {
this._data = d;
}
/**
*
*/
_saveToken () {
if (window.localStorage) {
localStorage.setItem(`wptoken${this.endpoint}`, JSON.stringify({
token: this._token,
data: this._data
}));
return true;
}
return false;
}
/**
*
*/
_restoreToken () {
if (window.localStorage) {
let ret = JSON.parse(localStorage.getItem(`wptoken${this.endpoint}`));
if (ret) {
this._token = ret.token;
this._data = ret.data;
}
}
return (this._token !== '');
}
/**
*
* @param {String} message
*/
static AuthException (message) {
this.message = message;
this.name = 'AuthException';
}
}