Skip to content

Commit fd04bd0

Browse files
committed
Update authClient
1 parent ba725b0 commit fd04bd0

File tree

7 files changed

+313
-251
lines changed

7 files changed

+313
-251
lines changed

lib/authClient.js

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
'use strict';
2+
3+
Object.defineProperty(exports, "__esModule", {
4+
value: true
5+
});
6+
var authClient = exports.authClient = function authClient(apiUrl, noAccessPage) {
7+
8+
return function (type, params) {
9+
if (type === 'AUTH_LOGIN') {
10+
var username = params.username,
11+
password = params.password;
12+
13+
var request = new Request(apiUrl + '/login', {
14+
method: 'POST',
15+
body: JSON.stringify({ username: username, password: password }),
16+
headers: new Headers({ 'Content-Type': 'application/json' })
17+
});
18+
return fetch(request).then(function (response) {
19+
if (response.status < 200 || response.status >= 300) {
20+
throw new Error(response.statusText);
21+
}
22+
return response.json();
23+
}).then(function (_ref) {
24+
var id = _ref.id;
25+
26+
localStorage.setItem('lbtoken', id);
27+
});
28+
}
29+
if (type === 'AUTH_LOGOUT') {
30+
localStorage.removeItem('lbtoken');
31+
return Promise.resolve();
32+
}
33+
if (type === 'AUTH_CHECK') {
34+
return localStorage.getItem('lbtoken') ? Promise.resolve() : Promise.reject({ redirectTo: noAccessPage });
35+
}
36+
return Promise.reject('Unkown method');
37+
};
38+
};

lib/fetch.js

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,13 @@ var fetchJson = exports.fetchJson = function fetchJson(url) {
2424
}
2525
if (options.user && options.user.authenticated && options.user.token) {
2626
requestHeaders.set('Authorization', options.user.token);
27+
} else {
28+
var token = localStorage.getItem('lbtoken');
29+
if (url.indexOf('?') >= 0) {
30+
url = url + '&access_token=' + token;
31+
} else {
32+
url = url + '?access_token=' + token;
33+
}
2734
}
2835

