仅在Codeigniter中将特定页面限制为已登录用户的最佳做法是什么? [英] What is the best practice for restricting specific pages to logged in users only in Codeigniter?

查看:114
本文介绍了仅在Codeigniter中将特定页面限制为已登录用户的最佳做法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我为我的网站创建了一个注册和登录,所有验证都适用于注册和登录。在用户提供有效凭证后,他/她登录到成员区域,并显示一个欢迎消息,说明Hello first_name last_name ..基本上从数据库中获取名字和姓氏。



任何我想做的是将成员区域限制为仅登录用户。任何其他人都将被重定向到首页或登录页面,或者我决定将它们重定向到。



我使用ci_sessions存储在表ci_sessions数据库。 Session_id,ip_address,user_agent,last_activity和user_data是列。所以我想这是一种形式的安全,而不是只存储在用户浏览器上的cookie有更多。



无论如何,现在停止任何人除了登录用户访问我的网站会员区例如 http://mysite.com/member_area 我在控制器中为成员区域使用一个简单的if语句:

  if(!$ this-> session-> userdata('first_name'))
{
redirect('login');
}

这将检查尝试访问成员区域页面的人员有一些类型的数据存储在我的ci_sessions表中的user_data中,如first_name,如果是这样,则允许他们访问页面,这意味着他们必须已经登录并仍然有活动会话。



如果在数据库中找不到任何内容,则将它们重定向到网站登录页面。我想知道的是,如果有一个更好的方法这样做?



以下是我的模型代码:

 <?php 
class Current_User {

private static $ user;

私有函数__construct(){}

public static function user(){

if(!isset(self :: $ user)) {

$ CI =& get_instance();
$ CI-> load-> library('session');

if(!$ user_id = $ CI-> session-> userdata('user_id')){
return FALSE;
}

if(!$ u = Doctrine :: getTable('User') - > find($ user_id)){
return FALSE;
}

self :: $ user = $ u;
}

return self :: $ user;
}


public static function login($ email,$ password){

//通过电子邮件获取用户对象
if $ u = Doctrine :: getTable('User') - > findOneByEmail($ email)){


//输入密码的变异版本
$ u_input = new User();
$ u_input-> password = $ password;

//密码匹配
if($ u-> password == $ u_input-> password){


$ CI =& ; get_instance();
$ CI-> load-> library('session');
$ CI-> session-> set_userdata('user_id',$ u-> id);
$ CI-> session-> set_userdata('username',$ u-> username);
$ CI-> session-> set_userdata('first_name',$ u-> first_name);
$ CI-> session-> set_userdata('last_name',$ u-> last_name);

self :: $ user = $ u;

return TRUE;
}

unset($ u_input);
}

//登录失败
return FALSE;

}


public function __clone(){
trigger_error('No duplicates allowed。',E_USER_ERROR);
}

}

/ p>

UPDATE



如何将它添加到我的模型

  $ CI-> session-> set_userdata('logged_in','TRUE'); 

这基本上在DB中的会话中添加logged_in到值为TRUE的用户数据。
在我的控制器中为我的成员区我编辑了if语句说:

  if $ this-> session-> userdata('logged_in')== TRUE)
{
redirect('login');

}



t存在,如果用户未登录,则不会存在,则将返回FALSE并将用户重定向到登录页面



您认为如何?



或者我甚至可以使用某些秘密,例如dsb453rerfksdhbdsks322。有些随机。

解决方案

你击中了头上的指甲,但有一个稍微更有效的方法。 / p>

以一种方式扩展基本控制器(我相信最初由Phil Sturgeon概述),但我将在此总结:



请参阅本文非常深入。



但实质上是



  ;?php 
class MY_Controller extends Controller
{
function __construct()
{
parent :: Controller();
if(!$ this-> session-> userdata('first_name'))
{
redirect('login'); //用户没有登录,重定向他们!
}
}
}

限制访问,只需:

  class Secret_page extends MY_Controller {

//您登录的特定控制器代码
}

,扩展控制器将自动检查用户是否登录构造函数。



如何,我可能设置user_id作为值来检查其设置,或者可能是一个用户组,然后你可以获得用户权限



编辑



/ strong>



将它添加到application / config.php

  / * 
| -------------------------------------------------- -----------------
|本机自动加载
| -------------------------------------------------- -----------------
|
|与cnfig / autoload.php无关,这允许PHP自动加载工作
|用于基本控制器和一些第三方库。
|
* /
function __autoload($ class)
{
if(strpos($ class,'CI_')!== 0)
{
@include_once(APPPATH。'core /'。$ class。EXT);
}
}

在使用CI 2.0时,



