CCLogin.m 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539
  1. //
  2. // CCLogin.m
  3. // Nextcloud iOS
  4. //
  5. // Created by Marino Faggiana on 09/04/15.
  6. // Copyright (c) 2017 TWS. All rights reserved.
  7. //
  8. // Author Marino Faggiana <m.faggiana@twsweb.it>
  9. //
  10. // This program is free software: you can redistribute it and/or modify
  11. // it under the terms of the GNU General Public License as published by
  12. // the Free Software Foundation, either version 3 of the License, or
  13. // (at your option) any later version.
  14. //
  15. // This program is distributed in the hope that it will be useful,
  16. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. // GNU General Public License for more details.
  19. //
  20. // You should have received a copy of the GNU General Public License
  21. // along with this program. If not, see <http://www.gnu.org/licenses/>.
  22. //
  23. #import "CCLogin.h"
  24. #import "AppDelegate.h"
  25. #import "CCUtility.h"
  26. #import "NCBridgeSwift.h"
  27. #import "NCNetworkingEndToEnd.h"
  28. @interface CCLogin () <CCLoginDelegateWeb>
  29. {
  30. AppDelegate *appDelegate;
  31. UIView *rootView;
  32. NSString *serverProductName;
  33. NSString *serverVersion;
  34. NSString *serverVersionString;
  35. NSInteger versionMajor;
  36. NSInteger versionMicro;
  37. NSInteger versionMinor;
  38. }
  39. @end
  40. @implementation CCLogin
  41. - (void)viewDidLoad
  42. {
  43. [super viewDidLoad];
  44. appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  45. // Background color
  46. self.view.backgroundColor = [NCBrandColor sharedInstance].customer;
  47. // Image Brand
  48. self.imageBrand.image = [UIImage imageNamed:@"loginLogo"];
  49. // Annulla
  50. [self.annulla setTitle:NSLocalizedString(@"_cancel_", nil) forState:UIControlStateNormal];
  51. self.annulla.tintColor = [NCBrandColor sharedInstance].customerText;
  52. // Base URL
  53. _imageBaseUrl.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"loginURL"] multiplier:2 color:[NCBrandColor sharedInstance].customerText];
  54. _baseUrl.textColor = [NCBrandColor sharedInstance].customerText;
  55. _baseUrl.tintColor = [NCBrandColor sharedInstance].customerText;
  56. _baseUrl.placeholder = NSLocalizedString(@"_login_url_", nil);
  57. [_baseUrl setValue:[UIColor lightGrayColor] forKeyPath:@"_placeholderLabel.textColor"];
  58. [self.baseUrl setFont:[UIFont systemFontOfSize:13]];
  59. [self.baseUrl setDelegate:self];
  60. // Loading Base Utl GIF
  61. self.loadingBaseUrl.image = [UIImage animatedImageWithAnimatedGIFURL:[[NSBundle mainBundle] URLForResource: @"loading@2x" withExtension:@"gif"]];
  62. self.loadingBaseUrl.hidden = YES;
  63. // User
  64. _imageUser.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"loginUser"] multiplier:2 color:[NCBrandColor sharedInstance].customerText];
  65. _user.textColor = [NCBrandColor sharedInstance].customerText;
  66. _user.tintColor = [NCBrandColor sharedInstance].customerText;
  67. _user.placeholder = NSLocalizedString(@"_username_", nil);
  68. [_user setValue:[UIColor lightGrayColor] forKeyPath:@"_placeholderLabel.textColor"];
  69. [self.user setFont:[UIFont systemFontOfSize:13]];
  70. [self.user setDelegate:self];
  71. // Password
  72. _imagePassword.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"loginPassword"] multiplier:2 color:[NCBrandColor sharedInstance].customerText];
  73. _password.textColor = [NCBrandColor sharedInstance].customerText;
  74. _password.tintColor = [NCBrandColor sharedInstance].customerText;
  75. _password.placeholder = NSLocalizedString(@"_password_", nil);
  76. [_password setValue:[UIColor lightGrayColor] forKeyPath:@"_placeholderLabel.textColor"];
  77. [self.password setFont:[UIFont systemFontOfSize:13]];
  78. [self.password setDelegate:self];
  79. // Login
  80. [self.login setTitle:[NSLocalizedString(@"_login_", nil) uppercaseString] forState:UIControlStateNormal] ;
  81. self.login.backgroundColor = [NCBrandColor sharedInstance].customerText;
  82. self.login.tintColor = [UIColor blackColor];
  83. // self.login.layer.cornerRadius = 3;
  84. // self.login.clipsToBounds = YES;
  85. // Type view
  86. [self.loginTypeView setTitle:NSLocalizedString(@"_traditional_login_", nil) forState:UIControlStateNormal];
  87. [self.loginTypeView setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
  88. // Preferred providers
  89. self.preferredProviders.text = NSLocalizedString([NCBrandOptions sharedInstance].textLoginProvider, nil);
  90. self.preferredProviders.textColor = [UIColor whiteColor];
  91. self.preferredProviders.userInteractionEnabled = YES;
  92. if ([NCBrandOptions sharedInstance].disable_linkLoginProvider) {
  93. self.preferredProviders.hidden = YES;
  94. }
  95. UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(loginPreferredProviders)];
  96. [self.preferredProviders addGestureRecognizer:tapGesture];
  97. if (self.view.frame.size.width == ([[UIScreen mainScreen] bounds].size.width*([[UIScreen mainScreen] bounds].size.width<[[UIScreen mainScreen] bounds].size.height))+([[UIScreen mainScreen] bounds].size.height*([[UIScreen mainScreen] bounds].size.width>[[UIScreen mainScreen] bounds].size.height))) {
  98. // Portrait
  99. if ([NCBrandOptions sharedInstance].disable_linkLoginProvider == NO)
  100. self.preferredProviders.hidden = NO;
  101. self.loginTypeView.hidden = NO;
  102. } else {
  103. // Landscape
  104. if (UI_USER_INTERFACE_IDIOM() != UIUserInterfaceIdiomPad) {
  105. self.preferredProviders.hidden = YES;
  106. self.loginTypeView.hidden = YES;
  107. }
  108. }
  109. // Brand
  110. if ([NCBrandOptions sharedInstance].disable_request_login_url) {
  111. _baseUrl.text = [NCBrandOptions sharedInstance].loginBaseUrl;
  112. _imageBaseUrl.hidden = YES;
  113. _baseUrl.hidden = YES;
  114. }
  115. if (_loginType == k_login_Add ) {
  116. // Login Flow ?
  117. _imageUser.hidden = YES;
  118. _user.hidden = YES;
  119. _imagePassword.hidden = YES;
  120. _password.hidden = YES;
  121. }
  122. if (_loginType == k_login_Add_Forced) {
  123. _annulla.hidden = YES;
  124. // Login Flow ?
  125. _imageUser.hidden = YES;
  126. _user.hidden = YES;
  127. _imagePassword.hidden = YES;
  128. _password.hidden = YES;
  129. }
  130. if (_loginType == k_login_Modify_Password) {
  131. _baseUrl.text = appDelegate.activeUrl;
  132. _baseUrl.userInteractionEnabled = NO;
  133. _baseUrl.textColor = [UIColor lightGrayColor];
  134. _user.text = appDelegate.activeUser;
  135. _user.userInteractionEnabled = NO;
  136. _user.textColor = [UIColor lightGrayColor];
  137. }
  138. }
  139. - (void)viewWillAppear:(BOOL)animated
  140. {
  141. [super viewWillAppear:animated];
  142. // verify URL
  143. if (_loginType == k_login_Modify_Password && [self.baseUrl.text length] > 0)
  144. [self testUrl];
  145. }
  146. // E' apparsa
  147. - (void)viewDidAppear:(BOOL)animated
  148. {
  149. [super viewDidAppear:animated];
  150. }
  151. //
  152. - (void)viewDidDisappear:(BOOL)animated
  153. {
  154. [super viewDidDisappear:animated];
  155. }
  156. - (BOOL)textFieldShouldReturn:(UITextField *)textField
  157. {
  158. [textField resignFirstResponder];
  159. return YES;
  160. }
  161. - (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator
  162. {
  163. [coordinator animateAlongsideTransition:nil completion:^(id<UIViewControllerTransitionCoordinatorContext> context) {
  164. if (self.view.frame.size.width == ([[UIScreen mainScreen] bounds].size.width*([[UIScreen mainScreen] bounds].size.width<[[UIScreen mainScreen] bounds].size.height))+([[UIScreen mainScreen] bounds].size.height*([[UIScreen mainScreen] bounds].size.width>[[UIScreen mainScreen] bounds].size.height))) {
  165. // Portrait
  166. if ([NCBrandOptions sharedInstance].disable_linkLoginProvider == NO)
  167. self.preferredProviders.hidden = NO;
  168. self.loginTypeView.hidden = NO;
  169. } else {
  170. // Landscape
  171. if (UI_USER_INTERFACE_IDIOM() != UIUserInterfaceIdiomPad) {
  172. self.preferredProviders.hidden = YES;
  173. self.loginTypeView.hidden = YES;
  174. }
  175. }
  176. }];
  177. [super viewWillTransitionToSize:size withTransitionCoordinator:coordinator];
  178. }
  179. - (void)dismissViewControllerAnimated:(BOOL)flag completion:(void (^)(void))completion
  180. {
  181. [super dismissViewControllerAnimated:flag completion:completion];
  182. NSArray *callStack = [NSThread callStackSymbols];
  183. NSString *callParent = [callStack objectAtIndex:1];
  184. if ([callParent containsString:@"CCLogin"])
  185. [self.delegate loginClose];
  186. }
  187. #pragma --------------------------------------------------------------------------------------------
  188. #pragma mark == Chech Server URL ==
  189. #pragma --------------------------------------------------------------------------------------------
  190. - (void)testUrl
  191. {
  192. self.login.enabled = NO;
  193. self.loadingBaseUrl.hidden = NO;
  194. // Check whether baseUrl contain protocol. If not add https:// by default.
  195. if(![self.baseUrl.text hasPrefix:@"https"] && ![self.baseUrl.text hasPrefix:@"http"]) {
  196. self.baseUrl.text = [NSString stringWithFormat:@"https://%@",self.baseUrl.text];
  197. }
  198. // Remove trailing slash
  199. if ([self.baseUrl.text hasSuffix:@"/"])
  200. self.baseUrl.text = [self.baseUrl.text substringToIndex:[self.baseUrl.text length] - 1];
  201. // add status.php for valid test url
  202. NSString *urlTest = [self.baseUrl.text stringByAppendingString:k_serverStatus];
  203. // Remove stored cookies
  204. NSHTTPCookieStorage *storage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
  205. for (NSHTTPCookie *cookie in [storage cookies])
  206. {
  207. [storage deleteCookie:cookie];
  208. }
  209. NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlTest] cachePolicy:0 timeoutInterval:20.0];
  210. [request addValue:[CCUtility getUserAgent] forHTTPHeaderField:@"User-Agent"];
  211. [request addValue:@"true" forHTTPHeaderField:@"OCS-APIRequest"];
  212. NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
  213. NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
  214. NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler: ^(NSData *data, NSURLResponse *response, NSError *error) {
  215. dispatch_async(dispatch_get_main_queue(), ^{
  216. self.loadingBaseUrl.hidden = YES;
  217. self.login.enabled = YES;
  218. if (error) {
  219. if ([error code] == NSURLErrorServerCertificateUntrusted) {
  220. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:self delegate:self];
  221. } else {
  222. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_connection_error_", nil) message:[error localizedDescription] preferredStyle:UIAlertControllerStyleAlert];
  223. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {}];
  224. [alertController addAction:okAction];
  225. [self presentViewController:alertController animated:YES completion:nil];
  226. }
  227. } else {
  228. [self serverStatus:data];
  229. // Login Flow
  230. if (_user.hidden && _password.hidden && versionMajor >= k_flow_version_available) {
  231. appDelegate.activeLoginWeb = [CCLoginWeb new];
  232. appDelegate.activeLoginWeb.loginType = _loginType;
  233. appDelegate.activeLoginWeb.delegate = self;
  234. appDelegate.activeLoginWeb.urlBase = self.baseUrl.text;
  235. [appDelegate.activeLoginWeb presentModalWithDefaultTheme:self];
  236. }
  237. // NO Login Flow available
  238. if (versionMajor < k_flow_version_available) {
  239. [self.loginTypeView setHidden:YES];
  240. _imageUser.hidden = NO;
  241. _user.hidden = NO;
  242. _imagePassword.hidden = NO;
  243. _password.hidden = NO;
  244. [_user becomeFirstResponder];
  245. }
  246. }
  247. });
  248. }];
  249. [task resume];
  250. }
  251. - (void)trustedCerticateAccepted
  252. {
  253. NSLog(@"[LOG] Certificate trusted");
  254. }
  255. - (void)trustedCerticateDenied
  256. {
  257. if (_loginType == k_login_Modify_Password)
  258. [self handleAnnulla:self];
  259. }
  260. -(void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential * _Nullable))completionHandler
  261. {
  262. // The pinnning check
  263. if ([[CCCertificate sharedManager] checkTrustedChallenge:challenge]) {
  264. completionHandler(NSURLSessionAuthChallengeUseCredential, [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust]);
  265. } else {
  266. completionHandler(NSURLSessionAuthChallengePerformDefaultHandling, nil);
  267. }
  268. }
  269. - (void)serverStatus:(NSData *)data
  270. {
  271. serverProductName = @"";
  272. serverVersion = @"0.0.0";
  273. serverVersionString = @"0.0.0";
  274. versionMajor = 0;
  275. versionMicro = 0;
  276. versionMinor = 0;
  277. NSError *error;
  278. NSDictionary *jsongParsed = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
  279. if (error)
  280. return;
  281. serverProductName = [jsongParsed valueForKey:@"productname"];
  282. serverVersion = [jsongParsed valueForKey:@"version"];
  283. serverVersionString = [jsongParsed valueForKey:@"versionstring"];
  284. NSArray *arrayVersion = [serverVersionString componentsSeparatedByString:@"."];
  285. if (arrayVersion.count >= 3) {
  286. versionMajor = [arrayVersion[0] integerValue];
  287. versionMicro = [arrayVersion[1] integerValue];
  288. versionMinor = [arrayVersion[2] integerValue];
  289. }
  290. }
  291. #pragma --------------------------------------------------------------------------------------------
  292. #pragma mark == TextField ==
  293. #pragma --------------------------------------------------------------------------------------------
  294. -(void)textFieldDidBeginEditing:(UITextField *)textField
  295. {
  296. if (textField == self.password) {
  297. self.toggleVisiblePassword.hidden = NO;
  298. self.password.defaultTextAttributes = @{NSFontAttributeName: [UIFont systemFontOfSize:14.0f], NSForegroundColorAttributeName:[NCBrandColor sharedInstance].customerText};
  299. }
  300. }
  301. -(void)textFieldDidEndEditing:(UITextField *)textField
  302. {
  303. if (textField == self.password) {
  304. self.toggleVisiblePassword.hidden = YES;
  305. self.password.defaultTextAttributes = @{NSFontAttributeName: [UIFont systemFontOfSize:14.0f], NSForegroundColorAttributeName:[NCBrandColor sharedInstance].customerText};
  306. }
  307. }
  308. #pragma --------------------------------------------------------------------------------------------
  309. #pragma mark === CCLoginDelegateWeb ===
  310. #pragma --------------------------------------------------------------------------------------------
  311. - (void)loginSuccess:(NSInteger)loginType
  312. {
  313. [self.delegate loginSuccess:_loginType];
  314. }
  315. - (void)loginWebClose
  316. {
  317. appDelegate.activeLoginWeb = nil;
  318. [self dismissViewControllerAnimated:YES completion:nil];
  319. }
  320. #pragma --------------------------------------------------------------------------------------------
  321. #pragma mark == Action ==
  322. #pragma --------------------------------------------------------------------------------------------
  323. - (void)loginPreferredProviders
  324. {
  325. // [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NCBrandOptions sharedInstance].linkLoginProvider]];
  326. appDelegate.activeLoginWeb = [CCLoginWeb new];
  327. appDelegate.activeLoginWeb.loginType = _loginType;
  328. appDelegate.activeLoginWeb.delegate = self;
  329. appDelegate.activeLoginWeb.urlBase = [[NCBrandOptions sharedInstance] loginPreferredProviders];
  330. [appDelegate.activeLoginWeb presentModalWithDefaultTheme:self];
  331. }
  332. - (IBAction)handlebaseUrlchange:(id)sender
  333. {
  334. if ([self.baseUrl.text length] > 0 && !_user.hidden && !_password.hidden)
  335. [self performSelector:@selector(testUrl) withObject:nil];
  336. }
  337. - (IBAction)handleButtonLogin:(id)sender
  338. {
  339. if ([self.baseUrl.text length] > 0 && _user.hidden && _password.hidden) {
  340. [self testUrl];
  341. return;
  342. }
  343. if ([self.baseUrl.text length] > 0 && [self.user.text length] && [self.password.text length]) {
  344. // remove last char if /
  345. if ([[self.baseUrl.text substringFromIndex:[self.baseUrl.text length] - 1] isEqualToString:@"/"])
  346. self.baseUrl.text = [self.baseUrl.text substringToIndex:[self.baseUrl.text length] - 1];
  347. NSString *url = self.baseUrl.text;
  348. NSString *user = self.user.text;
  349. NSString *password = self.password.text;
  350. OCnetworking *ocNetworking = [[OCnetworking alloc] initWithDelegate:self metadataNet:nil withUser:user withUserID:user withPassword:password withUrl:nil];
  351. self.login.enabled = NO;
  352. self.loadingBaseUrl.hidden = NO;
  353. [ocNetworking checkServer:[NSString stringWithFormat:@"%@%@", url, k_webDAV] success:^{
  354. // account
  355. NSString *account = [NSString stringWithFormat:@"%@ %@", user, url];
  356. if (_loginType == k_login_Modify_Password) {
  357. // Change Password
  358. tableAccount *tbAccount = [[NCManageDatabase sharedInstance] setAccountPassword:account password:password];
  359. // Setting appDelegate active account
  360. [appDelegate settingActiveAccount:tbAccount.account activeUrl:tbAccount.url activeUser:tbAccount.user activeUserID:tbAccount.userID activePassword:tbAccount.password];
  361. [self.delegate loginSuccess:_loginType];
  362. [self dismissViewControllerAnimated:YES completion:nil];
  363. } else {
  364. [[NCManageDatabase sharedInstance] deleteAccount:account];
  365. [[NCManageDatabase sharedInstance] addAccount:account url:url user:user password:password loginFlow:false];
  366. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] setAccountActive:account];
  367. // Setting appDelegate active account
  368. [appDelegate settingActiveAccount:tableAccount.account activeUrl:tableAccount.url activeUser:tableAccount.user activeUserID:tableAccount.userID activePassword:tableAccount.password];
  369. [self.delegate loginSuccess:_loginType];
  370. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 1 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  371. [self dismissViewControllerAnimated:YES completion:nil];
  372. });
  373. }
  374. } failure:^(NSString *message, NSInteger errorCode) {
  375. if (errorCode != NSURLErrorServerCertificateUntrusted) {
  376. NSString *messageAlert = [NSString stringWithFormat:@"%@.\n%@", NSLocalizedStringFromTable(@"_not_possible_connect_to_server_", @"Error", nil), message];
  377. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_error_", nil) message:messageAlert preferredStyle:UIAlertControllerStyleAlert];
  378. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {}];
  379. [alertController addAction:okAction];
  380. [self presentViewController:alertController animated:YES completion:nil];
  381. }
  382. self.login.enabled = YES;
  383. self.loadingBaseUrl.hidden = YES;
  384. }];
  385. }
  386. }
  387. - (IBAction)handleAnnulla:(id)sender
  388. {
  389. [self dismissViewControllerAnimated:YES completion:nil];
  390. }
  391. - (IBAction)handleToggleVisiblePassword:(id)sender
  392. {
  393. NSString *currentPassword = self.password.text;
  394. self.password.secureTextEntry = ! self.password.secureTextEntry;
  395. self.password.text = @"";
  396. self.password.text = currentPassword;
  397. self.password.defaultTextAttributes = @{NSFontAttributeName: [UIFont systemFontOfSize:14.0f], NSForegroundColorAttributeName: [NCBrandColor sharedInstance].customerText};
  398. }
  399. - (IBAction)handleLoginTypeView:(id)sender
  400. {
  401. if (_user.hidden && _password.hidden) {
  402. _imageUser.hidden = NO;
  403. _user.hidden = NO;
  404. _imagePassword.hidden = NO;
  405. _password.hidden = NO;
  406. [self.loginTypeView setTitle:NSLocalizedString(@"_web_login_", nil) forState:UIControlStateNormal];
  407. } else {
  408. _imageUser.hidden = YES;
  409. _user.hidden = YES;
  410. _imagePassword.hidden = YES;
  411. _password.hidden = YES;
  412. [self.loginTypeView setTitle:NSLocalizedString(@"_traditional_login_", nil) forState:UIControlStateNormal];
  413. }
  414. }
  415. @end