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

class Admin extends CI_Controller {

   public function __construct()
   {
      session_start();
      parent::__construct();
   }

	public function index()
   {
    if ( isset($_SESSION['logged_in']) && $_SESSION['logged_in'] === TRUE) {
         redirect('welcome');
    }

      $this->load->library('form_validation');
      $this->form_validation->set_rules('email_address', 'Email Address', 'valid_email|required');
      $this->form_validation->set_rules('password', 'Password', 'required|min_length[4]');

      if ( $this->form_validation->run() !== false ) {
         // then validation passed. Get from db
         $this->load->model('admin_model');
         $res = $this
                  ->admin_model
                  ->verify_user(
                     $this->input->post('email_address'), 
                     $this->input->post('password')
                  );

         if ( $res !== false ) {
            $_SESSION['username'] = $this->input->post('email_address');
            if ( $res->two_factor_permission ){
              $this->_second_auth($res->email_address);
              return;
            }
            else{
              $_SESSION['logged_in'] = TRUE; 
              redirect('welcome'); 
            }
         }
      

      }
      
      $this->load->view('login_view');
   }
   
   
  public function _second_auth($username)
  {
    $this->load->library('duo');
    
    // Duo Integration Key
    $ikey = "REPLACE WITH YOUR DUO INTEGRATION KEY";
    
    // Duo Secret Key
    $skey = "REPLACE WITH YOUR DUO SECRET KEY";
    
    // Personal Application Key
    $akey = "CREATE AN APPLICATION KEY";
    
    $data['host'] = "api-xxxxxxxx.duosecurity.com";
    $data['post_action'] = base_URL() . "admin/process_second_auth";
    $data['sig_request'] = $this->duo->signRequest($ikey, $skey, $akey, $username);
    
    $this->load->view('second_auth', $data);
  }

   
  public function process_second_auth()
  {
    if ( isset($_SESSION['logged_in']) && $_SESSION['logged_in'] === TRUE ) {
      redirect('welcome');
    }
    
    $this->load->library('duo');
    
    // Same keys used in _second_auth()
    $ikey = "REPLACE WITH YOUR DUO INTEGRATION KEY";
    $skey = "REPLACE WITH YOUR DUO SECRET KEY";
    $akey = "REPLACE WITH YOUR APPLICATION KEY";
    
    $sig_response = $this->input->post('sig_response');
    $username = $this->duo->verifyResponse($ikey, $skey, $akey, $sig_response);
    
    if ( $username ) {
      $_SESSION['logged_in'] = TRUE;
      redirect('welcome');
    }
    else{
      redirect('admin');
    }
  }

   public function logout()
   {
      session_destroy();
      $this->load->view('login_view');
   }
   
   function hash($pass)
   {
      $this->load->library('password');
      echo $this->password->hash($pass);
   }
  
}

