LoginViewController.m 18 KB

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