Codeigniter

참조 : 5 . 네이버 로그인 연동 - 2

참조 : http://macaronics.net/index.php/m03/codeigniter/view/905

네이버 개발자 센터 : https://developers.naver.com/main/

 

 1. 인증 과정에 대한 전체적인 내용은 

다음 아래 페이지(생활코딩) 에서 공부를 해야 한다.

http://macaronics.net/index.php/m03/codeigniter/view/904

 

 2. 나의 깃허브에서 SNS 연동 소스를 다운로드 한다.

 

CodeIgniter 3.1.5 버전에 맞게 SNS 연동 소스 변경후 파일 추가

 

네이버 에 개발자 등록이 되었으면 다음이 개발을 한다.

네이버에서 제공하는 기본적인 자바스크립트 연동 소스는 다음과 같다.

네이버 로그인 JavaScript 예제는 2개의 파일로 구성되어 있습니다. (naverlogin.html, callback.html)
1. APIExamNaverLogin.html
<!doctype html>
<html lang="ko">
<head>
  <meta charset="utf-8">
  <title>네이버 로그인</title>
  <script type="text/javascript" src="https://static.nid.naver.com/js/naverLogin_implicit-1.0.3.js" charset="utf-8"></script>
  <script type="text/javascript" src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
</head>
<body>
  <!-- 네이버아이디로로그인 버튼 노출 영역 -->
  <div id="naver_id_login"></div>
  <!-- //네이버아이디로로그인 버튼 노출 영역 -->
  <script type="text/javascript">
  	var naver_id_login = new naver_id_login("YOUR_CLIENT_ID", "YOUR_CALLBACK_URL");
  	var state = naver_id_login.getUniqState();
  	naver_id_login.setButton("white", 2,40);
  	naver_id_login.setDomain("YOUR_SERVICE_URL");
  	naver_id_login.setState(state);
  	naver_id_login.setPopup();
  	naver_id_login.init_naver_id_login();
  </script>
</html>

2. callback.html
<!doctype html>
<html lang="ko">
<head>
<script type="text/javascript" src="https://static.nid.naver.com/js/naverLogin_implicit-1.0.3.js" charset="utf-8"></script>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
</head>
<body>
<script type="text/javascript">
  var naver_id_login = new naver_id_login("YOUR_CLIENT_ID", "YOUR_CALLBACK_URL");
  // 접근 토큰 값 출력
  alert(naver_id_login.oauthParams.access_token);
  // 네이버 사용자 프로필 조회
  naver_id_login.get_naver_userprofile("naverSignInCallback()");
  // 네이버 사용자 프로필 조회 이후 프로필 정보를 처리할 callback function
  function naverSignInCallback() {
    alert(naver_id_login.getProfileData('email'));
    alert(naver_id_login.getProfileData('nickname'));
    alert(naver_id_login.getProfileData('age'));
  }
</script>
</body>
</html>

 

따라서, 다음과 같이 데이터 저장 및 세션 처리는 스프링 - jsp , php , ASP 환경에 맞게 개발 하면 된다.

여기서는 Codeigniter 로 개발 하였다.

class Auth extends CI_Controller

깃 허브에서 연동 처리 소스를 다운 받는다. 이 소스에는 네이버 연동 처리 부분 없다.

따라서, 다음과 같이 추가적으로 개발을 한다.

 

 

Auth.php 일부분

<?php
defined('BASEPATH') OR exit('No direct script access allowed');


class Auth extends CI_Controller {
	
	function __construct()
	{
		parent::__construct();
		$this->load->model('auth_m');
		$this->load->helper(array('alert', 'form','url', 'date'));
		$this->load->library(array('script', 'common', 'session','form_validation'));
		$this->load->model('admin_menu01_m');
	}

	/*
	 * 주소에서 메서도가 생략되었을 때 실행되는 기본 메서드
	 * 
	 */	
	public function index()
	{	 
		$this->login();
	}

	/*
	 * 사이트 헤더, 푸터가 자동으로 추가된다.
	 * 
	 */
	public function _remap($method)
	{
		if(method_exists($this, $method))
		{
			$this->{ "{$method}" }();	
		}
	}

   
~ 생략
public function login()

~ 생략

            $assign_data['btn_gg_login'] = $this->snslogin->google_login();
            $assign_data['btn_fb_login'] = $this->snslogin->facebook_login();
            $assign_data['btn_tw_login'] = $this->snslogin->twitter_login();
            $assign_data['btn_kk_login'] = $this->snslogin->kakao_login();
            $assign_data['returnURL']=$this->input->get('returnURL');
            
             $assign_data['naver']=$this->_naverInfo();
            
            
			$this->load->view('/auth/login_form_v', $assign_data);   

}

    function _naverInfo(){
        // 네이버 로그인 콜백 예제
        $data['client_id'] = "네이버 client_id";
        $data['client_secret'] = "네이버 Scret";
        $data['YOUR_CALLBACK_URL']='http://macaronics.net/index.php/auth/naver_login_action';
        $data['YOUR_SERVICE_URL']='http://macaronics.net/index.php';  
        return  $data;
    }
    
    public function naver_login_action(){
        $data['naver']=$this->_naverInfo();
        $this->load->view('naver_v.php', $data);            
    }


 

 

