LoginViewController.m 16 KB

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