Skip to content

Commit 246c3f9

Browse files
author
Simona Peneva
committed
Oauth authenticate without redirect uri
1 parent dd329f6 commit 246c3f9

File tree

9 files changed

+163
-51
lines changed

9 files changed

+163
-51
lines changed

docs/api-oauth.md

Lines changed: 19 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,11 @@
11
## pCloudSdk.oauth
22

3-
- This is the API Reference for the `oauth` export. For details how to use them see [Oauth](oauth.md).
4-
- If you want to built yourself a custom Oauth flow see the [pCloud's API Docs](https://docs.pcloud.com/methods/oauth_2.0/index.html).
3+
* This is the API Reference for the `oauth` export. For details how to use them see [Oauth](oauth.md).
4+
* If you want to built yourself a custom Oauth flow see the [pCloud's API Docs](https://docs.pcloud.com/methods/oauth_2.0/index.html).
55

66
#### initOauthToken
77

8-
``` js
8+
```js
99
initOauthToken({
1010
client_id: string,
1111
redirect_uri: string,
@@ -14,23 +14,36 @@ initOauthToken({
1414
});
1515
```
1616

17+
You can use following method for Oauth authenticate without redirect uri(see [listfolder example](../examples/listfolder.html)):
18+
19+
#### initOauthPollToken
20+
21+
```js
22+
initOauthPollToken({
23+
client_id: string,
24+
receiveToken: () => void,
25+
onError:() => void
26+
});
27+
```
28+
1729
#### popup()
1830

19-
``` html
31+
```html
2032
// inside redirect_uri window
2133
<script>
2234
pCloudSdk.oauth.popup();
2335
</script>
2436
```
2537

38+
2639
#### getTokenFromCode
2740

28-
``` js
41+
```js
2942
getTokenFromCode(
3043
code: string,
3144
client_id: string,
3245
app_secret: string
3346
): Promise<{ userid, access_token }>
3447
```
3548

36-
- `code` can be received either manually by the user via copy & paste (see [oauth example](../examples/node/token.js)) or by specifying `response_type: "code"` to `initOauthToken`.
49+
* `code` can be received either manually by the user via copy & paste (see [oauth example](../examples/node/token.js)) or by specifying `response_type: "code"` to `initOauthToken`.

docs/oauth.md

Lines changed: 23 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -6,13 +6,14 @@ In order to use pCloud api calls, you first need to acquire a token from the use
66
* (**Client side only**) Setup a redirect url to which you have access to and can place a static html page.
77

88
## Client side flow
9+
910
Use the following snippet in some user initiated action (click):
1011

11-
``` js
12+
```js
1213
pCloudSdk.oauth.initOauthToken({
13-
client_id: 'YOUR_CLIENT_ID',
14-
redirect_uri: 'YOUR_REDIRECT_URL',
15-
response_type: 'token' | 'code',
14+
client_id: "YOUR_CLIENT_ID",
15+
redirect_uri: "YOUR_REDIRECT_URL",
16+
response_type: "token" | "code",
1617
receiveToken: function(access_token) {
1718
// do something with the token.
1819
}
@@ -21,22 +22,36 @@ pCloudSdk.oauth.initOauthToken({
2122

2223
This will open a popup window where the user can authorize the usage of your app. After this he will be redirected to the `redirect_uri` page which needs to be a simple html that loads the SDK and runs the following:
2324

24-
``` js
25+
```js
2526
pCloudSdk.oauth.popup();
2627
```
2728

2829
This will ensure that the snippet above will work and the `access_token` will be received. Checkout the [oauth examples](../examples/) for more info.
2930

3031
## Server side flow
32+
3133
For server side applications you would be using a token received from the user via the client side flow and then saved in some kind persistent storage (database or else).
3234

3335
For easing you in using the SDK, you can use the tool provided in the `examples/node` folder of this repo. Enter your application's `client_id` and `app_secret` in `app.json` using the following format:
3436

35-
``` json
37+
```json
3638
{
3739
"client_id": "",
38-
"app_secret":""
40+
"app_secret": ""
3941
}
4042
```
4143

42-
Then run `node examples/node/token.js` and follow the prompts. The process will save the generated `access_token` and the `userid` of the user in the `app.json`. All examples will work afterwards.
44+
Then run `node examples/node/token.js` and follow the prompts. The process will save the generated `access_token` and the `userid` of the user in the `app.json`. All examples will work afterwards.
45+
46+
* (**Client side only with poll request**)
47+
Use the following snippet in some user initiated action (click):
48+
49+
```js
50+
pCloudSdk.oauth.initOauthPollToken({
51+
client_id: "YOUR_CLIENT_ID",
52+
receiveToken: function(access_token) {
53+
// do something with the token.
54+
},
55+
onError: function(err) {}
56+
});
57+
```

examples/listfolder.html

Lines changed: 42 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,31 @@
11
<html>
2+
23
<head>
34
<title>pCloud SDK: Examples / List folder</title>
45
<style>
56
body {
67
margin: 0;
78
padding: 20px;
89
}
9-
#gettoken {
10-
position: fixed;
10+
11+
#gettoken-redirect {
1112
top: 20px;
13+
position: fixed;
14+
right: 20px;
15+
}
16+
17+
#gettoken-poll {
18+
top: 50px;
19+
position: fixed;
1220
right: 20px;
1321
}
1422
</style>
1523
</head>
24+
1625
<body>
1726

18-
<button id="gettoken">Get Token</button>
27+
<button id="gettoken-redirect">Get Token(redirect)</button>
28+
<button id="gettoken-poll">Get Token(poll)</button>
1929

2030
<script type="text/javascript" src="examples/pcloudsdk.js"></script>
2131
<script>
@@ -85,26 +95,39 @@
8595
return client.listfolder(0).then(children).then(map(name));
8696
}
8797

88-
el('gettoken').addEventListener('click', function(e) {
98+
function receiveTokenCb(token) {
99+
console.log(token);
100+
access_token = token;
101+
client = pCloudSdk.createClient(token);
102+
103+
folderSize(0).then((a) => {
104+
console.log('Size: ', a);
105+
});
106+
107+
folderItems(0).then((a) => {
108+
console.log('Items: ', a);
109+
});
110+
}
111+
// Oauth authenticate with redirect uri
112+
el('gettoken-redirect').addEventListener('click', function (e) {
89113
pCloudSdk.oauth.initOauthToken({
90-
client_id: 'p1WznE2dEPm',
114+
client_id: 'BJpmGFpuj3S',
91115
redirect_uri: 'http://127.0.0.1:8080/oauth.html',
92-
receiveToken: function(token) {
93-
console.log(token);
94-
access_token = token;
95-
client = pCloudSdk.createClient(token);
96-
97-
folderSize(0).then((a) => {
98-
console.log('Size: ', a);
99-
});
100-
101-
folderItems(0).then((a) => {
102-
console.log('Items: ', a);
103-
});
104-
}
116+
receiveToken: receiveTokenCb,
117+
onError: err => console.log(err)
118+
});
119+
}, false);
120+
121+
// Oauth authenticate without redirect uri
122+
el('gettoken-poll').addEventListener('click', function (e) {
123+
pCloudSdk.oauth.initOauthPollToken({
124+
client_id: 'BJpmGFpuj3S',
125+
receiveToken: receiveTokenCb,
126+
onError: err => console.log(err)
105127
});
106128
}, false);
107129

108130
</script>
109131
</body>
110-
</html>
132+
133+
</html>

examples/node/download.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
const pcloud = require('../../lib');
1+
const pcloud = require('pcloud-sdk-js');
22
const invariant = require('invariant');
33
const path = require('path');
44

examples/node/token.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
var prompt = require('prompt');
22
var fs = require('fs');
33
var url = require('url');
4-
var oauth = require('../../lib').oauth;
4+
var oauth = require('pcloud-sdk-js').oauth;
55

66
if (!appExists()) {
77
resetAppJson();

examples/node/upload.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
const pcloud = require('../../lib');
1+
const pcloud = require('pcloud-sdk-js');
22
const invariant = require('invariant');
33
const app = require('./app.json');
44

package-lock.json

Lines changed: 1 addition & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

src/oauth/index.js

Lines changed: 64 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
import url from "url";
44
import invariant from "invariant";
55
import ApiMethod from "../api/ApiMethod";
6+
import { generateRandomString } from "../utils/functions";
67

78
const protocol = "https";
89
const host = "my.pcloud.com";
@@ -12,25 +13,41 @@ type oAuthOptions = {
1213
client_id: string,
1314
redirect_uri: string,
1415
response_type: "token" | "code",
15-
receiveToken(): void
16+
receiveToken: any => void
1617
};
1718

19+
type oAuthPollOptions = {
20+
client_id: string,
21+
response_type: "poll_token",
22+
receiveToken: string => void,
23+
onError: Error => void
24+
};
25+
26+
function buildOauthUrl(query) {
27+
return url.format({
28+
protocol: protocol,
29+
hostname: host,
30+
pathname: path,
31+
query: query
32+
});
33+
}
34+
1835
function initOauthToken(options: oAuthOptions) {
19-
const { client_id = false, redirect_uri = false, receiveToken = false, response_type = "token" } = options;
36+
const {
37+
client_id = null,
38+
redirect_uri = null,
39+
receiveToken = null,
40+
response_type = "token"
41+
} = options;
2042

2143
invariant(client_id, "`client_id` is required.");
2244
invariant(redirect_uri, "`redirect_uri` is required.");
2345
invariant(receiveToken, "`receiveToken` is required.");
2446

25-
const oauthUrl = url.format({
26-
protocol: protocol,
27-
hostname: host,
28-
pathname: path,
29-
query: {
30-
redirect_uri: redirect_uri,
31-
client_id: client_id,
32-
response_type: response_type
33-
}
47+
const oauthUrl = buildOauthUrl({
48+
redirect_uri: redirect_uri,
49+
client_id: client_id,
50+
response_type: response_type
3451
});
3552

3653
window.open(oauthUrl, "oauth", "width=680,height=535");
@@ -40,9 +57,37 @@ function initOauthToken(options: oAuthOptions) {
4057
};
4158
}
4259

60+
function initOauthPollToken(options: oAuthPollOptions) {
61+
const request_id: string = generateRandomString(40);
62+
const { client_id = null, receiveToken = null, onError = null } = options;
63+
64+
invariant(client_id, "`client_id` is required.");
65+
invariant(receiveToken, "`receiveToken` is required.");
66+
invariant(onError, "`onError` is required.");
67+
68+
const oauthUrl = buildOauthUrl({
69+
request_id: request_id,
70+
client_id: client_id,
71+
response_type: "poll_token"
72+
});
73+
const loginOauth = window.open(oauthUrl, "oauth", "width=680,height=535");
74+
75+
ApiMethod("oauth2_token", {
76+
params: { client_id: client_id, request_id: request_id }
77+
})
78+
.then(res => {
79+
receiveToken(res.access_token);
80+
loginOauth.close();
81+
})
82+
.catch(err => {
83+
onError(err);
84+
loginOauth.close();
85+
});
86+
}
87+
4388
function popup() {
44-
const matchToken = (location: any).hash.match(/access_token=([^&]+)/);
45-
const matchCode = (location: any).search.match(/code=([^&]+)/);
89+
const matchToken = location.hash.match(/access_token=([^&]+)/);
90+
const matchCode = location.search.match(/code=([^&]+)/);
4691
const token = matchToken ? matchToken[1] : matchCode[1];
4792

4893
window.opener.__setPcloudToken(token);
@@ -55,4 +100,9 @@ function getTokenFromCode(code: string, client_id: string, app_secret: string) {
55100
});
56101
}
57102

58-
export default { initOauthToken, popup, getTokenFromCode };
103+
export default {
104+
initOauthToken,
105+
initOauthPollToken,
106+
popup,
107+
getTokenFromCode
108+
};

src/utils/functions.js

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,3 +47,14 @@ export function methodStringify(method: string, params: Object): string {
4747
export function pCloudUrl(data: DownloadData) {
4848
return "https://" + data.hosts[0] + data.path;
4949
}
50+
51+
export function generateRandomString(length: number) {
52+
const strArr = [];
53+
const base = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
54+
55+
for (let i = 0; i < length; i++) {
56+
strArr.push(base[Math.floor(Math.random() * 100)]);
57+
}
58+
59+
return strArr.join("");
60+
}

0 commit comments

Comments
 (0)