CCLogin.m 14 KB

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