CodeIgniter Forums
Help with beginner login questions - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Archived Discussions (https://forum.codeigniter.com/forumdisplay.php?fid=20)
+--- Forum: Archived Development & Programming (https://forum.codeigniter.com/forumdisplay.php?fid=23)
+--- Thread: Help with beginner login questions (/showthread.php?tid=16709)

Pages: 1 2 3


Help with beginner login questions - El Forum - 03-14-2009

[eluser]Flying Fish[/eluser]
I'm autoloading the CI sessions class and storing session data in a table in my database (as shown in the user_guide).

I want to restrict access to certain pages of the site (a couple of classes actually 'order' and 'admin') to only logged in users.

I was thinking that I would put something like this on top of each class.
Code:
if($this->session->userdata('logged_in') === TRUE)
{...class here...}
else
{ redirect('...somewhere...');}

Will that work ok, or do I need to need to put something in each view that the classes load?

Also, is it typical to create a login model to lookup the user data in a database? I know there must be lots of handy user plugins for CI, but I wanted to force myself to learn it so I could dig a little deeper into the pure framework before I started relying heavily on other plugins.

Any feedback or suggestions would be much appreciated.


Thanks!


Help with beginner login questions - El Forum - 03-14-2009

[eluser]TheFuzzy0ne[/eluser]
I extend the Controller class:

./system/application/libraries/MY_Controller.php
Code:
<?php

class MY_Controller extends Controller {
    
    function _admin_restricted_area()
    {
        if (! $this->auth->isAdmin())
        {
            show_404();
        }
    }
    
    function _user_restricted_area()
    {
        if (! $this->auth->isLoggedIn())
        {
            redirect('/forums/member/login');
        }
    }    
}

// End of file: MY_Controller.php
// ./system/application/libraries/MY_Controller.php

Any other controller extend MY_Controller, and can contain $this->_admin_restrcited_area() or $this->_user_restricted_area(). You can modify those methods to work how you want, but in my case, if there user is not logged in, they are redirected to the login page, and if they aren't an admin, and try accessing an admin only page, they see a 404 error.

There are lots of good auth libraries around, I just needed something simple, but I'd suggest you check out the source code for some of them, it might give you some ideas.


Help with beginner login questions - El Forum - 03-15-2009

[eluser]Flying Fish[/eluser]
Ok, so you are actually extending Code Igniter's 'Controller' Class with your own custom library.

I just need something simple too, but I'll still look at some of the other auth libraries.

Couple of questions for you, if you don't mind.

1. Do I need to load my MY_Controller using $this->libraries->(or something like that) in any of my classes or does it load automatically with each controller.

2. Where do you actually put your isAdmin and IsLoggedIn functions?

3. Could you give me an example of how you would use $this->_admin_restrcited_area() in the class you want to restrict?

Thanks


Help with beginner login questions - El Forum - 03-15-2009

[eluser]jedd[/eluser]
Quote:Ok, so you are actually extending Code Igniter's 'Controller' Class with your own custom library.

Think of it less as a library, and more as modifying the parent class of Controller - by intercepting CI's controller with your own. You do this in your application's 'libraries' directory, yes.

Note this approach solves a bunch of common problems / queries, and doesn't seem to have much in the way of drawbacks.

Quote:I just need something simple too, but I'll still look at some of the other auth libraries.

I had a quick look around, and was keen on using DX for a while, but it was too heavy for what I wanted. I think if you want something very simple - admin and normal user levels only, no ACL's, no groups, no funky permissions - a very simple model could do it for.

Quote:1. Do I need to load my MY_Controller using $this->libraries->(or something like that) in any of my classes or does it load automatically with each controller.

There's more details in the [url="http://ellislab.com/codeigniter/user-guide/general/core_classes.html"] Extending Core Classes [/url] section of the user manual, but yes, you then code your controllers to extend MY_Controller .. and that's about it.

I suspect (2) comes down to what auth library you use / make, and where it lives. My money's on a model called Auth that is autoloaded.

Quote:3. Could you give me an example of how you would use $this->_admin_restrcited_area() in the class you want to restrict?

I'm guessing in your Controller you do a simple $this->_admin_restricted_area(); call - if you're not admin it'll bomb out straight to 404 at that point. You could presumably do that equally well in the constructor (if the entire class is admin-eyes only) or at the start of each method you wanted to restrict. You could write a slightly less brutal functions for just allowing visibility to specific bits of data on the fly, of course.


Help with beginner login questions - El Forum - 03-15-2009

[eluser]Flying Fish[/eluser]
"My money’s on a model called Auth that is autoloaded."

Sounds pretty good, but I think I'll need some help if I would go that route. Do you know of any tutorials or threads that help beginners get started with models. I've been leaning hard on the forum, since there really isn't anything about model's in the video tutorials and the MVC concept is new to me.

Hope I'm not asking for too much.


Help with beginner login questions - El Forum - 03-15-2009

[eluser]jedd[/eluser]
Well, there's always the [url="http://ellislab.com/codeigniter/user-guide/general/models.html"]http://ellislab.com/codeigniter/user-guide/general/models.html[/url] section of the user guide for an overview.

Models are .. a way to abstract your database. Hmm. No. They're your interface to your database. Hmm. They're the only place you should put any code that talks to, or indeed 'knows about the nature' of your database.

You don't have to use them - a lot of people put their db stuff into their controllers and live very happy and meaningful lives. But the idea is that the controller has the LOGIC of what you're doing, and the model has the tedious database CRUD stuff.

Anyhoo .. if you want, I can post what I've done so far with my system. It's not hugely secure (though I gather encrypted cookies are tricky things for 3rd parties to hack into?) but I'm not handling anything important with my system. I imagine Pete's probably happy to share the rest of his code too. In which case, politely ignore my code.


Help with beginner login questions - El Forum - 03-15-2009

[eluser]TheFuzzy0ne[/eluser]
To reiterate on what Jedd says, as far as your controllers, helper, libraries etc. are concerned, models ARE your database. The underlying data storage could be files, a database or something else. The model is responsible for translating the data and passing it back on request. The rest of your code just needs to know how to use the models, thus your data storage type and structure is transparent to the rest of your code.


Help with beginner login questions - El Forum - 03-16-2009

[eluser]Flying Fish[/eluser]
Thanks for the input. I'm going this route for now...I've created a custom library called Authentication

Code:
/system/application/libraries/Authentication.php

and I'm also auto loading this library so it's always available

It's a stripped down version of the simplelogin library from the wiki, I would have liked to do more with models and extending the controller class, but it's just over my head at this point.

I attached the Authentication library to this post.

Then I've added a welcome class for me to test a simple login/logout, to make sure everything is working ok

Here's the controller
Code:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

/*

    The Welcome class serves as the home page.
    Users can choose to 'Get Started' which will walk them through the process of creating their account and ordering itmes
    Or they can choose to 'Login' if they have already ordered some items


*/


class Welcome extends Controller {

    function __construct()
    {
        parent::Controller();
        
        $this->load->helper(array('form', 'url'));                
        $this->load->library(array('form_validation'));
        
        // Customize the tags that wrap arround the form validation error messages
        $this->form_validation->set_error_delimiters('<div class="error">', '</div>');
    }
    
    function index()
    {
        // Check if the form is being submitted. If it is, run validation
        // Find Validation Rules in '/system/application/config/form_validation.php'
        // Rules are named after their class and method, ex. order/index
        if ($this->input->post('submit') && $this->form_validation->run() === TRUE)
        {
            // If the validation has passed, redirect to the next step            
            // log user in - display session data so I know it's working
            $this->authentication->login($this->input->post('user_email'), $this->input->post('user_password'));
            redirect('welcome');

            // send them on to the order page
            redirect('/welcome/');
            
        } else if ($this->input->post('submit') && $this->form_validation->run() === FALSE)
        {
            // The form has been submitted and there are errors
            $data['title'] = "Oops! Let's double check that form.";
            $data['heading'] = "Oops! Let's double check that form.";
        } else
        {
            // The form has never been submitted, first time visitor here
            $data['title'] = "Order Flyers, Postcards, Banners, and More :: NBT Supplies";
            $data['heading'] = "Welcome";
        }
                
        // Load this view by default
        $this->load->view('welcome_index', $data);
    }
    
    function logout()
    {
        $this->authentication->logout();
        
        $data['title'] = "Logged Out";
        $data['heading'] = "You have been logged out.";
        
        // Load this view by default
        $this->load->view('welcome_index', $data);
    }
    
}

/* End of file welcome.php */
/* Location: ./system/application/controllers/welcome.php */

I'm having trouble getting it to work though...will attach the view file as well.

I can log in ok, but if I try to log out by clicking the logout link, the 'You are logged in!' message still shows up.

Here's what it looks like

[code] &lt;?
if($this->session->userdata('logged_in')) {
echo 'You are logged in! <a href="/welcome/logout">logout</a>';
}
?&gt;
[code]

I've got to be missing something, any idea what I'm doing wrong?


Help with beginner login questions - El Forum - 03-16-2009

[eluser]jedd[/eluser]
Wow .. that looks like a complex way of doing things. For what it's worth, I think by the sounds of it I'm about 8 days ahead of you .. and three days ago I decided to drop the idea of a library for authentication and do it all through a model. It was just less pain.

if it reckons you're still logged in, find out where in the source it assesses your state - it's probably (!) based on your session data - and so when you log out it's just failing to unset the relevant variable in your session. If it is using session data, you're looking for code like this: $this->session->unset_userdata ('logged_in'); .

(You've also discovered the main reason I opted to code my own, rather than trying to drop-in some drop-in code.)


Help with beginner login questions - El Forum - 03-16-2009

[eluser]Flying Fish[/eluser]
the logout function should destroy the whole session

so I gather it's not really doing that?

[code]
function logout() {
$CI =& get_instance();

//Destroy session
$CI->session->sess_destroy();
}

[code]