forked from mainmatter/ember-simple-auth
/
devise.js
212 lines (182 loc) · 6.9 KB
/
devise.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
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
import Ember from 'ember';
import BaseAuthenticator from './base';
import fetch from 'ember-network/fetch';
const { RSVP: { Promise }, isEmpty, run, assign: emberAssign, merge, computed } = Ember;
const assign = emberAssign || merge;
const JSON_CONTENT_TYPE = 'application/json';
/**
Authenticator that works with the Ruby gem
[devise](https://github.com/plataformatec/devise).
__As token authentication is not actually part of devise anymore, the server
needs to implement some customizations__ to work with this authenticator -
see [this gist](https://gist.github.com/josevalim/fb706b1e933ef01e4fb6).
@class DeviseAuthenticator
@module ember-simple-auth/authenticators/devise
@extends BaseAuthenticator
@public
*/
export default BaseAuthenticator.extend({
/**
The endpoint on the server that the authentication request is sent to.
@property serverTokenEndpoint
@type String
@default '/users/sign_in'
@public
*/
serverTokenEndpoint: '/users/sign_in',
/**
The devise resource name. __This will be used in the request and also be
expected in the server's response.__
@property resourceName
@type String
@default 'user'
@public
*/
resourceName: 'user',
/**
The token attribute name. __This will be used in the request and also be
expected in the server's response.__
@property tokenAttributeName
@type String
@default 'token'
@public
*/
tokenAttributeName: 'token',
/**
The identification attribute name. __This will be used in the request and
also be expected in the server's response.__
@property identificationAttributeName
@type String
@default 'email'
@public
*/
identificationAttributeName: 'email',
/**
When authentication fails, the rejection callback is provided with the whole
Fetch API [Response](https://fetch.spec.whatwg.org/#response-class) object
instead of its responseJSON or responseText.
This is useful for cases when the backend provides additional context not
available in the response body.
@property rejectWithXhr
@type Boolean
@default false
@deprecated DeviseAuthenticator/rejectWithResponse:property
@public
*/
rejectWithXhr: computed.deprecatingAlias('rejectWithResponse', {
id: `ember-simple-auth.authenticator.reject-with-xhr`,
until: '2.0.0'
}),
/**
When authentication fails, the rejection callback is provided with the whole
Fetch API [Response](https://fetch.spec.whatwg.org/#response-class) object
instead of its responseJSON or responseText.
This is useful for cases when the backend provides additional context not
available in the response body.
@property rejectWithResponse
@type Boolean
@default false
@public
*/
rejectWithResponse: false,
/**
Restores the session from a session data object; __returns a resolving
promise when there are non-empty
{{#crossLink "DeviseAuthenticator/tokenAttributeName:property"}}token{{/crossLink}}
and
{{#crossLink "DeviseAuthenticator/identificationAttributeName:property"}}identification{{/crossLink}}
values in `data`__ and a rejecting promise otherwise.
@method restore
@param {Object} data The data to restore the session from
@return {Ember.RSVP.Promise} A promise that when it resolves results in the session becoming or remaining authenticated
@public
*/
restore(data) {
return this._validate(data) ? Promise.resolve(data) : Promise.reject();
},
/**
Authenticates the session with the specified `identification` and
`password`; the credentials are `POST`ed to the
{{#crossLink "DeviseAuthenticator/serverTokenEndpoint:property"}}server{{/crossLink}}.
If the credentials are valid the server will responds with a
{{#crossLink "DeviseAuthenticator/tokenAttributeName:property"}}token{{/crossLink}}
and
{{#crossLink "DeviseAuthenticator/identificationAttributeName:property"}}identification{{/crossLink}}.
__If the credentials are valid and authentication succeeds, a promise that
resolves with the server's response is returned__, otherwise a promise that
rejects with the server error is returned.
@method authenticate
@param {String} identification The user's identification
@param {String} password The user's password
@return {Ember.RSVP.Promise} A promise that when it resolves results in the session becoming authenticated
@public
*/
authenticate(identification, password) {
return new Promise((resolve, reject) => {
const useResponse = this.get('rejectWithResponse');
const { resourceName, identificationAttributeName, tokenAttributeName } = this.getProperties('resourceName', 'identificationAttributeName', 'tokenAttributeName');
const data = {};
data[resourceName] = { password };
data[resourceName][identificationAttributeName] = identification;
this.makeRequest(data).then((response) => {
if (response.ok) {
response.json().then((json) => {
if (this._validate(json)) {
const resourceName = this.get('resourceName');
const _json = json[resourceName] ? json[resourceName] : json;
run(null, resolve, _json);
} else {
run(null, reject, `Check that server response includes ${tokenAttributeName} and ${identificationAttributeName}`);
}
});
} else {
if (useResponse) {
run(null, reject, response);
} else {
response.json().then((json) => run(null, reject, json));
}
}
}).catch((error) => run(null, reject, error));
});
},
/**
Does nothing
@method invalidate
@return {Ember.RSVP.Promise} A resolving promise
@public
*/
invalidate() {
return Promise.resolve();
},
/**
Makes a request to the Devise server using
[ember-network/fetch](https://github.com/tomdale/ember-network#fetch).
@method makeRequest
@param {Object} data The request data
@param {Object} options request options that are passed to `fetch`
@return {Promise} The promise returned by `fetch`
@protected
*/
makeRequest(data, options = {}) {
let url = options.url || this.get('serverTokenEndpoint');
let requestOptions = {};
let body = JSON.stringify(data);
assign(requestOptions, {
body,
method: 'POST',
headers: {
'accept': JSON_CONTENT_TYPE,
'content-type': JSON_CONTENT_TYPE
}
});
assign(requestOptions, options || {});
return fetch(url, requestOptions);
},
_validate(data) {
const tokenAttributeName = this.get('tokenAttributeName');
const identificationAttributeName = this.get('identificationAttributeName');
const resourceName = this.get('resourceName');
const _data = data[resourceName] ? data[resourceName] : data;
return !isEmpty(_data[tokenAttributeName]) && !isEmpty(_data[identificationAttributeName]);
}
});