This repository has been archived by the owner on Dec 12, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 71
/
MXKAuthenticationViewController.m
2090 lines (1685 loc) · 78.9 KB
/
MXKAuthenticationViewController.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
Copyright 2015 OpenMarket Ltd
Copyright 2017 Vector Creations Ltd
Copyright 2019 The Matrix.org Foundation C.I.C
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#import "MXKAuthenticationViewController.h"
#import "MXKAuthInputsEmailCodeBasedView.h"
#import "MXKAuthInputsPasswordBasedView.h"
#import "MXKAccountManager.h"
#import "NSBundle+MatrixKit.h"
#import <AFNetworking/AFNetworking.h>
@interface MXKAuthenticationViewController ()
{
/**
The matrix REST client used to make matrix API requests.
*/
MXRestClient *mxRestClient;
/**
Current request in progress.
*/
MXHTTPOperation *mxCurrentOperation;
/**
The MXKAuthInputsView class or a sub-class used when logging in.
*/
Class loginAuthInputsViewClass;
/**
The MXKAuthInputsView class or a sub-class used when registering.
*/
Class registerAuthInputsViewClass;
/**
The MXKAuthInputsView class or a sub-class used to handle forgot password case.
*/
Class forgotPasswordAuthInputsViewClass;
/**
Customized block used to handle unrecognized certificate (nil by default).
*/
MXHTTPClientOnUnrecognizedCertificate onUnrecognizedCertificateCustomBlock;
/**
The current authentication fallback URL (if any).
*/
NSString *authenticationFallback;
/**
The cancel button added in navigation bar when fallback page is opened.
*/
UIBarButtonItem *cancelFallbackBarButton;
/**
The timer used to postpone the registration when the authentication is pending (for example waiting for email validation)
*/
NSTimer* registrationTimer;
/**
Identity Server discovery.
*/
MXAutoDiscovery *autoDiscovery;
MXHTTPOperation *checkIdentityServerOperation;
}
/**
The identity service used to make identity server API requests.
*/
@property (nonatomic) MXIdentityService *identityService;
@end
@implementation MXKAuthenticationViewController
#pragma mark - Class methods
+ (UINib *)nib
{
return [UINib nibWithNibName:NSStringFromClass([MXKAuthenticationViewController class])
bundle:[NSBundle bundleForClass:[MXKAuthenticationViewController class]]];
}
+ (instancetype)authenticationViewController
{
return [[[self class] alloc] initWithNibName:NSStringFromClass([MXKAuthenticationViewController class])
bundle:[NSBundle bundleForClass:[MXKAuthenticationViewController class]]];
}
#pragma mark -
- (void)finalizeInit
{
[super finalizeInit];
// Set initial auth type
_authType = MXKAuthenticationTypeLogin;
_deviceDisplayName = nil;
// Initialize authInputs view classes
loginAuthInputsViewClass = MXKAuthInputsPasswordBasedView.class;
registerAuthInputsViewClass = nil; // No registration flow is supported yet
forgotPasswordAuthInputsViewClass = nil;
}
#pragma mark -
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
// Check whether the view controller has been pushed via storyboard
if (!_authenticationScrollView)
{
// Instantiate view controller objects
[[[self class] nib] instantiateWithOwner:self options:nil];
}
self.authFallbackWebView = [[MXKAuthenticationFallbackWebView alloc] initWithFrame:self.authFallbackWebViewContainer.bounds];
[self.authFallbackWebViewContainer addSubview:self.authFallbackWebView];
[self.authFallbackWebView.leadingAnchor constraintEqualToAnchor:self.authFallbackWebViewContainer.leadingAnchor constant:0].active = YES;
[self.authFallbackWebView.trailingAnchor constraintEqualToAnchor:self.authFallbackWebViewContainer.trailingAnchor constant:0].active = YES;
[self.authFallbackWebView.topAnchor constraintEqualToAnchor:self.authFallbackWebViewContainer.topAnchor constant:0].active = YES;
[self.authFallbackWebView.bottomAnchor constraintEqualToAnchor:self.authFallbackWebViewContainer.bottomAnchor constant:0].active = YES;
// Load welcome image from MatrixKit asset bundle
self.welcomeImageView.image = [NSBundle mxk_imageFromMXKAssetsBundleWithName:@"logoHighRes"];
_authenticationScrollView.autoresizingMask = UIViewAutoresizingFlexibleWidth;
_subTitleLabel.numberOfLines = 0;
_submitButton.enabled = NO;
_authSwitchButton.enabled = YES;
_homeServerTextField.text = _defaultHomeServerUrl;
_identityServerTextField.text = _defaultIdentityServerUrl;
// Hide the identity server by default
[self setIdentityServerHidden:YES];
// Create here REST client (if homeserver is defined)
[self updateRESTClient];
// Localize labels
_homeServerLabel.text = [NSBundle mxk_localizedStringForKey:@"login_home_server_title"];
_homeServerTextField.placeholder = [NSBundle mxk_localizedStringForKey:@"login_server_url_placeholder"];
_homeServerInfoLabel.text = [NSBundle mxk_localizedStringForKey:@"login_home_server_info"];
_identityServerLabel.text = [NSBundle mxk_localizedStringForKey:@"login_identity_server_title"];
_identityServerTextField.placeholder = [NSBundle mxk_localizedStringForKey:@"login_server_url_placeholder"];
_identityServerInfoLabel.text = [NSBundle mxk_localizedStringForKey:@"login_identity_server_info"];
[_cancelAuthFallbackButton setTitle:[NSBundle mxk_localizedStringForKey:@"cancel"] forState:UIControlStateNormal];
[_cancelAuthFallbackButton setTitle:[NSBundle mxk_localizedStringForKey:@"cancel"] forState:UIControlStateHighlighted];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onTextFieldChange:) name:UITextFieldTextDidChangeNotification object:nil];
}
- (void)viewWillDisappear:(BOOL)animated
{
[super viewWillDisappear:animated];
[self dismissKeyboard];
// close any opened alert
if (alert)
{
[alert dismissViewControllerAnimated:NO completion:nil];
alert = nil;
}
[[NSNotificationCenter defaultCenter] removeObserver:self name:AFNetworkingReachabilityDidChangeNotification object:nil];
[[NSNotificationCenter defaultCenter] removeObserver:self name:UITextFieldTextDidChangeNotification object:nil];
}
#pragma mark - Override MXKViewController
- (void)onKeyboardShowAnimationComplete
{
// Report the keyboard view in order to track keyboard frame changes
// TODO define inputAccessoryView for each text input
// and report the inputAccessoryView.superview of the firstResponder in self.keyboardView.
}
- (void)setKeyboardHeight:(CGFloat)keyboardHeight
{
// Deduce the bottom inset for the scroll view (Don't forget the potential tabBar)
CGFloat scrollViewInsetBottom = keyboardHeight - self.bottomLayoutGuide.length;
// Check whether the keyboard is over the tabBar
if (scrollViewInsetBottom < 0)
{
scrollViewInsetBottom = 0;
}
UIEdgeInsets insets = self.authenticationScrollView.contentInset;
insets.bottom = scrollViewInsetBottom;
self.authenticationScrollView.contentInset = insets;
}
- (void)destroy
{
self.authInputsView = nil;
if (registrationTimer)
{
[registrationTimer invalidate];
registrationTimer = nil;
}
if (mxCurrentOperation)
{
[mxCurrentOperation cancel];
mxCurrentOperation = nil;
}
[self cancelIdentityServerCheck];
[mxRestClient close];
mxRestClient = nil;
authenticationFallback = nil;
cancelFallbackBarButton = nil;
[super destroy];
}
#pragma mark - Class methods
- (void)registerAuthInputsViewClass:(Class)authInputsViewClass forAuthType:(MXKAuthenticationType)authType
{
// Sanity check: accept only MXKAuthInputsView classes or sub-classes
NSParameterAssert([authInputsViewClass isSubclassOfClass:MXKAuthInputsView.class]);
if (authType == MXKAuthenticationTypeLogin)
{
loginAuthInputsViewClass = authInputsViewClass;
}
else if (authType == MXKAuthenticationTypeRegister)
{
registerAuthInputsViewClass = authInputsViewClass;
}
else if (authType == MXKAuthenticationTypeForgotPassword)
{
forgotPasswordAuthInputsViewClass = authInputsViewClass;
}
}
- (void)setAuthType:(MXKAuthenticationType)authType
{
if (_authType != authType)
{
_authType = authType;
// Cancel external registration parameters if any
_externalRegistrationParameters = nil;
// Remove the current inputs view
self.authInputsView = nil;
isPasswordReseted = NO;
[self.authInputsContainerView bringSubviewToFront: _authenticationActivityIndicator];
[_authenticationActivityIndicator startAnimating];
}
// Restore user interaction
self.userInteractionEnabled = YES;
if (authType == MXKAuthenticationTypeLogin)
{
_subTitleLabel.hidden = YES;
[_submitButton setTitle:[NSBundle mxk_localizedStringForKey:@"login"] forState:UIControlStateNormal];
[_submitButton setTitle:[NSBundle mxk_localizedStringForKey:@"login"] forState:UIControlStateHighlighted];
[_authSwitchButton setTitle:[NSBundle mxk_localizedStringForKey:@"create_account"] forState:UIControlStateNormal];
[_authSwitchButton setTitle:[NSBundle mxk_localizedStringForKey:@"create_account"] forState:UIControlStateHighlighted];
// Update supported authentication flow and associated information (defined in authentication session)
[self refreshAuthenticationSession];
}
else if (authType == MXKAuthenticationTypeRegister)
{
_subTitleLabel.hidden = NO;
_subTitleLabel.text = [NSBundle mxk_localizedStringForKey:@"login_create_account"];
[_submitButton setTitle:[NSBundle mxk_localizedStringForKey:@"sign_up"] forState:UIControlStateNormal];
[_submitButton setTitle:[NSBundle mxk_localizedStringForKey:@"sign_up"] forState:UIControlStateHighlighted];
[_authSwitchButton setTitle:[NSBundle mxk_localizedStringForKey:@"back"] forState:UIControlStateNormal];
[_authSwitchButton setTitle:[NSBundle mxk_localizedStringForKey:@"back"] forState:UIControlStateHighlighted];
// Update supported authentication flow and associated information (defined in authentication session)
[self refreshAuthenticationSession];
}
else if (authType == MXKAuthenticationTypeForgotPassword)
{
_subTitleLabel.hidden = YES;
if (isPasswordReseted)
{
[_submitButton setTitle:[NSBundle mxk_localizedStringForKey:@"back"] forState:UIControlStateNormal];
[_submitButton setTitle:[NSBundle mxk_localizedStringForKey:@"back"] forState:UIControlStateHighlighted];
}
else
{
[_submitButton setTitle:[NSBundle mxk_localizedStringForKey:@"submit"] forState:UIControlStateNormal];
[_submitButton setTitle:[NSBundle mxk_localizedStringForKey:@"submit"] forState:UIControlStateHighlighted];
[self refreshForgotPasswordSession];
}
[_authSwitchButton setTitle:[NSBundle mxk_localizedStringForKey:@"back"] forState:UIControlStateNormal];
[_authSwitchButton setTitle:[NSBundle mxk_localizedStringForKey:@"back"] forState:UIControlStateHighlighted];
}
[self checkIdentityServer];
}
- (void)setAuthInputsView:(MXKAuthInputsView *)authInputsView
{
// Here a new view will be loaded, hide first subviews which depend on auth flow
_submitButton.hidden = YES;
_noFlowLabel.hidden = YES;
_retryButton.hidden = YES;
if (_authInputsView)
{
[_authInputsView removeObserver:self forKeyPath:@"viewHeightConstraint.constant"];
if ([NSLayoutConstraint respondsToSelector:@selector(deactivateConstraints:)])
{
[NSLayoutConstraint deactivateConstraints:_authInputsView.constraints];
}
else
{
[_authInputsContainerView removeConstraints:_authInputsView.constraints];
}
[_authInputsView removeFromSuperview];
_authInputsView.delegate = nil;
[_authInputsView destroy];
_authInputsView = nil;
}
_authInputsView = authInputsView;
CGFloat previousInputsContainerViewHeight = _authInputContainerViewHeightConstraint.constant;
if (_authInputsView)
{
_authInputsView.translatesAutoresizingMaskIntoConstraints = NO;
[_authInputsContainerView addSubview:_authInputsView];
_authInputsView.delegate = self;
_submitButton.hidden = NO;
_authInputsView.hidden = NO;
_authInputContainerViewHeightConstraint.constant = _authInputsView.viewHeightConstraint.constant;
NSLayoutConstraint* topConstraint = [NSLayoutConstraint constraintWithItem:_authInputsContainerView
attribute:NSLayoutAttributeTop
relatedBy:NSLayoutRelationEqual
toItem:_authInputsView
attribute:NSLayoutAttributeTop
multiplier:1.0f
constant:0.0f];
NSLayoutConstraint* leadingConstraint = [NSLayoutConstraint constraintWithItem:_authInputsContainerView
attribute:NSLayoutAttributeLeading
relatedBy:NSLayoutRelationEqual
toItem:_authInputsView
attribute:NSLayoutAttributeLeading
multiplier:1.0f
constant:0.0f];
NSLayoutConstraint* trailingConstraint = [NSLayoutConstraint constraintWithItem:_authInputsContainerView
attribute:NSLayoutAttributeTrailing
relatedBy:NSLayoutRelationEqual
toItem:_authInputsView
attribute:NSLayoutAttributeTrailing
multiplier:1.0f
constant:0.0f];
if ([NSLayoutConstraint respondsToSelector:@selector(activateConstraints:)])
{
[NSLayoutConstraint activateConstraints:@[topConstraint, leadingConstraint, trailingConstraint]];
}
else
{
[_authInputsContainerView addConstraint:topConstraint];
[_authInputsContainerView addConstraint:leadingConstraint];
[_authInputsContainerView addConstraint:trailingConstraint];
}
[_authInputsView addObserver:self forKeyPath:@"viewHeightConstraint.constant" options:0 context:nil];
}
else
{
// No input fields are displayed
_authInputContainerViewHeightConstraint.constant = _authInputContainerViewMinHeightConstraint.constant;
}
[self.view layoutIfNeeded];
// Refresh content view height by considering the updated height of inputs container
_contentViewHeightConstraint.constant += (_authInputContainerViewHeightConstraint.constant - previousInputsContainerViewHeight);
}
- (void)setDefaultHomeServerUrl:(NSString *)defaultHomeServerUrl
{
_defaultHomeServerUrl = defaultHomeServerUrl;
if (!_homeServerTextField.text.length)
{
[self setHomeServerTextFieldText:defaultHomeServerUrl];
}
}
- (void)setDefaultIdentityServerUrl:(NSString *)defaultIdentityServerUrl
{
_defaultIdentityServerUrl = defaultIdentityServerUrl;
if (!_identityServerTextField.text.length)
{
[self setIdentityServerTextFieldText:defaultIdentityServerUrl];
}
}
- (void)setHomeServerTextFieldText:(NSString *)homeServerUrl
{
if (!homeServerUrl.length)
{
// Force refresh with default value
homeServerUrl = _defaultHomeServerUrl;
}
_homeServerTextField.text = homeServerUrl;
if (!mxRestClient || ![mxRestClient.homeserver isEqualToString:homeServerUrl])
{
[self updateRESTClient];
if (_authType == MXKAuthenticationTypeLogin || _authType == MXKAuthenticationTypeRegister)
{
// Restore default UI
self.authType = _authType;
}
else
{
// Refresh the IS anyway
[self checkIdentityServer];
}
}
}
- (void)setIdentityServerTextFieldText:(NSString *)identityServerUrl
{
_identityServerTextField.text = identityServerUrl;
[self updateIdentityServerURL:identityServerUrl];
}
- (void)updateIdentityServerURL:(NSString*)url
{
if (![self.identityService.identityServer isEqualToString:url])
{
if (url.length)
{
self.identityService = [[MXIdentityService alloc] initWithIdentityServer:url accessToken:nil andHomeserverRestClient:mxRestClient];
}
else
{
self.identityService = nil;
}
}
[mxRestClient setIdentityServer:url.length ? url : nil];
}
- (void)setIdentityServerHidden:(BOOL)hidden
{
_identityServerContainer.hidden = hidden;
}
- (void)checkIdentityServer
{
[self cancelIdentityServerCheck];
// Hide the field while checking data
[self setIdentityServerHidden:YES];
NSString *homeserver = mxRestClient.homeserver;
// First, fetch the IS advertised by the HS
if (homeserver)
{
NSLog(@"[MXKAuthenticationVC] checkIdentityServer for homeserver %@", homeserver);
autoDiscovery = [[MXAutoDiscovery alloc] initWithUrl:homeserver];
MXWeakify(self);
checkIdentityServerOperation = [autoDiscovery findClientConfig:^(MXDiscoveredClientConfig * _Nonnull discoveredClientConfig) {
MXStrongifyAndReturnIfNil(self);
NSString *identityServer = discoveredClientConfig.wellKnown.identityServer.baseUrl;
NSLog(@"[MXKAuthenticationVC] checkIdentityServer: Identity server: %@", identityServer);
if (identityServer)
{
// Apply the provided IS
[self setIdentityServerTextFieldText:identityServer];
}
// Then, check if the HS needs an IS for running
MXWeakify(self);
MXHTTPOperation *operation = [self checkIdentityServerRequirementWithCompletion:^(BOOL identityServerRequired) {
MXStrongifyAndReturnIfNil(self);
self->checkIdentityServerOperation = nil;
// Show the field only if an IS is required so that the user can customise it
[self setIdentityServerHidden:!identityServerRequired];
}];
if (operation)
{
[self->checkIdentityServerOperation mutateTo:operation];
}
else
{
self->checkIdentityServerOperation = nil;
}
self->autoDiscovery = nil;
} failure:^(NSError *error) {
MXStrongifyAndReturnIfNil(self);
// No need to report this error to the end user
// There will be already an error about failing to get the auth flow from the HS
NSLog(@"[MXKAuthenticationVC] checkIdentityServer. Error: %@", error);
self->autoDiscovery = nil;
}];
}
}
- (void)cancelIdentityServerCheck
{
if (checkIdentityServerOperation)
{
[checkIdentityServerOperation cancel];
checkIdentityServerOperation = nil;
}
}
- (MXHTTPOperation*)checkIdentityServerRequirementWithCompletion:(void (^)(BOOL identityServerRequired))completion
{
MXHTTPOperation *operation;
if (_authType == MXKAuthenticationTypeLogin)
{
// The identity server is only required for registration and password reset
// It is then stored in the user account data
completion(NO);
}
else
{
operation = [mxRestClient supportedMatrixVersions:^(MXMatrixVersions *matrixVersions) {
NSLog(@"[MXKAuthenticationVC] checkIdentityServerRequirement: %@", matrixVersions.doesServerRequireIdentityServerParam ? @"YES": @"NO");
completion(matrixVersions.doesServerRequireIdentityServerParam);
} failure:^(NSError *error) {
// No need to report this error to the end user
// There will be already an error about failing to get the auth flow from the HS
NSLog(@"[MXKAuthenticationVC] checkIdentityServerRequirement. Error: %@", error);
}];
}
return operation;
}
- (void)setUserInteractionEnabled:(BOOL)userInteractionEnabled
{
_submitButton.enabled = (userInteractionEnabled && _authInputsView.areAllRequiredFieldsSet);
_authSwitchButton.enabled = userInteractionEnabled;
_homeServerTextField.enabled = userInteractionEnabled;
_identityServerTextField.enabled = userInteractionEnabled;
_userInteractionEnabled = userInteractionEnabled;
}
- (void)refreshAuthenticationSession
{
// Remove reachability observer
[[NSNotificationCenter defaultCenter] removeObserver:self name:AFNetworkingReachabilityDidChangeNotification object:nil];
// Cancel potential request in progress
[mxCurrentOperation cancel];
mxCurrentOperation = nil;
// Reset potential authentication fallback url
authenticationFallback = nil;
if (mxRestClient)
{
if (_authType == MXKAuthenticationTypeLogin)
{
mxCurrentOperation = [mxRestClient getLoginSession:^(MXAuthenticationSession* authSession) {
[self handleAuthenticationSession:authSession];
} failure:^(NSError *error) {
[self onFailureDuringMXOperation:error];
}];
}
else if (_authType == MXKAuthenticationTypeRegister)
{
mxCurrentOperation = [mxRestClient getRegisterSession:^(MXAuthenticationSession* authSession){
[self handleAuthenticationSession:authSession];
} failure:^(NSError *error){
[self onFailureDuringMXOperation:error];
}];
}
else
{
// Not supported for other types
NSLog(@"[MXKAuthenticationVC] refreshAuthenticationSession is ignored");
}
}
}
- (void)handleAuthenticationSession:(MXAuthenticationSession *)authSession
{
mxCurrentOperation = nil;
[_authenticationActivityIndicator stopAnimating];
// Check whether fallback is defined, and retrieve the right input view class.
Class authInputsViewClass;
if (_authType == MXKAuthenticationTypeLogin)
{
authenticationFallback = [mxRestClient loginFallback];
authInputsViewClass = loginAuthInputsViewClass;
}
else if (_authType == MXKAuthenticationTypeRegister)
{
authenticationFallback = [mxRestClient registerFallback];
authInputsViewClass = registerAuthInputsViewClass;
}
else
{
// Not supported for other types
NSLog(@"[MXKAuthenticationVC] handleAuthenticationSession is ignored");
return;
}
MXKAuthInputsView *authInputsView = nil;
if (authInputsViewClass)
{
// Instantiate a new auth inputs view, except if the current one is already an instance of this class.
if (self.authInputsView && self.authInputsView.class == authInputsViewClass)
{
// Use the current view
authInputsView = self.authInputsView;
}
else
{
authInputsView = [authInputsViewClass authInputsView];
}
}
if (authInputsView)
{
// Apply authentication session on inputs view
if ([authInputsView setAuthSession:authSession withAuthType:_authType] == NO)
{
NSLog(@"[MXKAuthenticationVC] Received authentication settings are not supported");
authInputsView = nil;
}
else if (!_softLogoutCredentials)
{
// If all listed flows in this authentication session are not supported we suggest using the fallback page.
if (authenticationFallback.length && authInputsView.authSession.flows.count == 0)
{
NSLog(@"[MXKAuthenticationVC] No supported flow, suggest using fallback page");
authInputsView = nil;
}
else if (authInputsView.authSession.flows.count != authSession.flows.count)
{
NSLog(@"[MXKAuthenticationVC] The authentication session contains at least one unsupported flow");
}
}
}
if (authInputsView)
{
// Check whether the current view must be replaced
if (self.authInputsView != authInputsView)
{
// Refresh layout
self.authInputsView = authInputsView;
}
// Refresh user interaction
self.userInteractionEnabled = _userInteractionEnabled;
// Check whether an external set of parameters have been defined to pursue a registration
if (self.externalRegistrationParameters)
{
if ([authInputsView setExternalRegistrationParameters:self.externalRegistrationParameters])
{
// Launch authentication now
[self onButtonPressed:_submitButton];
}
else
{
[self onFailureDuringAuthRequest:[NSError errorWithDomain:MXKAuthErrorDomain code:0 userInfo:@{NSLocalizedDescriptionKey:[NSBundle mxk_localizedStringForKey:@"not_supported_yet"]}]];
_externalRegistrationParameters = nil;
// Restore login screen on failure
self.authType = MXKAuthenticationTypeLogin;
}
}
if (_softLogoutCredentials)
{
[authInputsView setSoftLogoutCredentials:_softLogoutCredentials];
}
}
else
{
// Remove the potential auth inputs view
self.authInputsView = nil;
// Cancel external registration parameters if any
_externalRegistrationParameters = nil;
// Notify user that no flow is supported
if (_authType == MXKAuthenticationTypeLogin)
{
_noFlowLabel.text = [NSBundle mxk_localizedStringForKey:@"login_error_do_not_support_login_flows"];
}
else
{
_noFlowLabel.text = [NSBundle mxk_localizedStringForKey:@"login_error_registration_is_not_supported"];
}
NSLog(@"[MXKAuthenticationVC] Warning: %@", _noFlowLabel.text);
if (authenticationFallback.length)
{
[_retryButton setTitle:[NSBundle mxk_localizedStringForKey:@"login_use_fallback"] forState:UIControlStateNormal];
[_retryButton setTitle:[NSBundle mxk_localizedStringForKey:@"login_use_fallback"] forState:UIControlStateNormal];
}
else
{
[_retryButton setTitle:[NSBundle mxk_localizedStringForKey:@"retry"] forState:UIControlStateNormal];
[_retryButton setTitle:[NSBundle mxk_localizedStringForKey:@"retry"] forState:UIControlStateNormal];
}
_noFlowLabel.hidden = NO;
_retryButton.hidden = NO;
}
}
- (void)setExternalRegistrationParameters:(NSDictionary*)parameters
{
if (parameters.count)
{
NSLog(@"[MXKAuthenticationVC] setExternalRegistrationParameters");
// Cancel the current operation if any.
[self cancel];
// Load the view controller’s view if it has not yet been loaded.
// This is required before updating view's textfields (homeserver url...)
[self loadViewIfNeeded];
// Force register mode
self.authType = MXKAuthenticationTypeRegister;
// Apply provided homeserver if any
id hs_url = parameters[@"hs_url"];
NSString *homeserverURL = nil;
if (hs_url && [hs_url isKindOfClass:NSString.class])
{
homeserverURL = hs_url;
}
[self setHomeServerTextFieldText:homeserverURL];
// Apply provided identity server if any
id is_url = parameters[@"is_url"];
NSString *identityURL = nil;
if (is_url && [is_url isKindOfClass:NSString.class])
{
identityURL = is_url;
}
[self setIdentityServerTextFieldText:identityURL];
// Disable user interaction
self.userInteractionEnabled = NO;
// Cancel potential request in progress
[mxCurrentOperation cancel];
mxCurrentOperation = nil;
// Remove the current auth inputs view
self.authInputsView = nil;
// Set external parameters and trigger a refresh (the parameters will be taken into account during [handleAuthenticationSession:])
_externalRegistrationParameters = parameters;
[self refreshAuthenticationSession];
}
else
{
NSLog(@"[MXKAuthenticationVC] reset externalRegistrationParameters");
_externalRegistrationParameters = nil;
// Restore default UI
self.authType = _authType;
}
}
- (void)setSoftLogoutCredentials:(MXCredentials *)softLogoutCredentials
{
NSLog(@"[MXKAuthenticationVC] setSoftLogoutCredentials");
// Cancel the current operation if any.
[self cancel];
// Load the view controller’s view if it has not yet been loaded.
// This is required before updating view's textfields (homeserver url...)
[self loadViewIfNeeded];
// Force register mode
self.authType = MXKAuthenticationTypeLogin;
[self setHomeServerTextFieldText:softLogoutCredentials.homeServer];
[self setIdentityServerTextFieldText:softLogoutCredentials.identityServer];
// Cancel potential request in progress
[mxCurrentOperation cancel];
mxCurrentOperation = nil;
// Remove the current auth inputs view
self.authInputsView = nil;
// Set parameters and trigger a refresh (the parameters will be taken into account during [handleAuthenticationSession:])
_softLogoutCredentials = softLogoutCredentials;
[self refreshAuthenticationSession];
}
- (void)setOnUnrecognizedCertificateBlock:(MXHTTPClientOnUnrecognizedCertificate)onUnrecognizedCertificateBlock
{
onUnrecognizedCertificateCustomBlock = onUnrecognizedCertificateBlock;
}
- (void)isUserNameInUse:(void (^)(BOOL isUserNameInUse))callback
{
mxCurrentOperation = [mxRestClient isUserNameInUse:self.authInputsView.userId callback:^(BOOL isUserNameInUse) {
self->mxCurrentOperation = nil;
if (callback)
{
callback (isUserNameInUse);
}
}];
}
- (void)testUserRegistration:(void (^)(MXError *mxError))callback
{
mxCurrentOperation = [mxRestClient testUserRegistration:self.authInputsView.userId callback:callback];
}
- (IBAction)onButtonPressed:(id)sender
{
[self dismissKeyboard];
if (sender == _submitButton)
{
// Disable user interaction to prevent multiple requests
self.userInteractionEnabled = NO;
// Check parameters validity
NSString *errorMsg = [self.authInputsView validateParameters];
if (errorMsg)
{
[self onFailureDuringAuthRequest:[NSError errorWithDomain:MXKAuthErrorDomain code:0 userInfo:@{NSLocalizedDescriptionKey:errorMsg}]];
}
else
{
[self.authInputsContainerView bringSubviewToFront: _authenticationActivityIndicator];
// Launch the authentication according to its type
if (_authType == MXKAuthenticationTypeLogin)
{
// Prepare the parameters dict
[self.authInputsView prepareParameters:^(NSDictionary *parameters, NSError *error) {
if (parameters && self->mxRestClient)
{
[self->_authenticationActivityIndicator startAnimating];
[self loginWithParameters:parameters];
}
else
{
NSLog(@"[MXKAuthenticationVC] Failed to prepare parameters");
[self onFailureDuringAuthRequest:error];
}
}];
}
else if (_authType == MXKAuthenticationTypeRegister)
{
// Check here the availability of the userId
if (self.authInputsView.userId.length)
{
[_authenticationActivityIndicator startAnimating];
if (self.authInputsView.password.length)
{
// Trigger here a register request in order to associate the filled userId and password to the current session id
// This will check the availability of the userId at the same time
NSDictionary *parameters = @{@"auth": @{},
@"username": self.authInputsView.userId,
@"password": self.authInputsView.password,
@"bind_email": @(NO),
@"initial_device_display_name":self.deviceDisplayName
};
mxCurrentOperation = [mxRestClient registerWithParameters:parameters success:^(NSDictionary *JSONResponse) {
// Unexpected case where the registration succeeds without any other stages
MXLoginResponse *loginResponse;
MXJSONModelSetMXJSONModel(loginResponse, MXLoginResponse, JSONResponse);
MXCredentials *credentials = [[MXCredentials alloc] initWithLoginResponse:loginResponse
andDefaultCredentials:self->mxRestClient.credentials];
// Sanity check
if (!credentials.userId || !credentials.accessToken)
{
[self onFailureDuringAuthRequest:[NSError errorWithDomain:MXKAuthErrorDomain code:0 userInfo:@{NSLocalizedDescriptionKey:[NSBundle mxk_localizedStringForKey:@"not_supported_yet"]}]];
}
else
{
NSLog(@"[MXKAuthenticationVC] Registration succeeded");
// Report the certificate trusted by user (if any)
credentials.allowedCertificate = self->mxRestClient.allowedCertificate;
[self onSuccessfulLogin:credentials];
}
} failure:^(NSError *error) {
self->mxCurrentOperation = nil;