-
Notifications
You must be signed in to change notification settings - Fork 213
/
Copy pathA0Auth0.m
303 lines (256 loc) · 13.9 KB
/
A0Auth0.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
#import "A0Auth0.h"
#import <SafariServices/SafariServices.h>
#if __has_include("AuthenticationServices/AuthenticationServices.h")
#import <AuthenticationServices/AuthenticationServices.h>
#endif
#import <CommonCrypto/CommonCrypto.h>
#import <React/RCTUtils.h>
#import "A0Auth0-Swift.h"
#define ERROR_CANCELLED @{@"error": @"a0.session.user_cancelled",@"error_description": @"User cancelled the Auth"}
#define ERROR_FAILED_TO_LOAD @{@"error": @"a0.session.failed_load",@"error_description": @"Failed to load url"}
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 130000
@interface A0Auth0 () <SFSafariViewControllerDelegate, ASWebAuthenticationPresentationContextProviding>
@end
#else
@interface A0Auth0 () <SFSafariViewControllerDelegate>
@end
#endif
@interface A0Auth0 () <SFSafariViewControllerDelegate>
@property (weak, nonatomic) SFSafariViewController *last;
@property (strong, nonatomic) NSObject *authenticationSession;
@property (strong, nonatomic) CredentialsManagerBridge *credentialsManagerBridge;
@property (copy, nonatomic) RCTResponseSenderBlock sessionCallback;
@property (assign, nonatomic) BOOL closeOnLoad;
@end
@implementation A0Auth0
- (dispatch_queue_t)methodQueue
{
return dispatch_get_main_queue();
}
RCT_EXPORT_MODULE();
RCT_EXPORT_METHOD(hide) {
[self terminateWithError:nil dismissing:YES animated:YES];
}
RCT_EXPORT_METHOD(hasValidCredentialManagerInstance:(RCTPromiseResolveBlock)resolve
rejecter:(RCTPromiseRejectBlock)reject) {
BOOL valid = [self checkHasValidCredentialManagerInstance];
resolve(@(valid));
}
RCT_EXPORT_METHOD(initializeCredentialManager:(NSString *)clientId domain:(NSString *)domain) {
[self tryAndInitializeCredentialManager:clientId domain:domain];
}
RCT_EXPORT_METHOD(saveCredentials:(NSDictionary *)credentials resolver:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject) {
[self.credentialsManagerBridge saveCredentialsWithCredentialsDict:credentials resolve:resolve reject:reject];
}
RCT_EXPORT_METHOD(getCredentials:(NSString *)scope minTTL:(NSInteger)minTTL parameters:(NSDictionary *)parameters resolver:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject) {
[self.credentialsManagerBridge getCredentialsWithScope:scope minTTL:minTTL parameters:parameters resolve:resolve reject:reject];
}
RCT_EXPORT_METHOD(hasValidCredentials:(NSInteger)minTTL resolver:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject) {
[self.credentialsManagerBridge hasValidCredentialsWithMinTTL:minTTL resolve:resolve];
}
RCT_EXPORT_METHOD(clearCredentials:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject) {
[self.credentialsManagerBridge clearCredentialsWithResolve:resolve reject:reject];
}
RCT_EXPORT_METHOD(enableLocalAuthentication:(NSString *)title cancelTitle:(NSString *)cancelTitle fallbackTitle:(NSString *)fallbackTitle evaluationPolicy:(NSInteger)evaluationPolicy) {
[self.credentialsManagerBridge enableLocalAuthenticationWithTitle:title cancelTitle:cancelTitle fallbackTitle:fallbackTitle evaluationPolicy: evaluationPolicy];
}
RCT_EXPORT_METHOD(showUrl:(NSString *)urlString
usingEphemeralSession:(BOOL)ephemeralSession
closeOnLoad:(BOOL)closeOnLoad
callback:(RCTResponseSenderBlock)callback) {
if (@available(iOS 11.0, *)) {
self.sessionCallback = callback;
self.closeOnLoad = closeOnLoad;
[self presentAuthenticationSession:[NSURL URLWithString:urlString] usingEphemeralSession:ephemeralSession];
} else {
[self presentSafariWithURL:[NSURL URLWithString:urlString]];
self.sessionCallback = callback;
self.closeOnLoad = closeOnLoad;
}
}
RCT_EXPORT_METHOD(oauthParameters:(RCTResponseSenderBlock)callback) {
callback(@[[self generateOAuthParameters]]);
}
- (NSDictionary *)constantsToExport {
return @{ @"bundleIdentifier": [[NSBundle mainBundle] bundleIdentifier] };
}
+ (BOOL)requiresMainQueueSetup {
return YES;
}
#pragma mark - Internal methods
UIBackgroundTaskIdentifier taskId;
- (BOOL)checkHasValidCredentialManagerInstance {
BOOL valid = self.credentialsManagerBridge != nil;
return valid;
}
- (void)tryAndInitializeCredentialManager:(NSString *)clientId domain:(NSString *)domain {
CredentialsManagerBridge *bridge = [[CredentialsManagerBridge alloc] initWithClientId: clientId domain: domain];
self.credentialsManagerBridge = bridge;
}
- (void)presentSafariWithURL:(NSURL *)url {
UIWindow *window = [[UIApplication sharedApplication] keyWindow];
SFSafariViewController *controller = [[SFSafariViewController alloc] initWithURL:url];
controller.delegate = self;
[self terminateWithError:RCTMakeError(@"Only one Safari can be visible", nil, nil) dismissing:YES animated:NO];
[[self topViewControllerWithRootViewController:window.rootViewController] presentViewController:controller animated:YES completion:nil];
self.last = controller;
}
- (void)presentAuthenticationSession:(NSURL *)url usingEphemeralSession:(BOOL)ephemeralSession {
NSURLComponents *urlComponents = [NSURLComponents componentsWithURL:url
resolvingAgainstBaseURL:NO];
NSArray *queryItems = urlComponents.queryItems;
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name=%@", @"redirect_uri"];
NSURLQueryItem *queryItem = [[queryItems
filteredArrayUsingPredicate:predicate]
firstObject];
NSString *callbackURLScheme = [[NSURL URLWithString: queryItem.value] scheme];
RCTResponseSenderBlock callback = self.sessionCallback ? self.sessionCallback : ^void(NSArray *_unused) {};
if (@available(iOS 12.0, *)) {
taskId = [UIApplication.sharedApplication beginBackgroundTaskWithExpirationHandler:^{
[UIApplication.sharedApplication endBackgroundTask:taskId];
taskId = UIBackgroundTaskInvalid;
}];
ASWebAuthenticationSession* authenticationSession = [[ASWebAuthenticationSession alloc]
initWithURL:url callbackURLScheme:callbackURLScheme
completionHandler:^(NSURL * _Nullable callbackURL,
NSError * _Nullable error) {
if ([[error domain] isEqualToString:ASWebAuthenticationSessionErrorDomain] &&
[error code] == ASWebAuthenticationSessionErrorCodeCanceledLogin) {
callback(@[ERROR_CANCELLED, [NSNull null]]);
} else if(error) {
callback(@[error, [NSNull null]]);
} else if(callbackURL) {
callback(@[[NSNull null], callbackURL.absoluteString]);
}
self.authenticationSession = nil;
[UIApplication.sharedApplication endBackgroundTask:taskId];
taskId = UIBackgroundTaskInvalid;
}];
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 130000
if (@available(iOS 13.0, *)) {
authenticationSession.presentationContextProvider = self;
authenticationSession.prefersEphemeralWebBrowserSession = ephemeralSession;
}
#endif
self.authenticationSession = authenticationSession;
[(ASWebAuthenticationSession*) self.authenticationSession start];
} else if (@available(iOS 11.0, *)) {
taskId = [UIApplication.sharedApplication beginBackgroundTaskWithExpirationHandler:^{
[UIApplication.sharedApplication endBackgroundTask:taskId];
taskId = UIBackgroundTaskInvalid;
}];
self.authenticationSession = [[SFAuthenticationSession alloc]
initWithURL:url callbackURLScheme:callbackURLScheme
completionHandler:^(NSURL * _Nullable callbackURL,
NSError * _Nullable error) {
if ([[error domain] isEqualToString:SFAuthenticationErrorDomain] &&
[error code] == SFAuthenticationErrorCanceledLogin) {
callback(@[ERROR_CANCELLED, [NSNull null]]);
} else if(error) {
callback(@[error, [NSNull null]]);
} else if(callbackURL) {
callback(@[[NSNull null], callbackURL.absoluteString]);
}
self.authenticationSession = nil;
[UIApplication.sharedApplication endBackgroundTask:taskId];
taskId = UIBackgroundTaskInvalid;
}];
[(SFAuthenticationSession*) self.authenticationSession start];
}
}
- (void)terminateWithError:(id)error dismissing:(BOOL)dismissing animated:(BOOL)animated {
RCTResponseSenderBlock callback = self.sessionCallback ? self.sessionCallback : ^void(NSArray *_unused) {};
if (dismissing) {
if (self.last.presentingViewController) {
[self.last.presentingViewController dismissViewControllerAnimated:animated
completion:^{
if (error) {
callback(@[error, [NSNull null]]);
}
}];
} else {
if ([self.authenticationSession isKindOfClass:ASWebAuthenticationSession.class]) {
[(ASWebAuthenticationSession *)self.authenticationSession cancel];
} else if ([self.authenticationSession isKindOfClass:SFAuthenticationSession.class]) {
[(SFAuthenticationSession *)self.authenticationSession cancel];
}
if (error) {
callback(@[error, [NSNull null]]);
}
}
} else if (error) {
callback(@[error, [NSNull null]]);
}
self.sessionCallback = nil;
self.authenticationSession = nil;
self.last = nil;
self.closeOnLoad = NO;
}
- (NSString *)randomValue {
NSMutableData *data = [NSMutableData dataWithLength:32];
int result __attribute__((unused)) = SecRandomCopyBytes(kSecRandomDefault, 32, data.mutableBytes);
NSString *value = [[[[data base64EncodedStringWithOptions:0]
stringByReplacingOccurrencesOfString:@"+" withString:@"-"]
stringByReplacingOccurrencesOfString:@"/" withString:@"_"]
stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"="]];
return value;
}
- (NSString *)sign:(NSString*)value {
CC_SHA256_CTX ctx;
uint8_t * hashBytes = malloc(CC_SHA256_DIGEST_LENGTH * sizeof(uint8_t));
memset(hashBytes, 0x0, CC_SHA256_DIGEST_LENGTH);
NSData *valueData = [value dataUsingEncoding:NSUTF8StringEncoding];
CC_SHA256_Init(&ctx);
CC_SHA256_Update(&ctx, [valueData bytes], (CC_LONG)[valueData length]);
CC_SHA256_Final(hashBytes, &ctx);
NSData *hash = [NSData dataWithBytes:hashBytes length:CC_SHA256_DIGEST_LENGTH];
if (hashBytes) {
free(hashBytes);
}
return [[[[hash base64EncodedStringWithOptions:0]
stringByReplacingOccurrencesOfString:@"+" withString:@"-"]
stringByReplacingOccurrencesOfString:@"/" withString:@"_"]
stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"="]];
}
- (NSDictionary *)generateOAuthParameters {
NSString *verifier = [self randomValue];
return @{
@"verifier": verifier,
@"code_challenge": [self sign:verifier],
@"code_challenge_method": @"S256",
@"state": [self randomValue]
};
}
#pragma mark - SFSafariViewControllerDelegate
- (void)safariViewControllerDidFinish:(SFSafariViewController *)controller {
[self terminateWithError:ERROR_CANCELLED dismissing:NO animated:NO];
}
- (void)safariViewController:(SFSafariViewController *)controller didCompleteInitialLoad:(BOOL)didLoadSuccessfully {
if (self.closeOnLoad && didLoadSuccessfully) {
[self terminateWithError:[NSNull null] dismissing:YES animated:YES];
} else if (!didLoadSuccessfully) {
[self terminateWithError:ERROR_FAILED_TO_LOAD dismissing:YES animated:YES];
}
}
# pragma mark - Utility
- (UIViewController*)topViewControllerWithRootViewController:(UIViewController*)rootViewController {
if ([rootViewController isKindOfClass:[UITabBarController class]]) {
UITabBarController* tabBarController = (UITabBarController*)rootViewController;
return [self topViewControllerWithRootViewController:tabBarController.selectedViewController];
} else if ([rootViewController isKindOfClass:[UINavigationController class]]) {
UINavigationController* navigationController = (UINavigationController*)rootViewController;
return [self topViewControllerWithRootViewController:navigationController.visibleViewController];
} else if (rootViewController.presentedViewController) {
UIViewController* presentedViewController = rootViewController.presentedViewController;
return [self topViewControllerWithRootViewController:presentedViewController];
} else {
return rootViewController;
}
}
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 130000
#pragma mark - ASWebAuthenticationPresentationContextProviding
- (ASPresentationAnchor)presentationAnchorForWebAuthenticationSession:(ASWebAuthenticationSession *)session API_AVAILABLE(ios(13.0)){
return [UIApplication sharedApplication].keyWindow;
}
#endif
@end