Skip to content
This repository was archived by the owner on Jan 10, 2024. It is now read-only.

Commit 3adbf2f

Browse files
committed
adding forceoauth + modularizing forcetk
1 parent 29176db commit 3adbf2f

File tree

3 files changed

+282
-80
lines changed

3 files changed

+282
-80
lines changed

.gitignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,2 @@
11
.DS_Store
2+
.idea

forceoauth.js

Lines changed: 207 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,207 @@
1+
"use strict";
2+
3+
let // The login URL for the OAuth process
4+
// To override default, pass loginURL in init(props)
5+
loginURL = 'https://login.salesforce.com',
6+
7+
// The Connected App client Id. Default app id provided - Not for production use.
8+
// This application supports http://localhost:8200/oauthcallback.html as a valid callback URL
9+
// To override default, pass appId in init(props)
10+
appId = '3MVG9fMtCkV6eLheIEZplMqWfnGlf3Y.BcWdOf1qytXo9zxgbsrUbS.ExHTgUPJeb3jZeT8NYhc.hMyznKU92',
11+
12+
// The force.com API version to use.
13+
// To override default, pass apiVersion in init(props)
14+
apiVersion = 'v35.0',
15+
16+
// Keep track of OAuth data (access_token, refresh_token, and instance_url)
17+
oauthData,
18+
19+
// By default we store fbtoken in sessionStorage. This can be overridden in init()
20+
tokenStore = {},
21+
22+
// if page URL is http://localhost:3000/myapp/index.html, context is /myapp
23+
context = window.location.pathname.substring(0, window.location.pathname.lastIndexOf("/")),
24+
25+
// if page URL is http://localhost:3000/myapp/index.html, serverURL is http://localhost:3000
26+
serverURL = window.location.protocol + '//' + window.location.hostname + (window.location.port ? ':' + window.location.port : ''),
27+
28+
// if page URL is http://localhost:3000/myapp/index.html, baseURL is http://localhost:3000/myapp
29+
baseURL = serverURL + context,
30+
31+
// Only required when using REST APIs in an app hosted on your own server to avoid cross domain policy issues
32+
// To override default, pass proxyURL in init(props)
33+
proxyURL = baseURL,
34+
35+
// if page URL is http://localhost:3000/myapp/index.html, oauthCallbackURL is http://localhost:3000/myapp/oauthcallback.html
36+
// To override default, pass oauthCallbackURL in init(props)
37+
oauthCallbackURL = baseURL + '/oauthcallback.html',
38+
39+
// Whether or not to use a CORS proxy. Defaults to false if app running in Cordova, in a VF page,
40+
// or using the Salesforce console. Can be overriden in init()
41+
useProxy = (window.SfdcApp || window.sforce) ? false : true;
42+
43+
let parseQueryString = queryString => {
44+
let qs = decodeURIComponent(queryString),
45+
obj = {},
46+
params = qs.split('&');
47+
params.forEach(param => {
48+
let splitter = param.split('=');
49+
obj[splitter[0]] = splitter[1];
50+
});
51+
return obj;
52+
};
53+
54+
let toQueryString = obj => {
55+
let parts = [],
56+
i;
57+
for (i in obj) {
58+
if (obj.hasOwnProperty(i)) {
59+
parts.push(encodeURIComponent(i) + "=" + encodeURIComponent(obj[i]));
60+
}
61+
}
62+
return parts.join("&");
63+
};
64+
65+
let refreshToken = () => new Promise((resolve, reject) => {
66+
67+
if (!oauthData.refresh_token) {
68+
console.log('ERROR: refresh token does not exist');
69+
reject();
70+
return;
71+
}
72+
73+
let xhr = new XMLHttpRequest(),
74+
75+
params = {
76+
'grant_type': 'refresh_token',
77+
'refresh_token': oauthData.refresh_token,
78+
'client_id': appId
79+
},
80+
81+
url = useProxy ? proxyURL : loginURL;
82+
83+
url = url + '/services/oauth2/token?' + toQueryString(params);
84+
85+
xhr.onreadystatechange = () => {
86+
if (xhr.readyState === 4) {
87+
if (xhr.status === 200) {
88+
console.log('Token refreshed');
89+
let res = JSON.parse(xhr.responseText);
90+
oauthData.access_token = res.access_token;
91+
tokenStore.forceOAuth = JSON.stringify(oauthData);
92+
resolve();
93+
} else {
94+
console.log('Error while trying to refresh token: ' + xhr.responseText);
95+
reject();
96+
}
97+
}
98+
};
99+
100+
xhr.open('POST', url, true);
101+
if (!useProxy) {
102+
xhr.setRequestHeader("Target-URL", loginURL);
103+
}
104+
xhr.send();
105+
106+
});
107+
108+
/**
109+
* Initialize ForceJS
110+
* @param params
111+
* appId (optional)
112+
* loginURL (optional)
113+
* proxyURL (optional)
114+
* oauthCallbackURL (optional)
115+
* apiVersion (optional)
116+
* accessToken (optional)
117+
* instanceURL (optional)
118+
* refreshToken (optional)
119+
*/
120+
export let init = params => {
121+
122+
if (params) {
123+
appId = params.appId || appId;
124+
apiVersion = params.apiVersion || apiVersion;
125+
loginURL = params.loginURL || loginURL;
126+
oauthCallbackURL = params.oauthCallbackURL || oauthCallbackURL;
127+
proxyURL = params.proxyURL || proxyURL;
128+
useProxy = params.useProxy === undefined ? useProxy : params.useProxy;
129+
130+
if (params.accessToken) {
131+
if (!oauthData) oauthData = {};
132+
oauthData.access_token = params.accessToken;
133+
}
134+
135+
if (params.instanceURL) {
136+
if (!oauthData) oauthData = {};
137+
oauthData.instance_url = params.instanceURL;
138+
}
139+
140+
if (params.refreshToken) {
141+
if (!oauthData) oauthData = {};
142+
oauthData.refresh_token = params.refreshToken;
143+
}
144+
}
145+
146+
console.log("useProxy: " + useProxy);
147+
148+
};
149+
150+
/**
151+
* Discard the OAuth access_token. Use this function to test the refresh token workflow.
152+
*/
153+
export let discardToken = () => {
154+
delete oauthData.access_token;
155+
tokenStore.forceOAuth = JSON.stringify(oauthData);
156+
};
157+
158+
export let login = () => new Promise((resolve, reject) => {
159+
160+
console.log('loginURL: ' + loginURL);
161+
console.log('oauthCallbackURL: ' + oauthCallbackURL);
162+
163+
let loginWindowURL = loginURL + '/services/oauth2/authorize?client_id=' + appId + '&redirect_uri=' + oauthCallbackURL + '&response_type=token';
164+
165+
document.addEventListener("oauthCallback", (event) => {
166+
167+
// Parse the OAuth data received from Salesforce
168+
let url = event.detail,
169+
queryString,
170+
obj;
171+
172+
if (url.indexOf("access_token=") > 0) {
173+
queryString = url.substr(url.indexOf('#') + 1);
174+
obj = parseQueryString(queryString);
175+
oauthData = obj;
176+
tokenStore.forceOAuth = JSON.stringify(oauthData);
177+
resolve(oauthData);
178+
} else if (url.indexOf("error=") > 0) {
179+
queryString = decodeURIComponent(url.substring(url.indexOf('?') + 1));
180+
obj = parseQueryString(queryString);
181+
reject(obj);
182+
} else {
183+
reject({status: 'access_denied'});
184+
}
185+
186+
});
187+
188+
window.open(loginWindowURL, '_blank', 'location=no');
189+
190+
});
191+
192+
/**
193+
* Gets the user's ID (if logged in)
194+
* @returns {string} | undefined
195+
*/
196+
export let getUserId = () => (typeof(oauthData) !== 'undefined') ? oauthData.id.split('/').pop() : undefined;
197+
198+
/**
199+
* Get the OAuth data returned by the Salesforce login process
200+
*/
201+
export let getOAuthData = () => oauthData;
202+
203+
/**
204+
* Check the login status
205+
* @returns {boolean}
206+
*/
207+
export let isAuthenticated = () => (oauthData && oauthData.access_token) ? true : false;

0 commit comments

Comments
 (0)