Advertisement
sh1fralf4tih

how to ion auth with ajax

Oct 29th, 2018
223
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 38.92 KB | None | 0 0
  1. <--- Controller --->
  2.  
  3. <?php defined('BASEPATH') OR exit('No direct script access allowed');
  4.  
  5. /**
  6.  * Class Auth
  7.  * @property Ion_auth|Ion_auth_model $ion_auth        The ION Auth spark
  8.  * @property CI_Form_validation      $form_validation The form validation library
  9.  */
  10. class Auth extends CI_Controller
  11. {
  12.     public function __construct()
  13.     {
  14.         parent::__construct();
  15.         $this->load->database();
  16.         $this->load->library(array('ion_auth', 'form_validation'));
  17.         $this->load->helper(array('url', 'language'));
  18.  
  19.         $this->form_validation->set_error_delimiters($this->config->item('error_start_delimiter', 'ion_auth'), $this->config->item('error_end_delimiter', 'ion_auth'));
  20.  
  21.         $this->lang->load('auth');
  22.     }
  23.  
  24.     /**
  25.      * Redirect if needed, otherwise display the user list
  26.      */
  27.     public function index()
  28.     {
  29.  
  30.         if (!$this->ion_auth->logged_in())
  31.         {
  32.             // redirect them to the login page
  33.             redirect('auth/login', 'refresh');
  34.         }else
  35.         {
  36.             redirect('dashboard');
  37.         }
  38.     }
  39.  
  40.  
  41.     public function crsf_ajax()
  42.     {
  43.         $crsf = $this->_get_csrf_nonce();
  44.  
  45.         echo json_encode(array('crsf' => $crsf));
  46.     }
  47.  
  48.     function member(){
  49.  
  50.         if (!$this->ion_auth->logged_in())
  51.         {
  52.             // redirect them to the login page
  53.             redirect('auth/login', 'refresh');
  54.         }
  55.         elseif (!$this->ion_auth->is_admin()) // remove this elseif if you want to enable this for non-admins
  56.         {
  57.             // redirect them to the home page because they must be an administrator to view this
  58.             return show_error('You must be an administrator to view this page.');
  59.         }
  60.         else
  61.         {
  62.             // set the flash data error message if there is one
  63.             $this->data['message'] = (validation_errors()) ? validation_errors() : $this->session->flashdata('message');
  64.  
  65.             //list the users
  66.             $this->data['tb_users'] = $this->ion_auth->users()->result();
  67.             foreach ($this->data['tb_users'] as $k => $user)
  68.             {
  69.                 $this->data['tb_users'][$k]->groups = $this->ion_auth->get_users_groups($user->id)->result();
  70.             }
  71.  
  72.             $this->template->display('auth/pengguna', $this->data);
  73.         }
  74.     }
  75.  
  76.     /**
  77.      * Log the user in
  78.      */
  79.     public function login()
  80.     {
  81.         $this->data['title'] = $this->lang->line('login_heading');
  82.  
  83.         // validate form input
  84.         $this->form_validation->set_rules('identity', str_replace(':', '', $this->lang->line('login_identity_label')), 'required');
  85.         $this->form_validation->set_rules('password', str_replace(':', '', $this->lang->line('login_password_label')), 'required');
  86.  
  87.         if ($this->form_validation->run() === TRUE)
  88.         {
  89.             // check to see if the user is logging in
  90.             // check for "remember me"
  91.             $remember = (bool)$this->input->post('remember');
  92.  
  93.             if ($this->ion_auth->login($this->input->post('identity'), $this->input->post('password'), $remember))
  94.             {
  95.                 //if the login is successful
  96.                 //redirect them back to the home page
  97.                 $this->session->set_flashdata('message', $this->ion_auth->messages());
  98.                 redirect('/', 'refresh');
  99.             }
  100.             else
  101.             {
  102.                 // if the login was un-successful
  103.                 // redirect them back to the login page
  104.                 $this->session->set_flashdata('message', $this->ion_auth->errors());
  105.                 redirect('auth/login', 'refresh'); // use redirects instead of loading views for compatibility with MY_Controller libraries
  106.             }
  107.         }
  108.         else
  109.         {
  110.             // the user is not logging in so display the login page
  111.             // set the flash data error message if there is one
  112.             $this->data['message'] = (validation_errors()) ? validation_errors() : $this->session->flashdata('message');
  113.  
  114.             $this->data['identity'] = array('name' => 'identity',
  115.                 'id' => 'identity',
  116.                 'type' => 'text',
  117.                 'value' => $this->form_validation->set_value('identity'),
  118.             );
  119.             $this->data['password'] = array('name' => 'password',
  120.                 'id' => 'password',
  121.                 'type' => 'password',
  122.             );
  123.  
  124.             $this->_render_page('auth' . DIRECTORY_SEPARATOR . 'login', $this->data);
  125.         }
  126.     }
  127.  
  128.     /**
  129.      * Log the user out
  130.      */
  131.     public function logout()
  132.     {
  133.         $this->data['title'] = "Logout";
  134.  
  135.         // log the user out
  136.         $logout = $this->ion_auth->logout();
  137.  
  138.         // redirect them to the login page
  139.         $this->session->set_flashdata('message', $this->ion_auth->messages());
  140.         redirect('auth/login', 'refresh');
  141.     }
  142.  
  143.     /**
  144.      * Change password
  145.      */
  146.     public function change_password()
  147.     {
  148.         $this->form_validation->set_rules('old', $this->lang->line('change_password_validation_old_password_label'), 'required');
  149.         $this->form_validation->set_rules('new', $this->lang->line('change_password_validation_new_password_label'), 'required|min_length[' . $this->config->item('min_password_length', 'ion_auth') . ']|max_length[' . $this->config->item('max_password_length', 'ion_auth') . ']|matches[new_confirm]');
  150.         $this->form_validation->set_rules('new_confirm', $this->lang->line('change_password_validation_new_password_confirm_label'), 'required');
  151.  
  152.         if (!$this->ion_auth->logged_in())
  153.         {
  154.             redirect('auth/login', 'refresh');
  155.         }
  156.  
  157.         $user = $this->ion_auth->user()->row();
  158.  
  159.         if ($this->form_validation->run() === FALSE)
  160.         {
  161.             // display the form
  162.             // set the flash data error message if there is one
  163.             $this->data['message'] = (validation_errors()) ? validation_errors() : $this->session->flashdata('message');
  164.  
  165.             $this->data['min_password_length'] = $this->config->item('min_password_length', 'ion_auth');
  166.             $this->data['old_password'] = array(
  167.                 'name' => 'old',
  168.                 'id' => 'old',
  169.                 'type' => 'password',
  170.             );
  171.             $this->data['new_password'] = array(
  172.                 'name' => 'new',
  173.                 'id' => 'new',
  174.                 'type' => 'password',
  175.                 'pattern' => '^.{' . $this->data['min_password_length'] . '}.*$',
  176.             );
  177.             $this->data['new_password_confirm'] = array(
  178.                 'name' => 'new_confirm',
  179.                 'id' => 'new_confirm',
  180.                 'type' => 'password',
  181.                 'pattern' => '^.{' . $this->data['min_password_length'] . '}.*$',
  182.             );
  183.             $this->data['user_id'] = array(
  184.                 'name' => 'user_id',
  185.                 'id' => 'user_id',
  186.                 'type' => 'hidden',
  187.                 'value' => $user->id,
  188.             );
  189.  
  190.             // render
  191.             $this->_render_page('auth' . DIRECTORY_SEPARATOR . 'change_password', $this->data);
  192.         }
  193.         else
  194.         {
  195.             $identity = $this->session->userdata('identity');
  196.  
  197.             $change = $this->ion_auth->change_password($identity, $this->input->post('old'), $this->input->post('new'));
  198.  
  199.             if ($change)
  200.             {
  201.                 //if the password was successfully changed
  202.                 $this->session->set_flashdata('message', $this->ion_auth->messages());
  203.                 $this->logout();
  204.             }
  205.             else
  206.             {
  207.                 $this->session->set_flashdata('message', $this->ion_auth->errors());
  208.                 redirect('auth/change_password', 'refresh');
  209.             }
  210.         }
  211.     }
  212.  
  213.     /**
  214.      * Forgot password
  215.      */
  216.     public function forgot_password()
  217.     {
  218.         // setting validation rules by checking whether identity is username or email
  219.         if ($this->config->item('identity', 'ion_auth') != 'email')
  220.         {
  221.             $this->form_validation->set_rules('identity', $this->lang->line('forgot_password_identity_label'), 'required');
  222.         }
  223.         else
  224.         {
  225.             $this->form_validation->set_rules('identity', $this->lang->line('forgot_password_validation_email_label'), 'required|valid_email');
  226.         }
  227.  
  228.  
  229.         if ($this->form_validation->run() === FALSE)
  230.         {
  231.             $this->data['type'] = $this->config->item('identity', 'ion_auth');
  232.             // setup the input
  233.             $this->data['identity'] = array('name' => 'identity',
  234.                 'id' => 'identity',
  235.             );
  236.  
  237.             if ($this->config->item('identity', 'ion_auth') != 'email')
  238.             {
  239.                 $this->data['identity_label'] = $this->lang->line('forgot_password_identity_label');
  240.             }
  241.             else
  242.             {
  243.                 $this->data['identity_label'] = $this->lang->line('forgot_password_email_identity_label');
  244.             }
  245.  
  246.             // set any errors and display the form
  247.             $this->data['message'] = (validation_errors()) ? validation_errors() : $this->session->flashdata('message');
  248.             $this->_render_page('auth' . DIRECTORY_SEPARATOR . 'forgot_password', $this->data);
  249.         }
  250.         else
  251.         {
  252.             $identity_column = $this->config->item('identity', 'ion_auth');
  253.             $identity = $this->ion_auth->where($identity_column, $this->input->post('identity'))->users()->row();
  254.  
  255.             if (empty($identity))
  256.             {
  257.  
  258.                 if ($this->config->item('identity', 'ion_auth') != 'email')
  259.                 {
  260.                     $this->ion_auth->set_error('forgot_password_identity_not_found');
  261.                 }
  262.                 else
  263.                 {
  264.                     $this->ion_auth->set_error('forgot_password_email_not_found');
  265.                 }
  266.  
  267.                 $this->session->set_flashdata('message', $this->ion_auth->errors());
  268.                 redirect("auth/forgot_password", 'refresh');
  269.             }
  270.  
  271.             // run the forgotten password method to email an activation code to the user
  272.             $forgotten = $this->ion_auth->forgotten_password($identity->{$this->config->item('identity', 'ion_auth')});
  273.  
  274.             if ($forgotten)
  275.             {
  276.                 // if there were no errors
  277.                 $this->session->set_flashdata('message', $this->ion_auth->messages());
  278.                 redirect("auth/login", 'refresh'); //we should display a confirmation page here instead of the login page
  279.             }
  280.             else
  281.             {
  282.                 $this->session->set_flashdata('message', $this->ion_auth->errors());
  283.                 redirect("auth/forgot_password", 'refresh');
  284.             }
  285.         }
  286.     }
  287.  
  288.     /**
  289.      * Reset password - final step for forgotten password
  290.      *
  291.      * @param string|null $code The reset code
  292.      */
  293.     public function reset_password($code = NULL)
  294.     {
  295.         if (!$code)
  296.         {
  297.             show_404();
  298.         }
  299.  
  300.         $user = $this->ion_auth->forgotten_password_check($code);
  301.  
  302.         if ($user)
  303.         {
  304.             // if the code is valid then display the password reset form
  305.  
  306.             $this->form_validation->set_rules('new', $this->lang->line('reset_password_validation_new_password_label'), 'required|min_length[' . $this->config->item('min_password_length', 'ion_auth') . ']|max_length[' . $this->config->item('max_password_length', 'ion_auth') . ']|matches[new_confirm]');
  307.             $this->form_validation->set_rules('new_confirm', $this->lang->line('reset_password_validation_new_password_confirm_label'), 'required');
  308.  
  309.             if ($this->form_validation->run() === FALSE)
  310.             {
  311.                 // display the form
  312.  
  313.                 // set the flash data error message if there is one
  314.                 $this->data['message'] = (validation_errors()) ? validation_errors() : $this->session->flashdata('message');
  315.  
  316.                 $this->data['min_password_length'] = $this->config->item('min_password_length', 'ion_auth');
  317.                 $this->data['new_password'] = array(
  318.                     'name' => 'new',
  319.                     'id' => 'new',
  320.                     'type' => 'password',
  321.                     'pattern' => '^.{' . $this->data['min_password_length'] . '}.*$',
  322.                 );
  323.                 $this->data['new_password_confirm'] = array(
  324.                     'name' => 'new_confirm',
  325.                     'id' => 'new_confirm',
  326.                     'type' => 'password',
  327.                     'pattern' => '^.{' . $this->data['min_password_length'] . '}.*$',
  328.                 );
  329.                 $this->data['user_id'] = array(
  330.                     'name' => 'user_id',
  331.                     'id' => 'user_id',
  332.                     'type' => 'hidden',
  333.                     'value' => $user->id,
  334.                 );
  335.                 $this->data['csrf'] = $this->_get_csrf_nonce();
  336.                 $this->data['code'] = $code;
  337.  
  338.                 // render
  339.                 $this->_render_page('auth' . DIRECTORY_SEPARATOR . 'reset_password', $this->data);
  340.             }
  341.             else
  342.             {
  343.                 // do we have a valid request?
  344.                 if ($this->_valid_csrf_nonce() === FALSE || $user->id != $this->input->post('user_id'))
  345.                 {
  346.  
  347.                     // something fishy might be up
  348.                     $this->ion_auth->clear_forgotten_password_code($code);
  349.  
  350.                     show_error($this->lang->line('error_csrf'));
  351.  
  352.                 }
  353.                 else
  354.                 {
  355.                     // finally change the password
  356.                     $identity = $user->{$this->config->item('identity', 'ion_auth')};
  357.  
  358.                     $change = $this->ion_auth->reset_password($identity, $this->input->post('new'));
  359.  
  360.                     if ($change)
  361.                     {
  362.                         // if the password was successfully changed
  363.                         $this->session->set_flashdata('message', $this->ion_auth->messages());
  364.                         redirect("auth/login", 'refresh');
  365.                     }
  366.                     else
  367.                     {
  368.                         $this->session->set_flashdata('message', $this->ion_auth->errors());
  369.                         redirect('auth/reset_password/' . $code, 'refresh');
  370.                     }
  371.                 }
  372.             }
  373.         }
  374.         else
  375.         {
  376.             // if the code is invalid then send them back to the forgot password page
  377.             $this->session->set_flashdata('message', $this->ion_auth->errors());
  378.             redirect("auth/forgot_password", 'refresh');
  379.         }
  380.     }
  381.  
  382.     /**
  383.      * Activate the user
  384.      *
  385.      * @param int         $id   The user ID
  386.      * @param string|bool $code The activation code
  387.      */
  388.     public function activate($id, $code = FALSE)
  389.     {
  390.         if ($code !== FALSE)
  391.         {
  392.             $activation = $this->ion_auth->activate($id, $code);
  393.         }
  394.         else if ($this->ion_auth->is_admin())
  395.         {
  396.             $activation = $this->ion_auth->activate($id);
  397.         }
  398.  
  399.         if ($activation)
  400.         {
  401.             // redirect them to the auth page
  402.             $this->session->set_flashdata('message', $this->ion_auth->messages());
  403.             redirect("auth", 'refresh');
  404.         }
  405.         else
  406.         {
  407.             // redirect them to the forgot password page
  408.             $this->session->set_flashdata('message', $this->ion_auth->errors());
  409.             redirect("auth/forgot_password", 'refresh');
  410.         }
  411.     }
  412.  
  413.     /**
  414.      * Deactivate the user
  415.      *
  416.      * @param int|string|null $id The user ID
  417.      */
  418.     public function deactivate($id = NULL)
  419.     {
  420.         if (!$this->ion_auth->logged_in() || !$this->ion_auth->is_admin())
  421.         {
  422.             // redirect them to the home page because they must be an administrator to view this
  423.             return show_error('You must be an administrator to view this page.');
  424.         }
  425.  
  426.         $id = (int)$id;
  427.  
  428.         $this->load->library('form_validation');
  429.         $this->form_validation->set_rules('confirm', $this->lang->line('deactivate_validation_confirm_label'), 'required');
  430.         $this->form_validation->set_rules('id', $this->lang->line('deactivate_validation_user_id_label'), 'required|alpha_numeric');
  431.  
  432.         if ($this->form_validation->run() === FALSE)
  433.         {
  434.             // insert csrf check
  435.             $this->data['csrf'] = $this->_get_csrf_nonce();
  436.             $this->data['user'] = $this->ion_auth->user($id)->row();
  437.  
  438.             $this->template->display('auth/deactivate_user', $this->data);
  439.         }
  440.         else
  441.         {
  442.             // do we really want to deactivate?
  443.             if ($this->input->post('confirm') == 'yes')
  444.             {
  445.                 // do we have a valid request?
  446.                 if ($this->_valid_csrf_nonce() === FALSE || $id != $this->input->post('id'))
  447.                 {
  448.                     return show_error($this->lang->line('error_csrf'));
  449.                 }
  450.  
  451.                 // do we have the right userlevel?
  452.                 if ($this->ion_auth->logged_in() && $this->ion_auth->is_admin())
  453.                 {
  454.                     $this->ion_auth->deactivate($id);
  455.                 }
  456.             }
  457.  
  458.             // redirect them back to the auth page
  459.             redirect('auth/member', 'refresh');
  460.         }
  461.     }
  462.  
  463.     /**
  464.      * Create a new user
  465.      */
  466.     public function create_user()
  467.     {
  468.         $this->data['title'] = $this->lang->line('create_user_heading');
  469.  
  470.         if (!$this->ion_auth->logged_in() || !$this->ion_auth->is_admin())
  471.         {
  472.             redirect('auth', 'refresh');
  473.         }
  474.  
  475.         $tables = $this->config->item('tables', 'ion_auth');
  476.         $identity_column = $this->config->item('identity', 'ion_auth');
  477.         $this->data['identity_column'] = $identity_column;
  478.  
  479.         // validate form input
  480.         $this->form_validation->set_rules('first_name', $this->lang->line('create_user_validation_fname_label'), 'trim|required');
  481.         $this->form_validation->set_rules('last_name', $this->lang->line('create_user_validation_lname_label'), 'trim|required');
  482.         if ($identity_column !== 'email')
  483.         {
  484.             $this->form_validation->set_rules('identity', $this->lang->line('create_user_validation_identity_label'), 'trim|required|is_unique[' . $tables['users'] . '.' . $identity_column . ']');
  485.             $this->form_validation->set_rules('email', $this->lang->line('create_user_validation_email_label'), 'trim|required|valid_email');
  486.         }
  487.         else
  488.         {
  489.             $this->form_validation->set_rules('email', $this->lang->line('create_user_validation_email_label'), 'trim|required|valid_email|is_unique[' . $tables['users'] . '.email]');
  490.         }
  491.         $this->form_validation->set_rules('phone', $this->lang->line('create_user_validation_phone_label'), 'trim');
  492.         $this->form_validation->set_rules('company', $this->lang->line('create_user_validation_company_label'), 'trim');
  493.         $this->form_validation->set_rules('password', $this->lang->line('create_user_validation_password_label'), 'required|min_length[' . $this->config->item('min_password_length', 'ion_auth') . ']|max_length[' . $this->config->item('max_password_length', 'ion_auth') . ']|matches[password_confirm]');
  494.         $this->form_validation->set_rules('password_confirm', $this->lang->line('create_user_validation_password_confirm_label'), 'required');
  495.  
  496.         if ($this->form_validation->run() === TRUE)
  497.         {
  498.             $email = strtolower($this->input->post('email'));
  499.             $identity = ($identity_column === 'email') ? $email : $this->input->post('identity');
  500.             $password = $this->input->post('password');
  501.  
  502.             $additional_data = array(
  503.                 'first_name' => $this->input->post('first_name'),
  504.                 'last_name' => $this->input->post('last_name'),
  505.                 'company' => $this->input->post('name_toko'),
  506.                 'phone' => $this->input->post('phone'),
  507.             );
  508.         }
  509.         if ($this->form_validation->run() === TRUE && $this->ion_auth->register($identity, $password, $email, $additional_data))
  510.         {
  511.             // check to see if we are creating the user
  512.             // redirect them back to the admin page
  513.             echo json_encode(array('status' => TRUE));
  514.             $this->session->set_flashdata('message', $this->ion_auth->messages());
  515.             redirect("auth/member", 'refresh');
  516.         }
  517.         else
  518.         {
  519.             // display the create user form
  520.             // set the flash data error message if there is one
  521.             $this->data['message'] = (validation_errors() ? validation_errors() : ($this->ion_auth->errors() ? $this->ion_auth->errors() : $this->session->flashdata('message')));
  522.  
  523.             $this->data['first_name'] = array(
  524.                 'name' => 'first_name',
  525.                 'id' => 'first_name',
  526.                 'type' => 'text',
  527.                 'value' => $this->form_validation->set_value('first_name'),
  528.             );
  529.             $this->data['last_name'] = array(
  530.                 'name' => 'last_name',
  531.                 'id' => 'last_name',
  532.                 'type' => 'text',
  533.                 'value' => $this->form_validation->set_value('last_name'),
  534.             );
  535.             $this->data['identity'] = array(
  536.                 'name' => 'identity',
  537.                 'id' => 'identity',
  538.                 'type' => 'text',
  539.                 'value' => $this->form_validation->set_value('identity'),
  540.             );
  541.             $this->data['email'] = array(
  542.                 'name' => 'email',
  543.                 'id' => 'email',
  544.                 'type' => 'text',
  545.                 'value' => $this->form_validation->set_value('email'),
  546.             );
  547.             $this->data['company'] = array(
  548.                 'name' => 'company',
  549.                 'id' => 'company',
  550.                 'type' => 'text',
  551.                 'value' => $this->form_validation->set_value('company'),
  552.             );
  553.             $this->data['phone'] = array(
  554.                 'name' => 'phone',
  555.                 'id' => 'phone',
  556.                 'type' => 'text',
  557.                 'value' => $this->form_validation->set_value('phone'),
  558.             );
  559.             $this->data['password'] = array(
  560.                 'name' => 'password',
  561.                 'id' => 'password',
  562.                 'type' => 'password',
  563.                 'value' => $this->form_validation->set_value('password'),
  564.             );
  565.             $this->data['password_confirm'] = array(
  566.                 'name' => 'password_confirm',
  567.                 'id' => 'password_confirm',
  568.                 'type' => 'password',
  569.                 'value' => $this->form_validation->set_value('password_confirm'),
  570.             );
  571.  
  572.             $this->_render_page('auth' . DIRECTORY_SEPARATOR . 'create_user', $this->data);
  573.         }
  574.     }
  575.     /**
  576.     * Redirect a user checking if is admin
  577.     */
  578.     public function redirectUser(){
  579.         if ($this->ion_auth->is_admin()){
  580.             redirect('auth', 'refresh');
  581.         }
  582.         redirect('/', 'refresh');
  583.     }
  584.  
  585.     /**
  586.      * Edit a user
  587.      *
  588.      * @param int|string $id
  589.      */
  590.     public function edit_user($id)
  591.     {
  592.         $this->data['title'] = $this->lang->line('edit_user_heading');
  593.  
  594.         if (!$this->ion_auth->logged_in() || (!$this->ion_auth->is_admin() && !($this->ion_auth->user()->row()->id == $id)))
  595.         {
  596.             redirect('auth', 'refresh');
  597.         }
  598.  
  599.         $user = $this->ion_auth->user($id)->row();
  600.         $groups = $this->ion_auth->groups()->result_array();
  601.         $currentGroups = $this->ion_auth->get_users_groups($id)->result();
  602.  
  603.         // validate form input
  604.         $this->form_validation->set_rules('first_name', $this->lang->line('edit_user_validation_fname_label'), 'trim|required');
  605.         $this->form_validation->set_rules('last_name', $this->lang->line('edit_user_validation_lname_label'), 'trim|required');
  606.         $this->form_validation->set_rules('phone', $this->lang->line('edit_user_validation_phone_label'), 'trim|required');
  607.         $this->form_validation->set_rules('company', $this->lang->line('edit_user_validation_company_label'), 'trim|required');
  608.  
  609.         if (isset($_POST) && !empty($_POST))
  610.         {
  611.             // do we have a valid request?
  612.             if ($this->_valid_csrf_nonce() === FALSE || $id != $this->input->post('id'))
  613.             {
  614.                 show_error($this->lang->line('error_csrf'));
  615.             }
  616.  
  617.             // update the password if it was posted
  618.             if ($this->input->post('password'))
  619.             {
  620.                 $this->form_validation->set_rules('password', $this->lang->line('edit_user_validation_password_label'), 'required|min_length[' . $this->config->item('min_password_length', 'ion_auth') . ']|max_length[' . $this->config->item('max_password_length', 'ion_auth') . ']|matches[password_confirm]');
  621.                 $this->form_validation->set_rules('password_confirm', $this->lang->line('edit_user_validation_password_confirm_label'), 'required');
  622.             }
  623.  
  624.             if ($this->form_validation->run() === TRUE)
  625.             {
  626.                 $data = array(
  627.                     'first_name' => $this->input->post('first_name'),
  628.                     'last_name' => $this->input->post('last_name'),
  629.                     'company' => $this->input->post('company'),
  630.                     'phone' => $this->input->post('phone'),
  631.                 );
  632.  
  633.                 // update the password if it was posted
  634.                 if ($this->input->post('password'))
  635.                 {
  636.                     $data['password'] = $this->input->post('password');
  637.                 }
  638.  
  639.                 // Only allow updating groups if user is admin
  640.                 if ($this->ion_auth->is_admin())
  641.                 {
  642.                     // Update the groups user belongs to
  643.                     $groupData = $this->input->post('groups');
  644.  
  645.                     if (isset($groupData) && !empty($groupData))
  646.                     {
  647.  
  648.                         $this->ion_auth->remove_from_group('', $id);
  649.  
  650.                         foreach ($groupData as $grp)
  651.                         {
  652.                             $this->ion_auth->add_to_group($grp, $id);
  653.                         }
  654.  
  655.                     }
  656.                 }
  657.  
  658.                 // check to see if we are updating the user
  659.                 if ($this->ion_auth->update($user->id, $data))
  660.                 {
  661.                     // redirect them back to the admin page if admin, or to the base url if non admin
  662.                     $this->session->set_flashdata('message', $this->ion_auth->messages());
  663.                     $this->redirectUser();
  664.  
  665.                 }
  666.                 else
  667.                 {
  668.                     // redirect them back to the admin page if admin, or to the base url if non admin
  669.                     $this->session->set_flashdata('message', $this->ion_auth->errors());
  670.                     $this->redirectUser();
  671.  
  672.                 }
  673.  
  674.             }
  675.         }
  676.  
  677.         // set the flash data error message if there is one
  678.         $this->data['message'] = (validation_errors() ? validation_errors() : ($this->ion_auth->errors() ? $this->ion_auth->errors() : $this->session->flashdata('message')));
  679.  
  680.         // pass the user to the view
  681.         $this->data['user'] = $user;
  682.         $this->data['groups'] = $groups;
  683.         $this->data['currentGroups'] = $currentGroups;
  684.  
  685.         echo json_encode($this->data);
  686.     }
  687.  
  688.     /**
  689.      * Create a new group
  690.      */
  691.     public function create_group()
  692.     {
  693.         $this->data['title'] = $this->lang->line('create_group_title');
  694.  
  695.         if (!$this->ion_auth->logged_in() || !$this->ion_auth->is_admin())
  696.         {
  697.             redirect('auth', 'refresh');
  698.         }
  699.  
  700.         // validate form input
  701.         $this->form_validation->set_rules('group_name', $this->lang->line('create_group_validation_name_label'), 'trim|required|alpha_dash');
  702.  
  703.         if ($this->form_validation->run() === TRUE)
  704.         {
  705.             $new_group_id = $this->ion_auth->create_group($this->input->post('group_name'), $this->input->post('description'));
  706.             if ($new_group_id)
  707.             {
  708.                 // check to see if we are creating the group
  709.                 // redirect them back to the admin page
  710.                 $this->session->set_flashdata('message', $this->ion_auth->messages());
  711.                 redirect("auth", 'refresh');
  712.             }
  713.         }
  714.         else
  715.         {
  716.             // display the create group form
  717.             // set the flash data error message if there is one
  718.             $this->data['message'] = (validation_errors() ? validation_errors() : ($this->ion_auth->errors() ? $this->ion_auth->errors() : $this->session->flashdata('message')));
  719.  
  720.             $this->data['group_name'] = array(
  721.                 'name'  => 'group_name',
  722.                 'id'    => 'group_name',
  723.                 'type'  => 'text',
  724.                 'value' => $this->form_validation->set_value('group_name'),
  725.             );
  726.             $this->data['description'] = array(
  727.                 'name'  => 'description',
  728.                 'id'    => 'description',
  729.                 'type'  => 'text',
  730.                 'value' => $this->form_validation->set_value('description'),
  731.             );
  732.  
  733.             $this->_render_page('auth' . DIRECTORY_SEPARATOR . 'create_group', $this->data);
  734.         }
  735.     }
  736.  
  737.     /**
  738.      * Edit a group
  739.      *
  740.      * @param int|string $id
  741.      */
  742.     public function edit_group($id)
  743.     {
  744.         // bail if no group id given
  745.         if (!$id || empty($id))
  746.         {
  747.             redirect('auth', 'refresh');
  748.         }
  749.  
  750.         $this->data['title'] = $this->lang->line('edit_group_title');
  751.  
  752.         if (!$this->ion_auth->logged_in() || !$this->ion_auth->is_admin())
  753.         {
  754.             redirect('auth', 'refresh');
  755.         }
  756.  
  757.         $group = $this->ion_auth->group($id)->row();
  758.  
  759.         // validate form input
  760.         $this->form_validation->set_rules('group_name', $this->lang->line('edit_group_validation_name_label'), 'required|alpha_dash');
  761.  
  762.         if (isset($_POST) && !empty($_POST))
  763.         {
  764.             if ($this->form_validation->run() === TRUE)
  765.             {
  766.                 $group_update = $this->ion_auth->update_group($id, $_POST['group_name'], $_POST['group_description']);
  767.  
  768.                 if ($group_update)
  769.                 {
  770.                     $this->session->set_flashdata('message', $this->lang->line('edit_group_saved'));
  771.                 }
  772.                 else
  773.                 {
  774.                     $this->session->set_flashdata('message', $this->ion_auth->errors());
  775.                 }
  776.                 redirect("auth", 'refresh');
  777.             }
  778.         }
  779.  
  780.         // set the flash data error message if there is one
  781.         $this->data['message'] = (validation_errors() ? validation_errors() : ($this->ion_auth->errors() ? $this->ion_auth->errors() : $this->session->flashdata('message')));
  782.  
  783.         // pass the user to the view
  784.         $this->data['group'] = $group;
  785.  
  786.         $readonly = $this->config->item('admin_group', 'ion_auth') === $group->name ? 'readonly' : '';
  787.  
  788.         $this->data['group_name'] = array(
  789.             'name'    => 'group_name',
  790.             'id'      => 'group_name',
  791.             'type'    => 'text',
  792.             'value'   => $this->form_validation->set_value('group_name', $group->name),
  793.             $readonly => $readonly,
  794.         );
  795.         $this->data['group_description'] = array(
  796.             'name'  => 'group_description',
  797.             'id'    => 'group_description',
  798.             'type'  => 'text',
  799.             'value' => $this->form_validation->set_value('group_description', $group->description),
  800.         );
  801.  
  802.         $this->_render_page('auth' . DIRECTORY_SEPARATOR . 'edit_group', $this->data);
  803.     }
  804.  
  805.     /**
  806.      * @return array A CSRF key-value pair
  807.      */
  808.     public function _get_csrf_nonce()
  809.     {
  810.         $this->load->helper('string');
  811.         $key = random_string('alnum', 8);
  812.         $value = random_string('alnum', 20);
  813.         $this->session->set_flashdata('csrfkey', $key);
  814.         $this->session->set_flashdata('csrfvalue', $value);
  815.  
  816.         return array($key => $value);
  817.     }
  818.  
  819.     /**
  820.      * @return bool Whether the posted CSRF token matches
  821.      */
  822.     public function _valid_csrf_nonce(){
  823.         $csrfkey = $this->input->post($this->session->flashdata('csrfkey'));
  824.         if ($csrfkey && $csrfkey === $this->session->flashdata('csrfvalue')){
  825.             return TRUE;
  826.         }
  827.             return FALSE;
  828.     }
  829.  
  830.     /**
  831.      * @param string     $view
  832.      * @param array|null $data
  833.      * @param bool       $returnhtml
  834.      *
  835.      * @return mixed
  836.      */
  837.     public function _render_page($view, $data = NULL, $returnhtml = FALSE)//I think this makes more sense
  838.     {
  839.  
  840.         $this->viewdata = (empty($data)) ? $this->data : $data;
  841.  
  842.         $view_html = $this->load->view($view, $this->viewdata, $returnhtml);
  843.  
  844.         // This will return html on 3rd argument being true
  845.         if ($returnhtml)
  846.         {
  847.             return $view_html;
  848.         }
  849.     }
  850.  
  851.     public function delete($id){
  852.         $this->load->model('Ion_auth_model');
  853.         $this->Ion_auth_model->delete_user($id);
  854.         redirect('auth/member');
  855.     }
  856.  
  857. }
  858.  
  859. <--- VIEWS--->
  860. <section class="content-header">
  861.     <h1>
  862.         <?php echo strtoupper(lang('index_heading'));?>
  863.         <small><?php echo lang('index_subheading');?></small>
  864.     </h1>
  865.     <ol class="breadcrumb">
  866.         <li><a href="#"><i class="fa fa-suitcase"></i>Seting</a></li>
  867.         <li class="active"><?php echo lang('index_heading');?></li>
  868.     </ol>
  869. </section>
  870. <section class="content">  
  871.  
  872.     <div class="row">
  873.         <div class="col-md-12">
  874.             <div class="box box-primary">
  875.                 <div class='box-header with-border'>
  876.                     <h3 class='box-title'><a onclick="add_user()" class="btn btn-primary btn-small">
  877.                             <i class="glyphicon glyphicon-plus"></i> <?php echo lang('index_create_user_link');?></a></h3>
  878.                             <label calss='control-label' ></label>
  879.                 </div>
  880.                 <div class="box-body table-responsive">
  881.                     <table id="mytable" class="table table-bordered table-striped" cellspacing="0" width="100%">
  882.                         <thead>
  883.                             <tr>
  884.                                 <th>No.</th>
  885.                                 <th>Nama User</th>
  886.                                 <th>Nama Lengkap</th>
  887.                                 <th>Alamat Email</th>
  888.                                 <th>Nama Perusahaan</th>
  889.                                 <th>Telpn</th>  
  890.                                 <th>Status</th>                                                          
  891.                                 <th>Edit</th>  
  892.                                 <th>Delete</th>                                
  893.                             </tr>
  894.                         </thead>
  895.                        <?php
  896.                        $no=1;                  
  897.                        foreach ($tb_users as $user){
  898.                            echo"
  899.                               <tr>
  900.                               <td>$no</td>
  901.                               <td>".$user->username."</td>
  902.                               <td>".strtoupper($user->first_name),' ',strtoupper($user->last_name)."</td>
  903.                               <td>".$user->email."</td>
  904.                               <td>".strtoupper($user->company)."</td>
  905.                               <td>".$user->phone."</td>
  906.                               ";?>                            
  907.                                <td><?php echo ($user->active) ? anchor("auth/deactivate/".$user->id, lang('index_active_link')) : anchor("auth/activate/". $user->id, lang('index_inactive_link'));?></td>
  908.  
  909.                                <td><a onclick="edit_user(<?php echo $user->id;?>)"><i class="btn btn-info btn-sm glyphicon glyphicon-edit" data-toggle="tooltip" title="Edit"></i></a></td>
  910.                               <?php
  911.                                echo"
  912.                               <td>" . anchor('auth/delete/' . $user->id, '<i class="btn-sm btn-info glyphicon glyphicon-trash" data-toggle="tooltip" title="Delete"></i>', array('onclick' => "return confirm('Data Akan di Hapus?')")) . "</td>
  913.  
  914.                               </tr>";
  915.                            $no++;
  916.                        }
  917.                        ?>
  918.                     </Table>
  919.                 </div><!-- /.box-body -->
  920.             </div><!-- /.box -->
  921.         </div>
  922.     </div>
  923. </section><!-- /.content -->
  924. <script src="<?php echo base_url();?>assets/js/jquery-1.12.0.min.js"></script>
  925. <script src="<?php echo base_url();?>assets/js/plugins/datatables/jquery.dataTables.min.js"></script>
  926. <script type="text/javascript">
  927.     $(document).ready(function () {
  928.         $("#mytable").dataTable();
  929.     });
  930. </script>
  931. <script type="text/javascript">
  932.  
  933. var save_method; //for save method string
  934. var table;
  935.  
  936.   function get_crsf(){
  937.     $("input[id='crsf']").remove();
  938.  
  939.     $.ajax({
  940.         url : "<?php echo site_url('auth/crsf_ajax');?>",
  941.         type: "POST",
  942.         dataType: "JSON",
  943.         success: function(data)
  944.         {
  945.             $.map(data.crsf, function(k, v){
  946.             crsfKey = v;
  947.             crsfValue = k;
  948.             });
  949.  
  950.             var crsf = [];
  951.            
  952.             var crsf = '<input type="hidden" id="crsf" name="'+crsfKey+'" value="'+crsfValue+'" /> ';
  953.  
  954.             $('#form').append(crsf);
  955.         },
  956.         error: function (xhr, ajaxoptions, errorThrown)
  957.         {
  958.             console.log('Error get crsf ajax data');
  959.             console.log(xhr.status);
  960.             console.log(errorThrown);
  961.             console.log(xhr.responseText)
  962.         }
  963.     });
  964.   };
  965.  
  966.   function add_user()
  967.   {
  968.       save_method = 'add';
  969.       $('#form')[0].reset(); // reset form on modals
  970.       $('.form-group').removeClass('has-error'); // clear error class
  971.       $('.help-block').empty(); // clear error string
  972.       get_crsf();
  973.       $('#myModal').modal('show'); // show bootstrap modal
  974.       $('.modal-title').text('MENAMBAHKAN USER'); // Set Title to Bootstrap modal title
  975.   }
  976.  
  977.   function simpan(id)
  978.   {
  979.       var url;
  980.  
  981.       if(save_method == 'add') {
  982.           url = "<?php echo site_url('auth/create_user');?>";
  983.       } else {
  984.           url = "<?php echo site_url('auth/edit_user/')?>"+id;
  985.       }
  986.       // ajax adding data to database
  987.       $.ajax({
  988.           url : url,
  989.           type: "POST",
  990.           data: $('#form').serialize(),
  991.           dataType: "JSON",
  992.           success: function(data)
  993.           {
  994.               $('#myModal').modal('hide');
  995.               alert('Success Adding/Update data');
  996.           },
  997.           error: function (jqXHR, textStatus, errorThrown)
  998.           {
  999.               alert("Gagal menambahkan/Edit user, mungkin user sudah ada/kesalahan data !!!");
  1000.           }
  1001.       });
  1002.   }
  1003.  
  1004.   function edit_user(id)
  1005.   {
  1006.     save_method = 'update';
  1007.     $('#form')[0].reset(); // reset form on modals
  1008.     // $('.form-group').removeClass('has-error'); // clear error class
  1009.     // $('.help-block').empty(); // clear error string
  1010.     //Ajax Load data from ajax
  1011.     $.ajax({
  1012.         url : "<?php echo site_url('auth/edit_user')?>/"+id,
  1013.         type: "GET",
  1014.         dataType: "JSON",
  1015.         success: function(data)
  1016.         {
  1017.             $('[name="id"]').val(data.id);
  1018.             $('[name="first_name"]').val(data.user['first_name']);
  1019.             $('[name="last_name"]').val(data.user['last_name']);
  1020.             $('[name="username"]').val(data.user['username']);
  1021.             $('[name="email"]').val(data.user['email']);
  1022.             $('[name="name_toko"]').val(data.user['company']);
  1023.             $('[name="phone"]').val(data.user['phone']);
  1024.             get_crsf();
  1025.  
  1026.             $('#myModal').modal('show'); // show bootstrap modal when complete loaded
  1027.             $('.modal-title').text('Edit User'); // Set title to Bootstrap modal title
  1028.  
  1029.         },
  1030.         error: function (jqXHR, textStatus, errorThrown)
  1031.         {
  1032.             alert('Error get data from ajax');
  1033.         }
  1034.     });
  1035.   }
  1036. </script>
  1037.  
  1038. <!-- Bootstrap modal -->
  1039. <div class="modal fade" id="myModal" role="dialog">
  1040.     <div class="modal-dialog">
  1041.         <div class="modal-content">
  1042.             <div class="modal-header">
  1043.                 <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
  1044.                 <h3 class="modal-title">Person Form</h3>
  1045.             </div>
  1046.             <div class="modal-body form">
  1047.                 <?php
  1048.                     echo form_open('auth/create_user','id=form');
  1049.                 ?>
  1050.                   <div class="text-red"><?php echo $message;?></div>
  1051.                     <div class="box-body">
  1052.                         <?php echo form_hidden('id', $user->id);?>
  1053.                         <div class="form-group">
  1054.                             <label for="example">Nama Depan</label>
  1055.                             <input type="text" name="first_name" id="first_name" class="form-control" required oninvalid="setCustomValidity('Nama Depan !')"
  1056.                                    oninput="setCustomValidity('')" placeholder="Masukan Nama Depan" >
  1057.                         </div>                                          
  1058.                         <div class="form-group">
  1059.                             <label for="">Nama Belakang</label>
  1060.                             <input type="text" class="form-control" name="last_name" id="last_name" required oninvalid="setCustomValidity('Nama Belakang !')"
  1061.                                    oninput="setCustomValidity('')" placeholder="Masukan Nama Belakang">
  1062.                         </div>
  1063.                          <div class="form-group">
  1064.                             <label for="">Nama Pengguna</label>
  1065.                             <input type="text" class="form-control" name="username" id="username" required oninvalid="setCustomValidity('Nama Pengguna !')"
  1066.                                    oninput="setCustomValidity('')" placeholder="Nama Pengguna">
  1067.                             <?php echo form_error('username', '<div class="text-red">', '</div>'); ?>
  1068.                         </div>  
  1069.                         <div class="form-group">
  1070.                             <label for="">Alamat Email (jika edit jangan di ganti)</label>
  1071.                             <input type="email" class="form-control" name="email" id="email" required oninvalid="setCustomValidity('Email Kosong/ Format Tidak Sesuai !')"
  1072.                                    oninput="setCustomValidity('')" placeholder="example@example.com">
  1073.                         </div>  
  1074.                         <div class="form-group">
  1075.                             <label for="">Nama Perusahaan</label>
  1076.                             <input type="text" class="form-control" name="name_toko" id="name_toko" required oninvalid="setCustomValidity('Nama Perusahaan Kosong !')"
  1077.                                    oninput="setCustomValidity('')" placeholder="Masukan Nama Perusahaan">
  1078.                         </div>
  1079.                         <div class="form-group">
  1080.                             <label for="">Nomor Handphone</label>
  1081.                             <input type="number" class="form-control" name="phone" id="phone" required oninvalid="setCustomValidity('Nama Perusahaan Kosong !')"
  1082.                                    oninput="setCustomValidity('')" placeholder="Masukan No Handphone">
  1083.                         </div>
  1084.                         <div class="form-group">
  1085.                             <label for="">Password</label>
  1086.                             <input type="password" class="form-control" name="password" id="password" required oninvalid="setCustomValidity('Password Kosong !')"
  1087.                                    oninput="setCustomValidity('')" placeholder="Masukan Password (min 8 max 20)">
  1088.                         </div>  
  1089.                         <div class="form-group">
  1090.                             <label for="">Ulangi Password</label>
  1091.                             <input type="password" class="form-control" name="password_confirm" id="password_confirm" required oninvalid="setCustomValidity('Ulang Password Kosong !')"
  1092.                                    oninput="setCustomValidity('')" placeholder="Ulangi Password">
  1093.                         </div>
  1094.                     </div><!-- /.box-body -->
  1095.  
  1096.             </div>
  1097.             <div class="modal-footer">
  1098.                 <button type="button" id="btnSave" onclick="simpan(<?php echo $user->id;?>)" class="btn btn-primary">Save</button>
  1099.                 <button type="button" class="btn btn-danger" data-dismiss="modal">Cancel</button>
  1100.             </div>
  1101.         </div><!-- /.modal-content -->
  1102.     </div><!-- /.modal-dialog -->
  1103. </div><!-- /.modal -->
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement