// // LoginViewController.m // kneet // // Created by Jason Lee on 2/4/15. // Copyright (c) 2015 ntels. All rights reserved. // @import QuartzCore; #import "RequestHandler.h" #import "CustomTextField.h" #import "CustomButton.h" #import "JDJSONModel.h" #import "LoginModel.h" #import "LoginViewController.h" #import "CustomLabel.h" #import "CustomCheckBox.h" #import "KeychainItemWrapper.h" #import "NewMobileViewController.h" #import "ValidateUtil.h" #import "CustomAlertView.h" #import "CustomImageView.h" #import "PwdPopupView.h" //#import "MobilesOverViewController.h" //#import "InvitationListViewController.h" /** ID / PW Input Box Text Color - 기본 : kUITextColor01 - Hint : kUITextColor03 - Disable : kUITextColor06 로그인 유지 / 아이디 저장 Text Color : kUITextColor01 아이디 찾기 / 비밀번호 찾기 / 회원가입하기 Text Color - 아이디 찾기,비밀번호 찾기 : kUITextColor01 - 회원가입 하기 : kUITextColor04 **/ @interface LoginViewController () { } @end #pragma mark - Class Definition @implementation LoginViewController - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view. [self initUI]; [self prepareViewDidLoad]; } - (void)initUI { [self.btnLogin setBackgroundImage:[UIImage imageNamed:@"img_btn_common_active"] forState:UIControlStateNormal capInsets:UIEdgeInsetsMake(kfTopInset,kfRightInset,kfBottomInset,kfLeftInset)]; [self.btnLogin setBackgroundImage:[UIImage imageNamed:@"img_btn_common_press"] forState:UIControlStateHighlighted capInsets:UIEdgeInsetsMake(kfTopInset,kfRightInset,kfBottomInset,kfLeftInset)]; [self.btnLogin setBackgroundImage:[UIImage imageNamed:@"img_btn_common_disable"] forState:UIControlStateDisabled capInsets:UIEdgeInsetsMake(kfTopInset,kfRightInset,kfBottomInset,kfLeftInset)]; [self.lblFindId setHidden:YES]; CGRect screen = [UIScreen mainScreen].bounds; if (screen.size.height == 480) {//iphone4s [_imgvBg setImage:[UIImage imageNamed:@"img_login_bg_4inch"]]; } if (screen.size.height == 667.0f) {//iphone6 _constraintLeftPadding.constant *= 1.25; _constraintRightPadding.constant *= 1.25; } else if (screen.size.height == 736.0f) {//iphone6 plus _constraintLeftPadding.constant *= 1.5; _constraintRightPadding.constant *= 1.5; } // [self.view layoutIfNeeded]; _txtEmail.customTextFieldSuperview = CustomTextFieldSuperviewIsScrollView; _txtPasswd.customTextFieldSuperview = CustomTextFieldSuperviewIsScrollView; _txtPasswd.secureTextEntry = YES; _txtEmail.keyboardType = UIKeyboardTypeDefault; _txtPasswd.keyboardType = UIKeyboardTypeDefault; _txtEmail.returnKeyType = UIReturnKeyNext; _txtPasswd.returnKeyType = UIReturnKeyDone; _txtPasswd.delegate = self; //Localization [_chkAutoLogin setTitle:NSLocalizedString(@"로그인 유지", @"로그인 유지") forState:UIControlStateNormal]; [_chkIdSave setTitle:NSLocalizedString(@"아이디 저장", @"아이디 저장") forState:UIControlStateNormal]; _txtEmail.placeholder = NSLocalizedString(@"아이디", @"아이디"); _txtPasswd.placeholder = NSLocalizedString(@"비밀번호", @"비밀번호"); _lblSignUp.text = NSLocalizedString(@"회원가입하기", @"회원가입하기"); _lblFindId.text = NSLocalizedString(@"아이디/비번찾기", @"아이디/비번찾기"); // [_lblSignUp setUnderLine:_lblSignUp.text]; [_lblSignUp addTouchEventHandler:^(id label) { [self lblSignUpTouched]; }]; [_lblFindId setUnderLine:_lblFindId.text]; [_lblFindId addTouchEventHandler:^(id label) { [self lblFindIdTouched]; }]; } - (void)prepareViewDidLoad { [RequestHandler handler].authorization = nil; _chkAutoLogin.checked = [[[JDFacade facade] objectForKeyFromUserDefaults:USDEF_APP_AUTO_LOGIN] boolValue]; _chkIdSave.checked = [[[JDFacade facade] objectForKeyFromUserDefaults:USDEF_APP_SAVE_ID] boolValue]; if (_chkAutoLogin.checked) { [self requestAutoLogin]; // _txtEmail.text = [[JDFacade facade] objectForKeyFromKeychain:USDEF_SESSION_LOGIN_ID]; // _txtPasswd.text = [[JDFacade facade] objectForKeyFromKeychain:USDEF_SESSION_LOGIN_PWD]; // // [self btnLogInTouched:_btnLogin]; } if (_chkIdSave.checked) { NSLog(@"Save ID : %@", [[JDFacade facade] objectForKeyFromKeychain:USDEF_SESSION_LOGIN_ID]); _txtEmail.text = [[JDFacade facade] objectForKeyFromKeychain:USDEF_SESSION_LOGIN_ID]; } } #pragma mark - Main Logic - (void)requestLogin { NSDictionary *param = @{@"member_id": [_txtEmail.text trim], @"password": [_txtPasswd.text trim], @"os_type": MOBILE_DEVICE_TYPE, @"device_token": [JDFacade facade].APNSToken ? [JDFacade facade].APNSToken : ksEmptyString, @"message_type": @"auth"}; [self sendDataToSocket:param]; [[JDFacade facade] loadIndicator:YES allowUserInteraction:NO]; // [[RequestHandler handler] sendAsyncPostRequestAPIPath:API_POST_SIGN_IN parameters:param modelClass:[LoginModel class] completion:^(id responseObject) { // if (!responseObject) {//응답결과가 잘못되었거나 없을 경우, // return; // } // // LoginModel *loginInfo = (LoginModel *)responseObject; // NSLog(@"%@", loginInfo); // // if (loginInfo) {//API 성공 ,함 // [self actionForLoginSucceed:loginInfo]; // // } // } failure:^(id errorObject) { // JDErrorModel *error = (JDErrorModel *)errorObject; // // if ([error.errorCode isEqualToString:API_RESPONSE_UNAUTHORIZED_EMAIL]) {//이메일 아이디 인증이 안 된 계정 // [self actionForWaiting]; // } else if ([error.errorCode isEqualToString:API_RESPONSE_UNAUTHORIZED_DEVICE]) {//새로운 단말 인증 필요 // [self actionForNeedsRegisteringNewDevice:error.nickname]; // } else if ([error.errorCode isEqualToString:API_RESPONSE_MOBILES_OVER]) {//단말 초과 // [self actionForMobilesOver:error.deviceList]; // } else { // [[JDFacade facade] alert:error.errorMessage]; // } // }]; } //자동로그인 요청 - (void)requestAutoLogin {; //parameters // NSString *memberId = [[JDFacade facade] objectForKeyFromKeychain:USDEF_SESSION_LOGIN_ID]; // NSString *authToken = [[JDFacade facade] objectForKeyFromKeychain:USDEF_SESSION_AUTOTOKEN]; LoginModel *tmpInfo = [[LoginModel alloc] init]; tmpInfo.memberId = [[JDFacade facade] objectForKeyFromKeychain:USDEF_SESSION_LOGIN_ID]; tmpInfo.authToken = [[JDFacade facade] objectForKeyFromKeychain:USDEF_SESSION_AUTOTOKEN]; // if ([authToken isEmptyString]) { // return; // } // NSLog(@"%@", authToken); // [RequestHandler handler].authorization = authToken; NSDictionary *parameter = @{@"Authorization": tmpInfo.authorization, @"device_token": [JDFacade facade].APNSToken ? [JDFacade facade].APNSToken : ksEmptyString, @"os_type": MOBILE_DEVICE_TYPE, @"message_type": @"auth.auto"}; [self sendDataToSocket:parameter]; [[JDFacade facade] loadIndicator:YES allowUserInteraction:NO]; // NSString *path = [NSString stringWithFormat:API_GET_SIGN_IN_AUTO]; // // [[RequestHandler handler] sendAsyncGetRequestAPIPath:path parameters:parameter modelClass:[LoginModel class] completion:^(id responseObject) { // if (!responseObject) {//응답결과가 잘못되었거나 없을 경우, // return; // } // // LoginModel *loginInfo = (LoginModel *)responseObject; // // if (loginInfo) {//API 성공 ,함 // [self actionForLoginSucceed:loginInfo]; // // } // } failure:^(id errorObject) { // JDErrorModel *error = (JDErrorModel *)errorObject; // // if ([error.errorCode isEqualToString:API_RESPONSE_UNAUTHORIZED_DEVICE]) {//새로운 단말 인증 필요 // [self actionForNeedsRegisteringNewDevice:error.nickname]; // } else { // [[JDFacade facade] alert:error.errorMessage]; // } // }]; } //인증 메일 재요청 - (void)requestAuthMail { //parameters NSDictionary *parameter = @{@"email_id": [JDFacade facade].tmpEmailId}; NSString *path = [NSString stringWithFormat:API_POST_AUTH_MAIL]; [[RequestHandler handler] sendAsyncPostRequestAPIPath:path parameters:parameter modelClass:[JDJSONModel class] completion:^(id responseObject) { if (!responseObject) {//응답결과가 잘못되었거나 없을 경우, return; } JDJSONModel *result = (JDJSONModel *) responseObject; if (result) {//API 성공 , [[JDFacade facade] toast:NSLocalizedString(@"인증 메일이 발송되었습니다", @"인증 메일이 발송되었습니다")]; } } failure:^(id errorObject) { JDErrorModel *error = (JDErrorModel *)errorObject; [[JDFacade facade] alert:error.errorMessage]; }]; } //로그인 이후 처리. - (void)actionForLoginSucceed:(LoginModel *)loginInfo { if (loginInfo) {//API 성공함 [JDFacade facade].loginUser = loginInfo; // [JDFacade facade].loginUser.gradeCode = KNEET_MEMBER_MASTER; // [JDFacade facade].loginUser.level = 90; NSLog(@"%@", [JDFacade facade].loginUser); if ([[JDFacade facade].loginUser.emailId isEqualToString:[JDFacade facade].tmpEmailId]) { [JDFacade facade].tmpEmailId = ksEmptyString; } if ([[JDFacade facade].loginUser.emailId isEqualToString:[JDFacade facade].loginUser.newEmailId]) {//이메일 변경 요청 중 [JDFacade facade].loginUser.newEmailId = ksEmptyString; } [RequestHandler handler].authorization = loginInfo.authorization; [[JDFacade facade] storeObjectToUserDefaults:@(_chkAutoLogin.checked) forKey:USDEF_APP_AUTO_LOGIN]; [[JDFacade facade] storeObjectToUserDefaults:@(_chkIdSave.checked) forKey:USDEF_APP_SAVE_ID]; if (_chkAutoLogin.checked) {//자동로그인 설정 시, 인증 토큰 저장 [[JDFacade facade] storeObjectToKeychain:loginInfo.memberId forKey:USDEF_SESSION_LOGIN_ID]; [[JDFacade facade] storeObjectToKeychain:loginInfo.authToken forKey:USDEF_SESSION_AUTOTOKEN]; } else { [[JDFacade facade] removeObjectAtKeychain:USDEF_SESSION_AUTOTOKEN]; [[JDFacade facade] removeObjectAtKeychain:USDEF_SESSION_LOGIN_PWD]; if (!_chkIdSave.checked) { [[JDFacade facade] removeObjectAtKeychain:USDEF_SESSION_LOGIN_ID]; } } if (_chkIdSave.checked) { [[JDFacade facade] storeObjectToKeychain:[_txtEmail.text trim] forKey:USDEF_SESSION_LOGIN_ID]; } else { if (!_chkAutoLogin.checked) { [[JDFacade facade] removeObjectAtKeychain:USDEF_SESSION_LOGIN_ID]; } } [self actionAfterLogin]; } } //홈그룹 체크 및 대시보드 이동 - (void)actionAfterLogin { if ([[JDFacade facade].loginUser.invitationsCount integerValue] > 0) { [self actionForInvitation]; return; } [self actionAfterInvitaion]; } //초대알림 화면으로 이동 - (void)actionForInvitation { [[JDFacade facade] loadInvitationView]; } //초대화면 액션이 종료된 후, - (void)actionAfterInvitaion { //메인으로 이동 [self gotoMainView]; } //새로운 단말 인증 필요 - 화면 이동 - (void)actionForNeedsRegisteringNewDevice:(NSString *)nickname { NewMobileViewController *vc = (NewMobileViewController *)[CommonUtil instantiateViewControllerWithIdentifier:@"NewMobileViewController" storyboardName:@"SignUp"]; vc.checkedAutoLogin = _chkAutoLogin.checked; vc.nickname = nickname; [[JDFacade facade] presentViewControllerByPush:vc pvc:self]; } //단말대수 초과 - (void)actionForMobilesOver:(NSArray *)deviceList { //SHA-2 } //인증대기중 - 화면 이동 - (void)actionForWaiting { NSString *message1 = [NSString stringWithFormat:@"%@에서\n인증 메일을 확인하세요", [JDFacade facade].tmpEmailId]; NSString *message2 = @"\n\n메일을 확인할 수 없는 경우에는\n스팸 메일함을 확인해보세요"; CustomAlertView *alert = [[CustomAlertView alloc] initWithTitle:@"메일을 확인하세요" message:[NSString stringWithFormat:@"%@%@", message1, message2] delegate:nil OKButtonTitle:@"확인" cancelButtonTitle:nil]; [alert.lblMessage1 setColor:kUITextColor02 text:message1]; [alert showWithCompletion:^(CustomAlertView *alertView, NSInteger buttonIndex) { if (buttonIndex == 1) {//재발송 [self requestAuthMail]; } }]; } - (void)gotoMainView { // UIViewController *vc = [CommonUtil instantiateViewControllerWithIdentifier:@"SignUpCompleteViewController" storyboardName:@"SignUp"]; UIViewController *vc = [CommonUtil instantiateViewControllerWithIdentifier:@"MainViewController" storyboardName:@"Main"]; [JDFacade facade].mainViewController = (MainViewController *)vc; [[JDFacade facade].appDelegate.window setRootViewController:vc]; } - (void)requestLogout { NSDictionary *param = @{API_AUTHORIZATION_KEY: [[JDFacade facade].loginUser authorization], @"message_type": @"auth.out"}; [self sendDataToSocket:param]; //parameters // [self actionAfterLogout]; // NSString *path = [NSString stringWithFormat:API_POST_SIGN_OUT]; // // [[RequestHandler handler] sendAsyncGetRequestAPIPath:path parameters:nil modelClass:[JDJSONModel class] completion:^(id responseObject) { // [self actionAfterLogout]; // // } failure:^(id errorObject) { // JDErrorModel *error = (JDErrorModel *)errorObject; // [[JDFacade facade] alert:error.errorMessage]; // }]; } - (void)actionAfterLogout { //자동 로그인 설정 - 취소 [[JDFacade facade] storeObjectToUserDefaults:@(NO) forKey:USDEF_APP_AUTO_LOGIN]; [[JDFacade facade] removeObjectAtKeychain:USDEF_SESSION_AUTOTOKEN]; if (![[[JDFacade facade] objectForKeyFromUserDefaults:USDEF_APP_SAVE_ID] boolValue]) { [[JDFacade facade] removeObjectAtKeychain:USDEF_SESSION_LOGIN_ID]; } [JDFacade facade].loginUser = nil; [self closeSocket]; //root view 변경 [[JDFacade facade].appDelegate.window setRootViewController:self]; } #pragma mark - UI Events - (IBAction)btnLogInTouched:(id)sender { #ifdef DEBUG_MODE if ([_txtEmail.text isEmptyString]) { _txtEmail.text = @"asura77"; } if ([_txtPasswd.text isEmptyString]) { _txtPasswd.text = @"09767955"; } #endif // TODO : 아이디 형식 검사할것 // if (![ValidateUtil validateTextfiled:_txtEmail type:ValidateTypeEmail title:@"이메일" ]) { // return; // } if (![ValidateUtil validateTextfiled:_txtEmail type:ValidateTypeNull title:@"비밀번호" ]) { return; } [JDFacade facade].tmpEmailId = [_txtEmail.text trim]; [JDFacade facade].tmpPassword = [_txtPasswd.text trim]; [self requestLogin]; } //회원가입 호출 - (void)lblSignUpTouched { UIViewController *vc = [CommonUtil instantiateViewControllerWithIdentifier:@"AgreementViewController" storyboardName:@"SignUp"]; UINavigationController *m_navi =[[UINavigationController alloc]initWithRootViewController:vc]; [self presentViewController:m_navi animated:YES completion:nil]; } - (void)lblFindIdTouched { UIViewController *vc = [CommonUtil instantiateViewControllerWithIdentifier:@"ResetPwdViewController" storyboardName:@"SignUp"]; [self presentViewController:vc animated:YES completion:nil]; } - (IBAction)btnIdFindTouched:(id)sender { NSLog(@"아이디 찾기"); } - (IBAction)btnPwFindTouched:(id)sender { NSLog(@"비밀번호 찾기"); } #pragma mark - CustomTextField - (BOOL)textFieldShouldReturn:(UITextField *)textField { if ([textField isEqual:_txtPasswd]) { [self btnLogInTouched:nil]; } if ([textField isEqual:_txtEmail]) { [_txtPasswd becomeFirstResponder]; } return YES; } #pragma mark - SocketService - (void) socketDidReceiveMessage:(id)message info:(NSDictionary *)info { SocketModel *result = (SocketModel *)message; NSLog(@"Result Info : %@", result); SWITCH(result.messageType) { CASE (@"auth") { [[JDFacade facade] loadIndicator:NO allowUserInteraction:YES]; if (result.isSuccess) { LoginModel *loginInfo = [[LoginModel alloc] initWithDictionary:info error:nil];; if (loginInfo) {//API 성공 ,함 [self actionForLoginSucceed:loginInfo]; } } else { [[JDFacade facade] toast:result.resultMsg]; } break; } CASE (@"auth.auto") { [[JDFacade facade] loadIndicator:NO allowUserInteraction:YES]; if (result.isSuccess) { LoginModel *loginInfo = [[LoginModel alloc] initWithDictionary:info error:nil];; if (loginInfo) {//API 성공 ,함 loginInfo.memberId = [[JDFacade facade] objectForKeyFromKeychain:USDEF_SESSION_LOGIN_ID]; loginInfo.authToken = [[JDFacade facade] objectForKeyFromKeychain:USDEF_SESSION_AUTOTOKEN]; [self actionForLoginSucceed:loginInfo]; } } else { [[JDFacade facade] toast:result.resultMsg]; } break; } CASE(@"auth.out") { if (result.isSuccess) { [self actionAfterLogout]; } else { NSLog(@"Result Info : %@", result); } } DEFAULT { break; } } } - (void) socketDidFailWithError:(NSError *)error { [[JDFacade facade] loadIndicator:NO allowUserInteraction:YES]; } #pragma mark - MemoryWarning - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } @end