Advertisement
VladimirsBudkins

refactoring task

Oct 3rd, 2016
119
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 14.37 KB | None | 0 0
  1. //auth controller
  2. <?php
  3. if (! defined ( 'BASEPATH' ))
  4.     exit ( 'No direct script access allowed' );
  5. class Auth extends CI_Controller {
  6.    
  7.     // this constructor checks if user has logged on
  8.     function __construct() {
  9.         parent::__construct();
  10.         $this->load->model('mod_auth');
  11.         $this->mod_auth->check_login();
  12.         $this->load->model('mod_log');
  13.         /* for debugging */
  14.         // $this->output->enable_profiler('TRUE');
  15.         error_log('b');
  16.     }
  17.    
  18.     public function index() {
  19.         redirect('home/'.$this->session->userdata('token'));
  20.     }
  21.    
  22.     // login attempt validation
  23.     public function login() {
  24.         $email = $this->input->post('email');
  25.         $pass = $this->input->post('pass');
  26.         $captcha = FALSE;
  27.         if ($this->input->post('captcha')) $captcha = $this->input->post('captcha');
  28.         if ($email || $pass){
  29.             //login script
  30.             if ($this->mod_auth->check_captcha($captcha)){
  31.                 if ($this->mod_auth->check_login_data($email,$pass)){
  32.                     $this->mod_log->log('login',array('email'=>$email,'status'=>'success'));
  33.                    
  34.                     // check next password change date
  35.                     $this->load->model('mod_user');
  36.                     $user_id = $this->session->userdata('user_id');
  37.                     $user_data = $this->mod_user->get_id($user_id);
  38.                     $date_now = new DateTime();
  39.                     $date_next = DateTime::createFromFormat('Y-m-d', $user_data['next_pw_change']);
  40.                     if ($date_now >= $date_next) {
  41.                         $data = [];
  42.                         $data['password'] = '';
  43.                         $data['change_password'] = 1;
  44.                         $this->mod_user->update($data, $user_id);
  45.                     }
  46.                    
  47.                     redirect('home/index/'.$this->session->userdata('token'));  
  48.                 } else {
  49.                     $ok = FALSE;
  50.                     $data['error'] = 'Invalid email or password';
  51.                     $this->mod_log->log('login',array('email'=>$email,'status'=>'Invalid email or password (active)'));
  52.                     $this->mod_auth->check_if_block($email);
  53.                 }
  54.             } else {
  55.                 $ok = FALSE;
  56.                 $data['error'] = 'Invalid captcha';
  57.                 $this->mod_log->log('login',array('email'=>$email,'status'=>$data['error']));
  58.             }
  59.             if (!$ok){
  60.                 // login fail
  61.                 $this->mod_auth->add_login_attempt();
  62.                 $this->load->view ( 'include/header' );
  63.                 $data['captcha'] = $this->mod_auth->login_captcha();
  64.                 $this->load->view ( 'auth/view_login',$data);
  65.             }
  66.         }
  67.         else {
  68.             //first time login page
  69.             $data = array();
  70.             $data['error'] = '';
  71.             $data['captcha'] = $this->mod_auth->login_captcha();
  72.             $this->load->view ( 'include/header' );
  73.             $this->load->view ( 'auth/view_login',$data);
  74.         }
  75.         $this->load->view('include/footer');
  76.     }
  77.    
  78.     // logout
  79.     public function logout(){
  80.         log_action('logout','success');
  81.         $this->session->sess_destroy();
  82.         redirect('auth/login');
  83.     }
  84.    
  85.     // forgot password page
  86.     public function forgot() {
  87.         $this->load->model('mod_user');
  88.        
  89.         if ($this->input->post()){
  90.             $this->form_validation->set_rules('email', 'Email', 'trim|xss_clean|required|valid_email|email_exists');
  91.             $this->load->view ( 'include/header' );
  92.             if($this->form_validation->run()===false){
  93.                 $this->load->view ( 'auth/view_forgot_pass' );
  94.             }else{
  95.                 $data['success'] = TRUE;
  96.                 $email = $this->input->post('email');
  97.                 $password = $this->mod_user->forgot_password($this->input->post('email'));
  98.                
  99.                 if ($password) {
  100.                     $to      = $email;
  101.                     $subject = 'Password reset';
  102.                     $message = "Dear customer,\n\nWe have received a Password Reset request for the account with Username :".$email." \n";
  103.                     $message = $message . "Your new password is $password. \nYou will be required to change the password after logging in. ";
  104.                     $headers = 'From: admin@taxfreeshopping.lv';
  105.                     mail($to, $subject, $message, $headers);
  106.                 }
  107.                
  108.                 $this->load->view ( 'auth/view_forgot_pass',$data );
  109.             }
  110.         } else {
  111.             $this->load->view ( 'include/header' );
  112.             $this->load->view ( 'auth/view_forgot_pass' );
  113.         }
  114.         $this->load->view('include/footer');
  115.     }
  116.    
  117.     // password change page
  118.     public function pass(){
  119.         $this->load->view ( 'include/header' );
  120.         if ($this->input->post('old') || $this->input->post('new1') || $this->input->post('new2')){
  121.             // load model
  122.             $this->load->model('mod_auth');
  123.            
  124.             // get post data
  125.             $this->form_validation->set_rules('old', 'Password', 'xss_clean|required');
  126.             $this->form_validation->set_rules('new1', 'Password', 'trim|required|xss_clean|matches[new2]|not_matches[old]|password_check');
  127.             $this->form_validation->set_rules('new2', 'Confirm', 'trim|required|xss_clean');
  128.            
  129.             // validate data
  130.             if(!$this->mod_auth->check_login_data($data['token']=$this->session->userdata('user_email'), $this->input->post('old'))){
  131.                 // wrong pass
  132.                 log_action('change password','wrong old password');
  133.                 $data = array();
  134.                 $data['error'] = 'Wrong old password!';
  135.                 $data['token']=$this->session->userdata('token');
  136.                 $this->load->view ( 'auth/view_user_change_pass',$data );
  137.             }else if($this->form_validation->run()===false){
  138.                 // validation fail
  139.                 log_action('change password',validation_errors());
  140.                 $data = array();
  141.                 $data['error'] = validation_errors();
  142.                 $data['token']=$this->session->userdata('token');
  143.                 $this->load->view ( 'auth/view_user_change_pass',$data );
  144.             }else{
  145.                 // password can be changed
  146.                 $id = $this->session->userdata('user_id');
  147.                 $new = $this->input->post('new1');
  148.                 $this->load->model('mod_user');
  149.                 $data = array();
  150.                 $data['password']=$new;
  151.                 $data['change_password']=0;
  152.                 $data['next_pw_change'] = date2sql(date_mod(today(), '+ 6 months'));
  153.                 log_action('change password','success');
  154.                 $this->mod_user->update($data,$id);
  155.                 redirect('home/index/token/'.$this->session->userdata('token'));
  156.             }
  157.         } else {
  158.             // just load page
  159.             $data = array();
  160.             $data['error'] = '';
  161.             $data['token']=$this->session->userdata('token');
  162.             $this->load->view ( 'auth/view_user_change_pass',$data );
  163.         }
  164.         $this->load->view('include/footer');
  165.     }
  166.    
  167. }
  168. //auth model
  169. <?php
  170. class Mod_auth extends CI_Model {
  171.     function check_login(){
  172.         if ($this->is_public_url())
  173.         {
  174.             return;
  175.         }  
  176.         // check login
  177.         if ($this->uri->uri_string() !== 'auth/login'
  178.             && $this->uri->uri_string() !== 'auth/forgot'
  179.             && $this->uri->uri_string() !== 'auth/logout'
  180.             )  {  
  181.             if (!$this->mod_auth->is_logged_in())
  182.             {
  183.                 //echo "no login";
  184.                 redirect('auth/login');
  185.             }
  186.             else if (permission('blocked')) {
  187.                 redirect('home/blocked');
  188.             }
  189.             else
  190.             {
  191.                 // check token
  192.                 $last_segment = $this->uri->total_segments();
  193.                 $token = $this->uri->segment($last_segment);
  194.                 if ($token!=$this->session->userdata('token'))
  195.                 {
  196.                     //echo "wrong token";
  197.                     redirect('auth/login');
  198.                 }
  199.                
  200.                 $uri = $this->uri->uri_string();
  201.                 if (strpos($uri,"pass") === false ) {
  202.                     $this->load->model('mod_user');
  203.                     $user = $this->mod_user->get_current();
  204.                     if ($user['change_password']) {
  205.                         redirect('auth/pass/'.$this->session->userdata('token'));
  206.                     }
  207.                 }
  208.             }
  209.         }
  210.     }
  211.    
  212.     function is_logged_in() {
  213.         $user_email = $this->session->userdata('user_email');
  214.         $id = $this->session->userdata('user_id');
  215.         if ($user_email && $id) {
  216.             return TRUE;
  217.         } else {
  218.             return FALSE;
  219.         }
  220.     }
  221.    
  222.     function check_if_block($email) {
  223.         //$query = $this->db->query('SELECT * FROM log WHERE user_email = "' . $email . '" AND action = "login" AND data = "Invalid email or password (active)" AND ts >= "' . date2sql(date_mod(today(), '- 1 day')) . '"');
  224.         $where = ['user_email' => $email, 'action' => 'login', 'data' => 'Invalid email or password (active)', 'ts >=' => date2sql(date_mod(today(), '- 1 day'))];
  225.         $query = $this->db->get_where('log', $where);
  226.         if ($query->num_rows() > 9) {
  227.             $query = $this->db->get_where('user', ['email' => $email]);
  228.             if ($query->num_rows() > 0) {
  229.                 $result = $query->result();
  230.                 $user = get_object_vars($result[0]);
  231.                 $this->db->delete('user_role', ['user_id' => $user['id'], 'role_code' => 'blocked']);
  232.                 $this->db->insert('user_role', ['user_id' => $user['id'], 'role_code' => 'blocked']);
  233.                 $this->db->update('log', ['data' => 'Invalid email or password'], $where);
  234.             }
  235.         }
  236.     }
  237.    
  238.     function add_login_attempt(){
  239.         $attempts = $this->session->userdata('attempt');
  240.         if (! $attempts){
  241.             $this->session->set_userdata('attempt',1);
  242.         } else {
  243.             $attempts++;
  244.             $this->session->set_userdata('attempt',$attempts);
  245.         }
  246.     }
  247.    
  248.     function is_max_login_attempts_exceeded() {
  249.         $atempts = $this->session->userdata('attempt');
  250.         if ($atempts) {
  251.             if ((int)$atempts > 2) {
  252.                 return TRUE;
  253.             } else {
  254.                 return FALSE;
  255.             }
  256.         } else {
  257.             return FALSE;
  258.         }
  259.     }
  260.    
  261.     function login_captcha(){
  262.         if ($this->is_max_login_attempts_exceeded()){
  263.             $this->load->helper('captcha');
  264.             $data = array(
  265.                 'img_path' => './assets/captcha/',
  266.                 'img_url' => base_url().'assets/captcha/',
  267.                 'img_width' => '130',
  268.                 'img_height' => '45'
  269.             );
  270.             $captcha = create_captcha($data);
  271.             $this->session->set_userdata(array('captcha'=>$captcha['word']));
  272.             return $captcha['image'];
  273.         } else {
  274.             return FALSE;
  275.         }
  276.     }
  277.    
  278.     function check_captcha($captcha){
  279.         if (!$this->is_max_login_attempts_exceeded())
  280.             return TRUE;
  281.            
  282.         if ($captcha == $this->session->userdata('captcha')){
  283.             return TRUE;
  284.         } else {
  285.             return FALSE;
  286.         }
  287.     }
  288.    
  289.     function check_login_data($email,$pass){
  290.        
  291.         $this->load->helper('security');
  292.         $hpass = do_hash($pass);
  293.         $condition = array(
  294.                 'email'=>$email,
  295.                 'password'=>$hpass,
  296.                 'deleted'=>0,
  297.             );
  298.        
  299.         $query = $this->db->get_where('user', $condition);
  300.         if ($query->num_rows != 1)
  301.         {
  302.             return FALSE;
  303.         }
  304.         else
  305.         {
  306.             $row = $query->row();
  307.             $this->session->set_userdata('user_email',$row->email);
  308.             $this->session->set_userdata('user_name',$row->name . ' ' . $row->surname);
  309.             $this->session->set_userdata('user_id',$row->id);
  310.             $this->session->set_userdata('token',do_hash($this->session->userdata('session_id').'o3secret'));
  311.             //roles to session
  312.             $this->load->model('mod_user_role');
  313.             $userRole=$this->mod_user_role->get_user($row->id);
  314.             $this->session->set_userdata('user_role',$userRole);
  315.            
  316.             // reset failed attempts
  317.             $this->session->set_userdata('attempt',0);
  318.             return TRUE;
  319.         }
  320.     }
  321.    
  322.     function email_exists($email){
  323.         $condition = array(
  324.             'email'=>$email,
  325.         );
  326.         $query = $this->db->get_where('user', $condition);
  327.         if ($query->num_rows != 1)
  328.         {
  329.             return FALSE;
  330.         }
  331.         else
  332.         {
  333.             return TRUE;
  334.         }
  335.     }
  336.    
  337.     function is_public_url(){
  338.         if ($this->uri->uri_string() === 'payment/transactpro_return')
  339.             return TRUE;
  340. /*      if ($this->uri->uri_string() === 'payment/transactpro_callback')
  341.             return TRUE;
  342.         if ($this->uri->uri_string() === 'payment/transactpro_callback_log')
  343.             return TRUE;*/
  344.         return FALSE;
  345.     }
  346.  
  347. }
  348. //bill view
  349. <?
  350. if (!permission('bill:view') || !permission('bill:insert'))
  351.     die();
  352. ?>
  353. <script>
  354.   $(function() {
  355.     $( "#date" ).datepicker(
  356.     {dateFormat: "dd.mm.yy",firstDay:1}
  357.     );
  358.     $( "#date_due" ).datepicker(
  359.     {dateFormat: "dd.mm.yy",firstDay:1}
  360.     );
  361.   });
  362.    
  363.     $("#date").mask("99.99.9999",{placeholder:"dd.mm.yyyy"});  
  364.     $("#date_due").mask("99.99.9999",{placeholder:"dd.mm.yyyy"});  
  365.    
  366. </script>
  367.  
  368. <div class="row">
  369.             <div class="col-md-8 col-md-offset-2">
  370.                 <div class="panel panel-primary">
  371.                     <div class="panel-heading">Bill</div>
  372.                     <div class="panel-body">
  373.  
  374.                         <form accept-charset="UTF-8"
  375.                             action="<?php echo base_url('bill/update_post/'.$id.'/'.$token)?>"
  376.                             class="form-horizontal" method="post">
  377.                             <div class="form-group">
  378.                                 <label class="control-label col-sm-3" for="num">N#:</label>
  379.                                 <div class="col-sm-4">
  380.                                     <input type="text" class="form-control" name="num" id="num" value="<?=$num?>"
  381.                                         required>
  382.                                 </div>
  383.                             </div>
  384.                                     <!-- Date -->
  385.                             <div class="form-group">
  386.                                 <label class="control-label col-sm-3" for="date">Date:</label>
  387.                                 <div class="col-sm-3">
  388.                                     <input type="text" class="form-control"  name="bill_date" id="date" value="<?=sql2date($bill_date)?>"
  389.                                         required <?=date_readonly()?>>
  390.                                 </div>
  391.                             </div>
  392.                                     <!--Company-->
  393.                             <div class="form-group" id=form_company>
  394.                                 <label class="control-label col-sm-3" for="nr">Company:</label>
  395.                                 <div class="col-sm-4">
  396.                                     <select class="form-control" id="company" name="company_id">
  397.                                         <option>-</option>
  398.                                         <?php foreach($companies as $obj):?>
  399.                                             <option value="<?php echo $obj->id; ?>" <? if($obj->id==$company_id) echo "selected"?> ><?php echo $obj->name;?></option>
  400.                                         <?php endforeach; ?>
  401.                                     </select>
  402.                                 </div>
  403.                             </div>
  404.                            
  405.                             <div class="form-group">
  406.                                 <label class="control-label col-sm-3" for="date">Credit:</label>
  407.                                 <div class="col-sm-3">
  408.                                     <input type="checkbox"  name="credit" id="credit" onclick="set_accounting_defaults()"
  409.                                     <? if ($credit ==1) echo "checked"; ?>>
  410.                                 </div>
  411.                             </div>
  412.                             <div class="form-group">
  413.                                 <label class="control-label col-sm-3" for="date">Date due:</label>
  414.                                 <div class="col-sm-3">
  415.                                     <input type="text" class="form-control"  name="due_date" id="date_due" value="<?=sql2date($due_date)?>"
  416.                                         required <?=date_readonly()?>>
  417.                                 </div>
  418.                             </div>
  419.                             <div class="form-group">
  420.                                 <label class="control-label col-sm-3" for="date">Note:</label>
  421.                                 <div class="col-sm-7">
  422.                                     <textarea class="form-control" name="note" id="note"><?=$note?></textarea>
  423.                                 </div>
  424.                             </div>
  425.                             <? if (permission('bill:update')) { ?>
  426.                             <div class="form-group">
  427.                                 <div class="col-sm-offset-3 col-sm-8">
  428.                                     <button type="submit" class="btn btn-success pull-right">Save</button>
  429.                                 </div>
  430.                             </div>
  431.                             <? } ?>
  432.                            
  433.                            
  434.                            
  435.                         </form>
  436.  
  437.                     </div>
  438.  
  439.                 </div>
  440.  
  441.             </div>
  442.         </div>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement