CCLogin.m 15 KB

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