http://macaronics.net/index.php/auth 의 주소를 클릭하면

로그인 화면으로 이동된다. 이때 _naverInfo 함수에 저장된 client_id 와 secret 등의 정보를 가지고

login_form_v 로 이동 하게 된다.

 

 

login_form_v.php 

네이버에서 제공하는 스크립트를 붙인후 F12 개발자 버전으로 소스르 확인 하면 url 이 ecoding 된 정보를 볼수 있다.

F12 html 로 변환 된 로그인 버튼 영역의 소스를 그대복사 하서 붙여 넣는다. 

왜 이러한 작업을 하는 이유는

naver_id_login.setButton("white", 2,40), 을 naver_id_login.setButton("green", 12,140) 으로 변경등을 해도

아이콘 이미지가 원하는 데로 조절이 안되기 때문이다.

 

네이버 아이콘 주소 : https://developers.naver.com/docs/login/bi/

<!-- 네이버아이디로로그인 버튼 노출 영역 -->
  <div id="naver_id_login"></div>
<!--
  <script type="text/javascript">
    var naver_id_login = new naver_id_login("<?php echo $naver['client_id'];?>", "<?php echo $naver['YOUR_CALLBACK_URL'];?>");
    var state = naver_id_login.getUniqState();
    naver_id_login.setButton("white", 2,40);
    naver_id_login.setDomain("<?php echo $naver['YOUR_SERVICE_URL'];?>");
    naver_id_login.setState(state);
    naver_id_login.setPopup();
    naver_id_login.init_naver_id_login();
  </script>-->

  <!-- //네이버아이디로로그인 버튼 노출 영역 -->
<div id="naver_id_login"><a href="https://nid.naver.com/oauth2.0/authorize?response_type=token&amp;client_id=Sqvg_RjXx8WajaKGcn3m&amp;redirect_uri=http%3A%2F%2Fmacaronics.net%2Findex.php%2Fauth%2Fnaver_login_action&amp;state=73ae0b8e-5dd8-45e8-8892-8a96ab7e1147" 
    onclick="window.open(this.href, 'naverloginpop', 'titlebar=1, resizable=1, scrollbars=yes, width=600, height=550'); return false" id="naver_id_login_anchor">
    <img src="/images/naverLogin.png" border="0" title="네이버 아이디로 로그인" width="320" height="35"></a>
 </div>

 

버튼을 클릭하면 네이버에서 정보를 가져오게 되고 

리다이렉션 주소로 naver_login_action 을 호출하게 되면 이동할 주소로 가게 만들었다.

여기서는 팝업창을 띄어 보여 줄 페이가. naver_v.php 페이지 이다.

 

 

naver_v.php 

팝업창이 띄어진 상태에서 Ajax 처리를 하였으나, 이미 데이터 전달이 안 되어서.

form 에 데이터를 입력 한후 이것을 post 전달 하는 방식을 취하였다.

<!doctype html>
<html lang="ko">
<head>
<script type="text/javascript" src="https://static.nid.naver.com/js/naverLogin_implicit-1.0.3.js" charset="utf-8"></script>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
</head>
<body>
<br>
<script type="text/javascript">
  var naver_id_login = new naver_id_login("<?php echo $naver['client_id']; ?>", "<?php echo $naver['YOUR_CALLBACK_URL']; ?>" );
  // 접근 토큰 값 출력
  //alert(naver_id_login.oauthParams.access_token);
  // 네이버 사용자 프로필 조회
  naver_id_login.get_naver_userprofile("naverSignInCallback()");
  // 네이버 사용자 프로필 조회 이후 프로필 정보를 처리할 callback function
  function naverSignInCallback() {
     
      var email=naver_id_login.getProfileData('email');
      var sns_type="naver";
      var name =naver_id_login.getProfileData('nickname');
      var age=naver_id_login.getProfileData('age');
      var birthday=naver_id_login.getProfileData('birthday');
      var gender=naver_id_login.getProfileData('gender');
      var profile_image=naver_id_login.getProfileData('profile_image');
      var sns_id=naver_id_login.getProfileData('id');
      
      $("#sns_id").val(sns_id);
      $("#email").val(email);
      $("#sns_type").val('naver');
      $("#name").val(name);
      $("#profile_image").val(profile_image);
        
      $("#form1").submit();
         
     /*
      $("#rt").html( email+"<br>"+sns_type+"<br>"+name+"<br>"+age+"<br>:birthday : "
                    +birthday+ " <br> profile_image: " +profile_image
                     +" <br> id : "+ sns_id
                    );*/
   
      /*  
       * 
        var csrf_test_name=getCookie('csrf_cookie_name'); 
         $.ajax({
                 url:"/index.php/auth/naverRegister",
                 type :"POST",
                 data:{
                     'sns_id':sns_id,
                    "csrf_test_name" :csrf_test_name,   
                     'email':email,
                     'sns_type': sns_type,
                     'name':name,
                     'profile_image':profile_image
                 },
                 dataType :"html",
                 
                 success:function(result){
                                      // window.opener.location.href="/";
                                     //  self.close();
                                     alert(result);
                                      
                                  },
                                  error:function(result){
                                      alert("로그인 실패");
                                  }
                 
           }); */
        
     
  }
  
  
  //  AJAX 전용 CSRF 보안 쿠기 생성 함수   
