Ion Auth - Create_User в другом контроллере не работает

Я взял контроллер «auth», скопировал его и переименовал в «сайт». Я переименовал ссылки на представления и т. д. на «сайт». Когда я захожу на www.mysite/index.php/site/create_user, форма загружается нормально. Однако при нажатии кнопки «Отправить» меня перенаправляют на www.mysite.com/index.php/site/login, и в базу данных ничего не добавляется. Может ли кто-нибудь сказать мне, почему это не работает? Мой контроллер сайта ниже:

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

class Site extends CI_Controller {

//
//Authentication
//

function __construct()
{
    parent::__construct();
    $this->load->database();
    $this->load->library(array('ion_auth','form_validation'));
    $this->load->helper(array('url','language'));

    $this->form_validation->set_error_delimiters($this->config->item('error_start_delimiter', 'ion_auth'), $this->config->item('error_end_delimiter', 'ion_auth'));

    $this->lang->load('auth');
}


//Function to log the user in       
function login()
{
    $this->data['title'] = "Login";

    //validate form input
    $this->form_validation->set_rules('identity', 'Identity', 'required');
    $this->form_validation->set_rules('password', 'Password', 'required');

    if ($this->form_validation->run() == true)
    {
        // check to see if the user is logging in
        // check for "remember me"
        $remember = (bool) $this->input->post('remember');

        if ($this->ion_auth->login($this->input->post('identity'), $this->input->post('password'), $remember))
        {
            //if the login is successful
            //redirect them back to the home page
            $this->session->set_flashdata('message', $this->ion_auth->messages());
            redirect('/', 'refresh');
        }
        else
        {
            // if the login was un-successful
            // redirect them back to the login page
            $this->session->set_flashdata('message', $this->ion_auth->errors());
            redirect('site/login', 'refresh'); // use redirects instead of loading views for compatibility with MY_Controller libraries
        }
    }
    else
    {
        // the user is not logging in so display the login page
        // set the flash data error message if there is one
        $this->data['message'] = (validation_errors()) ? validation_errors() : $this->session->flashdata('message');

        $this->data['identity'] = array('name' => 'identity',
            'id'    => 'identity',
            'type'  => 'text',
            'value' => $this->form_validation->set_value('identity'),
        );
        $this->data['password'] = array('name' => 'password',
            'id'   => 'password',
            'type' => 'password',
        );

        $this->_render_page('site/login', $this->data);
    }
}

//Function to log the user out
function logout()
{
    $this->data['title'] = "Logout";

    // log the user out
    $logout = $this->ion_auth->logout();

    // redirect them to the login page
    $this->session->set_flashdata('message', $this->ion_auth->messages());
    redirect('site/login', 'refresh');
}


//Function to create a user
function create_user()
{
    $this->data['title'] = "Create User";

    if (!$this->ion_auth->logged_in() || !$this->ion_auth->is_admin())
    {
        //redirect('site/login', 'refresh');
    }

    $tables = $this->config->item('tables','ion_auth');

    // validate form input
    $this->form_validation->set_rules('first_name', $this->lang->line('create_user_validation_fname_label'), 'required');
    $this->form_validation->set_rules('last_name', $this->lang->line('create_user_validation_lname_label'), 'required');
    $this->form_validation->set_rules('email', $this->lang->line('create_user_validation_email_label'), 'required|valid_email|is_unique['.$tables['users'].'.email]');
    $this->form_validation->set_rules('phone', $this->lang->line('create_user_validation_phone_label'), 'required');
    $this->form_validation->set_rules('company', $this->lang->line('create_user_validation_company_label'), 'required');
    $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]');
    $this->form_validation->set_rules('password_confirm', $this->lang->line('create_user_validation_password_confirm_label'), 'required');

