수업소개
현재 예제는 토픽 추가 버튼을 눌렀을 때 로그인이 필요하면 로그인을 요구한다. 로그인에 성공한 사용자를 메인 페이지로 이동시키는데 이것은 사용자가 목적하는 작업의 맥락을 흐트러트린다. 로그인 후 사용자의 원래 목적 페이지로 리다이렉션 시키는 방법을 알아본다.
토픽 작성 동선 개선
토픽을 추가하기 위해서 '추가' 버튼을 눌렀을 때 로그인 되지 않은 사용자는 로그인 페이지로 이동을 시킨다. 로그인 후에는 글 작성 페이지로 이동하지 않고 메인 페이지로 이동하고 있는데 이 부분을 개선해보자.
인증이 필요할 때 /auth/login 페이지로 이동시키면서 returnURL을 파라미터로 전달한다. 이 값은 로그인에 성공한 후에 페이지를 리다이렉션시키는 근거가 된다.
/application/controllers/topic.php

function add(){
// 로그인 필요
// 로그인이 되어 있지 않다면 로그인 페이지로 리다이렉션
if(!$this->session->userdata('is_login')){
$this->load->helper('url');
redirect('/auth/login?returnURL='.rawurlencode(site_url('/topic/add')));
}
/application/controllers/auth.php
로그인 페이지에서 아이디/비밀번호를 입력하고 전송(submit)을 할 때 실제 인증은 /auth/authentication에서 이루어지고, 인증 후에 최종적인 페이지 리다이렉션도 /auth/authentication에서 이루어지기 때문에 /auth/authentication에 returnURL을 전달하기 위해서는 로그인 페이지의 form action 의 파라미터로 returnURL을 전달해야 한다. 아래는 이를 위한 단계이다.

function login(){
$this->_head();
$this->load->view('login', array('returnURL'=>$this->input->get('returnURL')));
$this->_footer();
}
/application/views/login.php

</div> <form class="form-horizontal" action="/index.php/auth/authentication<?=empty($returnURL) ? '' : '?returnURL='.rawurlencode($returnURL) ?>" method="post"> <div class="modal-body">
사용자가 로그인 버튼을 누르면 returnURL 값을 가지고 /auth/authentication 로 이동하게 된다. authentication 메소드는 사용자 인증을 시도하고, 성공했다면 전달된 returnURL로 페이지를 리다이렉션 시킨다.
/application/controllers/auth.php

function authentication(){
$this->load->model('user_model');
$user = $this->user_model->getByEmail(array('email'=>$this->input->post('email')));
if(!function_exists('password_hash')){
$this->load->helper('password');
}
if(
$this->input->post('email') == $user->email &&
password_verify($this->input->post('password'), $user->password)
) {
$this->session->set_userdata('is_login', true);
$this->load->helper('url');
$returnURL = $this->input->get('returnURL');
log_message('info', $returnURL);
redirect($returnURL ? $returnURL : '/');
} else {
echo "불일치";
$this->session->set_flashdata('message', '로그인에 실패 했습니다.');
$this->load->helper('url');
redirect('/auth/login');
}
}
이런 방법으로 로그인 이후에 적절한 페이지로 리다이렉션을 적용하면 된다. 이것은 사용자가 로그인으로 인해서 하고자하는 일에 대한 맥락을 잃어버리지 않게 한다.
태그
- 태그명 : redirection_login_process
- 태그주소 : https://github.com/egoing/codeigniter_codeingeverbody/tree/redirection_login_process

