-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathauth-service.js
179 lines (161 loc) · 4.34 KB
/
auth-service.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
import URI from 'urijs';
import { post } from './json-api-client';
import services from '../config/services';
import * as cache from '../services/cache-env';
import * as logger from '../services/logger';
export class AuthServiceError {
/*
Used whenever AuthService misbehaves and returns errors not listed in the
API specification.
*/
constructor(message, url, response, code) {
this.message = message;
this.url = url;
this.response = response;
this.code = code;
}
}
export class UnauthorizedError {
/*
Used when bad username or password is supplied.
*/
constructor(url, response, statusCode) {
this.message = 'Username or password is not valid.';
this.url = url;
this.response = response;
this.statusCode = statusCode;
}
}
const tokensUrl = new URI(services.authService)
.segment('/v1/auth/tokens')
.toString();
const appAccessTokenUrl = new URI(services.authService)
.segment('/v1/auth/tokens')
.toString();
function getBasicAuthHeaderValue(email, password) {
return `Basic ${Buffer.from(`${email}:${password}`).toString('base64')}`;
}
export async function createRefreshToken(email, password) {
try {
const response = await post(tokensUrl, null, {
headers: {
Authorization: getBasicAuthHeaderValue(email, password),
},
});
const { token } = response;
return token;
} catch (err) {
if (err.statusCode === 401) {
throw new UnauthorizedError(err.url, err.response, err.statusCode);
}
throw err;
}
}
export async function createAppAccessToken(appId, refreshToken) {
const body = {
data: {
type: 'shoutem.auth.tokens',
attributes: {
tokenType: 'access-token',
subjectType: 'application',
subjectId: appId.toString(),
},
},
};
const { token } = await post(appAccessTokenUrl, body, {
headers: {
Authorization: `Bearer ${refreshToken}`,
},
});
return token;
}
export async function getRefreshToken({ email, password } = {}) {
if (email && password) {
const refreshToken = await cache.setValue(
'refresh-token',
await createRefreshToken(email, password),
);
await cache.setValue('access-token', null);
return refreshToken;
}
return await cache.getValue('refresh-token');
}
export async function clearTokens() {
await cache.setValue('access-token', null);
await cache.setValue('refresh-token', null);
}
const authorizationConfig = {
createAccessTokenRequest(refreshToken) {
logger.info('createAccessTokenRequest', refreshToken);
return new Request(tokensUrl, {
method: 'POST',
headers: {
Authorization: `Bearer ${refreshToken}`,
Accept: 'application/vnd.api+json',
'Content-Type': 'application/vnd.api+json',
},
body: JSON.stringify({
data: {
type: 'shoutem.auth.tokens',
attributes: {
tokenType: 'access-token',
compressionType: 'gzip',
},
},
}),
});
},
async parseAccessToken(response) {
if (response.ok) {
const {
data: {
attributes: { token },
},
} = await response.json();
await cache.setValue('access-token', token);
return token;
}
logger.info('parseAccessToken', response);
throw new AuthServiceError(
'Could not get access token',
tokensUrl,
response,
'ACCESS_TOKEN_FAILURE',
);
},
shouldIntercept(request) {
return (
!request.headers.get('Authorization') &&
new URI(request.url).host() !== 'github.com'
);
},
shouldInvalidateAccessToken() {
return false;
},
authorizeRequest(request, accessToken) {
request.headers.set('Authorization', `Bearer ${accessToken}`);
logger.info('authorizeRequest', request.headers);
return request;
},
isResponseUnauthorized({ status }) {
return status === 401 || status === 403;
},
shouldWaitForTokenRenewal: true,
};
export async function authorizeRequests(refreshToken) {
if (!refreshToken) {
return false;
}
try {
const intercept = require('@shoutem/fetch-token-intercept');
intercept.configure(authorizationConfig);
intercept.authorize(refreshToken, await cache.getValue('access-token'));
return true;
} catch (err) {
logger.info(err);
if (err.statusCode !== 401) {
throw err;
}
return false;
}
}