我的应用程序/ Core看起来有点像:

  Admin_Controller.php 
MY_Controller.php
Public_Controller.php


I have created a sign-up and login for my website and all validation works fine for both sign-up and login. After user provides valid credentials he/she is logged into the member area with a welcome message that says Hello first_name last_name.. basically first name and last name is grabbed from database.

Any what I want to do is restrict the member area to only logged in users. Anyone else will be redirected to homepage or login page or where ever I decide they should be redirected to.

I use ci_sessions which are stored in a table "ci_sessions" in my database. Session_id, ip_address, user_agent, last_activity and user_data are the columns. So I guess that's some form form of security rather than have a cookie stored on the users browser alone there is more.

Anyway right now to stop anyone else apart from logged in users to access my website member area e.g. http://mysite.com/member_area I use a simple if statement in my controller for the member area:

if (! $this->session->userdata('first_name'))
    {
    redirect('login');
}

This checks to see whether the person who is attempting to access the member area page has some kind of data stored in user_data in my ci_sessions table such as a first_name and if so allows them to access the page meaning they must have logged in and still have an active session.

If nothing is found in the database they are redirected to the websites login page. What i want to know is if there is a better way of doing this? Is the way I'm doing it now secure enough?

Below is my model code:

<?php
class Current_User {

    private static $user;

    private function __construct() {}

    public static function user() {

        if(!isset(self::$user)) {

            $CI =& get_instance();
            $CI->load->library('session');

            if (!$user_id = $CI->session->userdata('user_id')) {
                return FALSE;
            }

            if (!$u = Doctrine::getTable('User')->find($user_id)) {
                return FALSE;
            }

            self::$user = $u;
        }

        return self::$user;
    }


    public static function login($email, $password) {

        // get User object by email
        if ($u = Doctrine::getTable('User')->findOneByEmail($email)) {


            // to ge the mutated version of the input password
            $u_input = new User();
            $u_input->password = $password;

            // password match
            if ($u->password == $u_input->password) {


                $CI =& get_instance();
                $CI->load->library('session');
                $CI->session->set_userdata('user_id',$u->id);
                $CI->session->set_userdata('username',$u->username);
                $CI->session->set_userdata('first_name',$u->first_name);
                $CI->session->set_userdata('last_name',$u->last_name);

                self::$user = $u;

                return TRUE;
            }

            unset($u_input);
        }

        // login failed
        return FALSE;

    }


    public function __clone() {
        trigger_error('No duplicates allowed.', E_USER_ERROR);
    }

}

All your advice is appreciated.

UPDATE

How about adding this to my model

$CI->session->set_userdata('logged_in', 'TRUE');

This basically adds "logged_in" to my user data in session in DB with the value "TRUE". in my controller for my "member area" I have edited the if statement to say this:

if (! $this->session->userdata('logged_in')==TRUE)
{
redirect('login');

}

If the item doesn't exist "which it won't if a user isn't logged in" then FALSE will be returned and user will be redirected to login page

What do you think?

or I could even make TRUE something secret like dsb453rerfksdhbdsks322 for example. Something random.

解决方案

You've hit the nail on the head, but there's a slightly more efficient way to do it.

Extend the base controllers, one way (i believe originally outlined by Phil Sturgeon) but I'll summarise here:

See this article for a very indepth write up.

but in essence:

<?php
class MY_Controller extends Controller
{
    function __construct()
    {
        parent::Controller();
        if (! $this->session->userdata('first_name'))
        {
            redirect('login'); // the user is not logged in, redirect them!
        }
    }
}

so now if you want to restrict access, simply:

class Secret_page extends MY_Controller {

 // your logged in specific controller code
}

and the extended controller will automatically check if the user is logged in in the constructor.

as for how, I'd probably set the user_id as the value to check if its set, or perhaps a user "group" - then you can get user permissions and varying levels of access in your system.

hope this helps a little.

edit

Add this to application/config.php

/*
| -------------------------------------------------------------------
|  Native Auto-load
| -------------------------------------------------------------------
| 
| Nothing to do with cnfig/autoload.php, this allows PHP autoload to work
| for base controllers and some third-party libraries.
|
*/
function __autoload($class)
{
    if(strpos($class, 'CI_') !== 0)
    {
        @include_once( APPPATH . 'core/'. $class . EXT );
    }
}

As you are using CI 2.0, you will need to place the MY_Controllers inside Application/CORE rather than Libraries.

My Application/Core Looks a little like:

Admin_Controller.php
MY_Controller.php
Public_Controller.php

这篇关于仅在Codeigniter中将特定页面限制为已登录用户的最佳做法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