LoginViewController.m 17 KB

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