Skip to content

Commit c0681ba

Browse files
committed
fix(jwt): use the same base64 decode for Node.js, browser and react native
1 parent a3910ca commit c0681ba

File tree

3 files changed

+21
-25
lines changed

3 files changed

+21
-25
lines changed

features/support/hooks.js

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,6 @@ async function clean () {
3636
}
3737
catch (error) {
3838
// rethrow to get a readable error
39-
console.error(error);
4039
throw error;
4140
}
4241

src/core/Jwt.js

Lines changed: 21 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,29 @@
11
'use strict';
22

3-
// used for unit tests
4-
const browserAtob = base64 => atob(base64);
5-
const bufferAvailable = () => typeof Buffer !== 'undefined';
3+
// atob is not available in React Native
4+
// https://stackoverflow.com/questions/42829838/react-native-atob-btoa-not-working-without-remote-js-debugging
65

7-
const decodeBase64 = base64 => {
8-
if (bufferAvailable()) {
9-
return Buffer.from(base64, 'base64').toString();
6+
const base64Charset = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
7+
8+
const decodeBase64 = input => {
9+
const str = input.replace(/=+$/, '');
10+
let output = '';
11+
12+
if (str.length % 4 === 1) {
13+
throw new Error('Malformated base64 string.');
14+
}
15+
16+
for (let bc = 0, bs = 0, buffer, i = 0;
17+
buffer = str.charAt(i++); // eslint-disable-line no-cond-assign
18+
19+
~buffer && (bs = bc % 4 ? bs * 64 + buffer : buffer, bc++ % 4)
20+
? output += String.fromCharCode(255 & bs >> (-2 * bc & 6))
21+
: 0
22+
) {
23+
buffer = base64Charset.indexOf(buffer);
1024
}
1125

12-
return browserAtob(base64);
26+
return output;
1327
};
1428

1529
class Jwt {

test/core/Jwt.test.js

Lines changed: 0 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -37,23 +37,6 @@ describe('Jwt', () => {
3737
new Jwt('this-is.not-json-payload.for-sure');
3838
}).throwError('Invalid JSON payload for JWT');
3939
});
40-
41-
it('should be able to decode the payload when Buffer is not available (browser)', () => {
42-
Jwt.__set__('browserAtob', base64 => Buffer.from(base64, 'base64').toString());
43-
Jwt.__set__('bufferAvailable', () => false);
44-
45-
const
46-
expiresAt = Date.now() + 3600 * 1000,
47-
encodedJwt = generateJwt('user-gordon', expiresAt);
48-
49-
50-
authenticationToken = new Jwt(encodedJwt);
51-
52-
should(authenticationToken.encodedJwt).be.eql(encodedJwt);
53-
should(authenticationToken.userId).be.eql('user-gordon');
54-
should(authenticationToken.expiresAt).be.eql(expiresAt);
55-
should(authenticationToken.expired).be.eql(false);
56-
});
5740
});
5841

5942
describe('#get expired', () => {

0 commit comments

Comments
 (0)