FLEXKeychainTableViewController.m 7.6 KB

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