FIROAuthProvider.m 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352
  1. /*
  2. * Copyright 2017 Google
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #include <CommonCrypto/CommonCrypto.h>
  17. #import "FIROAuthProvider.h"
  18. #import <FirebaseCore/FIRApp.h>
  19. #import <FirebaseCore/FIROptions.h>
  20. #import "FIRAuthBackend.h"
  21. #import "FIRAuth_Internal.h"
  22. #import "FIRAuthErrorUtils.h"
  23. #import "FIRAuthGlobalWorkQueue.h"
  24. #import "FIRAuthRequestConfiguration.h"
  25. #import "FIRAuthWebUtils.h"
  26. #import "FIROAuthCredential_Internal.h"
  27. #import "FIROAuthCredential.h"
  28. #if TARGET_OS_IOS
  29. #import "FIRAuthURLPresenter.h"
  30. #endif
  31. NS_ASSUME_NONNULL_BEGIN
  32. /** @typedef FIRHeadfulLiteURLCallBack
  33. @brief The callback invoked at the end of the flow to fetch a headful-lite URL.
  34. @param headfulLiteURL The headful lite URL.
  35. @param error The error that occurred while fetching the headful-lite, if any.
  36. */
  37. typedef void (^FIRHeadfulLiteURLCallBack)(NSURL *_Nullable headfulLiteURL,
  38. NSError *_Nullable error);
  39. /** @var kHeadfulLiteURLStringFormat
  40. @brief The format of the URL used to open the headful lite page during sign-in.
  41. */
  42. NSString *const kHeadfulLiteURLStringFormat = @"https://%@/__/auth/handler?%@";
  43. /** @var kauthTypeSignInWithRedirect
  44. @brief The auth type to be specified in the sign-in request with redirect request and response.
  45. */
  46. static NSString *const kAuthTypeSignInWithRedirect = @"signInWithRedirect";
  47. @implementation FIROAuthProvider {
  48. /** @var _auth
  49. @brief The auth instance used for launching the URL presenter.
  50. */
  51. FIRAuth *_auth;
  52. /** @var _callbackScheme
  53. @brief The callback URL scheme used for headful-lite sign-in.
  54. */
  55. NSString *_callbackScheme;
  56. }
  57. + (FIROAuthCredential *)credentialWithProviderID:(NSString *)providerID
  58. IDToken:(NSString *)IDToken
  59. accessToken:(nullable NSString *)accessToken {
  60. return [[FIROAuthCredential alloc] initWithProviderID:providerID
  61. IDToken:IDToken
  62. accessToken:accessToken
  63. secret:nil
  64. pendingToken:nil];
  65. }
  66. + (FIROAuthCredential *)credentialWithProviderID:(NSString *)providerID
  67. accessToken:(NSString *)accessToken {
  68. return [[FIROAuthCredential alloc] initWithProviderID:providerID
  69. IDToken:nil
  70. accessToken:accessToken
  71. secret:nil
  72. pendingToken:nil];
  73. }
  74. + (instancetype)providerWithProviderID:(NSString *)providerID {
  75. return [[self alloc]initWithProviderID:providerID auth:[FIRAuth auth]];
  76. }
  77. + (instancetype)providerWithProviderID:(NSString *)providerID auth:(FIRAuth *)auth {
  78. return [[self alloc] initWithProviderID:providerID auth:auth];
  79. }
  80. #if TARGET_OS_IOS
  81. - (void)getCredentialWithUIDelegate:(nullable id<FIRAuthUIDelegate>)UIDelegate
  82. completion:(nullable FIRAuthCredentialCallback)completion {
  83. if (![FIRAuthWebUtils isCallbackSchemeRegisteredForCustomURLScheme:self->_callbackScheme]) {
  84. [NSException raise:NSInternalInconsistencyException
  85. format:@"Please register custom URL scheme '%@' in the app's Info.plist file.",
  86. self->_callbackScheme];
  87. }
  88. __weak __typeof__(self) weakSelf = self;
  89. __weak FIRAuth *weakAuth = _auth;
  90. __weak NSString *weakProviderID = _providerID;
  91. dispatch_async(FIRAuthGlobalWorkQueue(), ^{
  92. FIRAuthCredentialCallback callbackOnMainThread = ^(FIRAuthCredential *_Nullable credential,
  93. NSError *_Nullable error) {
  94. if (completion) {
  95. dispatch_async(dispatch_get_main_queue(), ^{
  96. completion(credential, error);
  97. });
  98. }
  99. };
  100. NSString *eventID = [FIRAuthWebUtils randomStringWithLength:10];
  101. NSString *sessionID = [FIRAuthWebUtils randomStringWithLength:10];
  102. __strong __typeof__(self) strongSelf = weakSelf;
  103. [strongSelf getHeadFulLiteURLWithEventID:eventID
  104. sessionID:sessionID
  105. completion:^(NSURL *_Nullable headfulLiteURL,
  106. NSError *_Nullable error) {
  107. if (error) {
  108. callbackOnMainThread(nil, error);
  109. return;
  110. }
  111. FIRAuthURLCallbackMatcher callbackMatcher = ^BOOL(NSURL *_Nullable callbackURL) {
  112. return [FIRAuthWebUtils isExpectedCallbackURL:callbackURL
  113. eventID:eventID
  114. authType:kAuthTypeSignInWithRedirect
  115. callbackScheme:strongSelf->_callbackScheme];
  116. };
  117. __strong FIRAuth *strongAuth = weakAuth;
  118. [strongAuth.authURLPresenter presentURL:headfulLiteURL
  119. UIDelegate:UIDelegate
  120. callbackMatcher:callbackMatcher
  121. completion:^(NSURL *_Nullable callbackURL,
  122. NSError *_Nullable error) {
  123. if (error) {
  124. callbackOnMainThread(nil, error);
  125. return;
  126. }
  127. NSString *OAuthResponseURLString =
  128. [strongSelf OAuthResponseForURL:callbackURL error:&error];
  129. if (error) {
  130. callbackOnMainThread(nil, error);
  131. return;
  132. }
  133. __strong NSString *strongProviderID = weakProviderID;
  134. FIROAuthCredential *credential =
  135. [[FIROAuthCredential alloc] initWithProviderID:strongProviderID
  136. sessionID:sessionID
  137. OAuthResponseURLString:OAuthResponseURLString];
  138. callbackOnMainThread(credential, nil);
  139. }];
  140. }];
  141. });
  142. }
  143. #endif // TARGET_OS_IOS
  144. #pragma mark - Internal Methods
  145. /** @fn initWithProviderID:auth:
  146. @brief returns an instance of @c FIROAuthProvider associated with the provided auth instance.
  147. @param auth The Auth instance to be associated with the OAuthProvider instance.
  148. @return An Instance of @c FIROAuthProvider.
  149. */
  150. - (nullable instancetype)initWithProviderID:(NSString *)providerID auth:(FIRAuth *)auth {
  151. self = [super init];
  152. if (self) {
  153. _auth = auth;
  154. _providerID = providerID;
  155. _callbackScheme = [[[_auth.app.options.clientID componentsSeparatedByString:@"."]
  156. reverseObjectEnumerator].allObjects componentsJoinedByString:@"."];
  157. }
  158. return self;
  159. }
  160. /** @fn OAuthResponseForURL:error:
  161. @brief Parses the redirected URL and returns a string representation of the OAuth response URL.
  162. @param URL The url to be parsed for an OAuth response URL.
  163. @param error The error that occurred if any.
  164. @return The OAuth response if successful.
  165. */
  166. - (nullable NSString *)OAuthResponseForURL:(NSURL *)URL error:(NSError *_Nullable *_Nullable)error {
  167. NSDictionary<NSString *, NSString *> *URLQueryItems =
  168. [FIRAuthWebUtils dictionaryWithHttpArgumentsString:URL.query];
  169. NSURL *deepLinkURL = [NSURL URLWithString:URLQueryItems[@"deep_link_id"]];
  170. URLQueryItems =
  171. [FIRAuthWebUtils dictionaryWithHttpArgumentsString:deepLinkURL.query];
  172. NSString *queryItemLink = URLQueryItems[@"link"];
  173. if (queryItemLink) {
  174. return queryItemLink;
  175. }
  176. if (!error) {
  177. return nil;
  178. }
  179. NSData *errorData = [URLQueryItems[@"firebaseError"] dataUsingEncoding:NSUTF8StringEncoding];
  180. NSError *jsonError;
  181. NSDictionary *errorDict = [NSJSONSerialization JSONObjectWithData:errorData
  182. options:0
  183. error:&jsonError];
  184. if (jsonError) {
  185. *error = [FIRAuthErrorUtils JSONSerializationErrorWithUnderlyingError:jsonError];
  186. return nil;
  187. }
  188. *error = [FIRAuthErrorUtils URLResponseErrorWithCode:errorDict[@"code"]
  189. message:errorDict[@"message"]];
  190. if (!*error) {
  191. NSString *reason;
  192. if(errorDict[@"code"] && errorDict[@"message"]) {
  193. reason = [NSString stringWithFormat:@"[%@] - %@",errorDict[@"code"], errorDict[@"message"]];
  194. }
  195. *error = [FIRAuthErrorUtils webSignInUserInteractionFailureWithReason:reason];
  196. }
  197. return nil;
  198. }
  199. /** @fn getHeadFulLiteURLWithEventID:completion:
  200. @brief Constructs a URL used for opening a headful-lite flow using a given event
  201. ID and session ID.
  202. @param eventID The event ID used for this purpose.
  203. @param sessionID The session ID used when completing the headful lite flow.
  204. @param completion The callback invoked after the URL has been constructed or an error
  205. has been encountered.
  206. */
  207. - (void)getHeadFulLiteURLWithEventID:(NSString *)eventID
  208. sessionID:(NSString *)sessionID
  209. completion:(FIRHeadfulLiteURLCallBack)completion {
  210. __weak __typeof__(self) weakSelf = self;
  211. [FIRAuthWebUtils fetchAuthDomainWithRequestConfiguration:_auth.requestConfiguration
  212. completion:^(NSString *_Nullable authDomain,
  213. NSError *_Nullable error) {
  214. if (error) {
  215. if (completion) {
  216. completion(nil, error);
  217. }
  218. return;
  219. }
  220. __strong __typeof__(self) strongSelf = weakSelf;
  221. NSString *bundleID = [NSBundle mainBundle].bundleIdentifier;
  222. NSString *clienID = strongSelf->_auth.app.options.clientID;
  223. NSString *apiKey = strongSelf->_auth.requestConfiguration.APIKey;
  224. NSMutableDictionary *urlArguments = [@{
  225. @"apiKey" : apiKey,
  226. @"authType" : @"signInWithRedirect",
  227. @"ibi" : bundleID ?: @"",
  228. @"clientId" : clienID,
  229. @"sessionId" : [strongSelf hashforString:sessionID],
  230. @"v" : [FIRAuthBackend authUserAgent],
  231. @"eventId" : eventID,
  232. @"providerId" : strongSelf->_providerID,
  233. } mutableCopy];
  234. if (strongSelf.scopes.count) {
  235. urlArguments[@"scopes"] = [strongSelf.scopes componentsJoinedByString:@","];
  236. }
  237. if (strongSelf.customParameters.count) {
  238. NSString *customParameters = [strongSelf customParametersStringWithError:&error];
  239. if (error) {
  240. completion(nil, error);
  241. return;
  242. }
  243. if (customParameters) {
  244. urlArguments[@"customParameters"] = customParameters;
  245. }
  246. }
  247. if (strongSelf->_auth.requestConfiguration.languageCode) {
  248. urlArguments[@"hl"] = strongSelf->_auth.requestConfiguration.languageCode;
  249. }
  250. NSString *argumentsString = [strongSelf httpArgumentsStringForArgsDictionary:urlArguments];
  251. NSString *URLString =
  252. [NSString stringWithFormat:kHeadfulLiteURLStringFormat, authDomain, argumentsString];
  253. if (completion) {
  254. NSCharacterSet *set = [NSCharacterSet URLFragmentAllowedCharacterSet];
  255. completion([NSURL URLWithString:
  256. [URLString stringByAddingPercentEncodingWithAllowedCharacters:set]], nil);
  257. }
  258. }];
  259. }
  260. /** @fn customParametersString
  261. @brief Returns a JSON string representation of the custom parameters dictionary corresponding
  262. to the OAuthProvider.
  263. @return The JSON string representation of the custom parameters dictionary corresponding
  264. to the OAuthProvider.
  265. */
  266. - (nullable NSString *)customParametersStringWithError:(NSError *_Nullable *_Nullable)error {
  267. if (!_customParameters.count) {
  268. return nil;
  269. }
  270. if (!error) {
  271. return nil;
  272. }
  273. NSError *jsonError;
  274. NSData *customParametersJSONData =
  275. [NSJSONSerialization dataWithJSONObject:_customParameters
  276. options:0
  277. error:&jsonError];
  278. if (jsonError) {
  279. *error = [FIRAuthErrorUtils JSONSerializationErrorWithUnderlyingError:jsonError];
  280. return nil;
  281. }
  282. NSString *customParamsRawJSON =
  283. [[NSString alloc] initWithData:customParametersJSONData encoding:NSUTF8StringEncoding];
  284. return customParamsRawJSON;
  285. }
  286. /** @fn hashforString:
  287. @brief Returns the SHA256 hash representation of a given string object.
  288. @param string The string for which a SHA256 hash is desired.
  289. @return An hexadecimal string representation of the SHA256 hash.
  290. */
  291. - (NSString *)hashforString:(NSString *)string {
  292. NSData *sessionIDData = [string dataUsingEncoding:NSUTF8StringEncoding];
  293. NSMutableData *hashOutputData = [NSMutableData dataWithLength:CC_SHA256_DIGEST_LENGTH];
  294. if (CC_SHA256(sessionIDData.bytes,
  295. (CC_LONG)[sessionIDData length],
  296. hashOutputData.mutableBytes)) {
  297. }
  298. return [self hexStringFromData:hashOutputData];;
  299. }
  300. /** @fn hexStringFromData:
  301. @brief Returns the hexadecimal string representation of an NSData object.
  302. @param data The NSData object for which a hexadecical string is desired.
  303. @return The hexadecimal string representation of the supplied NSData object.
  304. */
  305. - (NSString *)hexStringFromData:(NSData *)data {
  306. const unsigned char *dataBuffer = (const unsigned char *)[data bytes];
  307. NSMutableString *string = [[NSMutableString alloc] init];
  308. for (unsigned int i = 0; i < data.length; i++){
  309. [string appendFormat:@"%02lx", (unsigned long)dataBuffer[i]];
  310. }
  311. return [string copy];
  312. }
  313. - (NSString *)httpArgumentsStringForArgsDictionary:(NSDictionary *)argsDictionary {
  314. NSMutableArray* arguments = [NSMutableArray arrayWithCapacity:argsDictionary.count];
  315. NSString* key;
  316. for (key in argsDictionary) {
  317. NSString *description = [argsDictionary[key] description];
  318. [arguments addObject:[NSString stringWithFormat:@"%@=%@",
  319. [FIRAuthWebUtils stringByUnescapingFromURLArgument:key],
  320. [FIRAuthWebUtils stringByUnescapingFromURLArgument:description]]] ;
  321. }
  322. return [arguments componentsJoinedByString:@"&"];
  323. }
  324. @end
  325. NS_ASSUME_NONNULL_END