LoginViewController.m 18 KB

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