function getCookie( name )
    {
        var nameOfCookie = name + "=";
        var x = 0;

        while ( x <= document.cookie.length )
        {
            var y = (x+nameOfCookie.length);

            if ( document.cookie.substring( x, y ) == nameOfCookie ) {
                if ( (endOfCookie=document.cookie.indexOf( ";", y )) == -1 )
                    endOfCookie = document.cookie.length;

                return unescape( document.cookie.substring( y, endOfCookie ) );
            }

            x = document.cookie.indexOf( " ", x ) + 1;

            if ( x == 0 )

            break;
        }

        return "";
    }
</script>


<?php 
    $attrs=array('method'=>"post", "id"=>"form1");
    echo form_open("index.php/auth/naverRegister", $attrs);
?>
    <input type="hidden" name="sns_id"  id="sns_id">
    <input type="hidden" name="email"  id="email">
    <input type="hidden" name="sns_type"  id="sns_type">
    <input type="hidden" name="name"  id="name">
    <input type="hidden" name="profile_image"  id="profile_image">
</form>


</body>
</html>

 

 

index.php/auth/naverRegister 주소로 데이터가 전달 된 후 DB에 유저 정보 데이터저장 및 로그인 세션을 

개발 해 주면 된다.

 

Auth.php 일부분

  function naverRegister()
    {
   
         $assign_data['sns_id']=$this->input->post('sns_id',TRUE);
         $assign_data['email']=$this->input->post('email',TRUE);
         $assign_data['sns_type']='naver';
         $assign_data['name']=$this->input->post('name',TRUE);
         $assign_data['profile_image']=$this->input->post('profile_image',TRUE);

         $this->_register_action($assign_data);    
    }
    
    // Register Action Process
    function _register_action($assign_data) {

         //sns 의경우 이메일이 없는 경우가 있으므로 없을 경우 sns_id 값으로 저장
        $insertId=$assign_data['email']!=null ? $assign_data['email'] :$assign_data['sns_id'];
        
        //sns_id 로 기존에 등록된 유저 확인
        $sql="select * from users where userid=?";
        $query=$this->db->query($sql,  $insertId);
        
       
        $message="";
        //등록된 userid 를 확인 한다.
        if($query->num_rows() > 0){
            //테스트 메시지
            $message="userid 가 존재";
        }
        else
        {
            //userid 값이 없으면 등록한다. 
             // Member Register in Your Code.       
             $data=array(
                'userid' =>$insertId,
                'sns_id'=>$assign_data['sns_id'],
                'sns_type'=>$assign_data['sns_type'],
                'register_auth_code'=>1,  //이메일 인증 코드 1로 
                'profile_img'=>$assign_data['profile_img'],
                'email'=>$assign_data['email'],
                'nickname'=>$assign_data['nickname'],
                'username'=>$assign_data['name'],
                'register_ip'=>$_SERVER['REMOTE_ADDR']
                );       
            $this->db->insert('users', $data);
              $message="등록했습니다.";
                      
        }
        
        //DB에서 정보를 다시 불러온다.
        $sql="select * from users where userid=?";
        $query=$this->db->query($sql,  $insertId);
        $result=$query->row();

         //세션 생성         
        if($result) {             
            //세션 생성         
            $newdata =array(
                'nickname' =>$result->nickname,
                'email' =>$result->email,
                'logged_in' =>TRUE,
                'auth_code' =>$result->auth_code,
                'icon'=>$result->icon,
                'sns_type'=>$result->sns_type,
                'userid' =>$result->userid
            );
            
            $this->session->set_userdata($newdata);
            
            if($assign_data['sns_type']=='naver'){
     
               echo "<script> window.opener.location.href='/' ;"; //부모창을 닫는다.
               echo "self.close(); </script>";   // 현재 팝업창 자기 자신을 닫는다.
                
            }else{
                redirect('/');
                exit;                
            } 
         }else{
             
             alert('로그인에 실패 하였습니다.', '/');
             exit;
         }                            
    }

 

 

로그인  처리가 완료 되면. 다음과 같이 부모 창과 현재   팝업창을 닫는 처리를 한다.

echo "<script> window.opener.location.href='/' ;"; //부모창을 닫는다.
               echo "self.close(); </script>";   // 현재 팝업창 자기 자신을 닫는다.

 

 

 

 

 

 

 

Codeigniter

 

about author

PHRASE

Level 60  머나먼나라

우리가 너무 자기 자신을 의식하면, 다른 사람들이 민망해 한다. 그리고 결국은 우리에게서 떨어져 나갈 것이다. 우리는 스스로 자신을 농담거리로 삼을 수 있어야 한다. -앤드류 매튜스

댓글 ( 6)

댓글 남기기

작성