SignInViewController.m 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435
  1. /*
  2. * Copyright 2021 Google LLC
  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 "SignInViewController.h"
  17. @import GoogleSignIn;
  18. #import "AuthInspectorViewController.h"
  19. #import "DataPickerState.h"
  20. #import "DataPickerViewController.h"
  21. #import <AppAuth/OIDTokenUtilities.h>
  22. static NSString *const kSignInViewTitle = @"Sign-In Sample";
  23. static NSString *const kPlaceholderUserName = @"<Name>";
  24. static NSString *const kPlaceholderEmailAddress = @"<Email>";
  25. static NSString *const kPlaceholderAvatarImageName = @"PlaceholderAvatar.png";
  26. // Labels for the cells that have in-cell control elements.
  27. static NSString *const kButtonWidthCellLabel = @"Width";
  28. // Labels for the cells that drill down to data pickers.
  29. static NSString *const kColorSchemeCellLabel = @"Color scheme";
  30. static NSString *const kStyleCellLabel = @"Style";
  31. // Accessibility Identifiers.
  32. static NSString *const kCredentialsButtonAccessibilityIdentifier = @"Credentials";
  33. @implementation SignInViewController {
  34. // This is an array of arrays, each one corresponding to the cell
  35. // labels for its respective section.
  36. NSArray *_sectionCellLabels;
  37. // These sets contain the labels corresponding to cells that have various types (each cell either
  38. // drills down to another table view or contains a slider).
  39. NSArray *_drillDownCells;
  40. NSArray *_sliderCells;
  41. // States storing the current set of selected elements for each data picker.
  42. DataPickerState *_colorSchemeState;
  43. DataPickerState *_styleState;
  44. // Map that keeps track of which cell corresponds to which DataPickerState.
  45. NSDictionary *_drilldownCellState;
  46. }
  47. #pragma mark - View lifecycle
  48. - (void)setUp {
  49. _sectionCellLabels = @[
  50. @[ kColorSchemeCellLabel, kStyleCellLabel, kButtonWidthCellLabel ]
  51. ];
  52. // Groupings of cell types.
  53. _drillDownCells = @[
  54. kColorSchemeCellLabel,
  55. kStyleCellLabel
  56. ];
  57. _sliderCells = @[ kButtonWidthCellLabel ];
  58. // Initialize data picker states.
  59. NSString *dictionaryPath =
  60. [[NSBundle mainBundle] pathForResource:@"DataPickerDictionary"
  61. ofType:@"plist"];
  62. NSDictionary *configOptionsDict = [NSDictionary dictionaryWithContentsOfFile:dictionaryPath];
  63. NSDictionary *colorSchemeDict = [configOptionsDict objectForKey:kColorSchemeCellLabel];
  64. NSDictionary *styleDict = [configOptionsDict objectForKey:kStyleCellLabel];
  65. _colorSchemeState = [[DataPickerState alloc] initWithDictionary:colorSchemeDict];
  66. _styleState = [[DataPickerState alloc] initWithDictionary:styleDict];
  67. _drilldownCellState = @{
  68. kColorSchemeCellLabel : _colorSchemeState,
  69. kStyleCellLabel : _styleState
  70. };
  71. // Make sure the GIDSignInButton class is linked in because references from
  72. // xib file doesn't count.
  73. [GIDSignInButton class];
  74. }
  75. - (id)initWithNibName:(NSString *)nibNameOrNil
  76. bundle:(NSBundle *)nibBundleOrNil {
  77. self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
  78. if (self) {
  79. [self setUp];
  80. self.title = kSignInViewTitle;
  81. }
  82. return self;
  83. }
  84. - (id)initWithCoder:(NSCoder *)aDecoder {
  85. self = [super initWithCoder:aDecoder];
  86. if (self) {
  87. [self setUp];
  88. self.title = kSignInViewTitle;
  89. }
  90. return self;
  91. }
  92. - (void)viewDidLoad {
  93. [super viewDidLoad];
  94. self.credentialsButton.accessibilityIdentifier = kCredentialsButtonAccessibilityIdentifier;
  95. }
  96. - (void)viewWillAppear:(BOOL)animated {
  97. [self adoptUserSettings];
  98. [self reportAuthStatus];
  99. [self updateButtons];
  100. [self.tableView reloadData];
  101. [super viewWillAppear:animated];
  102. }
  103. #pragma mark - Helper methods
  104. // Updates the GIDSignIn shared instance and the GIDSignInButton
  105. // to reflect the configuration settings that the user set
  106. - (void)adoptUserSettings {
  107. // There should only be one selected color scheme
  108. for (NSString *scheme in _colorSchemeState.selectedCells) {
  109. if ([scheme isEqualToString:@"Light"]) {
  110. _signInButton.colorScheme = kGIDSignInButtonColorSchemeLight;
  111. } else {
  112. _signInButton.colorScheme = kGIDSignInButtonColorSchemeDark;
  113. }
  114. }
  115. // There should only be one selected style
  116. for (NSString *style in _styleState.selectedCells) {
  117. GIDSignInButtonStyle newStyle;
  118. if ([style isEqualToString:@"Standard"]) {
  119. newStyle = kGIDSignInButtonStyleStandard;
  120. self.signInButtonWidthSlider.enabled = YES;
  121. } else if ([style isEqualToString:@"Wide"]) {
  122. newStyle = kGIDSignInButtonStyleWide;
  123. self.signInButtonWidthSlider.enabled = YES;
  124. } else {
  125. newStyle = kGIDSignInButtonStyleIconOnly;
  126. self.signInButtonWidthSlider.enabled = NO;
  127. }
  128. if (self.signInButton.style != newStyle) {
  129. self.signInButton.style = newStyle;
  130. self.signInButtonWidthSlider.minimumValue = [self minimumButtonWidth];
  131. }
  132. self.signInButtonWidthSlider.value = _signInButton.frame.size.width;
  133. }
  134. }
  135. // Temporarily force the sign in button to adopt its minimum allowed frame
  136. // so that we can find out its minimum allowed width (used for setting the
  137. // range of the width slider).
  138. - (CGFloat)minimumButtonWidth {
  139. CGRect frame = self.signInButton.frame;
  140. self.signInButton.frame = CGRectZero;
  141. CGFloat minimumWidth = self.signInButton.frame.size.width;
  142. self.signInButton.frame = frame;
  143. return minimumWidth;
  144. }
  145. - (void)reportAuthStatus {
  146. GIDGoogleUser *googleUser = [GIDSignIn.sharedInstance currentUser];
  147. if (googleUser) {
  148. _signInAuthStatus.text = @"Status: Authenticated";
  149. } else {
  150. // To authenticate, use Google Sign-In button.
  151. _signInAuthStatus.text = @"Status: Not authenticated";
  152. }
  153. [self refreshUserInfo];
  154. }
  155. // Update the interface elements containing user data to reflect the
  156. // currently signed in user.
  157. - (void)refreshUserInfo {
  158. if (!GIDSignIn.sharedInstance.currentUser) {
  159. self.userName.text = kPlaceholderUserName;
  160. self.userEmailAddress.text = kPlaceholderEmailAddress;
  161. self.userAvatar.image = [UIImage imageNamed:kPlaceholderAvatarImageName];
  162. return;
  163. }
  164. self.userEmailAddress.text = GIDSignIn.sharedInstance.currentUser.profile.email;
  165. self.userName.text = GIDSignIn.sharedInstance.currentUser.profile.name;
  166. if (!GIDSignIn.sharedInstance.currentUser.profile.hasImage) {
  167. // There is no Profile Image to be loaded.
  168. return;
  169. }
  170. // Load avatar image asynchronously, in background
  171. dispatch_queue_t backgroundQueue =
  172. dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
  173. __weak SignInViewController *weakSelf = self;
  174. NSUInteger dimension = round(self.userAvatar.frame.size.width * [[UIScreen mainScreen] scale]);
  175. NSURL *imageURL =
  176. [GIDSignIn.sharedInstance.currentUser.profile imageURLWithDimension:dimension];
  177. dispatch_async(backgroundQueue, ^{
  178. NSData *avatarData = [NSData dataWithContentsOfURL:imageURL];
  179. if (avatarData) {
  180. // Update UI from the main thread when available
  181. dispatch_async(dispatch_get_main_queue(), ^{
  182. SignInViewController *strongSelf = weakSelf;
  183. if (strongSelf) {
  184. strongSelf.userAvatar.image = [UIImage imageWithData:avatarData];
  185. }
  186. });
  187. }
  188. });
  189. }
  190. // Adjusts "Sign in", "Sign out", "Disconnect", and "Add Scopes" buttons to reflect the current
  191. // sign-in state (ie, the "Sign in" button becomes disabled when a user is already signed in).
  192. - (void)updateButtons {
  193. BOOL hasCurrentUser = (GIDSignIn.sharedInstance.currentUser != nil);
  194. self.signInButton.enabled = !hasCurrentUser;
  195. self.signOutButton.enabled = hasCurrentUser;
  196. self.disconnectButton.enabled = hasCurrentUser;
  197. self.addScopesButton.enabled = hasCurrentUser;
  198. self.credentialsButton.hidden = !hasCurrentUser;
  199. if (hasCurrentUser) {
  200. self.signInButton.alpha = 0.5;
  201. self.signOutButton.alpha = self.disconnectButton.alpha = self.addScopesButton.alpha = 1.0;
  202. } else {
  203. self.signInButton.alpha = 1.0;
  204. self.signOutButton.alpha = self.disconnectButton.alpha = self.addScopesButton.alpha = 0.5;
  205. }
  206. }
  207. #pragma mark - IBActions
  208. - (IBAction)signIn:(id)sender {
  209. NSString* nonce = [OIDTokenUtilities randomURLSafeStringWithSize:32];
  210. [GIDSignIn.sharedInstance signInWithPresentingViewController:self
  211. hint:nil
  212. additionalScopes:nil
  213. nonce:nonce
  214. completion:^(GIDSignInResult *signInResult,
  215. NSError *error) {
  216. if (error) {
  217. self->_signInAuthStatus.text =
  218. [NSString stringWithFormat:@"Status: Authentication error: %@", error];
  219. return;
  220. }
  221. [self reportAuthStatus];
  222. [self updateButtons];
  223. }];
  224. }
  225. - (IBAction)signOut:(id)sender {
  226. [GIDSignIn.sharedInstance signOut];
  227. [self reportAuthStatus];
  228. [self updateButtons];
  229. }
  230. - (IBAction)disconnect:(id)sender {
  231. [GIDSignIn.sharedInstance disconnectWithCompletion:^(NSError *error) {
  232. if (error) {
  233. self->_signInAuthStatus.text = [NSString stringWithFormat:@"Status: Failed to disconnect: %@",
  234. error];
  235. } else {
  236. self->_signInAuthStatus.text = [NSString stringWithFormat:@"Status: Disconnected"];
  237. }
  238. [self reportAuthStatus];
  239. [self updateButtons];
  240. }];
  241. }
  242. - (IBAction)addScopes:(id)sender {
  243. GIDGoogleUser *currentUser = GIDSignIn.sharedInstance.currentUser;
  244. [currentUser addScopes:@[ @"https://www.googleapis.com/auth/user.birthday.read" ]
  245. presentingViewController:self
  246. completion:^(GIDSignInResult *_Nullable signInResult,
  247. NSError *_Nullable error) {
  248. if (error) {
  249. self->_signInAuthStatus.text = [NSString stringWithFormat:@"Status: Failed to add scopes: %@",
  250. error];
  251. } else {
  252. self->_signInAuthStatus.text = [NSString stringWithFormat:@"Status: Scopes added"];
  253. }
  254. [self refreshUserInfo];
  255. }];
  256. }
  257. - (IBAction)showAuthInspector:(id)sender {
  258. AuthInspectorViewController *authInspector = [[AuthInspectorViewController alloc] init];
  259. [[self navigationController] pushViewController:authInspector animated:YES];
  260. }
  261. - (IBAction)checkSignIn:(id)sender {
  262. [self reportAuthStatus];
  263. }
  264. - (void)changeSignInButtonWidth:(UISlider *)sender {
  265. CGRect frame = self.signInButton.frame;
  266. frame.size.width = sender.value;
  267. self.signInButton.frame = frame;
  268. }
  269. #pragma mark - UITableView Data Source
  270. - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
  271. return [_sectionCellLabels count];
  272. }
  273. - (NSInteger)tableView:(UITableView *)tableView
  274. numberOfRowsInSection:(NSInteger)section {
  275. return [_sectionCellLabels[section] count];
  276. }
  277. - (NSString *)tableView:(UITableView *)tableView
  278. titleForHeaderInSection:(NSInteger)section {
  279. if (section == 0) {
  280. return @"Sign-In Button Options";
  281. } else if (section == 1) {
  282. return @"Other Options";
  283. } else {
  284. return nil;
  285. }
  286. }
  287. - (BOOL)tableView:(UITableView *)tableView
  288. shouldHighlightRowAtIndexPath:(NSIndexPath *)indexPath {
  289. // Cells that drill down to other table views should be highlight-able.
  290. // The other cells contain control elements, so they should not be selectable.
  291. NSString *label = _sectionCellLabels[indexPath.section][indexPath.row];
  292. if ([_drillDownCells containsObject:label]) {
  293. return YES;
  294. } else {
  295. return NO;
  296. }
  297. }
  298. - (UITableViewCell *)tableView:(UITableView *)tableView
  299. cellForRowAtIndexPath:(NSIndexPath *)indexPath {
  300. static NSString * const kDrilldownCell = @"DrilldownCell";
  301. static NSString * const kSliderCell = @"SliderCell";
  302. NSString *label = _sectionCellLabels[indexPath.section][indexPath.row];
  303. UITableViewCell *cell;
  304. NSString *identifier;
  305. if ([_drillDownCells containsObject:label]) {
  306. identifier = kDrilldownCell;
  307. } else if ([_sliderCells containsObject:label]) {
  308. identifier = kSliderCell;
  309. }
  310. cell = [tableView dequeueReusableCellWithIdentifier:identifier];
  311. if (cell == nil) {
  312. cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1
  313. reuseIdentifier:identifier];
  314. }
  315. // Assign accessibility labels to each cell row.
  316. cell.accessibilityLabel = label;
  317. if (identifier == kDrilldownCell) {
  318. cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
  319. DataPickerState *dataState = _drilldownCellState[label];
  320. if (dataState.multipleSelectEnabled) {
  321. cell.detailTextLabel.text = @"";
  322. } else {
  323. cell.detailTextLabel.text = [dataState.selectedCells anyObject];
  324. }
  325. cell.accessibilityValue = cell.detailTextLabel.text;
  326. } else if (identifier == kSliderCell) {
  327. UISlider *slider = [[UISlider alloc] initWithFrame:CGRectMake(0, 0, 150, 0)];
  328. slider.minimumValue = [self minimumButtonWidth];
  329. slider.maximumValue = 268.0;
  330. slider.value = self.signInButton.frame.size.width;
  331. slider.enabled = self.signInButton.style != kGIDSignInButtonStyleIconOnly;
  332. [slider addTarget:self
  333. action:@selector(changeSignInButtonWidth:)
  334. forControlEvents:UIControlEventValueChanged];
  335. slider.accessibilityIdentifier = [NSString stringWithFormat:@"%@ Slider", label];
  336. self.signInButtonWidthSlider = slider;
  337. cell.accessoryView = slider;
  338. [self.signInButtonWidthSlider sizeToFit];
  339. }
  340. cell.textLabel.text = label;
  341. return cell;
  342. }
  343. - (void)tableView:(UITableView *)tableView
  344. didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
  345. [tableView deselectRowAtIndexPath:indexPath animated:YES];
  346. UITableViewCell *selectedCell = [tableView cellForRowAtIndexPath:indexPath];
  347. NSString *label = selectedCell.textLabel.text;
  348. DataPickerState *dataState = [_drilldownCellState objectForKey:label];
  349. if (!dataState) {
  350. return;
  351. }
  352. DataPickerViewController *dataPicker =
  353. [[DataPickerViewController alloc] initWithNibName:nil
  354. bundle:nil
  355. dataState:dataState];
  356. dataPicker.navigationItem.title = label;
  357. // Force the back button title to be 'Back'
  358. UIBarButtonItem *newBackButton =
  359. [[UIBarButtonItem alloc] initWithTitle:@"Back"
  360. style:UIBarButtonItemStylePlain
  361. target:nil
  362. action:nil];
  363. [[self navigationItem] setBackBarButtonItem:newBackButton];
  364. [self.navigationController pushViewController:dataPicker animated:YES];
  365. }
  366. @end