LoginViewController.m 17 KB

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