CCLogin.m 18 KB

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