Skip to content

Commit 897ba2e

Browse files
authored
Merge branch 'master' into master
2 parents 0b8b674 + 87786d6 commit 897ba2e

File tree

10 files changed

+899
-29
lines changed

10 files changed

+899
-29
lines changed

.babelrc

+4
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
{
2+
"presets": ["env"],
3+
"plugins": ["transform-async-to-generator", "transform-object-rest-spread"]
4+
}

.gitignore

+1
Original file line numberDiff line numberDiff line change
@@ -17,3 +17,4 @@ xcuserdata/
1717
.idea
1818
.vscode
1919
javac-services.0.log*
20+
dist/

README.md

+4
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,10 @@ manager.authorize('google', {scopes: 'profile email'})
3434
.catch(err => console.log('There was an error'));
3535
```
3636

37+
### Help
38+
39+
Due to other time contraints, I cannot continue to work on react-native-oauth for the time it deserves. If you're interested in supporting this library, please help! It's a widely used library and I'd love to continue supporting it. Looking for maintainers!
40+
3741
## Features
3842

3943
* Isolates the OAuth experience to a few simple methods.

android/src/main/java/io/fullstack/oauth/OAuthManagerModule.java

+22-1
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,9 @@
66
import android.support.annotation.Nullable;
77
import android.util.Log;
88

9+
import com.google.gson.Gson;
10+
import com.google.gson.JsonSyntaxException;
11+
912
import com.facebook.react.bridge.Arguments;
1013
import com.facebook.react.bridge.Callback;
1114
import com.facebook.react.bridge.ReactApplicationContext;
@@ -400,7 +403,25 @@ private WritableMap accessTokenResponse(
400403
WritableMap response = Arguments.createMap();
401404

402405
Log.d(TAG, "Credential raw response: " + accessToken.getRawResponse());
403-
406+
407+
/* Some things return as JSON, some as x-www-form-urlencoded (querystring) */
408+
409+
Map accessTokenMap = null;
410+
try {
411+
accessTokenMap = new Gson().fromJson(accessToken.getRawResponse(), Map.class);
412+
} catch (JsonSyntaxException e) {
413+
/*
414+
failed to parse as JSON, so turn it into a HashMap which looks like the one we'd
415+
get back from the JSON parser, so the rest of the code continues unchanged.
416+
*/
417+
Log.d(TAG, "Credential looks like a querystring; parsing as such");
418+
accessTokenMap = new HashMap();
419+
accessTokenMap.put("user_id", accessToken.getParameter("user_id"));
420+
accessTokenMap.put("oauth_token_secret", accessToken.getParameter("oauth_token_secret"));
421+
accessTokenMap.put("token_type", accessToken.getParameter("token_type"));
422+
}
423+
424+
404425
resp.putString("status", "ok");
405426
resp.putBoolean("authorized", true);
406427
resp.putString("provider", providerName);

android/src/main/java/io/fullstack/oauth/OAuthManagerPackage.java

-2
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,6 @@ public OAuthManagerPackage() {
2222
* @param reactContext react application context that can be used to create modules
2323
* @return list of native modules to register with the newly created catalyst instance
2424
*/
25-
@Override
2625
public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) {
2726
List<NativeModule> modules = new ArrayList<>();
2827
modules.add(new OAuthManagerModule(reactContext));
@@ -45,7 +44,6 @@ public List<Class<? extends JavaScriptModule>> createJSModules() {
4544
* @param reactContext
4645
* @return a list of view managers that should be registered with {@link UIManagerModule}
4746
*/
48-
@Override
4947
public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {
5048
return Collections.emptyList();
5149
}

ios/OAuthManager/OAuthManager.h

+6-6
Original file line numberDiff line numberDiff line change
@@ -7,16 +7,16 @@
77

88
#import <Foundation/Foundation.h>
99

10-
#if __has_include("RCTBridgeModule.h")
11-
#import "RCTBridgeModule.h"
12-
#else
10+
#if __has_include(<React/RCTBridgeModule.h>)
1311
#import <React/RCTBridgeModule.h>
12+
#else
13+
#import "RCTBridgeModule.h"
1414
#endif
1515

16-
#if __has_include("RCTLinkingManager.h")
17-
#import "RCTLinkingManager.h"
18-
#else
16+
#if __has_include(<React/RCTLinkingManager.h>)
1917
#import <React/RCTLinkingManager.h>
18+
#else
19+
#import "RCTLinkingManager.h"
2020
#endif
2121

2222

ios/OAuthManager/OAuthManager.m

+39-16
Original file line numberDiff line numberDiff line change
@@ -88,9 +88,13 @@ + (BOOL)setupOAuthHandler:(UIApplication *)application
8888
[authPlatform setURLOpener: ^void(NSURL *URL, DCTAuthPlatformCompletion completion) {
8989
// [sharedManager setPendingAuthentication:YES];
9090
if ([SFSafariViewController class] != nil) {
91-
safariViewController = [[SFSafariViewController alloc] initWithURL:URL];
92-
UIViewController *viewController = application.keyWindow.rootViewController;
93-
[viewController presentViewController:safariViewController animated:YES completion: nil];
91+
dispatch_async(dispatch_get_main_queue(), ^{
92+
safariViewController = [[SFSafariViewController alloc] initWithURL:URL];
93+
UIViewController *viewController = application.keyWindow.rootViewController;
94+
dispatch_async(dispatch_get_main_queue(), ^{
95+
[viewController presentViewController:safariViewController animated:YES completion: nil];
96+
});
97+
});
9498
} else {
9599
[application openURL:URL];
96100
}
@@ -153,7 +157,7 @@ - (BOOL) _configureProvider:(NSString *)providerName andConfig:(NSDictionary *)c
153157
_callbackUrls = [arr copy];
154158
NSLog(@"Saved callback url: %@ in %@", saveCallbackUrl, _callbackUrls);
155159
}
156-
160+
157161

158162
// Convert objects of url type
159163
for (NSString *name in [config allKeys]) {
@@ -303,7 +307,8 @@ - (NSDictionary *) getConfigForProvider:(NSString *)name
303307
NSMutableDictionary *cfg = [[manager getConfigForProvider:providerName] mutableCopy];
304308

305309
DCTAuthAccount *existingAccount = [manager accountForProvider:providerName];
306-
NSString *clientID = ((DCTOAuth2Credential *) existingAccount).clientID;
310+
NSString *clientID = ([providerName isEqualToString:@"google"]) ? ((DCTOAuth2Credential *) existingAccount).clientID : (NSString *)nil;
311+
307312
if (([providerName isEqualToString:@"google"] && existingAccount && clientID != nil)
308313
|| (![providerName isEqualToString:@"google"] && existingAccount != nil)) {
309314
if ([existingAccount isAuthorized]) {
@@ -354,14 +359,14 @@ - (NSDictionary *) getConfigForProvider:(NSString *)name
354359

355360
[manager addPending:client];
356361
_pendingAuthentication = YES;
357-
362+
358363
NSLog(@"Calling authorizeWithUrl: %@ with callbackURL: %@\n %@", providerName, callbackUrl, cfg);
359364

360365
[client authorizeWithUrl:providerName
361366
url:callbackUrl
362367
cfg:cfg
363368
onSuccess:^(DCTAuthAccount *account) {
364-
NSLog(@"on success called with account: %@", account);
369+
NSLog(@"on success called with account: %@", account);
365370
NSDictionary *accountResponse = [manager getAccountResponse:account cfg:cfg];
366371
_pendingAuthentication = NO;
367372
[manager removePending:client];
@@ -443,16 +448,27 @@ - (NSDictionary *) getConfigForProvider:(NSString *)name
443448
URL:apiUrl
444449
items:items];
445450

451+
// Allow json body in POST / PUT requests
446452
NSDictionary *body = [opts objectForKey:@"body"];
447453
if (body != nil) {
454+
NSMutableArray *items = [NSMutableArray array];
455+
448456
for (NSString *key in body) {
449-
NSData *data = [[NSString stringWithFormat:@"%@", [body valueForKey:key]] dataUsingEncoding:NSUTF8StringEncoding];
450-
[request addMultiPartData:data withName:key type:@"application/json"]; // TODO: How should we handle different body types?
457+
NSString *value = [body valueForKey:key];
458+
459+
DCTAuthContentItem *item = [[DCTAuthContentItem alloc] initWithName:key value:value];
460+
461+
if(item != nil) {
462+
[items addObject: item];
463+
}
451464
}
465+
466+
DCTAuthContent *content = [[DCTAuthContent alloc] initWithEncoding:NSUTF8StringEncoding
467+
type:DCTAuthContentTypeJSON
468+
items:items];
469+
[request setContent:content];
452470
}
453471

454-
request.account = existingAccount;
455-
456472
// If there are headers
457473
NSDictionary *headers = [opts objectForKey:@"headers"];
458474
if (headers != nil) {
@@ -463,6 +479,8 @@ - (NSDictionary *) getConfigForProvider:(NSString *)name
463479
request.HTTPHeaders = existingHeaders;
464480
}
465481

482+
request.account = existingAccount;
483+
466484
[request performRequestWithHandler:^(DCTAuthResponse *response, NSError *error) {
467485
if (error != nil) {
468486
NSDictionary *errorDict = @{
@@ -473,9 +491,12 @@ - (NSDictionary *) getConfigForProvider:(NSString *)name
473491
} else {
474492
NSInteger statusCode = response.statusCode;
475493
NSData *rawData = response.data;
494+
NSDictionary *headers = response.HTTPHeaders;
476495

477496
NSError *err;
478497
NSArray *data;
498+
499+
479500

480501
// Check if returned data is a valid JSON
481502
// != nil returned if the rawdata is not a valid JSON
@@ -487,20 +508,21 @@ - (NSDictionary *) getConfigForProvider:(NSString *)name
487508

488509
// Parse XML
489510
data = [XMLReader dictionaryForXMLData:rawData
490-
options:XMLReaderOptionsProcessNamespaces
491-
error:&err];
511+
options:XMLReaderOptionsProcessNamespaces
512+
error:&err];
492513
}
493-
494514
if (err != nil) {
495515
NSDictionary *errResp = @{
496516
@"status": @"error",
497517
@"msg": [NSString stringWithFormat:@"JSON parsing error: %@", [err localizedDescription]]
498518
};
499519
callback(@[errResp]);
500520
} else {
521+
501522
NSDictionary *resp = @{
502523
@"status": @(statusCode),
503-
@"data": data
524+
@"data": data != nil ? data : @[],
525+
@"headers": headers,
504526
};
505527
callback(@[[NSNull null], resp]);
506528
}
@@ -527,7 +549,7 @@ - (DCTAuthAccount *) accountForProvider:(NSString *) providerName
527549
}
528550

529551
- (NSDictionary *) credentialForAccount:(NSString *)providerName
530-
cfg:(NSDictionary *)cfg
552+
cfg:(NSDictionary *)cfg
531553
{
532554
DCTAuthAccount *account = [self accountForProvider:providerName];
533555
if (!account) {
@@ -715,3 +737,4 @@ - (NSString *) stringHost:(NSURL *)url
715737
}
716738

717739
@end
740+

lib/authProviders.js

+13-2
Original file line numberDiff line numberDiff line change
@@ -73,7 +73,18 @@ export const authProviders = {
7373
client_id: [notEmpty],
7474
client_secret: [notEmpty]
7575
})
76-
}
76+
},
77+
'spotify': {
78+
auth_version: "2.0",
79+
authorize_url: 'https://accounts.spotify.com/authorize',
80+
api_url: 'https://api.spotify.com/',
81+
callback_url: ({app_name}) => `${app_name}://authorize`,
82+
83+
validate: validate({
84+
client_id: [notEmpty],
85+
client_secret: [notEmpty]
86+
})
87+
},
7788
}
7889

79-
export default authProviders;
90+
export default authProviders;

0 commit comments

Comments
 (0)