CCLogin.m 13 KB

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