처음부터 차근차근

Codeigniter Core 확장을 이용한 코드 정리와 admin 로그인 체크 본문

프로젝트/Hotel 예약 사이트 (Codeigniter)

Codeigniter Core 확장을 이용한 코드 정리와 admin 로그인 체크

_soyoung 2021. 12. 27. 17:01
반응형

admin 로그인 체크

admin 페이지는 데이터베이스에 대한 내용이 있기 때문에 보안이 중요한 웹페이지이다.

그래서 사용자가 url을 치고 admin 페이지에 들어오려고 할 때 로그인을 하지 않은 사용자는 들어올 수 없도록 만들었다.

function _checkAdminLogin() {
// admin이 login 되었는지 확인
    if(!$this->session->userdata('admin_id')) {
        $this->load->view("admin_warning");
        return false;
    }
    else {
        return true;
    }
}

세션 데이터중 key값이 admin_id인 세션의 value값을 받아오는데 이 값이 없다면 admin_warnig 페이지를 로드하고 false를 반환한다.

반환 값으로 false를 반환하면 함수 끝까지 실행하지 못하고 처음 부분에서 막는다.

function index() {
			
   // 로그인 체크
   if(!$this->_checkAdminLogin()){
       return;
   }
   
   // 밑의 코드는 실행하지 못함
   ... 생략...
}

결과

 

 

 

 

Codeigniter Core 확장을 이용한 코드 정리

codeigniter에서 제공하는 상속을 이용한 core확장 방법을 선택하여 코드를 정리했다.

application / core / MY_Controller.php

<?php
	defined('BASEPATH') OR exit('No direct script access allowed'); 
	class MY_Controller extends CI_Controller {
	
		function __construct() {
            parent::__construct();
        }
		
		function _checkAdminLogin() {
			// admin이 login 되었는지 확인
			if(!$this->session->userdata('admin_id')) {
				$this->load->view("admin_warning");
				return false;
			}
			else {
				return true;
			}
		}
		
		function _ajax_header() {
			header("Content-Type: text/html; charset=KS_C_5601-1987");
            header("Cache-Control:no-cache");
            header("Pragma:no-cache");
            header("Content-Type:application/json");
		}
		
		function _header() {
			$this->load->view("admin_header");
		}
		
		function _footer() {
			$this->load->view("admin_footer");
		}
	}
?>

MY_Controller라는 CI_Controller을 상속받는 새로운 controller를 만들고,

admin 페이지의 모든 contorller이 CI_Controller 대신 MY_Contorller을 상속받도록 만들었다.

 

 

사용 결과

<?php
	defined('BASEPATH') OR exit('No direct script access allowed'); 
	class Admin extends MY_Controller {
        function __construct() {
            parent::__construct();
			$this->load->database();
			$this->load->helper('url');
        }
        
        function main() {
			
			// 로그인 체크
			if(!$this->_checkAdminLogin()){
				return;
			}
			
			$this->load->model('Memo_m');
			
			$memos = $this->Memo_m->getAll();

			$this->_header();
			$this->load->view('admin_main', array('memos'=>$memos));
			$this->_footer();
		}
    }
?>

core 확장을 통해서 모든 controller에 중복되는 부분인 로그인 체크와 ajax header부분과 $this->load->view("admin_header");, $this->load->view("admin_footer"); 깔끔하고 유지보수하기 쉽게 정리했다.

 

반응형
Comments