From 9d78e7d654c51c22ce4be87efef5bc1f8d5a2d08 Mon Sep 17 00:00:00 2001 From: Vitaly Takmazov Date: Thu, 31 Oct 2019 16:16:48 +0300 Subject: Fix authentication --- Juick/ViewControllers/ChatViewController.m | 6 +- Juick/ViewControllers/DialogsViewController.m | 4 +- Juick/ViewControllers/DiscoverViewController.m | 3 +- Juick/ViewControllers/DiscussionsController.m | 5 +- Juick/ViewControllers/FeedViewController.m | 16 ++--- Juick/ViewControllers/JuickNavigationController.h | 4 +- Juick/ViewControllers/JuickNavigationController.m | 35 +++++++++-- Juick/ViewControllers/LoginViewController.h | 7 ++- Juick/ViewControllers/LoginViewController.m | 77 ++++++++++++++--------- Juick/ViewControllers/MessagesViewController.m | 8 +-- Juick/ViewControllers/NewPostViewController.m | 8 +-- Juick/ViewControllers/ThreadViewController.m | 8 +-- 12 files changed, 105 insertions(+), 76 deletions(-) (limited to 'Juick/ViewControllers') diff --git a/Juick/ViewControllers/ChatViewController.m b/Juick/ViewControllers/ChatViewController.m index 2612719..695d7ec 100644 --- a/Juick/ViewControllers/ChatViewController.m +++ b/Juick/ViewControllers/ChatViewController.m @@ -8,7 +8,6 @@ #import "ChatViewController.h" #import "BubbleMessageCell.h" -#import "APIClient.h" #import "MessageInputView.h" @@ -29,7 +28,6 @@ self.tableView.keyboardDismissMode = UIScrollViewKeyboardDismissModeInteractive; self.tableView.allowsSelection = NO; self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentAutomatic; - self.me = [APIClient sharedClient].credential.user; [self reloadChat]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillChangeFrame:) name:UIKeyboardWillChangeFrameNotification object:nil]; self.refreshControl = [UIRefreshControl new]; @@ -40,7 +38,7 @@ -(void) reloadChat { self.messages = [NSMutableArray array]; [self.tableView reloadData]; - [[APIClient sharedClient] fetchChatWithUser:self.uname callback:^(NSArray *messages, NSError *err) { + [[AppDelegate shared].api fetchChatWithUser:self.uname callback:^(NSArray *messages, NSError *err) { if (err == nil) { [self.messages addObjectsFromArray:[[messages reverseObjectEnumerator] allObjects]]; NSMutableArray *indexPaths = [NSMutableArray new]; @@ -107,7 +105,7 @@ } -(void) textSent:(NSString *)text { - [[APIClient sharedClient] postPMToUser:self.uname text:text result:^(NSError *err) { + [[AppDelegate shared].api postPMToUser:self.uname text:text result:^(NSError *err) { if (!err) { NSLog(@"Success!"); [self.accessoryView becomeFirstResponder]; diff --git a/Juick/ViewControllers/DialogsViewController.m b/Juick/ViewControllers/DialogsViewController.m index 0b7f2ca..432cd53 100644 --- a/Juick/ViewControllers/DialogsViewController.m +++ b/Juick/ViewControllers/DialogsViewController.m @@ -9,8 +9,6 @@ #import "DialogsViewController.h" #import "ChatViewController.h" #import "ConversationCell.h" -#import "APIClient.h" -#import "AppDelegate.h" @implementation DialogsViewController - (void)viewDidLoad { @@ -31,7 +29,7 @@ - (void) refreshData { self.chats = [NSMutableArray array]; [self.tableView reloadData]; - [[APIClient sharedClient] fetchChats:^(NSArray *groups, NSError *err) { + [[AppDelegate shared].api fetchChats:^(NSArray *groups, NSError *err) { if (err == nil) { [self.chats addObjectsFromArray:groups]; NSMutableArray *indexPaths = [NSMutableArray new]; diff --git a/Juick/ViewControllers/DiscoverViewController.m b/Juick/ViewControllers/DiscoverViewController.m index 7bf9f74..10185ef 100644 --- a/Juick/ViewControllers/DiscoverViewController.m +++ b/Juick/ViewControllers/DiscoverViewController.m @@ -7,7 +7,6 @@ // #import "DiscoverViewController.h" -#import "APIClient.h" @interface DiscoverViewController () @@ -17,7 +16,7 @@ - (void)viewDidLoad { self.messagesDelegate = self; self.title = @"Discover"; - self.path = [APIClient messagesUrl]; + self.path = [API messagesUrl]; [self setShouldScrollToUnreadOnRefresh:NO]; [super viewDidLoad]; } diff --git a/Juick/ViewControllers/DiscussionsController.m b/Juick/ViewControllers/DiscussionsController.m index 607ac26..47ee7f2 100644 --- a/Juick/ViewControllers/DiscussionsController.m +++ b/Juick/ViewControllers/DiscussionsController.m @@ -7,7 +7,6 @@ // #import "DiscussionsController.h" -#import "APIClient.h" @interface DiscussionsController () @@ -18,7 +17,7 @@ - (void)viewDidLoad { self.messagesDelegate = self; self.title = @"Discussions"; - self.path = [APIClient discussionsUrl]; + self.path = [API discussionsUrl]; [self setShouldScrollToUnreadOnRefresh:NO]; [super viewDidLoad]; } @@ -26,7 +25,7 @@ - (void)loadMore { Message *lastMsg = [self.messages lastObject]; if (lastMsg != nil) { - NSDate *msgDate = [[APIClient sharedClient].dateFormatter dateFromString:lastMsg.timestamp]; + NSDate *msgDate = [[AppDelegate shared].sharedDateFormatter dateFromString:lastMsg.timestamp]; self.params = [@{@"to" : [NSString stringWithFormat:@"%.0f", [msgDate timeIntervalSince1970] * 1000]} mutableCopy]; [self setShouldScrollToUnreadOnRefresh:NO]; [self refreshData]; diff --git a/Juick/ViewControllers/FeedViewController.m b/Juick/ViewControllers/FeedViewController.m index da1b914..c492f2e 100644 --- a/Juick/ViewControllers/FeedViewController.m +++ b/Juick/ViewControllers/FeedViewController.m @@ -10,8 +10,6 @@ #import "ThreadViewController.h" #import "BlogViewController.h" #import "MessageCell.h" -#import "APIClient.h" -#import "AppDelegate.h" #import "LoginViewController.h" NSString * const UserNotAuthenticatedNotificationName = @"UserNotAuthenticated"; @@ -28,7 +26,7 @@ NSString * const UserNotAuthenticatedNotificationName = @"UserNotAuthenticated"; [self refreshPath]; [self setShouldScrollToUnreadOnRefresh:NO]; [super viewDidLoad]; - [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(userDidSignedIn:) name:UserSignedInNotificationName object:nil]; + [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(userDidSignedIn:) name:UserChangedNotificationName object:nil]; } -(void)avatarClicked:(NSString *)uname { @@ -46,17 +44,11 @@ NSString * const UserNotAuthenticatedNotificationName = @"UserNotAuthenticated"; } } - - -- (void)didReceiveChallenge { - -} - -(void) refreshPath { - if ([[APIClient sharedClient] isAuthenticated]) { - self.path = [APIClient feedUrl]; + if ([[AppDelegate shared].api currentUser]) { + self.path = [API feedUrl]; } else { - self.path = [APIClient messagesUrl]; + self.path = [API messagesUrl]; self.params = @{@"popular": @1}; } } diff --git a/Juick/ViewControllers/JuickNavigationController.h b/Juick/ViewControllers/JuickNavigationController.h index b508466..974c177 100644 --- a/Juick/ViewControllers/JuickNavigationController.h +++ b/Juick/ViewControllers/JuickNavigationController.h @@ -11,7 +11,9 @@ NS_ASSUME_NONNULL_BEGIN @interface JuickNavigationController : UITabBarController -- (IBAction)newMessage:(id)sender; +- (IBAction)showLoginForm:(id)sender; +- (void) refreshStatus; +@property (weak, nonatomic) IBOutlet UIBarButtonItem *leftButton; @end NS_ASSUME_NONNULL_END diff --git a/Juick/ViewControllers/JuickNavigationController.m b/Juick/ViewControllers/JuickNavigationController.m index 8673866..aaf3765 100644 --- a/Juick/ViewControllers/JuickNavigationController.m +++ b/Juick/ViewControllers/JuickNavigationController.m @@ -8,31 +8,54 @@ #import "JuickNavigationController.h" -#import "AppDelegate.h" -#import "APIClient.h" #import "MessagesViewController.h" #import "ThreadViewController.h" #import "NewPostViewController.h" #import "Message.h" +#import "LoginViewController.h" @interface JuickNavigationController () +@property(nonatomic, strong) UIButton *avatarButton; @end @implementation JuickNavigationController + +-(void) refreshStatus { + [[AppDelegate shared].api me:^(User *user, NSError *err) { + NSString *avatarUrl; + if (err || !user) { + avatarUrl = @"https://i.juick.com/av-96.png"; + } else { + avatarUrl = user.avatar; + } + [[AppDelegate shared].api fetchImageWithURL:[NSURL URLWithString:avatarUrl] callback:^(NSData *data) { + self.avatarButton = [UIButton buttonWithType:UIButtonTypeCustom]; + [self.avatarButton addTarget:self action:@selector(showLoginForm:) forControlEvents:UIControlEventTouchUpInside]; + [self.avatarButton setImage:[UIImage imageWithImage:[UIImage imageWithData:data] fitInsideWidth:44 fitInsideHeight:44] forState:UIControlStateNormal]; + self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:self.avatarButton]; + }]; + }]; +} + - (void)viewDidLoad { [super viewDidLoad]; - // Do any additional setup after loading the view. + [self refreshStatus]; + [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(userDidSignedIn:) name:UserChangedNotificationName object:nil]; +} + +- (void)userDidSignedIn:(NSNotification *) notification { + [self refreshStatus]; } #pragma mark - Navigation - (BOOL)shouldPerformSegueWithIdentifier:(NSString *)identifier sender:(id)sender { if ([identifier isEqualToString:@"editorSegue"]) { - if ([[APIClient sharedClient] isAuthenticated]) { + if ([[AppDelegate shared].api currentUser]) { return YES; } else { [[AppDelegate shared] presentLoginView:self]; @@ -71,7 +94,7 @@ } } -- (IBAction)newMessage:(id)sender { - [[AppDelegate shared] presentLoginView:self]; +- (IBAction)showLoginForm:(id)sender { + [self performSegueWithIdentifier:@"loginSegue" sender:self]; } @end diff --git a/Juick/ViewControllers/LoginViewController.h b/Juick/ViewControllers/LoginViewController.h index e1a4900..451a99c 100644 --- a/Juick/ViewControllers/LoginViewController.h +++ b/Juick/ViewControllers/LoginViewController.h @@ -10,11 +10,14 @@ #import "User.h" -extern NSString * const UserSignedInNotificationName; +extern NSString * const UserChangedNotificationName; @interface LoginViewController : UIViewController +@property (weak, nonatomic) IBOutlet UILabel *currentUser; @property (weak, nonatomic) IBOutlet UITextField *usernameField; @property (weak, nonatomic) IBOutlet UITextField *passwordField; -@property (weak, nonatomic) IBOutlet UIVisualEffectView *visualEffectView; +@property (weak, nonatomic) IBOutlet UIButton *signOutButton; +@property (weak, nonatomic) IBOutlet UIImageView *imageView; +- (IBAction)signoutPressed:(id)sender; @property (strong, nonatomic) IBOutlet NSLayoutConstraint *bottomConstraint; @end diff --git a/Juick/ViewControllers/LoginViewController.m b/Juick/ViewControllers/LoginViewController.m index 55099eb..a0e9b97 100644 --- a/Juick/ViewControllers/LoginViewController.m +++ b/Juick/ViewControllers/LoginViewController.m @@ -8,33 +8,32 @@ #import "LoginViewController.h" #import "User.h" -#import "AppDelegate.h" -#import "APIClient.h" -NSString * const UserSignedInNotificationName = @"UserSignedIn"; +NSString * const UserChangedNotificationName = @"UserSignedIn"; @interface LoginViewController() @property (nonatomic, assign) int paddingValue; +-(void) refreshState; @end @implementation LoginViewController - (void) awakeFromNib { [super awakeFromNib]; - self.title = @"Sign in"; [self.view setBackgroundColor:[UIColor colorNamed:@"Background"]]; - [self.visualEffectView.contentView setBackgroundColor:[UIColor colorNamed:@"Background"]]; self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(cancelSignIn)]; self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemSave target:self action:@selector(doneSignIn)]; - self.usernameField.text = [APIClient sharedClient].credential.user; - self.passwordField.text = [APIClient sharedClient].credential.password; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardDidShow:) name:UIKeyboardDidShowNotification object:nil]; } +- (void)viewWillAppear:(BOOL)animated { + [self refreshState]; +} + -(void) keyboardDidShow:(NSNotification *)sender { CGRect keyboardRect = [sender.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue]; self.bottomConstraint.constant = keyboardRect.size.height - self.view.safeAreaInsets.bottom + self.paddingValue; @@ -47,32 +46,54 @@ NSString * const UserSignedInNotificationName = @"UserSignedIn"; - (void) cancelSignIn { - CATransition* transition = [CATransition animation]; - transition.duration = 0.3; - transition.type = kCATransitionFade; - transition.subtype = kCATransitionFromTop; - - [self.navigationController.view.layer addAnimation:transition forKey:kCATransition]; - [self.navigationController dismissViewControllerAnimated:NO completion:nil]; + [self.navigationController dismissViewControllerAnimated:YES completion:nil]; } - (void) doneSignIn { - [[APIClient sharedClient] setCredential:[NSURLCredential credentialWithUser:self.usernameField.text password:self.passwordField.text persistence:NSURLCredentialPersistenceSynchronizable]]; - [[APIClient sharedClient] authenticate:^(User *user, NSError *error) { - if (user) { - [[NSNotificationCenter defaultCenter] postNotificationName:UserSignedInNotificationName object:user]; + + [[NSURLCache sharedURLCache] removeAllCachedResponses]; + [[AppDelegate shared].api authenticateWithUser:self.usernameField.text password:self.passwordField.text callback:^(BOOL success){ + if (success) { + [[NSNotificationCenter defaultCenter] postNotificationName:UserChangedNotificationName object:nil]; [[AppDelegate shared] registerForRemoteNotifications]; - CATransition* transition = [CATransition animation]; - transition.duration = 0.3; - transition.type = kCATransitionFade; - transition.subtype = kCATransitionFromTop; - - [self.navigationController.view.layer addAnimation:transition forKey:kCATransition]; - [self.navigationController dismissViewControllerAnimated:NO completion:nil]; - } else { - [User throwUnableToLogin:self error:error]; - [[APIClient sharedClient] setCredential:nil]; + [self.navigationController dismissViewControllerAnimated:YES completion:nil]; } }]; } + +- (void)refreshState { + if ([AppDelegate shared].api.currentUser) { + self.title = @"Profile"; + [self.usernameField setHidden:YES]; + [self.passwordField setHidden:YES]; + [self.currentUser setHidden:NO]; + self.currentUser.text = [AppDelegate shared].api.currentUser.uname; + __weak UIImageView *weakAttach = self.imageView; + [[AppDelegate shared].api fetchImageWithURL:[NSURL URLWithString:[AppDelegate shared].api.currentUser.avatar] callback:^(NSData *data) { + [UIView transitionWithView:weakAttach + duration:0.3 + options:UIViewAnimationOptionTransitionCrossDissolve + animations:^{ + weakAttach.image = [UIImage imageWithData:data]; + } + completion:nil]; + }]; + [self.signOutButton setHidden:NO]; + } else { + self.title = @"Sign in"; + self.imageView.image = [UIImage imageNamed:@"Splash"]; + [self.usernameField setHidden:NO]; + [self.passwordField setHidden:NO]; + [self.currentUser setHidden:YES]; + [self.signOutButton setHidden:YES]; + } +} + +- (IBAction)signoutPressed:(id)sender { + [[AppDelegate shared].api signout]; + [[NSURLCache sharedURLCache] removeAllCachedResponses]; + [self.navigationController dismissViewControllerAnimated:YES completion:^{ + [[NSNotificationCenter defaultCenter] postNotificationName:UserChangedNotificationName object:nil]; + }]; +} @end diff --git a/Juick/ViewControllers/MessagesViewController.m b/Juick/ViewControllers/MessagesViewController.m index 25a2ca5..f61d8b4 100644 --- a/Juick/ViewControllers/MessagesViewController.m +++ b/Juick/ViewControllers/MessagesViewController.m @@ -9,8 +9,6 @@ #import "MessagesViewController.h" #import "MessageCell.h" -#import "AppDelegate.h" -#import "APIClient.h" #import "Message.h" #import "NewPostViewController.h" @@ -35,20 +33,20 @@ NSString* const messageCellIdentifier = @"messageCell"; if (self.messages.count == 0) { [self.tableView reloadData]; } - [[APIClient sharedClient] pullNextFromPath:self.path params:self.params callback:^(NSArray *next, NSError *err) { + [[AppDelegate shared].api pullNextFromPath:self.path params:self.params callback:^(NSArray *next, NSError *err) { if (err) { [User throwUnableToLogin:self error:err]; return; } NSArray *newMsgs = next; if ([self isAtTop:self.params]) { - if (![self.path isEqualToString:[APIClient threadUrl]]) { + if (![self.path isEqualToString:[API threadUrl]]) { [self.messages removeAllObjects]; [self.tableView reloadData]; } } NSUInteger oldCount = [self.messages count]; - if ([self.path isEqualToString:[APIClient threadUrl]]) { + if ([self.path isEqualToString:[API threadUrl]]) { NSUInteger lastRid = [((Message *)[self.messages lastObject]).rid unsignedIntegerValue] + 1; NSUInteger count = [next count]; if (oldCount > 0) { diff --git a/Juick/ViewControllers/NewPostViewController.m b/Juick/ViewControllers/NewPostViewController.m index e4b5ac7..344e7b9 100644 --- a/Juick/ViewControllers/NewPostViewController.m +++ b/Juick/ViewControllers/NewPostViewController.m @@ -9,8 +9,6 @@ #import "NewPostViewController.h" #import "MessagesViewController.h" #import "QuoteView.h" -#import "APIClient.h" -#import "AppDelegate.h" NSString * const NewMessageNotificationName = @"NewMessage"; NSString * const ReplyPostedNotificationName = @"ReplyPosted"; @@ -47,8 +45,8 @@ NSString * const ReplyPostedNotificationName = @"ReplyPosted"; - (IBAction)sendAction:(id)sender { self.navigationItem.rightBarButtonItem.enabled = NO; if (_replyTo == nil) { - self.navigationItem.rightBarButtonItem.enabled = YES; - [[APIClient sharedClient] postMessage:self.textView.text result:^(Message *msg, NSError *err) { + [[AppDelegate shared].api postMessage:self.textView.text result:^(Message *msg, NSError *err) { + self.navigationItem.rightBarButtonItem.enabled = YES; if (!err) { [self dismissViewControllerAnimated:YES completion:^{ [[NSNotificationCenter defaultCenter] postNotificationName:NewMessageNotificationName object:msg]; @@ -60,7 +58,7 @@ NSString * const ReplyPostedNotificationName = @"ReplyPosted"; }]; } else { self.navigationItem.rightBarButtonItem.enabled = NO; - [[APIClient sharedClient] postReplyToThread:_replyTo.mid inReplyTo:_replyTo.rid text:self.textView.text result:^(Message *msg, NSError *err) { + [[AppDelegate shared].api postReplyToThread:_replyTo.mid inReplyTo:_replyTo.rid text:self.textView.text result:^(Message *msg, NSError *err) { if (!err) { [self dismissViewControllerAnimated:YES completion:^{ [[NSNotificationCenter defaultCenter] postNotificationName:ReplyPostedNotificationName object:msg]; diff --git a/Juick/ViewControllers/ThreadViewController.m b/Juick/ViewControllers/ThreadViewController.m index c345822..8ee7623 100644 --- a/Juick/ViewControllers/ThreadViewController.m +++ b/Juick/ViewControllers/ThreadViewController.m @@ -9,14 +9,12 @@ #import "ThreadViewController.h" #import "NewPostViewController.h" #import "MessageCell.h" -#import "APIClient.h" -#import "AppDelegate.h" @implementation ThreadViewController -(void) viewDidLoad { - [self setPath:[APIClient threadUrl]]; + [self setPath:[API threadUrl]]; [super viewDidLoad]; self.messagesDelegate = self; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(replyPosted:) name:ReplyPostedNotificationName object:nil]; @@ -30,10 +28,10 @@ - (BOOL)shouldPerformSegueWithIdentifier:(NSString *)identifier sender:(id)sender { if ([identifier isEqualToString:@"editorSegue"]) { - if ([[APIClient sharedClient] isAuthenticated]) { + if ([[NSUserDefaults standardUserDefaults] stringForKey:@"token"]) { return YES; } else { - [[AppDelegate shared] presentLoginView:self]; + [[AppDelegate shared] unauthorized]; return NO; } } -- cgit v1.2.3