FLEXKeychainViewController.m 7.5 KB

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