Skip to content

Commit 1ddd4a7

Browse files
author
Kai Wood
committed
Client side auth urls
1 parent 2d67bca commit 1ddd4a7

File tree

2 files changed

+56
-3
lines changed

2 files changed

+56
-3
lines changed

lib/pnut.js

Lines changed: 37 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -56,10 +56,44 @@ const pnut = () => {
5656
* @param {string} method - HTTP verb, defaults to GET
5757
* @return {Promise}
5858
*/
59-
custom(endpoint, method = 'GET', data = {}) {
59+
custom(endpoint, method = 'GET', data = {}) {
6060
endpoint = endpoint.startsWith('/') ? `${endpoint}` : `/${endpoint}`
61-
return call(`${_base}${endpoint}`, {httpMethod: method, data: data})
62-
},
61+
return call(`${_base}${endpoint}`, { httpMethod: method, data: data })
62+
},
63+
64+
/**
65+
* Generate a URL for client side authentication
66+
* @param {string} - Client ID token
67+
* @param {string} redirectURI - URI you want to be redirected at
68+
* @param {object} [scope] - The scope you want to request
69+
* @returns {string}
70+
*/
71+
authenticateClientURL(clientId = '', redirectURI = '', scope = {
72+
basic: true,
73+
stream: true,
74+
write_post: true,
75+
follow: true,
76+
update_profile: true,
77+
presence: true,
78+
messages: true,
79+
public_messages: true,
80+
81+
}) {
82+
83+
if (clientId.length < 1) {
84+
throw new Error('You need a client ID for this request');
85+
} else if (redirectURI.length < 1) {
86+
throw new Error('You need a redirect URI for this request');
87+
}
88+
89+
let url = `${_base}/authenticate?`;
90+
url += `clientId=${clientId}`;
91+
url += `&redirect_uri=${redirectURI}`
92+
url += `&scope=${Object.keys(scope).join(',')}`
93+
url += `&response_type=token`
94+
95+
return url
96+
},
6397

6498
/**
6599
* The global timeline

test/pnut.js

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -107,6 +107,25 @@ describe('The pnut API wrapper', function () {
107107
return pnut.custom('/somewhere', 'PATCH', {text: 'sometext'});
108108
})
109109

110+
/**
111+
* Authentication
112+
*/
113+
describe('When requesting an authentication url, it', () => {
114+
it('should fail when no client id is given', () => {
115+
expect(() => pnut.authenticateClientURL('', 'http://github.com')).to.throw(Error)
116+
});
117+
118+
it('should fail if no redirect uri is given', () => {
119+
expect(() => pnut.authenticateClientURL('sometoken', '')).to.throw(Error)
120+
});
121+
122+
it('should give back a correct url where the client can authenticate', () => {
123+
let expectedURL = 'https://api.pnut.io/v0/authenticate?clientId=mytoken&redirect_uri=http://github.com&scope=basic,stream,write_post,follow,update_profile,presence,messages,public_messages&response_type=token';
124+
125+
expect(pnut.authenticateClientURL('mytoken', 'http://github.com')).to.equal(expectedURL);
126+
})
127+
})
128+
110129
/**
111130
* User context
112131
*/

0 commit comments

Comments
 (0)