    if ($this->form_validation->run() == true)
    {
        $username = strtolower($this->input->post('first_name')) . ' ' . strtolower($this->input->post('last_name'));
        $email    = strtolower($this->input->post('email'));
        $password = $this->input->post('password');

        $additional_data = array(
            'first_name' => $this->input->post('first_name'),
            'last_name'  => $this->input->post('last_name'),
            'company'    => $this->input->post('company'),
            'phone'      => $this->input->post('phone'),
        );
    }
    if ($this->form_validation->run() == true && $this->ion_auth->register($username, $password, $email, $additional_data))
    {
        // check to see if we are creating the user
        // redirect them back to the admin page
        $this->session->set_flashdata('message', $this->ion_auth->messages());
        redirect("site", 'refresh');
    }
    else
    {
        // display the create user form
        // set the flash data error message if there is one
        $this->data['message'] = (validation_errors() ? validation_errors() : ($this->ion_auth->errors() ? $this->ion_auth->errors() : $this->session->flashdata('message')));

        $this->data['first_name'] = array(
            'name'  => 'first_name',
            'id'    => 'first_name',
            'type'  => 'text',
            'value' => $this->form_validation->set_value('first_name'),
        );
        $this->data['last_name'] = array(
            'name'  => 'last_name',
            'id'    => 'last_name',
            'type'  => 'text',
            'value' => $this->form_validation->set_value('last_name'),
        );
        $this->data['email'] = array(
            'name'  => 'email',
            'id'    => 'email',
            'type'  => 'text',
            'value' => $this->form_validation->set_value('email'),
        );
        $this->data['company'] = array(
            'name'  => 'company',
            'id'    => 'company',
            'type'  => 'text',
            'value' => $this->form_validation->set_value('company'),
        );
        $this->data['phone'] = array(
            'name'  => 'phone',
            'id'    => 'phone',
            'type'  => 'text',
            'value' => $this->form_validation->set_value('phone'),
        );
        $this->data['password'] = array(
            'name'  => 'password',
            'id'    => 'password',
            'type'  => 'password',
            'value' => $this->form_validation->set_value('password'),
        );
        $this->data['password_confirm'] = array(
            'name'  => 'password_confirm',
            'id'    => 'password_confirm',
            'type'  => 'password',
            'value' => $this->form_validation->set_value('password_confirm'),
        );

        $this->_render_page('site/create_user', $this->data);
    }
}


//Function to render the page
function _render_page($view, $data=null, $returnhtml=false)//I think this makes more sense
{

    $this->viewdata = (empty($data)) ? $this->data: $data;

    $view_html = $this->load->view($view, $this->viewdata, $returnhtml);

    if ($returnhtml) return $view_html;//This will return html on 3rd argument being true
}

}

Этот точный код работает в контроллере авторизации. Когда в контроллере сайта я делаю это так, что вы должны войти в систему, и вы должны быть администратором, чтобы сделать пользователя (т.е. раскомментировать эту строку //redirect('site/login', 'refresh');) тогда это также работает, но по какой-то причине, когда эта строка закомментирована, она работает в контроллере авторизации, но не в контроллере сайта.

Любая помощь горячо приветствуется. Я пытался понять это, но не могу понять, почему это работает в одном, а не в другом (и почему это работает на сайте, но только в качестве администратора, когда этот код раскомментирован, и не совсем, когда он прокомментирован, в то время как в авторизация работает в любом случае).

Заранее спасибо.


person RandyS    schedule 07.09.2015    source источник


Ответы (1)


Причина, по которой вас перенаправляют, может быть одной из двух.

Первый : $this->_render_page('site/login', $this->data);

Когда вы нажимаете кнопку отправки, она все еще указывает на контроллер входа в систему.

Второй : if (!$this->ion_auth->logged_in() || !$this->ion_auth->is_admin())

Функция создания пользователя в контроллере аутентификации предназначена только для администраторов. Вам придется // ввести код, иначе вы будете перенаправлены на страницу входа из-за того, что не вошли в систему и не являетесь администратором.

попробуй это:

//$this->_render_page('site/login', $this->data);

//if (!$this->ion_auth->logged_in() || !$this->ion_auth->is_admin())

Отметив эти две строки, вы сможете просматривать и отправлять свою страницу без перенаправления. :)

person izaya Fearon    schedule 08.12.2015