SettingsViewController.m 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417
  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. #import "SettingsViewController.h"
  17. #import <objc/runtime.h>
  18. #import "AppManager.h"
  19. #import <FirebaseCore/FIRApp.h>
  20. #import "FIRAuth_Internal.h"
  21. #import "FIRAuthAPNSToken.h"
  22. #import "FIRAuthAPNSTokenManager.h"
  23. #import "FIRAuthAppCredential.h"
  24. #import "FIRAuthAppCredentialManager.h"
  25. #import <FirebaseCore/FIROptions.h>
  26. #import "FirebaseAuth.h"
  27. #import "StaticContentTableViewManager.h"
  28. #import "UIViewController+Alerts.h"
  29. /** @var kIdentityToolkitRequestClassName
  30. @brief The class name of Identity Toolkit requests.
  31. */
  32. static NSString *const kIdentityToolkitRequestClassName = @"FIRIdentityToolkitRequest";
  33. /** @var kSecureTokenRequestClassName
  34. @brief The class name of Secure Token Service requests.
  35. */
  36. static NSString *const kSecureTokenRequestClassName = @"FIRSecureTokenRequest";
  37. /** @var kIdentityToolkitSandboxHost
  38. @brief The host of Identity Toolkit sandbox server.
  39. */
  40. static NSString *const kIdentityToolkitSandboxHost = @"staging-www.sandbox.googleapis.com";
  41. /** @var kSecureTokenSandboxHost
  42. @brief The host of Secure Token Service sandbox server.
  43. */
  44. static NSString *const kSecureTokenSandboxHost = @"staging-securetoken.sandbox.googleapis.com";
  45. /** @var kGoogleServiceInfoPlists
  46. @brief a C-array of plist file base names of Google service info to initialize FIRApp.
  47. */
  48. static NSString *const kGoogleServiceInfoPlists[] = {
  49. @"GoogleService-Info",
  50. @"GoogleService-Info_multi"
  51. };
  52. /** @var gAPIEndpoints
  53. @brief List of API Hosts by request class name.
  54. */
  55. static NSDictionary<NSString *, NSArray<NSString *> *> *gAPIHosts;
  56. /** @var gFirebaseAppOptions
  57. @brief List of FIROptions.
  58. */
  59. static NSArray<FIROptions *> *gFirebaseAppOptions;
  60. /** @protocol RequestClass
  61. @brief A de-facto protocol followed by request class objects to access its API host.
  62. */
  63. @protocol RequestClass <NSObject>
  64. - (NSString *)host;
  65. - (void)setHost:(NSString *)host;
  66. @end
  67. /** @fn versionString
  68. @brief Constructs a version string to display.
  69. @param string The version in string form.
  70. @param number The version in number form.
  71. */
  72. static NSString *versionString(const unsigned char *string, const double number) {
  73. return [NSString stringWithFormat:@"\"%s\" (%g)", string, number];
  74. }
  75. /** @fn requestHost
  76. @brief Retrieves the API host for the request class.
  77. @param requestClassName The name of the request class.
  78. */
  79. static NSString *APIHost(NSString *requestClassName) {
  80. return [(id<RequestClass>)NSClassFromString(requestClassName) host];
  81. }
  82. /** @fn truncatedString
  83. @brief Truncates a string under a maximum length.
  84. @param string The original string to be truncated.
  85. @param length The maximum length of the truncated string.
  86. @return The truncated string, which is not longer than @c length.
  87. */
  88. static NSString *truncatedString(NSString *string, NSUInteger length) {
  89. if (string.length <= length) {
  90. return string;
  91. }
  92. NSUInteger half = (length - 3) / 2;
  93. return [NSString stringWithFormat:@"%@...%@",
  94. [string substringToIndex:half],
  95. [string substringFromIndex:string.length - half]];
  96. }
  97. @implementation SettingsViewController
  98. - (void)viewDidLoad {
  99. [super viewDidLoad];
  100. [self setUpAPIHosts];
  101. [self setUpFirebaseAppOptions];
  102. [self loadTableView];
  103. }
  104. - (IBAction)done:(id)sender {
  105. [self dismissViewControllerAnimated:YES completion:nil];
  106. }
  107. - (void)setUpAPIHosts {
  108. if (gAPIHosts) {
  109. return;
  110. }
  111. gAPIHosts = @{
  112. kIdentityToolkitRequestClassName : @[
  113. APIHost(kIdentityToolkitRequestClassName),
  114. kIdentityToolkitSandboxHost,
  115. ],
  116. kSecureTokenRequestClassName : @[
  117. APIHost(kSecureTokenRequestClassName),
  118. kSecureTokenSandboxHost,
  119. ],
  120. };
  121. }
  122. - (void)setUpFirebaseAppOptions {
  123. if (gFirebaseAppOptions) {
  124. return;
  125. }
  126. int numberOfOptions = sizeof(kGoogleServiceInfoPlists) / sizeof(*kGoogleServiceInfoPlists);
  127. NSMutableArray *appOptions = [[NSMutableArray alloc] initWithCapacity:numberOfOptions];
  128. for (int i = 0; i < numberOfOptions; i++) {
  129. NSString *plistFileName = kGoogleServiceInfoPlists[i];
  130. NSString *plistFilePath = [[NSBundle mainBundle] pathForResource:plistFileName
  131. ofType:@"plist"];
  132. FIROptions *options = [[FIROptions alloc] initWithContentsOfFile:plistFilePath];
  133. [appOptions addObject:options];
  134. }
  135. gFirebaseAppOptions = [appOptions copy];
  136. }
  137. - (void)loadTableView {
  138. __weak typeof(self) weakSelf = self;
  139. _tableViewManager.contents = [StaticContentTableViewContent contentWithSections:@[
  140. [StaticContentTableViewSection sectionWithTitle:@"Versions" cells:@[
  141. [StaticContentTableViewCell cellWithTitle:@"FirebaseAuth"
  142. value:versionString(
  143. FirebaseAuthVersionStr, FirebaseAuthVersionNum)],
  144. ]],
  145. [StaticContentTableViewSection sectionWithTitle:@"API Hosts" cells:@[
  146. [StaticContentTableViewCell cellWithTitle:@"Identity Toolkit"
  147. value:APIHost(kIdentityToolkitRequestClassName)
  148. action:^{
  149. [weakSelf toggleAPIHostWithRequestClassName:kIdentityToolkitRequestClassName];
  150. }],
  151. [StaticContentTableViewCell cellWithTitle:@"Secure Token"
  152. value:APIHost(kSecureTokenRequestClassName)
  153. action:^{
  154. [weakSelf toggleAPIHostWithRequestClassName:kSecureTokenRequestClassName];
  155. }],
  156. ]],
  157. [StaticContentTableViewSection sectionWithTitle:@"Firebase Apps" cells:@[
  158. [StaticContentTableViewCell cellWithTitle:@"Active App"
  159. value:[self activeAppDescription]
  160. action:^{
  161. [weakSelf toggleActiveApp];
  162. }],
  163. [StaticContentTableViewCell cellWithTitle:@"Default App"
  164. value:[self projectIDForAppAtIndex:0]
  165. action:^{
  166. [weakSelf toggleProjectForAppAtIndex:0];
  167. }],
  168. [StaticContentTableViewCell cellWithTitle:@"Other App"
  169. value:[self projectIDForAppAtIndex:1]
  170. action:^{
  171. [weakSelf toggleProjectForAppAtIndex:1];
  172. }],
  173. ]],
  174. [StaticContentTableViewSection sectionWithTitle:@"Phone Auth" cells:@[
  175. [StaticContentTableViewCell cellWithTitle:@"APNs Token"
  176. value:[self APNSTokenString]
  177. action:^{
  178. [weakSelf clearAPNSToken];
  179. }],
  180. [StaticContentTableViewCell cellWithTitle:@"App Credential"
  181. value:[self appCredentialString]
  182. action:^{
  183. [weakSelf clearAppCredential];
  184. }],
  185. ]],
  186. [StaticContentTableViewSection sectionWithTitle:@"Language" cells:@[
  187. [StaticContentTableViewCell cellWithTitle:@"Auth Language"
  188. value:[AppManager auth].languageCode ?: @"[none]"
  189. action:^{
  190. [weakSelf showLanguageInput];
  191. }],
  192. [StaticContentTableViewCell cellWithTitle:@"Use App language" action:^{
  193. [[AppManager auth] useAppLanguage];
  194. [weakSelf loadTableView];
  195. }],
  196. ]],
  197. [StaticContentTableViewSection sectionWithTitle:@"Auth Settings" cells:@[
  198. [StaticContentTableViewCell cellWithTitle:@"Disable App Verification (Phone)"
  199. value:[AppManager auth].settings.
  200. appVerificationDisabledForTesting ? @"Yes" : @"No"
  201. action:^{
  202. [weakSelf toggleDisableAppVerification];
  203. [weakSelf loadTableView];
  204. }],
  205. ]],
  206. ]];
  207. }
  208. /** @fn toggleDisableAppVerification
  209. @brief Toggles the appVerificationDisabledForTesting flag on the current Auth instance.
  210. */
  211. - (void)toggleDisableAppVerification {
  212. [AppManager auth].settings.appVerificationDisabledForTesting =
  213. ![AppManager auth].settings.appVerificationDisabledForTesting;
  214. }
  215. /** @fn toggleAPIHostWithRequestClassName:
  216. @brief Toggles the host name of the server that handles RPCs.
  217. @param requestClassName The name of the RPC request class.
  218. */
  219. - (void)toggleAPIHostWithRequestClassName:(NSString *)requestClassName {
  220. NSString *currentHost = APIHost(requestClassName);
  221. NSArray<NSString *> *allHosts = gAPIHosts[requestClassName];
  222. NSString *newHost = allHosts[([allHosts indexOfObject:currentHost] + 1) % allHosts.count];
  223. [(id<RequestClass>)NSClassFromString(requestClassName) setHost:newHost];
  224. [self loadTableView];
  225. }
  226. /** @fn activeAppDescription
  227. @brief Returns the description for the currently active Firebase app.
  228. */
  229. - (NSString *)activeAppDescription {
  230. return [AppManager sharedInstance].active == 0 ? @"[Default]" : @"[Other]";
  231. }
  232. /** @fn toggleActiveApp
  233. @brief Toggles the active Firebase app for the rest of the application.
  234. */
  235. - (void)toggleActiveApp {
  236. AppManager *apps = [AppManager sharedInstance];
  237. // This changes the FIRAuth instance returned from `[AppManager auth]` to be one that is
  238. // associated with a different `FIRApp` instance. The sample app uses `[AppManager auth]`
  239. // instead of `[FIRAuth auth]` almost everywhere. Thus, this statement switches between default
  240. // and non-default `FIRApp` instances for the sample app to test against.
  241. apps.active = (apps.active + 1) % apps.count;
  242. [self loadTableView];
  243. }
  244. /** @fn projectIDForAppAtIndex:
  245. @brief Returns the Firebase project ID for the Firebase app at the given index.
  246. @param index The index for the app in the app manager.
  247. @return The ID of the project.
  248. */
  249. - (NSString *)projectIDForAppAtIndex:(int)index {
  250. NSString *APIKey = [[AppManager sharedInstance] appAtIndex:index].options.APIKey;
  251. for (FIROptions *options in gFirebaseAppOptions) {
  252. if ([options.APIKey isEqualToString:APIKey]) {
  253. return options.projectID;
  254. }
  255. }
  256. return @"[none]";
  257. }
  258. /** @fn googleAppIDForAppAtIndex:
  259. @brief Returns the Google App ID for the Firebase app at the given index.
  260. @param index The index for the app in the app manager.
  261. @return The Google App ID of the project.
  262. */
  263. - (NSString *)googleAppIDForAppAtIndex:(int)index {
  264. NSString *APIKey = [[AppManager sharedInstance] appAtIndex:index].options.APIKey;
  265. for (FIROptions *options in gFirebaseAppOptions) {
  266. if ([options.APIKey isEqualToString:APIKey]) {
  267. return options.googleAppID;
  268. }
  269. }
  270. return @"[none]";
  271. }
  272. /** @fn toggleProjectForAppAtIndex:
  273. @brief Toggles the Firebase project for the Firebase app at the given index by recreating the
  274. FIRApp instance with different options.
  275. @param index The index for the app to be recreated in the app manager.
  276. */
  277. - (void)toggleProjectForAppAtIndex:(int)index {
  278. NSString *APIKey = [[AppManager sharedInstance] appAtIndex:index].options.APIKey;
  279. int optionIndex;
  280. for (optionIndex = 0; optionIndex < gFirebaseAppOptions.count; optionIndex++) {
  281. FIROptions *options = gFirebaseAppOptions[optionIndex];
  282. if ([options.APIKey isEqualToString:APIKey]) {
  283. break;
  284. }
  285. }
  286. FIROptions *options;
  287. if (index == 0) {
  288. // For default apps, the next options cannot be `nil`.
  289. optionIndex = (optionIndex + 1) % gFirebaseAppOptions.count;
  290. options = gFirebaseAppOptions[optionIndex];
  291. } else {
  292. // For non-default apps, `nil` is considered the next options after the last options in the array.
  293. optionIndex = (optionIndex + 1) % (gFirebaseAppOptions.count + 1);
  294. if (optionIndex != gFirebaseAppOptions.count) {
  295. options = gFirebaseAppOptions[optionIndex];
  296. }
  297. }
  298. __weak typeof(self) weakSelf = self;
  299. [[AppManager sharedInstance] recreateAppAtIndex:index withOptions:options completion:^() {
  300. dispatch_async(dispatch_get_main_queue(), ^() {
  301. [weakSelf loadTableView];
  302. });
  303. }];
  304. }
  305. /** @fn APNSTokenString
  306. @brief Returns a string representing APNS token.
  307. */
  308. - (NSString *)APNSTokenString {
  309. FIRAuthAPNSToken *token = [AppManager auth].tokenManager.token;
  310. if (!token) {
  311. return @"";
  312. }
  313. return [NSString stringWithFormat:@"%@(%@)",
  314. truncatedString(token.string, 19),
  315. token.type == FIRAuthAPNSTokenTypeProd ? @"P" : @"S"];
  316. }
  317. /** @fn clearAPNSToken
  318. @brief Clears the saved app credential.
  319. */
  320. - (void)clearAPNSToken {
  321. FIRAuthAPNSToken *token = [AppManager auth].tokenManager.token;
  322. if (!token) {
  323. return;
  324. }
  325. NSString *tokenType = token.type == FIRAuthAPNSTokenTypeProd ? @"Production" : @"Sandbox";
  326. NSString *message = [NSString stringWithFormat:@"token: %@\ntype: %@",
  327. token.string, tokenType];
  328. [self showMessagePromptWithTitle:@"Clear APNs Token?"
  329. message:message
  330. showCancelButton:YES
  331. completion:^(BOOL userPressedOK, NSString *_Nullable userInput) {
  332. if (userPressedOK) {
  333. [AppManager auth].tokenManager.token = nil;
  334. [self loadTableView];
  335. }
  336. }];
  337. }
  338. /** @fn appCredentialString
  339. @brief Returns a string representing app credential.
  340. */
  341. - (NSString *)appCredentialString {
  342. FIRAuthAppCredential *credential = [AppManager auth].appCredentialManager.credential;
  343. if (!credential) {
  344. return @"";
  345. }
  346. return [NSString stringWithFormat:@"%@/%@",
  347. truncatedString(credential.receipt, 13),
  348. truncatedString(credential.secret, 13)];
  349. }
  350. /** @fn clearAppCredential
  351. @brief Clears the saved app credential.
  352. */
  353. - (void)clearAppCredential {
  354. FIRAuthAppCredential *credential = [AppManager auth].appCredentialManager.credential;
  355. if (!credential) {
  356. return;
  357. }
  358. NSString *message = [NSString stringWithFormat:@"receipt: %@\nsecret: %@",
  359. credential.receipt, credential.secret];
  360. [self showMessagePromptWithTitle:@"Clear App Credential?"
  361. message:message
  362. showCancelButton:YES
  363. completion:^(BOOL userPressedOK, NSString *_Nullable userInput) {
  364. if (userPressedOK) {
  365. [[AppManager auth].appCredentialManager clearCredential];
  366. [self loadTableView];
  367. }
  368. }];
  369. }
  370. /** @fn showLanguageInput
  371. @brief Show language code input field.
  372. */
  373. - (void)showLanguageInput {
  374. [self showTextInputPromptWithMessage:@"Enter Language Code For Auth:"
  375. completionBlock:^(BOOL userPressedOK, NSString *_Nullable languageCode) {
  376. if (!userPressedOK) {
  377. return;
  378. }
  379. [AppManager auth].languageCode = languageCode.length ? languageCode : nil;
  380. [self loadTableView];
  381. }];
  382. }
  383. @end