LoginViewController.m 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547
  1. //
  2. // LoginViewController.m
  3. // kneet
  4. //
  5. // Created by Jason Lee on 2/4/15.
  6. // Copyright (c) 2015 ntels. All rights reserved.
  7. //
  8. @import QuartzCore;
  9. #import "RequestHandler.h"
  10. #import "CustomTextField.h"
  11. #import "CustomButton.h"
  12. #import "JDJSONModel.h"
  13. #import "LoginModel.h"
  14. #import "LoginViewController.h"
  15. #import "CustomLabel.h"
  16. #import "CustomCheckBox.h"
  17. #import "KeychainItemWrapper.h"
  18. #import "NewMobileViewController.h"
  19. #import "ValidateUtil.h"
  20. #import "CustomAlertView.h"
  21. #import "CustomImageView.h"
  22. #import "PwdPopupView.h"
  23. //#import "MobilesOverViewController.h"
  24. //#import "InvitationListViewController.h"
  25. /**
  26. ID / PW Input Box Text Color
  27. - 기본 : kUITextColor01
  28. - Hint : kUITextColor03
  29. - Disable : kUITextColor06
  30. 로그인 유지 / 아이디 저장 Text Color : kUITextColor01
  31. 아이디 찾기 / 비밀번호 찾기 / 회원가입하기 Text Color
  32. - 아이디 찾기,비밀번호 찾기 : kUITextColor01
  33. - 회원가입 하기 : kUITextColor04
  34. **/
  35. @interface LoginViewController () <CustomTextFieldDelegate> {
  36. }
  37. @end
  38. #pragma mark - Class Definition
  39. @implementation LoginViewController
  40. - (void)viewDidLoad {
  41. [super viewDidLoad];
  42. // Do any additional setup after loading the view.
  43. [self initUI];
  44. [self prepareViewDidLoad];
  45. }
  46. - (void)initUI {
  47. [self.btnLogin setBackgroundImage:[UIImage imageNamed:@"img_btn_common_active"] forState:UIControlStateNormal capInsets:UIEdgeInsetsMake(kfTopInset,kfRightInset,kfBottomInset,kfLeftInset)];
  48. [self.btnLogin setBackgroundImage:[UIImage imageNamed:@"img_btn_common_press"] forState:UIControlStateHighlighted capInsets:UIEdgeInsetsMake(kfTopInset,kfRightInset,kfBottomInset,kfLeftInset)];
  49. [self.btnLogin setBackgroundImage:[UIImage imageNamed:@"img_btn_common_disable"] forState:UIControlStateDisabled capInsets:UIEdgeInsetsMake(kfTopInset,kfRightInset,kfBottomInset,kfLeftInset)];
  50. [self.lblFindId setHidden:YES];
  51. CGRect screen = [UIScreen mainScreen].bounds;
  52. if (screen.size.height == 480) {//iphone4s
  53. [_imgvBg setImage:[UIImage imageNamed:@"img_login_bg_4inch"]];
  54. } if (screen.size.height == 667.0f) {//iphone6
  55. _constraintLeftPadding.constant *= 1.25;
  56. _constraintRightPadding.constant *= 1.25;
  57. } else if (screen.size.height == 736.0f) {//iphone6 plus
  58. _constraintLeftPadding.constant *= 1.5;
  59. _constraintRightPadding.constant *= 1.5;
  60. }
  61. // [self.view layoutIfNeeded];
  62. _txtEmail.customTextFieldSuperview = CustomTextFieldSuperviewIsScrollView;
  63. _txtPasswd.customTextFieldSuperview = CustomTextFieldSuperviewIsScrollView;
  64. _txtPasswd.secureTextEntry = YES;
  65. _txtEmail.keyboardType = UIKeyboardTypeDefault;
  66. _txtPasswd.keyboardType = UIKeyboardTypeDefault;
  67. _txtEmail.returnKeyType = UIReturnKeyNext;
  68. _txtPasswd.returnKeyType = UIReturnKeyDone;
  69. _txtPasswd.delegate = self;
  70. //Localization
  71. [_chkAutoLogin setTitle:NSLocalizedString(@"로그인 유지", @"로그인 유지") forState:UIControlStateNormal];
  72. [_chkIdSave setTitle:NSLocalizedString(@"아이디 저장", @"아이디 저장") forState:UIControlStateNormal];
  73. _txtEmail.placeholder = NSLocalizedString(@"아이디", @"아이디");
  74. _txtPasswd.placeholder = NSLocalizedString(@"비밀번호", @"비밀번호");
  75. _lblSignUp.text = NSLocalizedString(@"회원가입하기", @"회원가입하기");
  76. _lblFindId.text = NSLocalizedString(@"아이디/비번찾기", @"아이디/비번찾기");
  77. // [_lblSignUp setUnderLine:_lblSignUp.text];
  78. [_lblSignUp addTouchEventHandler:^(id label) {
  79. [self lblSignUpTouched];
  80. }];
  81. [_lblFindId setUnderLine:_lblFindId.text];
  82. [_lblFindId addTouchEventHandler:^(id label) {
  83. [self lblFindIdTouched];
  84. }];
  85. }
  86. - (void)prepareViewDidLoad {
  87. [RequestHandler handler].authorization = nil;
  88. _chkAutoLogin.checked = [[[JDFacade facade] objectForKeyFromUserDefaults:USDEF_APP_AUTO_LOGIN] boolValue];
  89. _chkIdSave.checked = [[[JDFacade facade] objectForKeyFromUserDefaults:USDEF_APP_SAVE_ID] boolValue];
  90. if (_chkAutoLogin.checked) {
  91. [self requestAutoLogin];
  92. // _txtEmail.text = [[JDFacade facade] objectForKeyFromKeychain:USDEF_SESSION_LOGIN_ID];
  93. // _txtPasswd.text = [[JDFacade facade] objectForKeyFromKeychain:USDEF_SESSION_LOGIN_PWD];
  94. //
  95. // [self btnLogInTouched:_btnLogin];
  96. }
  97. if (_chkIdSave.checked) {
  98. NSLog(@"Save ID : %@", [[JDFacade facade] objectForKeyFromKeychain:USDEF_SESSION_LOGIN_ID]);
  99. _txtEmail.text = [[JDFacade facade] objectForKeyFromKeychain:USDEF_SESSION_LOGIN_ID];
  100. }
  101. }
  102. #pragma mark - Main Logic
  103. - (void)requestLogin {
  104. NSDictionary *param = @{@"member_id": [_txtEmail.text trim],
  105. @"password": [_txtPasswd.text trim],
  106. @"os_type": MOBILE_DEVICE_TYPE,
  107. @"device_token": [JDFacade facade].APNSToken ? [JDFacade facade].APNSToken : ksEmptyString,
  108. @"message_type": @"auth"};
  109. [self sendDataToSocket:param];
  110. [[JDFacade facade] loadIndicator:YES allowUserInteraction:NO];
  111. // [[RequestHandler handler] sendAsyncPostRequestAPIPath:API_POST_SIGN_IN parameters:param modelClass:[LoginModel class] completion:^(id responseObject) {
  112. // if (!responseObject) {//응답결과가 잘못되었거나 없을 경우,
  113. // return;
  114. // }
  115. //
  116. // LoginModel *loginInfo = (LoginModel *)responseObject;
  117. // NSLog(@"%@", loginInfo);
  118. //
  119. // if (loginInfo) {//API 성공 ,함
  120. // [self actionForLoginSucceed:loginInfo];
  121. //
  122. // }
  123. // } failure:^(id errorObject) {
  124. // JDErrorModel *error = (JDErrorModel *)errorObject;
  125. //
  126. // if ([error.errorCode isEqualToString:API_RESPONSE_UNAUTHORIZED_EMAIL]) {//이메일 아이디 인증이 안 된 계정
  127. // [self actionForWaiting];
  128. // } else if ([error.errorCode isEqualToString:API_RESPONSE_UNAUTHORIZED_DEVICE]) {//새로운 단말 인증 필요
  129. // [self actionForNeedsRegisteringNewDevice:error.nickname];
  130. // } else if ([error.errorCode isEqualToString:API_RESPONSE_MOBILES_OVER]) {//단말 초과
  131. // [self actionForMobilesOver:error.deviceList];
  132. // } else {
  133. // [[JDFacade facade] alert:error.errorMessage];
  134. // }
  135. // }];
  136. }
  137. //자동로그인 요청
  138. - (void)requestAutoLogin {;
  139. //parameters
  140. // NSString *memberId = [[JDFacade facade] objectForKeyFromKeychain:USDEF_SESSION_LOGIN_ID];
  141. // NSString *authToken = [[JDFacade facade] objectForKeyFromKeychain:USDEF_SESSION_AUTOTOKEN];
  142. LoginModel *tmpInfo = [[LoginModel alloc] init];
  143. tmpInfo.memberId = [[JDFacade facade] objectForKeyFromKeychain:USDEF_SESSION_LOGIN_ID];
  144. tmpInfo.authToken = [[JDFacade facade] objectForKeyFromKeychain:USDEF_SESSION_AUTOTOKEN];
  145. // if ([authToken isEmptyString]) {
  146. // return;
  147. // }
  148. // NSLog(@"%@", authToken);
  149. // [RequestHandler handler].authorization = authToken;
  150. NSDictionary *parameter = @{@"Authorization": tmpInfo.authorization,
  151. @"device_token": [JDFacade facade].APNSToken ? [JDFacade facade].APNSToken : ksEmptyString,
  152. @"os_type": MOBILE_DEVICE_TYPE,
  153. @"message_type": @"auth.auto"};
  154. [self sendDataToSocket:parameter];
  155. [[JDFacade facade] loadIndicator:YES allowUserInteraction:NO];
  156. // NSString *path = [NSString stringWithFormat:API_GET_SIGN_IN_AUTO];
  157. //
  158. // [[RequestHandler handler] sendAsyncGetRequestAPIPath:path parameters:parameter modelClass:[LoginModel class] completion:^(id responseObject) {
  159. // if (!responseObject) {//응답결과가 잘못되었거나 없을 경우,
  160. // return;
  161. // }
  162. //
  163. // LoginModel *loginInfo = (LoginModel *)responseObject;
  164. //
  165. // if (loginInfo) {//API 성공 ,함
  166. // [self actionForLoginSucceed:loginInfo];
  167. //
  168. // }
  169. // } failure:^(id errorObject) {
  170. // JDErrorModel *error = (JDErrorModel *)errorObject;
  171. //
  172. // if ([error.errorCode isEqualToString:API_RESPONSE_UNAUTHORIZED_DEVICE]) {//새로운 단말 인증 필요
  173. // [self actionForNeedsRegisteringNewDevice:error.nickname];
  174. // } else {
  175. // [[JDFacade facade] alert:error.errorMessage];
  176. // }
  177. // }];
  178. }
  179. //인증 메일 재요청
  180. - (void)requestAuthMail {
  181. //parameters
  182. NSDictionary *parameter = @{@"email_id": [JDFacade facade].tmpEmailId};
  183. NSString *path = [NSString stringWithFormat:API_POST_AUTH_MAIL];
  184. [[RequestHandler handler] sendAsyncPostRequestAPIPath:path parameters:parameter modelClass:[JDJSONModel class] completion:^(id responseObject) {
  185. if (!responseObject) {//응답결과가 잘못되었거나 없을 경우,
  186. return;
  187. }
  188. JDJSONModel *result = (JDJSONModel *) responseObject;
  189. if (result) {//API 성공 ,
  190. [[JDFacade facade] toast:NSLocalizedString(@"인증 메일이 발송되었습니다", @"인증 메일이 발송되었습니다")];
  191. }
  192. } failure:^(id errorObject) {
  193. JDErrorModel *error = (JDErrorModel *)errorObject;
  194. [[JDFacade facade] alert:error.errorMessage];
  195. }];
  196. }
  197. //로그인 이후 처리.
  198. - (void)actionForLoginSucceed:(LoginModel *)loginInfo {
  199. if (loginInfo) {//API 성공함
  200. [JDFacade facade].loginUser = loginInfo;
  201. // [JDFacade facade].loginUser.gradeCode = KNEET_MEMBER_MASTER;
  202. // [JDFacade facade].loginUser.level = 90;
  203. NSLog(@"%@", [JDFacade facade].loginUser);
  204. if ([[JDFacade facade].loginUser.emailId isEqualToString:[JDFacade facade].tmpEmailId]) {
  205. [JDFacade facade].tmpEmailId = ksEmptyString;
  206. }
  207. if ([[JDFacade facade].loginUser.emailId isEqualToString:[JDFacade facade].loginUser.newEmailId]) {//이메일 변경 요청 중
  208. [JDFacade facade].loginUser.newEmailId = ksEmptyString;
  209. }
  210. [RequestHandler handler].authorization = loginInfo.authorization;
  211. [[JDFacade facade] storeObjectToUserDefaults:@(_chkAutoLogin.checked) forKey:USDEF_APP_AUTO_LOGIN];
  212. [[JDFacade facade] storeObjectToUserDefaults:@(_chkIdSave.checked) forKey:USDEF_APP_SAVE_ID];
  213. if (_chkAutoLogin.checked) {//자동로그인 설정 시, 인증 토큰 저장
  214. [[JDFacade facade] storeObjectToKeychain:loginInfo.memberId forKey:USDEF_SESSION_LOGIN_ID];
  215. [[JDFacade facade] storeObjectToKeychain:loginInfo.authToken forKey:USDEF_SESSION_AUTOTOKEN];
  216. } else {
  217. [[JDFacade facade] removeObjectAtKeychain:USDEF_SESSION_AUTOTOKEN];
  218. [[JDFacade facade] removeObjectAtKeychain:USDEF_SESSION_LOGIN_PWD];
  219. if (!_chkIdSave.checked) {
  220. [[JDFacade facade] removeObjectAtKeychain:USDEF_SESSION_LOGIN_ID];
  221. }
  222. }
  223. if (_chkIdSave.checked) {
  224. [[JDFacade facade] storeObjectToKeychain:[_txtEmail.text trim] forKey:USDEF_SESSION_LOGIN_ID];
  225. } else {
  226. if (!_chkAutoLogin.checked) {
  227. [[JDFacade facade] removeObjectAtKeychain:USDEF_SESSION_LOGIN_ID];
  228. }
  229. }
  230. [self actionAfterLogin];
  231. }
  232. }
  233. //홈그룹 체크 및 대시보드 이동
  234. - (void)actionAfterLogin {
  235. if ([[JDFacade facade].loginUser.invitationsCount integerValue] > 0) {
  236. [self actionForInvitation];
  237. return;
  238. }
  239. [self actionAfterInvitaion];
  240. }
  241. //초대알림 화면으로 이동
  242. - (void)actionForInvitation {
  243. [[JDFacade facade] loadInvitationView];
  244. }
  245. //초대화면 액션이 종료된 후,
  246. - (void)actionAfterInvitaion {
  247. //메인으로 이동
  248. [self gotoMainView];
  249. }
  250. //새로운 단말 인증 필요 - 화면 이동
  251. - (void)actionForNeedsRegisteringNewDevice:(NSString *)nickname {
  252. NewMobileViewController *vc = (NewMobileViewController *)[CommonUtil instantiateViewControllerWithIdentifier:@"NewMobileViewController" storyboardName:@"SignUp"];
  253. vc.checkedAutoLogin = _chkAutoLogin.checked;
  254. vc.nickname = nickname;
  255. [[JDFacade facade] presentViewControllerByPush:vc pvc:self];
  256. }
  257. //단말대수 초과
  258. - (void)actionForMobilesOver:(NSArray<MobileDeviceModel> *)deviceList {
  259. //SHA-2
  260. }
  261. //인증대기중 - 화면 이동
  262. - (void)actionForWaiting {
  263. NSString *message1 = [NSString stringWithFormat:@"%@에서\n인증 메일을 확인하세요", [JDFacade facade].tmpEmailId];
  264. NSString *message2 = @"\n\n메일을 확인할 수 없는 경우에는\n스팸 메일함을 확인해보세요";
  265. CustomAlertView *alert = [[CustomAlertView alloc] initWithTitle:@"메일을 확인하세요" message:[NSString stringWithFormat:@"%@%@", message1, message2] delegate:nil OKButtonTitle:@"확인" cancelButtonTitle:nil];
  266. [alert.lblMessage1 setColor:kUITextColor02 text:message1];
  267. [alert showWithCompletion:^(CustomAlertView *alertView, NSInteger buttonIndex) {
  268. if (buttonIndex == 1) {//재발송
  269. [self requestAuthMail];
  270. }
  271. }];
  272. }
  273. - (void)gotoMainView {
  274. // UIViewController *vc = [CommonUtil instantiateViewControllerWithIdentifier:@"SignUpCompleteViewController" storyboardName:@"SignUp"];
  275. UIViewController *vc = [CommonUtil instantiateViewControllerWithIdentifier:@"MainViewController" storyboardName:@"Main"];
  276. [JDFacade facade].mainViewController = (MainViewController *)vc;
  277. [[JDFacade facade].appDelegate.window setRootViewController:vc];
  278. }
  279. - (void)requestLogout {
  280. NSDictionary *param = @{API_AUTHORIZATION_KEY: [[JDFacade facade].loginUser authorization],
  281. @"message_type": @"auth.out"};
  282. [self sendDataToSocket:param];
  283. //parameters
  284. // [self actionAfterLogout];
  285. // NSString *path = [NSString stringWithFormat:API_POST_SIGN_OUT];
  286. //
  287. // [[RequestHandler handler] sendAsyncGetRequestAPIPath:path parameters:nil modelClass:[JDJSONModel class] completion:^(id responseObject) {
  288. // [self actionAfterLogout];
  289. //
  290. // } failure:^(id errorObject) {
  291. // JDErrorModel *error = (JDErrorModel *)errorObject;
  292. // [[JDFacade facade] alert:error.errorMessage];
  293. // }];
  294. }
  295. - (void)actionAfterLogout {
  296. //자동 로그인 설정 - 취소
  297. [[JDFacade facade] storeObjectToUserDefaults:@(NO) forKey:USDEF_APP_AUTO_LOGIN];
  298. [[JDFacade facade] removeObjectAtKeychain:USDEF_SESSION_AUTOTOKEN];
  299. if (![[[JDFacade facade] objectForKeyFromUserDefaults:USDEF_APP_SAVE_ID] boolValue]) {
  300. [[JDFacade facade] removeObjectAtKeychain:USDEF_SESSION_LOGIN_ID];
  301. }
  302. [JDFacade facade].loginUser = nil;
  303. [self closeSocket];
  304. //root view 변경
  305. [[JDFacade facade].appDelegate.window setRootViewController:self];
  306. }
  307. #pragma mark - UI Events
  308. - (IBAction)btnLogInTouched:(id)sender {
  309. #ifdef DEBUG_MODE
  310. if ([_txtEmail.text isEmptyString]) {
  311. _txtEmail.text = @"asura77";
  312. }
  313. if ([_txtPasswd.text isEmptyString]) {
  314. _txtPasswd.text = @"09767955";
  315. }
  316. #endif
  317. // TODO : 아이디 형식 검사할것
  318. // if (![ValidateUtil validateTextfiled:_txtEmail type:ValidateTypeEmail title:@"이메일" ]) {
  319. // return;
  320. // }
  321. if (![ValidateUtil validateTextfiled:_txtEmail type:ValidateTypeNull title:@"비밀번호" ]) {
  322. return;
  323. }
  324. [JDFacade facade].tmpEmailId = [_txtEmail.text trim];
  325. [JDFacade facade].tmpPassword = [_txtPasswd.text trim];
  326. [self requestLogin];
  327. }
  328. //회원가입 호출
  329. - (void)lblSignUpTouched {
  330. UIViewController *vc = [CommonUtil instantiateViewControllerWithIdentifier:@"AgreementViewController" storyboardName:@"SignUp"];
  331. UINavigationController *m_navi =[[UINavigationController alloc]initWithRootViewController:vc];
  332. [self presentViewController:m_navi animated:YES completion:nil];
  333. }
  334. - (void)lblFindIdTouched {
  335. UIViewController *vc = [CommonUtil instantiateViewControllerWithIdentifier:@"ResetPwdViewController" storyboardName:@"SignUp"];
  336. [self presentViewController:vc animated:YES completion:nil];
  337. }
  338. - (IBAction)btnIdFindTouched:(id)sender {
  339. NSLog(@"아이디 찾기");
  340. }
  341. - (IBAction)btnPwFindTouched:(id)sender {
  342. NSLog(@"비밀번호 찾기");
  343. }
  344. #pragma mark - CustomTextField
  345. - (BOOL)textFieldShouldReturn:(UITextField *)textField {
  346. if ([textField isEqual:_txtPasswd])
  347. {
  348. [self btnLogInTouched:nil];
  349. }
  350. if ([textField isEqual:_txtEmail])
  351. {
  352. [_txtPasswd becomeFirstResponder];
  353. }
  354. return YES;
  355. }
  356. #pragma mark - SocketService
  357. - (void) socketDidReceiveMessage:(id)message info:(NSDictionary *)info
  358. {
  359. SocketModel *result = (SocketModel *)message;
  360. NSLog(@"Result Info : %@", result);
  361. SWITCH(result.messageType)
  362. {
  363. CASE (@"auth")
  364. {
  365. [[JDFacade facade] loadIndicator:NO allowUserInteraction:YES];
  366. if (result.isSuccess) {
  367. LoginModel *loginInfo = [[LoginModel alloc] initWithDictionary:info error:nil];;
  368. if (loginInfo) {//API 성공 ,함
  369. [self actionForLoginSucceed:loginInfo];
  370. }
  371. }
  372. else
  373. {
  374. [[JDFacade facade] toast:result.resultMsg];
  375. }
  376. break;
  377. }
  378. CASE (@"auth.auto")
  379. {
  380. [[JDFacade facade] loadIndicator:NO allowUserInteraction:YES];
  381. if (result.isSuccess) {
  382. LoginModel *loginInfo = [[LoginModel alloc] initWithDictionary:info error:nil];;
  383. if (loginInfo) {//API 성공 ,함
  384. loginInfo.memberId = [[JDFacade facade] objectForKeyFromKeychain:USDEF_SESSION_LOGIN_ID];
  385. loginInfo.authToken = [[JDFacade facade] objectForKeyFromKeychain:USDEF_SESSION_AUTOTOKEN];
  386. [self actionForLoginSucceed:loginInfo];
  387. }
  388. }
  389. else
  390. {
  391. [[JDFacade facade] toast:result.resultMsg];
  392. }
  393. break;
  394. }
  395. CASE(@"auth.out")
  396. {
  397. if (result.isSuccess) {
  398. [self actionAfterLogout];
  399. }
  400. else {
  401. NSLog(@"Result Info : %@", result);
  402. }
  403. }
  404. DEFAULT
  405. {
  406. break;
  407. }
  408. }
  409. }
  410. - (void) socketDidFailWithError:(NSError *)error {
  411. [[JDFacade facade] loadIndicator:NO allowUserInteraction:YES];
  412. }
  413. #pragma mark - MemoryWarning
  414. - (void)didReceiveMemoryWarning
  415. {
  416. [super didReceiveMemoryWarning];
  417. // Dispose of any resources that can be recreated.
  418. }
  419. @end