SettingsViewController.m 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393
  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 toggleProjectForAppAtIndex:
  259. @brief Toggles the Firebase project for the Firebase app at the given index by recreating the
  260. FIRApp instance with different options.
  261. @param index The index for the app to be recreated in the app manager.
  262. */
  263. - (void)toggleProjectForAppAtIndex:(int)index {
  264. NSString *APIKey = [[AppManager sharedInstance] appAtIndex:index].options.APIKey;
  265. int optionIndex;
  266. for (optionIndex = 0; optionIndex < gFirebaseAppOptions.count; optionIndex++) {
  267. FIROptions *options = gFirebaseAppOptions[optionIndex];
  268. if ([options.APIKey isEqualToString:APIKey]) {
  269. break;
  270. }
  271. }
  272. // For non-default apps, `nil` is considered the next option after the last options in the array.
  273. int useNil = index > 0;
  274. optionIndex = (optionIndex + 1 + useNil) % (gFirebaseAppOptions.count + useNil) - useNil;
  275. FIROptions *options = optionIndex >= 0 ? gFirebaseAppOptions[optionIndex] : nil;
  276. __weak typeof(self) weakSelf = self;
  277. [[AppManager sharedInstance] recreateAppAtIndex:index withOptions:options completion:^() {
  278. dispatch_async(dispatch_get_main_queue(), ^() {
  279. [weakSelf loadTableView];
  280. });
  281. }];
  282. }
  283. /** @fn APNSTokenString
  284. @brief Returns a string representing APNS token.
  285. */
  286. - (NSString *)APNSTokenString {
  287. FIRAuthAPNSToken *token = [AppManager auth].tokenManager.token;
  288. if (!token) {
  289. return @"";
  290. }
  291. return [NSString stringWithFormat:@"%@(%@)",
  292. truncatedString(token.string, 19),
  293. token.type == FIRAuthAPNSTokenTypeProd ? @"P" : @"S"];
  294. }
  295. /** @fn clearAPNSToken
  296. @brief Clears the saved app credential.
  297. */
  298. - (void)clearAPNSToken {
  299. FIRAuthAPNSToken *token = [AppManager auth].tokenManager.token;
  300. if (!token) {
  301. return;
  302. }
  303. NSString *tokenType = token.type == FIRAuthAPNSTokenTypeProd ? @"Production" : @"Sandbox";
  304. NSString *message = [NSString stringWithFormat:@"token: %@\ntype: %@",
  305. token.string, tokenType];
  306. [self showMessagePromptWithTitle:@"Clear APNs Token?"
  307. message:message
  308. showCancelButton:YES
  309. completion:^(BOOL userPressedOK, NSString *_Nullable userInput) {
  310. if (userPressedOK) {
  311. [AppManager auth].tokenManager.token = nil;
  312. [self loadTableView];
  313. }
  314. }];
  315. }
  316. /** @fn appCredentialString
  317. @brief Returns a string representing app credential.
  318. */
  319. - (NSString *)appCredentialString {
  320. FIRAuthAppCredential *credential = [AppManager auth].appCredentialManager.credential;
  321. if (!credential) {
  322. return @"";
  323. }
  324. return [NSString stringWithFormat:@"%@/%@",
  325. truncatedString(credential.receipt, 13),
  326. truncatedString(credential.secret, 13)];
  327. }
  328. /** @fn clearAppCredential
  329. @brief Clears the saved app credential.
  330. */
  331. - (void)clearAppCredential {
  332. FIRAuthAppCredential *credential = [AppManager auth].appCredentialManager.credential;
  333. if (!credential) {
  334. return;
  335. }
  336. NSString *message = [NSString stringWithFormat:@"receipt: %@\nsecret: %@",
  337. credential.receipt, credential.secret];
  338. [self showMessagePromptWithTitle:@"Clear App Credential?"
  339. message:message
  340. showCancelButton:YES
  341. completion:^(BOOL userPressedOK, NSString *_Nullable userInput) {
  342. if (userPressedOK) {
  343. [[AppManager auth].appCredentialManager clearCredential];
  344. [self loadTableView];
  345. }
  346. }];
  347. }
  348. /** @fn showLanguageInput
  349. @brief Show language code input field.
  350. */
  351. - (void)showLanguageInput {
  352. [self showTextInputPromptWithMessage:@"Enter Language Code For Auth:"
  353. completionBlock:^(BOOL userPressedOK, NSString *_Nullable languageCode) {
  354. if (!userPressedOK) {
  355. return;
  356. }
  357. [AppManager auth].languageCode = languageCode.length ? languageCode : nil;
  358. [self loadTableView];
  359. }];
  360. }
  361. @end