FLEXKeychainTableViewController.m 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236
  1. //
  2. // FLEXKeychainTableViewController.m
  3. // FLEX
  4. //
  5. // Created by ray on 2019/8/17.
  6. // Copyright © 2019 Flipboard. All rights reserved.
  7. //
  8. #import "FLEXKeychain.h"
  9. #import "FLEXKeychainQuery.h"
  10. #import "FLEXKeychainTableViewController.h"
  11. #import "FLEXTableViewCell.h"
  12. #import "FLEXMutableListSection.h"
  13. #import "FLEXUtility.h"
  14. #import "UIPasteboard+FLEX.h"
  15. #import "UIBarButtonItem+FLEX.h"
  16. @interface FLEXKeychainTableViewController ()
  17. @property (nonatomic, readonly) FLEXMutableListSection<NSDictionary *> *section;
  18. @end
  19. @implementation FLEXKeychainTableViewController
  20. - (id)init {
  21. return [self initWithStyle:UITableViewStyleGrouped];
  22. }
  23. #pragma mark - Overrides
  24. - (void)viewDidLoad {
  25. [super viewDidLoad];
  26. self.navigationItem.rightBarButtonItems = @[
  27. [UIBarButtonItem systemItem:UIBarButtonSystemItemTrash target:self action:@selector(trashPressed:)],
  28. [UIBarButtonItem systemItem:UIBarButtonSystemItemAdd target:self action:@selector(addPressed)],
  29. ];
  30. [self reloadData];
  31. }
  32. - (NSArray<FLEXTableViewSection *> *)makeSections {
  33. _section = [FLEXMutableListSection list:FLEXKeychain.allAccounts.mutableCopy
  34. cellConfiguration:^(__kindof FLEXTableViewCell *cell, NSDictionary *item, NSInteger row) {
  35. cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
  36. id account = item[kFLEXKeychainAccountKey];
  37. if ([account isKindOfClass:[NSString class]]) {
  38. cell.textLabel.text = account;
  39. } else {
  40. cell.textLabel.text = [NSString stringWithFormat:
  41. @"[%@]\n\n%@",
  42. NSStringFromClass([account class]),
  43. [account description]
  44. ];
  45. }
  46. } filterMatcher:^BOOL(NSString *filterText, NSDictionary *item) {
  47. // Loop over contents of the keychain item looking for a match
  48. for (NSString *field in item.allValues) {
  49. if ([field isKindOfClass:[NSString class]]) {
  50. if ([field localizedCaseInsensitiveContainsString:filterText]) {
  51. return YES;
  52. }
  53. }
  54. }
  55. return NO;
  56. }
  57. ];
  58. return @[self.section];
  59. }
  60. /// We always want to show this section
  61. - (NSArray<FLEXTableViewSection *> *)nonemptySections {
  62. return @[self.section];
  63. }
  64. - (void)reloadSections {
  65. self.section.list = FLEXKeychain.allAccounts.mutableCopy;
  66. }
  67. - (void)refreshSectionTitle {
  68. self.section.customTitle = FLEXPluralString(
  69. self.section.filteredList.count, @"items", @"item"
  70. );
  71. }
  72. - (void)reloadData {
  73. [self reloadSections];
  74. [self refreshSectionTitle];
  75. [super reloadData];
  76. }
  77. #pragma mark - Private
  78. - (FLEXKeychainQuery *)queryForItemAtIndex:(NSInteger)idx {
  79. NSDictionary *item = self.section.filteredList[idx];
  80. FLEXKeychainQuery *query = [FLEXKeychainQuery new];
  81. query.service = item[kFLEXKeychainWhereKey];
  82. query.account = item[kFLEXKeychainAccountKey];
  83. [query fetch:nil];
  84. return query;
  85. }
  86. - (void)deleteItem:(NSDictionary *)item {
  87. NSError *error = nil;
  88. BOOL success = [FLEXKeychain
  89. deletePasswordForService:item[kFLEXKeychainWhereKey]
  90. account:item[kFLEXKeychainAccountKey]
  91. error:&error
  92. ];
  93. if (!success) {
  94. [FLEXAlert makeAlert:^(FLEXAlert *make) {
  95. make.title(@"Error Deleting Item");
  96. make.message(error.localizedDescription);
  97. } showFrom:self];
  98. }
  99. }
  100. #pragma mark Buttons
  101. - (void)trashPressed:(UIBarButtonItem *)sender {
  102. [FLEXAlert makeSheet:^(FLEXAlert *make) {
  103. make.title(@"Clear Keychain");
  104. make.message(@"This will remove all keychain items for this app.\n");
  105. make.message(@"This action cannot be undone. Are you sure?");
  106. make.button(@"Yes, clear the keychain").destructiveStyle().handler(^(NSArray *strings) {
  107. for (id account in self.section.list) {
  108. [self deleteItem:account];
  109. }
  110. [self reloadData];
  111. });
  112. make.button(@"Cancel").cancelStyle();
  113. } showFrom:self source:sender];
  114. }
  115. - (void)addPressed {
  116. [FLEXAlert makeAlert:^(FLEXAlert *make) {
  117. make.title(@"Add Keychain Item");
  118. make.textField(@"Service name, i.e. Instagram");
  119. make.textField(@"Account");
  120. make.textField(@"Password");
  121. make.button(@"Cancel").cancelStyle();
  122. make.button(@"Save").handler(^(NSArray<NSString *> *strings) {
  123. // Display errors
  124. NSError *error = nil;
  125. if (![FLEXKeychain setPassword:strings[2] forService:strings[0] account:strings[1] error:&error]) {
  126. [FLEXAlert showAlert:@"Error" message:error.localizedDescription from:self];
  127. }
  128. [self reloadData];
  129. });
  130. } showFrom:self];
  131. }
  132. #pragma mark - FLEXGlobalsEntry
  133. + (NSString *)globalsEntryTitle:(FLEXGlobalsRow)row {
  134. return @"🔑 Keychain";
  135. }
  136. + (UIViewController *)globalsEntryViewController:(FLEXGlobalsRow)row {
  137. FLEXKeychainTableViewController *viewController = [self new];
  138. viewController.title = [self globalsEntryTitle:row];
  139. return viewController;
  140. }
  141. #pragma mark - Table View Data Source
  142. - (void)tableView:(UITableView *)tv commitEditingStyle:(UITableViewCellEditingStyle)style forRowAtIndexPath:(NSIndexPath *)ip {
  143. if (style == UITableViewCellEditingStyleDelete) {
  144. // Update the model
  145. NSDictionary *toRemove = self.section.filteredList[ip.row];
  146. [self deleteItem:toRemove];
  147. [self.section mutate:^(NSMutableArray *list) {
  148. [list removeObject:toRemove];
  149. }];
  150. // Delete the row
  151. [tv deleteRowsAtIndexPaths:@[ip] withRowAnimation:UITableViewRowAnimationAutomatic];
  152. // Update the title by refreshing the section without disturbing the delete animation
  153. //
  154. // This is an ugly hack, but literally nothing else works, save for manually getting
  155. // the header and setting its title, which I personally think is worse since it
  156. // would need to make assumptions about the default style of the header (CAPS)
  157. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
  158. [self refreshSectionTitle];
  159. [tv reloadSections:[NSIndexSet indexSetWithIndex:0] withRowAnimation:UITableViewRowAnimationNone];
  160. });
  161. }
  162. }
  163. #pragma mark - Table View Delegate
  164. - (BOOL)tableView:(UITableView *)tableView shouldHighlightRowAtIndexPath:(NSIndexPath *)indexPath {
  165. return YES;
  166. }
  167. - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
  168. FLEXKeychainQuery *query = [self queryForItemAtIndex:indexPath.row];
  169. [FLEXAlert makeAlert:^(FLEXAlert *make) {
  170. make.title(query.service);
  171. make.message(@"Service: ").message(query.service);
  172. make.message(@"\nAccount: ").message(query.account);
  173. make.message(@"\nPassword: ").message(query.password);
  174. make.button(@"Copy Service").handler(^(NSArray<NSString *> *strings) {
  175. [UIPasteboard.generalPasteboard flex_copy:query.service];
  176. });
  177. make.button(@"Copy Account").handler(^(NSArray<NSString *> *strings) {
  178. [UIPasteboard.generalPasteboard flex_copy:query.account];
  179. });
  180. make.button(@"Copy Password").handler(^(NSArray<NSString *> *strings) {
  181. [UIPasteboard.generalPasteboard flex_copy:query.password];
  182. });
  183. make.button(@"Dismiss").cancelStyle();
  184. } showFrom:self];
  185. [tableView deselectRowAtIndexPath:indexPath animated:YES];
  186. }
  187. @end