2936
return fetch(url, _extends({}, options, { headers: requestHeaders })).then(function (response) {

lib/index.js

Lines changed: 138 additions & 126 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,23 @@
11
'use strict';
22

33
Object.defineProperty(exports, "__esModule", {
4-
value: true
4+
value: true
55
});
66

77
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
88

9+
var _authClient = require('./authClient');
10+
11+
Object.keys(_authClient).forEach(function (key) {
12+
if (key === "default" || key === "__esModule") return;
13+
Object.defineProperty(exports, key, {
14+
enumerable: true,
15+
get: function get() {
16+
return _authClient[key];
17+
}
18+
});
19+
});
20+
921
var _fetch = require('./fetch');
1022

1123
var _types = require('./types');
@@ -23,138 +35,138 @@ var _types = require('./types');
2335
* DELETE => DELETE http://my.api.url/posts/123
2436
*/
2537
exports.default = function (apiUrl) {
26-
var httpClient = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : _fetch.fetchJson;
38+
var httpClient = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : _fetch.fetchJson;
2739

28-
/**
29-
* @param {String} type One of the constants appearing at the top if this file, e.g. 'UPDATE'
30-
* @param {String} resource Name of the resource to fetch, e.g. 'posts'
31-
* @param {Object} params The REST request params, depending on the type
32-
* @returns {Object} { url, options } The HTTP request parameters
33-
*/
34-
var convertRESTRequestToHTTP = function convertRESTRequestToHTTP(type, resource, params) {
35-
resource = resource.toLowerCase();
36-
var url = '';
37-
var options = {};
38-
switch (type) {
39-
case _types.GET_LIST:
40-
{
41-
var _params$pagination = params.pagination,
42-
page = _params$pagination.page,
43-
perPage = _params$pagination.perPage;
44-
var _params$sort = params.sort,
45-
field = _params$sort.field,
46-
order = _params$sort.order;
40+
/**
41+
* @param {String} type One of the constants appearing at the top if this file, e.g. 'UPDATE'
42+
* @param {String} resource Name of the resource to fetch, e.g. 'posts'
43+
* @param {Object} params The REST request params, depending on the type
44+
* @returns {Object} { url, options } The HTTP request parameters
45+
*/
46+
var convertRESTRequestToHTTP = function convertRESTRequestToHTTP(type, resource, params) {
47+
resource = resource.toLowerCase();
48+
var url = '';
49+
var options = {};
50+
switch (type) {
51+
case _types.GET_LIST:
52+
{
53+
var _params$pagination = params.pagination,
54+
page = _params$pagination.page,
55+
perPage = _params$pagination.perPage;
56+
var _params$sort = params.sort,
57+
field = _params$sort.field,
58+
order = _params$sort.order;
4759

48-
var query = {};
49-
query['where'] = _extends({}, params.filter);
50-
if (field) query['order'] = [field + ' ' + order];
51-
if (perPage > 0) {
52-
query['limit'] = perPage;
53-
if (page >= 0) {
54-
query['skip'] = (page - 1) * perPage;
55-
}
56-
}
57-
url = apiUrl + '/' + resource + '?' + (0, _fetch.queryParameters)({ filter: JSON.stringify(query) });
58-
break;
59-
}
60-
case _types.GET_ONE:
61-
url = apiUrl + '/' + resource + '/' + params.id;
62-
break;
63-
case _types.GET_MANY:
64-
{
65-
var listId = params.ids.map(function (id) {
66-
return { 'id': id };
67-
});
68-
var _query = {
69-
'where': { 'or': listId }
70-
};
71-
url = apiUrl + '/' + resource + '?' + (0, _fetch.queryParameters)({ filter: _query });
72-
break;
73-
}
74-
case _types.GET_MANY_REFERENCE:
75-
{
76-
var _params$pagination2 = params.pagination,
77-
_page = _params$pagination2.page,
78-
_perPage = _params$pagination2.perPage;
79-
var _params$sort2 = params.sort,
80-
_field = _params$sort2.field,
81-
_order = _params$sort2.order;
60+
var query = {};
61+
query['where'] = _extends({}, params.filter);
62+
if (field) query['order'] = [field + ' ' + order];
63+
if (perPage > 0) {
64+
query['limit'] = perPage;
65+
if (page >= 0) {
66+
query['skip'] = (page - 1) * perPage;
67+
}
68+
}
69+
url = apiUrl + '/' + resource + '?' + (0, _fetch.queryParameters)({ filter: JSON.stringify(query) });
70+
break;
71+
}
72+
case _types.GET_ONE:
73+
url = apiUrl + '/' + resource + '/' + params.id;
74+
break;
75+
case _types.GET_MANY:
76+
{
77+
var listId = params.ids.map(function (id) {
78+
return { 'id': id };
79+
});
80+
var _query = {
81+
'where': { 'or': listId }
82+
};
83+
url = apiUrl + '/' + resource + '?' + (0, _fetch.queryParameters)({ filter: _query });
84+
break;
85+
}
86+
case _types.GET_MANY_REFERENCE:
87+
{
88+
var _params$pagination2 = params.pagination,
89+
_page = _params$pagination2.page,
90+
_perPage = _params$pagination2.perPage;
91+
var _params$sort2 = params.sort,
92+
_field = _params$sort2.field,
93+
_order = _params$sort2.order;
8294

83-
var _query2 = {};
84-
_query2['where'] = _extends({}, params.filter);
85-
_query2['where'][params.target] = params.id;
86-
if (_field) _query2['order'] = [_field + ' ' + _order];
87-
if (_perPage > 0) {
88-
_query2['limit'] = _perPage;
89-
if (_page >= 0) {
90-
_query2['skip'] = (_page - 1) * _perPage;
91-
}
92-
}
93-
url = apiUrl + '/' + resource + '?' + (0, _fetch.queryParameters)({ filter: _query2 });
94-
break;
95+
var _query2 = {};
96+
_query2['where'] = _extends({}, params.filter);
97+
_query2['where'][params.target] = params.id;
98+
if (_field) _query2['order'] = [_field + ' ' + _order];
99+
if (_perPage > 0) {
100+
_query2['limit'] = _perPage;
101+
if (_page >= 0) {
102+
_query2['skip'] = (_page - 1) * _perPage;
103+
}
104+
}
105+
url = apiUrl + '/' + resource + '?' + (0, _fetch.queryParameters)({ filter: _query2 });
106+
break;
107+
}
108+
case _types.UPDATE:
109+
url = apiUrl + '/' + resource + '/' + params.id;
110+
options.method = 'PUT';
111+
options.body = JSON.stringify(params.data);
112+
break;
113+
case _types.CREATE:
114+
url = apiUrl + '/' + resource;
115+
options.method = 'POST';
116+
options.body = JSON.stringify(params.data);
117+
break;
118+
case _types.DELETE:
119+
url = apiUrl + '/' + resource + '/' + params.id;
120+
options.method = 'DELETE';
121+
break;
122+
default:
123+
throw new Error('Unsupported fetch action type ' + type);
95124
}
96-
case _types.UPDATE:
97-
url = apiUrl + '/' + resource + '/' + params.id;
98-
options.method = 'PUT';
99-
options.body = JSON.stringify(params.data);
100-
break;
101-
case _types.CREATE:
102-
url = apiUrl + '/' + resource;
103-
options.method = 'POST';
104-
options.body = JSON.stringify(params.data);
105-
break;
106-
case _types.DELETE:
107-
url = apiUrl + '/' + resource + '/' + params.id;
108-
options.method = 'DELETE';
109-
break;
110-
default:
111-
throw new Error('Unsupported fetch action type ' + type);
112-
}
113-
return { url: url, options: options };
114-
};
125+
return { url: url, options: options };
126+
};
115127

116-
/**
117-
* @param {Object} response HTTP response from fetch()
118-
* @param {String} type One of the constants appearing at the top if this file, e.g. 'UPDATE'
119-
* @param {String} resource Name of the resource to fetch, e.g. 'posts'
120-
* @param {Object} params The REST request params, depending on the type
121-
* @returns {Object} REST response
122-
*/
123-
var convertHTTPResponseToREST = function convertHTTPResponseToREST(response, type, resource, params) {
124-
var headers = response.headers,
125-
json = response.json;
128+
/**
129+
* @param {Object} response HTTP response from fetch()
130+
* @param {String} type One of the constants appearing at the top if this file, e.g. 'UPDATE'
131+
* @param {String} resource Name of the resource to fetch, e.g. 'posts'
132+
* @param {Object} params The REST request params, depending on the type
133+
* @returns {Object} REST response
134+
*/
135+
var convertHTTPResponseToREST = function convertHTTPResponseToREST(response, type, resource, params) {
136+
var headers = response.headers,
137+
json = response.json;
126138

127-
switch (type) {
128-
case _types.GET_LIST:
129-
if (!headers.has('x-total-count')) {
130-
throw new Error('The X-Total-Count header is missing in the HTTP Response. The jsonServer REST client expects responses for lists of resources to contain this header with the total number of results to build the pagination. If you are using CORS, did you declare X-Total-Count in the Access-Control-Expose-Headers header?');
139+
switch (type) {
140+
case _types.GET_LIST:
141+
if (!headers.has('x-total-count')) {
142+
throw new Error('The X-Total-Count header is missing in the HTTP Response. The jsonServer REST client expects responses for lists of resources to contain this header with the total number of results to build the pagination. If you are using CORS, did you declare X-Total-Count in the Access-Control-Expose-Headers header?');
143+
}
144+
return {
145+
data: json.map(function (x) {
146+
return x;
147+
}),
148+
total: parseInt(headers.get('x-total-count').split('/').pop(), 10)
149+
};
150+
case _types.CREATE:
151+
return _extends({}, params.data, { id: json.id });
152+
default:
153+
return json;
131154
}
132-
return {
133-
data: json.map(function (x) {
134-
return x;
135-
}),
136-
total: parseInt(headers.get('x-total-count').split('/').pop(), 10)
137-
};
138-
case _types.CREATE:
139-
return _extends({}, params.data, { id: json.id });
140-
default:
141-
return json;
142-
}
143-
};
155+
};
144156

145-
/**
146-
* @param {string} type Request type, e.g GET_LIST
147-
* @param {string} resource Resource name, e.g. "posts"
148-
* @param {Object} payload Request parameters. Depends on the request type
149-
* @returns {Promise} the Promise for a REST response
150-
*/
151-
return function (type, resource, params) {
152-
var _convertRESTRequestTo = convertRESTRequestToHTTP(type, resource, params),
153-
url = _convertRESTRequestTo.url,
154-
options = _convertRESTRequestTo.options;
157+
/**
158+
* @param {string} type Request type, e.g GET_LIST
159+
* @param {string} resource Resource name, e.g. "posts"
160+
* @param {Object} payload Request parameters. Depends on the request type
161+
* @returns {Promise} the Promise for a REST response
162+
*/
163+
return function (type, resource, params) {
164+
var _convertRESTRequestTo = convertRESTRequestToHTTP(type, resource, params),
165+
url = _convertRESTRequestTo.url,
166+
options = _convertRESTRequestTo.options;
155167

156-
return httpClient(url, options).then(function (response) {
157-
return convertHTTPResponseToREST(response, type, resource, params);
158-
});
159-
};
168+
return httpClient(url, options).then(function (response) {
169+
return convertHTTPResponseToREST(response, type, resource, params);
170+
});
171+
};
160172
};

package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "aor-loopback",
3-
"version": "1.0.4",
3+
"version": "1.0.8",
44
"description": "Loopback-style REST Client for Admin-on-rest, the frontend framework for building admin applications on top of REST services",
55
"main": "lib/index.js",
66
"scripts": {

src/authClient.js

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,10 @@
11

2-
export default (apiUrl, noAccessPage) => {
2+
export const authClient = (apiUrl, noAccessPage) => {
33

44
return (type, params) => {
55
if (type === 'AUTH_LOGIN') {
66
const { username, password } = params;
7-
const request = new Request(apiUrl, {
7+
const request = new Request(apiUrl + '/login', {
88
method: 'POST',
99
body: JSON.stringify({ username, password }),
1010
headers: new Headers({ 'Content-Type': 'application/json' }),
@@ -17,15 +17,15 @@ export default (apiUrl, noAccessPage) => {
1717
return response.json();
1818
})
1919
.then(({ id }) => {
20-
localStorage.setItem('token', id)
20+
localStorage.setItem('lbtoken', id)
2121
});
2222
}
2323
if (type === 'AUTH_LOGOUT') {
24-
localStorage.removeItem('token');
24+
localStorage.removeItem('lbtoken');
2525
return Promise.resolve();
2626
}
2727
if (type === 'AUTH_CHECK') {
28-
return localStorage.getItem('token') ? Promise.resolve() : Promise.reject({ redirectTo: noAccessPage });
28+
return localStorage.getItem('lbtoken') ? Promise.resolve() : Promise.reject({ redirectTo: noAccessPage });
2929
}
3030
return Promise.reject('Unkown method');
3131
};

0 commit comments

Comments
 (0)