First of all, this post is going to be long, thanks for helping tho.
Hello so I've been trying to create a login and register system on my CodeIgniter Application. So far it works great, I can create and fetch them(if not logged in) wherever I want them to be displayed, the problem that now comes to me is the restricting part.
For example I have an admin_controller to which I need to restrict the access. Rather than adding a code to any controller that needs the same configuration, I created a "MY_Controller" in the core folder, here is my code:
<?php
class MY_Controller extends CI_Controller{
function __construct(){
parent::__construct();
}
}
class Admin_Controller extends MY_Controller{
function __construct(){
parent::__construct();
// Check Login
/*if(!$this->session->userdata('logged_in')){
redirect('admin/login');
}*/
}
}
class Public_Controller extends MY_Controller{
public function __construct(){
parent::__construct();
$this->load->library('menu');
$pages_public /*$this->pages*/ = $this->menu->get_pages();
// Brand/Logo
$this->brand = 'My Website';
// Banner
$this->banner_heading = 'Welcome To Our Website';
$this->banner_text = 'This example is a quick exercise to illustrate how the default, static navbar and fixed to top navbar work. It includes the responsive CSS and HTML, so it also adapts to your viewport and device.';
$this->banner_link = 'pages/show/our-team';
}
}
and this is what I have on my admin_controller, so far nothing wrong:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Pages extends Admin_Controller {
public function index(){
$data['pages'] = $this->Page_model->get_list();
// Load template
$this->template->load('admin', 'default', 'pages/index', $data);
}
public function add(){
// Field Rules
$this->form_validation->set_rules('title', 'Title', 'trim|required|min_length[3]');
$this->form_validation->set_rules('subject_id', 'Subject', 'trim|required');
$this->form_validation->set_rules('body', 'Body', 'trim|required');
$this->form_validation->set_rules('is_published', 'Publish', 'required');
$this->form_validation->set_rules('is_featured', 'Feature', 'required');
$this->form_validation->set_rules('order', 'Order', 'integer');
if($this->form_validation->run() == FALSE){
$subject_options = array();
$subject_options[0] = 'Select Page Category';
$subject_list = $this->Pages_categories_model->get_list();
foreach($subject_list as $subject){
$subject_options[$subject->id] = $subject->name;
}
$data['subject_options'] = $subject_options;
// Load template
$this->template->load('admin', 'default', 'pages/add', $data);
} else {
$slug = str_replace(' ', '-', $this->input->post('title'));
$slug = strtolower($slug);
// Page Data
$data = array(
'title' => $this->input->post('title'),
'slug' => $slug,
'subject_id' => $this->input->post('subject_id'),
'body' => $this->input->post('body'),
'is_published' => $this->input->post('is_published'),
'is_featured' => $this->input->post('is_featured'),
'in_menu' => $this->input->post('in_menu'),
'user_id' => $this->session->userdata('user_id'),
'order' => $this->input->post('order')
);
// Insert Page
$this->Page_model->add($data);
// Activity Array
$data = array(
'resource_id' => $this->db->insert_id(),
'type' => 'page',
'action' => 'added',
'user_id' => $this->session->userdata('user_id'),
'message' => 'A new page was added ('.$data["title"].')'
);
// Insert Activity
$this->Activity_model->add($data);
// Set Message
$this->session->set_flashdata('success', 'Page has been added');
// Redirect
redirect('admin/pages');
}
}
public function edit($id){
// Field Rules
$this->form_validation->set_rules('title', 'Title', 'trim|required|min_length[3]');
$this->form_validation->set_rules('subject_id', 'Subject', 'trim|required');
$this->form_validation->set_rules('body', 'Body', 'trim|required');
$this->form_validation->set_rules('is_published', 'Publish', 'required');
$this->form_validation->set_rules('is_featured', 'Feature', 'required');
$this->form_validation->set_rules('order', 'Order', 'integer');
if($this->form_validation->run() == FALSE){
$data['item'] = $this->Page_model->get($id);
$subject_options = array();
$subject_options[0] = 'Select Page Category';
$subject_list = $this->Pages_categories_model->get_list();
foreach($this->Pages_categories_model->get_list() as $subject){
$subject_options[$subject->id] = $subject->name;
}
$data['subject_options'] = $subject_options;
// Load template
$this->template->load('admin', 'default', 'pages/edit', $data);
} else {
$slug = str_replace(' ', '-', $this->input->post('title'));
$slug = strtolower($slug);
// Page Data
$data = array(
'title' => $this->input->post('title'),
'slug' => $slug,
'subject_id' => $this->input->post('subject_id'),
'body' => $this->input->post('body'),
'is_published' => $this->input->post('is_published'),
'is_featured' => $this->input->post('is_featured'),
'in_menu' => $this->input->post('in_menu'),
'user_id' => $this->session->userdata('user_id'),
'order' => $this->input->post('order')
);
// Update Page
$this->Page_model->update($id, $data);
// Activity Array
$data = array(
'resource_id' => $this->db->insert_id(),
'type' => 'page',
'action' => 'updated',
'user_id' => $this->session->userdata('user_id'),
'message' => 'A page was updated ('.$data["title"].')'
);
// Insert Activity
$this->Activity_model->add($data);
// Set Message
$this->session->set_flashdata('success', 'Page has been updated');
// Redirect
redirect('admin/pages');
}
}
public function delete($id){
$title = $this->Page_model->get($id)->title;
// Delete Page
$this->Page_model->delete($id);
// Activity Array
$data = array(
'resource_id' => $this->db->insert_id(),
'type' => 'page',
'action' => 'deleted',
'user_id' => $this->session->userdata('user_id'),
'message' => 'A page was deleted'
);
// Insert Activity
$this->Activity_model->add($data);
// Set Message
$this->session->set_flashdata('success', 'Page has been deleted');
// Redirect
redirect('admin/pages');
}
}
the problem comes from the controller users_controller. I already created an account with some data and that data should at least allow me to have access to the admin_controller which it does not, instead it redirects me to the admin/login form.
I would like to say that for some reason when I tried to add a page, I get an error message saying that user_id cannot be null, but as I'm "supposed" to be logged in that error should not appear. Any knows how to fix it?
Error Message
Error Number: 1048 Column 'user_id' cannot be null INSERT INTO 'pages'
('title', 'slug', 'subject_id', 'body', 'is_published', 'is_featured',
'in_menu', 'user_id', 'order') VALUES ('Page One', 'page-one', '1', '
thrhjtyjrjrj ', '1', '0', '1', NULL, '1')
Filename:
C:/xampp/htdocs/codeigniter/application/models/page_model.php Line
Number: 20
User_Controller:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Users extends CI_Controller {
function __construct(){
parent::__construct();
}
public function index(){
// Check Login
if(!$this->session->userdata('logged_in')){
redirect('admin/login');
}
$data['users'] = $this->User_model->get_list();
// Load template
$this->template->load('admin', 'default', 'users/index', $data);
}
public function add(){
// Check Login
if(!$this->session->userdata('logged_in')){
redirect('admin/login');
}
$this->form_validation->set_rules('first_name','First Name','trim|required|min_length[2]');
$this->form_validation->set_rules('last_name','Last Name','trim|required|min_length[2]');
$this->form_validation->set_rules('username','Username','trim|required|min_length[4]');
$this->form_validation->set_rules('email','Email','trim|required|min_length[7]|valid_email');
$this->form_validation->set_rules('password','Password','trim|required|min_length[4]|matches[password2]');
$this->form_validation->set_rules('password2','Confirm Password','trim|required|min_length[6]|matches[password2]');
if ($this->form_validation->run() == FALSE){
// Load View Into Template
$this->template->load('admin','default','users/add');
} else {
// Create Page Data Array
$data = array(
'first_name' => $this->input->post('first_name'),
'last_name' => $this->input->post('last_name'),
'email' => $this->input->post('email'),
'username' => $this->input->post('username'),
'password' => md5($this->input->post('password'))
);
// Add User
$this->User_model->add($data);
//Activity Array
$data = array(
'resource_id' => $this->db->insert_id(),
'type' => 'user',
'action' => 'added',
'user_id' => $this->session->userdata('user_id'),
'message' => 'A new user was added ('.$data["username"].')'
);
// Add Activity
$this->Activity_model->add($data);
// Create Message
$this->session->set_flashdata('success', 'User has been added');
// Redirect to pages
redirect('admin/users');
}
}
public function edit($id){
// Check Login
if(!$this->session->userdata('logged_in')){
redirect('admin/login');
}
$this->form_validation->set_rules('first_name','First Name','trim|required|min_length[2]');
$this->form_validation->set_rules('last_name','Last Name','trim|required|min_length[2]');
$this->form_validation->set_rules('username','Username','trim|required|min_length[4]');
$this->form_validation->set_rules('email','Email','trim|required|min_length[7]|valid_email');
if ($this->form_validation->run() == FALSE){
// Get Current Subject
$data['item'] = $this->User_model->get($id);
//Load View Into Template
$this->template->load('admin','default','users/edit', $data);
} else {
// Create User Data Array
$data = array(
'first_name' => $this->input->post('first_name'),
'last_name' => $this->input->post('last_name'),
'email' => $this->input->post('email'),
'username' => $this->input->post('username')
);
// Update User
$this->User_model->update($id, $data);
// Activity Array
$data = array(
'resource_id' => $this->db->insert_id(),
'type' => 'user',
'action' => 'updated',
'user_id' => $this->session->userdata('user_id'),
'message' => 'A user was updated ('.$data["username"].')'
);
// Add Activity
$this->Activity_model->add($data);
//Create Message
$this->session->set_flashdata('success', 'User has been updated');
//Redirect to Users
redirect('admin/users');
}
}
public function delete($id){
// Check Login
if(!$this->session->userdata('logged_in')){
redirect('admin/login');
}
// Get Username
$username = $this->User_model->get($id)->username;
// Delete User
$this->User_model->delete($id);
// Activity Array
$data = array(
'resource_id' => $this->db->insert_id(),
'type' => 'user',
'action' => 'deleted',
'user_id' => $this->session->userdata('user_id'),
'message' => 'A user was deleted'
);
// Add Activity
$this->Activity_model->add($data);
// Create Message
$this->session->set_flashdata('success', 'User has been deleted');
// Redirect to Subjects
redirect('admin/users');
}
public function login(){
$this->form_validation->set_rules('username','Username','trim|required|min_length[4]');
$this->form_validation->set_rules('password','Password','trim|required|min_length[4]');
if ($this->form_validation->run() == FALSE){
//Load View Into Template
$this->template->load('admin','login','users/login');
} else {
// Get Post Data
$username = $this->input->post('username');
$password = $this->input->post('password');
$enc_password = md5($password);
$user_id = $this->User_model->login($username, $enc_password);
if($user_id){
$user_data = array(
'user_id' => $user_id,
'username' => $username,
'logged_in' => true
);
// Set Session Data
$this->session->set_userdata($user_data);
// Create Message
$this->session->set_flashdata('success', 'You are logged in');
// Redirect to pages
redirect('admin');
} else {
// Create Error
$this->session->set_flashdata('error', 'Invalid Login');
// Redirect to pages
redirect('admin/users/login');
}
}
}
public function register(){
$this->form_validation->set_rules('first_name','First Name','trim|required|min_length[2]');
$this->form_validation->set_rules('last_name','Last Name','trim|required|min_length[2]');
$this->form_validation->set_rules('username','Username','trim|required|min_length[4]');
$this->form_validation->set_rules('email','Email','trim|required|min_length[7]|valid_email');
$this->form_validation->set_rules('password','Password','trim|required|min_length[4]|matches[password2]');
$this->form_validation->set_rules('password2','Confirm Password','trim|required|min_length[6]|matches[password2]');
if ($this->form_validation->run() == FALSE){
// Load View Into Template
$this->template->load('admin','login','users/register');
} else {
// Create Page Data Array
$data = array(
'first_name' => $this->input->post('first_name'),
'last_name' => $this->input->post('last_name'),
'email' => $this->input->post('email'),
'username' => $this->input->post('username'),
'password' => md5($this->input->post('password'))
);
// Add User
$this->User_model->add($data);
//Activity Array
$data = array(
'resource_id' => $this->db->insert_id(),
'type' => 'user',
'action' => 'registered',
'user_id' => $this->session->userdata('username'),
'message' => 'A new user was registered ('.$data["username"].')'
);
// Add Activity
$this->Activity_model->add($data);
// Create Message
$this->session->set_flashdata('success', 'User has been registered');
// Redirect to pages
redirect('admin/users/login');
}
}
public function logout(){
$this->session->unset_userdata('logged_in');
$this->session->unset_userdata('user_id');
$this->session->unset_userdata('username');
$this->session->sess_destroy();
// Message
$this->session->set_flashdata('success', 'You are logged out');
redirect(base_url());
}
}
Here is my user_model(in case you would like to check it):
<?php
class User_model extends CI_MODEL{
function __construct(){
parent::__construct();
$this->table = 'users';
}
public function get_list(){
$query = $this->db->get($this->table);
return $query->result();
}
public function get($id){
$this->db->where('id', $id);
$query = $this->db->get($this->table);
return $query->row();
}
public function add($data){
$this->db->insert($this->table, $data);
}
public function update($id, $data){
$this->db->where('id', $id);
$this->db->update($this->table, $data);
}
public function delete($id){
$this->db->where('id', $id);
$this->db->delete($this->table);
}
public function login($username, $password){
$this->db->select('*');
$this->db->from($this->table);
$this->db->where('username', $username);
$this->db->where('password', $password);
$this->db->limit(1);
$query = $this->db->get();
if($query->num_rows() == 1){
return $query->row()->id;
} else {
return false;
}
}
}
1/ You should write a private method for checking logged user like this
private function checkLogin()
{
if(!$this->session->userdata('logged_in')){
redirect('admin/login');
}
}
2/ You must make sure that you loaded the library session.
I've been stuck, when I sign up and want to redirect controller to another controller for showing dashboard then that time created session does not working on redirected controller. Here is my sample code.
My Sign up controller :
class Signup extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->helper('url');
$this->load->model('admin_model');
$this->load->library('form_validation');
$this->load->helper('cookie');
$this->load->library('session');
$this->load->library('email');
$this->load->helper('string');
$this->load->library('upload');
}
public function index() {
if(!$_POST) {
$this->load->view('web_pages/signup/signup');
} else {
$insert_data = array(
'firstName' => $signup_data['firstName'],
'lastName' => $signup_data['lastName'],
'email' => $signup_data['email'],
'password' => $signup_data['password'],
'phoneNo' => $signup_data['phoneNo'],
'userType' => $signup_data['userType'],
'image' => $image,
'createDate' => date('Y-m-d H:i:s')
);
$this->db->insert('users', $insert_data);
$this->session->set_userdata(array(
'user_id' => $insert_data['email'],
'userType' => $insert_data['userType'],
'status' => TRUE
));
redirect('dashboard'); //another controller.
}
}
}
Below is my dashboard controller
class Dashboard extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->helper('url');
$this->load->model('admin_model');
$this->load->library('form_validation');
$this->load->helper('cookie');
$this->load->library('session');
$this->load->library('email');
$this->load->helper('string');
$this->load->library('upload');
}
public function index() {
print_r($_SESSION); die;
}
}
Above dashboard controller doesn't print anything.
Please help me . Thanks in advance.
Print the data in session using
public function index() {
$this->load->library('session');
print_r($this->session->all_userdata());
}
Check the config file with below params
$config['sess_expiration'] = 8600;
$config['sess_match_useragent'] = FALSE;
Also check the cookie config
$config['cookie_prefix'] = "";
$config['cookie_domain'] = "";
$config['cookie_path'] = "/";
Make an entry in autoload.php for session
$autoload['libraries'] = array('session'); //in autoload.php
See this updated code segment
if(!$_POST) {
$this->load->view('web_pages/signup/signup');
} else {
$insert_data = array(
'firstName' => $this->input->post('firstName'),
'lastName' => $this->input->post('lastName'),
'email' => $this->input->post('email'),
'password' => $this->input->post('password'),
'phoneNo' => $this->input->post('phoneNo'),
'userType' => $this->input->post('userType'),
'image' => $image,
'createDate' => date('Y-m-d H:i:s')
);
$this->db->insert('users', $insert_data);
$this->session->set_userdata(array(
'user_id' => $this->input->post('email'),
'userType' => $this->input->post('userType'),
'status' => TRUE
));
redirect('dashboard'); //another controller.
}
}
Then simply to access the session data
echo $this->session->userdata('firstname');
Hey guys i have read and studied the kohana orm and auth modules. so i want to implement am admin section to my website. i get the error above and i have googled but can't seem to find the answer. am using Kohana 3.3.4
so a created a controller called admin:
<?php defined('SYSPATH') or die('No direct script access!');
class Controller_Admin extends Controller_Dev
{
public $template = 'login_template';
public function action_index()
{
if (Auth::instance()->logged_in()) {
$this->redirect->body('admin/dashboard', 302);
}
$this->redirect('admin/login');
}
//lets login user
public function action_login()
{
$view = new View('admin_login');
$this->template->title = "Log in";
if ($_POST) {
$user = ORM::factory('user');
$status = $user->login($_POST);
if ($status) {
$this->redirect('admin/dashboard', 302);
}
else {
$errors = $_POST->errors('admin/login');
}
}
// Display the login form
$this->template->content = $view;
}
//lets logout user
public function action_logout()
{
Auth::instance()->logout();
$this->redirect('admin/login', 302);
}
//lets register new users
public function action_register()
{
$view = View::factory('admin_register')
->set('values', $_POST)
->bind('errors', $errors);
$this->template->title = "Registration Page";
if ($_POST)
{
$user = ORM::factory('User');
// The ORM::values() method is a shortcut to assign many values at once
/* $external_values = array(
// The unhashed password is needed for comparing to the password_confirm field
'password' => Arr::get($_POST, 'password'),
// Add all external values
) + Arr::get($_POST, '_external', array());
$extra = Validation::factory($external_values)
->rule('confirm_password', 'matches', array(':validation', ':field', 'password')); */
try
{
//$test = $extra; //Arr::get($_POST, 'password');
//$view->test = $test;
$data = $this->request->post();
$user->register($data);
// Redirect the user to his page
$this->redirect('admin/login');
}
catch (ORM_Validation_Exception $e)
{
$errors = $e->errors('models');
}
}
$this->template->content = $view;
}
and i created a model called user to help me validate the new user account before save it to the database:
<?php defined('SYSPATH') or die('No direct access allowed.');
class Model_User extends Model_Auth_User {
//public $_table_name = 'users';
protected $_has_many = array(
'user_tokens' => array('model' => 'user_token'),
'roles' => array('model' => 'role', 'through', 'roles_users'),
// for facbook, google+, twitter and yahoo indentities
'user_identity' => array(),
);
protected $_ignored_columns = array('confirm_password');
public function rules()
{
return array(
'username' => array(
array('not_empty'),
array('min_length', array(':value', 4)),
array('max_length', array(':value', 32)),
array(array($this, 'username_available')),
),
'password' => array(
'not_empty' => NULL,
'min_length' => array(5),
'max_length' => array(42),
),
'password_confirm' => array(
'matches' => array('password'),
),
'email' => array(
'not_empty' => NULL,
'min_length' => array(4),
'max_length' => array(127),
'email' => NULL,
),
);
}
public function filters()
{
return array(
'password' => array(
array(array($this, 'hash_password')),
),
);
}
public function username_available($username)
{
// There are simpler ways to do this, but I will use ORM for the sake of the example
//return ORM::factory('Member', array('username' => $username))->loaded();
// Check if the username already exists in the database
return ! DB::select(array(DB::expr('COUNT(username)'), 'total'))
->from('users')
->where('username', '=', $username)
->execute()
->get('total');
}
public function hash_password($password)
{
// Do something to hash the password
}
public function register($array)
{
$this->values($array);
$this->save();
// Create a new user record in the database
// Save the new user id to a cookie
cookie::set('user', $id);
return $id;
}
}
When i visit the admin registration page. it fails displaying an error which says:
ErrorException [ Warning ]: call_user_func_array() expects parameter 1 to be a valid callback, no array or string given
so please help me out because i think i might be missing something. Thanks in advance guys. Am using Kohana 3.3.4
I had the same error recently. You need to change line:
array(array($this, 'username_available')),
to line (for username):
array(array($this, 'unique'), array('username', ':value')),
as stated in https://kohanaframework.org/3.3/guide-api/Model_Auth_User#rules
I hope this helps you.
I'm looking for a solution to my problem. I'm trying create a webservice using CakePHP 2.
I created a CRUD and configured using AuthComponent to login. The AuthComponent was configured to use Form. When I try execute some function of controller to return a JSON doesn't works and show me code of page index.php
I think if I do configure Basic Auth works, but when I try add Basic Auth in $components it's opened access, all actions can be access on browser.
How could I configure Basic and Form of AuthComponent to works together ?
I'm trying this, but doesn't works, because all actions are opened to access
class AppController extends Controller {
public $components = array("RequestHandler", "Auth", "Session");
public function beforeFilter(){
$this->Auth->authenticate = array(
'Basic' => array('userModel' => 'User',
'fields'=> array(
'username' => 'email',
'password' => 'senha'
),
'scope' => array(
'User.status' => 1
)
),
'Form' => array('userModel' => 'User',
'fields'=> array(
'username' => 'email',
'password' => 'senha'
),
'scope' => array(
'User.status' => 1
)
),
);
$this->Auth->loginAction = array(
'controller' => 'users',
'action' => 'login'
);
$this->Auth->loginRedirect = array(
'controller' => 'matriculas',
'action' => 'index'
);
$this->Auth->logoutRedirect = array(
'controller' => 'users',
'action' => 'login'
);
$this->Auth->authorize = "Controller";
$this->Auth->authError = "Efetue login de acesso";
$this->Auth->allow("login");
}
public function isAuthorized($user) {
if (isset($user['role']) && $user['role'] === 'admin') {
return true; // Admin pode acessar todas actions
}
return false; // Os outros usuários não podem
}
}
UsersController
class UsersController extends AppController {
public $components = array('Paginator');
public function index() {
$this->User->recursive = 0;
$this->set('users', $this->Paginator->paginate());
}
public function add() {
if ($this->request->is('post')) {
$this->User->create();
if ($this->User->save($this->request->data)) {
$this->Session->setFlash(__('The user has been saved.'));
return $this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The user could not be saved. Please, try again.'));
}
}
}
public function edit($id = null) {
if (!$this->User->exists($id)) {
throw new NotFoundException(__('Invalid user'));
}
if ($this->request->is(array('post', 'put'))) {
if ($this->User->save($this->request->data)) {
$this->Session->setFlash(__('The user has been saved.'));
return $this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The user could not be saved. Please, try again.'));
}
} else {
$options = array('conditions' => array('User.' . $this->User->primaryKey => $id));
$this->request->data = $this->User->find('first', $options);
}
}
public function login(){
$this->layout = "layout";
if($this->request->is("post")){
if ($this->Auth->login()) {
$this->redirect($this->Auth->redirect());
}else{
$this->Session->setFlash(__('Usuário ou senha inválido'));
}
}
}
public function logout(){
$this->redirect($this->Auth->logout());
}
/********** WEB SERVICES FUNCTIONS *********/
/** return all users **/
public function findAll(){
$this->set("users", $this->User->find('all'));
$this->set(array(
"_serialize" => 'users',
));
}
/** add new user from app **/
public function addUserFromApp(){
$this->layout=null;
$data = $this->request->input("json_decode", true);
echo $data;
}
}
Good Day Fellows .
I have a problem in my CMS login , When i Click the login button, The login page refreshes and comes again.
Session library is defined. Session encryption key is set.
Login Controller Code is :
<?php
class User extends Admin_Controller {
public function __construct(){
parent::__construct();
}
public function login(){
$dashboard = 'admin/dashboard';
$this->user_m->loggedin() == FALSE || redirect($dashboard);
$rules = $this->user_m->rules;
$this->form_validation->set_rules($rules);
if ($this->form_validation->run() == TRUE) {
// We can login and redirect
if ($this->user_m->login() == TRUE) {
redirect($dashboard);
}
else {
$this->session->set_flashdata('error', 'That email/password combination does not exist');
redirect('admin/user/login', 'refresh');
}
}
$this->data['subview'] = 'admin/user/login';
$this->load->view('admin/_layout_modal', $this->data);
}
public function logout(){
$this->user_m->logout();
redirect('admin/user/login');
}
}
Login Model code is :
<?php
class User_M extends MY_Model
{
protected $_table_name = 'users';
protected $_order_by = 'name';
public $rules = array(
'email' => array(
'field' => 'email',
'label' => 'Email',
'rules' => 'trim|required|valid_email|xss_clean'
),
'password' => array(
'field' => 'password',
'label' => 'Password',
'rules' => 'trim|required'
)
);
function __construct ()
{
parent::__construct();
}
public function login ()
{
$user = $this->get_by(array(
'email' => $this->input->post('email'),
'password' => $this->hash($this->input->post('password')),
), TRUE);
if (count($user)) {
// Log in user
$data = array(
'name' => $user->name,
'email' => $user->email,
'id' => $user->id,
'loggedin' => TRUE,
);
$this->session->set_userdata($data);
}
}
public function logout ()
{
$this->session->sess_destroy();
}
public function loggedin ()
{
return (bool) $this->session->userdata('loggedin');
}
public function hash ($string)
{
return hash('sha512', $string . config_item('encryption_key'));
}
}
I suggest better to put login view in else condition ,
public function login(){
$dashboard = 'admin/dashboard';
$this->user_m->loggedin() == FALSE || redirect($dashboard);
$rules = $this->user_m->rules;
$this->form_validation->set_rules($rules);
if($this->input->post()) { //check if request if post
if ($this->form_validation->run() == TRUE) {
// We can login and redirect
if ($this->user_m->login() == TRUE) {
redirect($dashboard);
}
else {
$this->session->set_flashdata('error', 'That email/password combination does not exist');
redirect('admin/user/login', 'refresh');
}
}
} else { //defult login page
$this->data['subview'] = 'admin/user/login';
$this->load->view('admin/_layout_modal', $this->data);
} }
If you still faces the problem , please manually debug and check where it getting stuck!