CCLogin.m 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443
  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. @interface CCLogin ()
  28. {
  29. UIView *rootView;
  30. }
  31. @end
  32. @implementation CCLogin
  33. - (void)viewDidLoad
  34. {
  35. [super viewDidLoad];
  36. self.imageBrand.image = [UIImage imageNamed:@"loginLogo"];
  37. self.login.backgroundColor = [NCBrandColor sharedInstance].customer;
  38. // Bottom label
  39. self.bottomLabel.text = NSLocalizedString([NCBrandOptions sharedInstance].textLoginProvider, nil);
  40. self.bottomLabel.userInteractionEnabled = YES;
  41. if ([NCBrandOptions sharedInstance].disable_linkLoginProvider) {
  42. self.bottomLabel.hidden = YES;
  43. }
  44. UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tabBottomLabel)];
  45. [self.bottomLabel addGestureRecognizer:tapGesture];
  46. 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))) {
  47. // Portrait
  48. self.bottomLabel.hidden = NO;
  49. } else {
  50. // Landscape
  51. self.bottomLabel.hidden = YES;
  52. }
  53. self.annulla.tintColor = [NCBrandColor sharedInstance].customer;
  54. [self.baseUrl setDelegate:self];
  55. [self.password setDelegate:self];
  56. [self.user setDelegate:self];
  57. [self.baseUrl setFont:[UIFont systemFontOfSize:13]];
  58. [self.user setFont:[UIFont systemFontOfSize:13]];
  59. [self.password setFont:[UIFont systemFontOfSize:13]];
  60. self.imageBaseUrl.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"loginURL"] color:[NCBrandColor sharedInstance].customer];
  61. self.imageUser.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"loginUser"] color:[NCBrandColor sharedInstance].customer];
  62. self.imagePassword.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"loginPassword"] color:[NCBrandColor sharedInstance].customer];
  63. self.loadingBaseUrl.image = [UIImage animatedImageWithAnimatedGIFURL:[[NSBundle mainBundle] URLForResource: @"loading" withExtension:@"gif"]];
  64. self.loadingBaseUrl.hidden = YES;
  65. // Brand
  66. if ([NCBrandOptions sharedInstance].disable_request_login_url) {
  67. _baseUrl.text = [NCBrandOptions sharedInstance].loginBaseUrl;
  68. _imageBaseUrl.hidden = YES;
  69. _baseUrl.hidden = YES;
  70. }
  71. if (_loginType == loginAdd) {
  72. }
  73. if (_loginType == loginAddForced) {
  74. _annulla.hidden = YES;
  75. }
  76. if (_loginType == loginModifyPasswordUser) {
  77. _baseUrl.text = app.activeUrl;
  78. _baseUrl.userInteractionEnabled = NO;
  79. _baseUrl.textColor = [UIColor lightGrayColor];
  80. _user.text = app.activeUser;
  81. _user.userInteractionEnabled = NO;
  82. _user.textColor = [UIColor lightGrayColor];
  83. }
  84. self.baseUrl.placeholder = NSLocalizedString(@"_login_url_", nil);
  85. self.user.placeholder = NSLocalizedString(@"_username_", nil);
  86. self.password.placeholder = NSLocalizedString(@"_password_", nil);
  87. [self.annulla setTitle:NSLocalizedString(@"_cancel_", nil) forState:UIControlStateNormal];
  88. [self.login setTitle:NSLocalizedString(@"_login_", nil) forState:UIControlStateNormal];
  89. }
  90. - (void)viewWillAppear:(BOOL)animated
  91. {
  92. [super viewWillAppear:animated];
  93. // verify URL
  94. if (_loginType == loginModifyPasswordUser && [self.baseUrl.text length] > 0)
  95. [self testUrl];
  96. }
  97. // E' apparsa
  98. - (void)viewDidAppear:(BOOL)animated
  99. {
  100. [super viewDidAppear:animated];
  101. }
  102. - (BOOL)textFieldShouldReturn:(UITextField *)textField
  103. {
  104. [textField resignFirstResponder];
  105. return YES;
  106. }
  107. - (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator
  108. {
  109. [coordinator animateAlongsideTransition:nil completion:^(id<UIViewControllerTransitionCoordinatorContext> context) {
  110. 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))) {
  111. // Portrait
  112. self.bottomLabel.hidden = NO;
  113. } else {
  114. // Landscape
  115. self.bottomLabel.hidden = YES;
  116. }
  117. }];
  118. [super viewWillTransitionToSize:size withTransitionCoordinator:coordinator];
  119. }
  120. #pragma --------------------------------------------------------------------------------------------
  121. #pragma mark == Chech Server URL ==
  122. #pragma --------------------------------------------------------------------------------------------
  123. - (void)testUrl
  124. {
  125. // Use MultiDomain check if this is correct
  126. if ([NCBrandOptions sharedInstance].use_multiDomains == YES) {
  127. BOOL foundDomain = NO;
  128. NSString *message = @"";
  129. for (NSString *domain in [NCBrandOptions sharedInstance].loginBaseUrlMultiDomains) {
  130. message = [NSString stringWithFormat:@"%@ %@", message, domain.lowercaseString];
  131. if ([self.baseUrl.text.lowercaseString containsString:domain.lowercaseString])
  132. foundDomain = YES;
  133. }
  134. if (!foundDomain) {
  135. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_error_", nil) message:[NSString stringWithFormat:@"%@ %@", NSLocalizedString(@"_error_multidomain_", nil), message] preferredStyle:UIAlertControllerStyleAlert];
  136. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  137. self.baseUrl.text = @"";
  138. }]];
  139. [self presentViewController:alertController animated:YES completion:nil];
  140. return;
  141. }
  142. }
  143. self.login.enabled = NO;
  144. self.loadingBaseUrl.hidden = NO;
  145. // Check whether baseUrl contain protocol. If not add https:// by default.
  146. if(![self.baseUrl.text hasPrefix:@"https"] && ![self.baseUrl.text hasPrefix:@"http"]) {
  147. self.baseUrl.text = [NSString stringWithFormat:@"https://%@",self.baseUrl.text];
  148. }
  149. NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:self.baseUrl.text] cachePolicy:0 timeoutInterval:20.0];
  150. [request addValue:[CCUtility getUserAgent] forHTTPHeaderField:@"User-Agent"];
  151. NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
  152. NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
  153. NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler: ^(NSData *data, NSURLResponse *response, NSError *error) {
  154. dispatch_async(dispatch_get_main_queue(), ^{
  155. self.login.enabled = YES;
  156. self.loadingBaseUrl.hidden = YES;
  157. });
  158. if (error != nil) {
  159. NSLog(@"[LOG] Error: %ld - %@",(long)[error code] , [error localizedDescription]);
  160. // self signed certificate
  161. if ([error code] == NSURLErrorServerCertificateUntrusted) {
  162. NSLog(@"[LOG] Error NSURLErrorServerCertificateUntrusted");
  163. dispatch_async(dispatch_get_main_queue(), ^{
  164. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:self delegate:self];
  165. });
  166. } else {
  167. dispatch_async(dispatch_get_main_queue(), ^{
  168. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_connection_error_", nil) message:[error localizedDescription] preferredStyle:UIAlertControllerStyleAlert];
  169. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {}];
  170. [alertController addAction:okAction];
  171. [self presentViewController:alertController animated:YES completion:nil];
  172. });
  173. }
  174. }
  175. }];
  176. [task resume];
  177. }
  178. - (void)trustedCerticateAccepted
  179. {
  180. NSLog(@"[LOG] Certificate trusted");
  181. }
  182. - (void)trustedCerticateDenied
  183. {
  184. if (_loginType == loginModifyPasswordUser)
  185. [self handleAnnulla:self];
  186. }
  187. -(void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential * _Nullable))completionHandler
  188. {
  189. // The pinnning check
  190. if ([[CCCertificate sharedManager] checkTrustedChallenge:challenge]) {
  191. completionHandler(NSURLSessionAuthChallengeUseCredential, [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust]);
  192. } else {
  193. completionHandler(NSURLSessionAuthChallengePerformDefaultHandling, nil);
  194. }
  195. }
  196. #pragma --------------------------------------------------------------------------------------------
  197. #pragma mark == Login ==
  198. #pragma --------------------------------------------------------------------------------------------
  199. - (void)loginCloud
  200. {
  201. self.login.enabled = NO;
  202. self.loadingBaseUrl.hidden = NO;
  203. // remove last char if /
  204. if ([[self.baseUrl.text substringFromIndex:[self.baseUrl.text length] - 1] isEqualToString:@"/"])
  205. self.baseUrl.text = [self.baseUrl.text substringToIndex:[self.baseUrl.text length] - 1];
  206. OCnetworking *ocNet = [[OCnetworking alloc] initWithDelegate:self metadataNet:nil withUser:self.user.text withUserID:self.user.text withPassword:self.password.text withUrl:nil];
  207. NSError *error = [ocNet checkServerSync:[NSString stringWithFormat:@"%@%@", self.baseUrl.text, webDAV]];
  208. if (!error) {
  209. // account
  210. NSString *account = [NSString stringWithFormat:@"%@ %@", self.user.text, self.baseUrl.text];
  211. if (_loginType == loginModifyPasswordUser) {
  212. // Change Password
  213. tableAccount *tbAccount = [[NCManageDatabase sharedInstance] setAccountPassword:account password:self.password.text];
  214. // Setting App active account
  215. [app settingActiveAccount:tbAccount.account activeUrl:tbAccount.url activeUser:tbAccount.user activeUserID:tbAccount.userID activePassword:tbAccount.password];
  216. // Dismiss
  217. [self.delegate loginSuccess:_loginType];
  218. [self dismissViewControllerAnimated:YES completion:nil];
  219. } else {
  220. [[NCManageDatabase sharedInstance] deleteAccount:account];
  221. [[NCManageDatabase sharedInstance] addAccount:account url:self.baseUrl.text user:self.user.text password:self.password.text];
  222. // Read User Profile
  223. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:account];
  224. metadataNet.action = actionGetUserProfile;
  225. [app.netQueue addOperation:[[OCnetworking alloc] initWithDelegate:self metadataNet:metadataNet withUser:self.user.text withUserID:self.user.text withPassword:self.password.text withUrl:self.baseUrl.text]];
  226. }
  227. } else {
  228. if ([error code] != NSURLErrorServerCertificateUntrusted) {
  229. NSString *description = [error.userInfo objectForKey:@"NSLocalizedDescription"];
  230. NSString *message = [NSString stringWithFormat:@"%@.\n%@", NSLocalizedStringFromTable(@"_not_possible_connect_to_server_", @"Error", nil), description];
  231. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_error_", nil) message:message preferredStyle:UIAlertControllerStyleAlert];
  232. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {}];
  233. [alertController addAction:okAction];
  234. [self presentViewController:alertController animated:YES completion:nil];
  235. }
  236. }
  237. self.login.enabled = YES;
  238. self.loadingBaseUrl.hidden = YES;
  239. }
  240. #pragma --------------------------------------------------------------------------------------------
  241. #pragma mark ==== User Profile ====
  242. #pragma --------------------------------------------------------------------------------------------
  243. - (void)getUserProfileFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  244. {
  245. [[NCManageDatabase sharedInstance] deleteAccount:metadataNet.account];
  246. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_error_", nil) message:message preferredStyle:UIAlertControllerStyleAlert];
  247. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {}];
  248. [alertController addAction:okAction];
  249. [self presentViewController:alertController animated:YES completion:nil];
  250. }
  251. - (void)getUserProfileSuccess:(CCMetadataNet *)metadataNet userProfile:(OCUserProfile *)userProfile
  252. {
  253. // Verify if the account already exists
  254. if (userProfile.id.length > 0 && self.baseUrl.text.length > 0 && self.user.text.length > 0) {
  255. tableAccount *accountAlreadyExists = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"url = %@ AND user = %@ AND userID != %@", self.baseUrl.text, userProfile.id, self.user.text]];
  256. if (accountAlreadyExists) {
  257. [[NCManageDatabase sharedInstance] deleteAccount:metadataNet.account];
  258. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_error_", nil) message:[NSString stringWithFormat:NSLocalizedString(@"_account_already_exists_", nil), userProfile.id] preferredStyle:UIAlertControllerStyleAlert];
  259. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {}];
  260. [alertController addAction:okAction];
  261. [self presentViewController:alertController animated:YES completion:nil];
  262. return;
  263. }
  264. }
  265. // Verify if account is a valid account
  266. tableAccount *account = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account = %@", metadataNet.account]];
  267. if (account) {
  268. // Update User (+ userProfile.id)
  269. [[NCManageDatabase sharedInstance] setAccountsUserProfile:userProfile];
  270. // Set this account as default
  271. tableAccount *account = [[NCManageDatabase sharedInstance] setAccountActive:metadataNet.account];
  272. // Setting App active account
  273. [app settingActiveAccount:account.account activeUrl:account.url activeUser:account.user activeUserID:account.userID activePassword:account.password];
  274. // Ok ! Dismiss
  275. [self.delegate loginSuccess:_loginType];
  276. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 1 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  277. [self dismissViewControllerAnimated:YES completion:nil];
  278. });
  279. }
  280. }
  281. #pragma --------------------------------------------------------------------------------------------
  282. #pragma mark == TextField ==
  283. #pragma --------------------------------------------------------------------------------------------
  284. -(void)textFieldDidBeginEditing:(UITextField *)textField
  285. {
  286. if (textField == self.password) {
  287. self.toggleVisiblePassword.hidden = NO;
  288. self.password.defaultTextAttributes = @{NSFontAttributeName: [UIFont systemFontOfSize:14.0f], NSForegroundColorAttributeName: [UIColor darkGrayColor]};
  289. }
  290. }
  291. -(void)textFieldDidEndEditing:(UITextField *)textField
  292. {
  293. if (textField == self.password) {
  294. self.toggleVisiblePassword.hidden = YES;
  295. self.password.defaultTextAttributes = @{NSFontAttributeName: [UIFont systemFontOfSize:14.0f], NSForegroundColorAttributeName: [UIColor darkGrayColor]};
  296. }
  297. }
  298. #pragma --------------------------------------------------------------------------------------------
  299. #pragma mark == Action ==
  300. #pragma --------------------------------------------------------------------------------------------
  301. - (void)tabBottomLabel
  302. {
  303. [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NCBrandOptions sharedInstance].linkLoginProvider]];
  304. }
  305. - (IBAction)handlebaseUrlchange:(id)sender
  306. {
  307. if ([self.baseUrl.text length] > 0)
  308. [self performSelector:@selector(testUrl) withObject:nil];
  309. }
  310. - (IBAction)handleButtonLogin:(id)sender
  311. {
  312. if ([self.baseUrl.text length] > 0 && [self.user.text length] && [self.password.text length])
  313. [self performSelector:@selector(loginCloud) withObject:nil];
  314. }
  315. - (IBAction)handleAnnulla:(id)sender
  316. {
  317. [self dismissViewControllerAnimated:YES completion:nil];
  318. }
  319. - (IBAction)handleToggleVisiblePassword:(id)sender
  320. {
  321. NSString *currentPassword = self.password.text;
  322. self.password.secureTextEntry = ! self.password.secureTextEntry;
  323. self.password.text = @"";
  324. self.password.text = currentPassword;
  325. self.password.defaultTextAttributes = @{NSFontAttributeName: [UIFont systemFontOfSize:14.0f], NSForegroundColorAttributeName: [UIColor darkGrayColor]};
  326. }
  327. @end