Welcome Guest, Not a member yet? Register   Sign In
Tank Auth v1.0 (CI authentication library)

[eluser]NiconPhantom[/eluser]
Hi

if-else construction of:
if (!$this->tank_auth->is_logged_in()) {
redirect('/auth/login/');
} else {}

Sometimes is overkill...

My solution is:

1. To Tank_auth.php library add function

function is_logged_in()
{

if ($this->ci->session)
{
$_username = $this->ci->session->userdata('username');


if ($_username != false)
{
// Some function
}
else{

redirect('your_controller', 'location');
}}}
2. In your application after parent::Controller();
add line $this->tank_auth->is_logged_in();


Alex

[eluser]NiconPhantom[/eluser]
[quote author="frogsaway" date="1267897902"][quote author="cyberbobjr" date="1267895673"]Hi,
[quote author="rip_pit" date="1263274930"]hi guys, first, thanks for the good work and helpful topic.

Working with tank auth, even if it works fine "out of the box" I would need some advices to go further.

I'm trying (without success) to insert tank_auth's parts into another page.

It's to say, I would want to insert (like with an include) the login_form part from tank auth into my own page (instead of having to load the auth/login existing page).

Does any of you have any clues about what's the best way to do it ?

instead of
Code:
if (!$this->tank_auth->is_logged_in())
redirect('/auth/login/');

i would want something like
Code:
if (!$this->tank_auth->is_logged_in())
//show the login form from tank auth (like with include('login_form');
//in order the user could log in from the first page, not only from auth/login

Hope someone could help coz i'm having a bad time trying to do it alone. thanx for reading Wink[/quote]
I've exactly the same question, please someone can explain us how to do that ?
Thanks you so much !
Best regards[/quote]


I have managed it by messing around a lot with the way the controller & library work.
Basically to get it to function correctly I had to break the standard way of processing forms works in CI.

Created a new function in the library which builds the data required to generate the login form. Then messed around with a custom controller to pass the error messages etc back to the login_form view.

Serious pain to get it to work correctly.

Dave.[/quote]


Hi

You can use HMVC and something like

function login ()
{
$data['text'] = modules::run('auth/login');
$this->load->view($this->_container, $data);
}

[eluser]theshiftexchange[/eluser]
How to easily add basic role management to Tank Auth - Part 1/3

I would like to thank "Colin Williams" for his posts in another thread about overall Role Management that lead to this solution.


in "Tank_Auth.php" __construct() add this line
Code:
$this->ci->load->model('tank_auth/roles');

in "Tank_Auth.php" login() function, modify the "set_userdata" function (around line 74) to this
Code:
$this->ci->session->set_userdata(array(
                                'user_id'    => $user->id,
                                'username'    => $user->username,
                                                                'email'         => $user->email,
                                                                'roles'         => $this->ci->roles->get_user_roles($user->id),
                                'status'    => ($user->activated == 1) ? STATUS_ACTIVATED : STATUS_NOT_ACTIVATED,
                        ));

in "Tank_Auth.php" add the following function somewhere
Code:
/**
     * Check roles
     * This function provides an ability to check for a particular role
         *
         * Keep in mind that during the login process all the users roles were
         * grabbed from the DB and stored in a variable for easy access
         *
         * Any 'role changes' would therefore require a user to logout of the site and
         * log back in to take effect OR update the session yourself
         *
         * the model uses '%' as a string seperator
     *
         * @param       string
     * @return    bool
     */
        function check_roles($role)
        {
            $current_roles = $this->ci->session->userdata('roles');
            $current_roles = explode("%", $current_roles);
            reset ($current_roles);          
            foreach ($current_roles as $roles)
            {
                if (strcmp($role,$roles) == 0)
                        return TRUE;
            }
            return FALSE;
        }

[eluser]theshiftexchange[/eluser]
continued Part 2/3

Create a "roles.php" file in the same directory as the "users.php" file
Code:
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

/**
* Roles
*
* This model represents roles. It operates the following two tables
*
* @package    Tank_auth
* @author    theshiftexchange
*/
class Roles extends Model
{
        function __construct()
    {
        parent::__construct();
    }

    /**
     * Get all user roles and return them as a string with a '%' seperating them
     *
     * @param    int
     * @return    string
     */
    function get_user_roles($user_id)
    {
            $query = $this->db->query("SELECT *
                                       FROM users_roles
                                       INNER JOIN roles ON users_roles.rolesID=roles.rolesID
                                       WHERE userID = ".$user_id);

            $roles = null;

            foreach ($query->result() as $row)
            {
                $roles = ($roles."%".$row->name);
            }

            return $roles;
    }
}

/* End of file roles.php */
/* Location: ./application/models/auth/roles.php */

Finally in your database create two tables;

Code:
CREATE TABLE IF NOT EXISTS `roles` (
  `rolesID` int(16) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(30) COLLATE utf8_unicode_ci NOT NULL,
  `description` varchar(200) COLLATE utf8_unicode_ci NOT NULL,
  PRIMARY KEY (`rolesID`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=24 ;

Code:
CREATE TABLE IF NOT EXISTS `users_roles` (
  `userID` int(16) unsigned NOT NULL,
  `rolesID` int(16) unsigned NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

[eluser]theshiftexchange[/eluser]
Part 3/3

The way it works is really simple.

You create "roles" in your database. For example - Role "Purchasing" (RolesID 1), "HR" (RolesID 2), "Admin" (RolesID 3)

You assign "roles" to users. For example - UserID 1 has RolesID 1, UserID 1 has RolesID 2

In your normal controllers you want to know if a user has the "Purchasing" role you would write:

Code:
if ($this->tank_auth->check_roles('Purchasing'))
{    
// user has the role
}
else
{
// user does NOT have the role
}

Please note the "check_roles" IS CASE SENSITIVE so "PURCHASING" would fail in the above example

The great thing about this solution is you are not modifying your current database tables - you only add two more (so it can be 'bolted on' to a current solution).

You can read some posts by Collin such as http://ellislab.com/forums/viewthread/121172/#600448 if you want to add even more functionality - but for me this did the job

[eluser]rip_pit[/eluser]
Simply great! i've tested it and it works like a charm!

I will just notice that my databases script is slightly different, based on my existing CI tables, I modified the values for :
ENGINE=InnoDB
DEFAULT CHARSET=utf8
COLLATE=utf8_bin
AUTO INCREMENT: removed

Then i wrote i "quick start" tutorial to clarify some points after successfull installation.


BASIC ROLE MANAGEMENT : QUICK START TUTORIAL

here is a quick start guide after integration of the "basic role management" system
"How to easily add basic role management to Tank Auth" by theshiftexchange


1. In the "roles" table, create a new row per possible role, ex:
Code:
-- THESE ARE SAMPLE ROLES, YOU CAN MODIFY THE VALUES BEFORE TO INSERT THEM IN THE TABLE
       INSERT INTO `roles` (`rolesID`, `name`, `description`) VALUES
        (1, 'Purchasing', 'Purchasing role''s description goes here'),
        (2, 'HR', 'HR role''s description goes here'),
        (3, 'Admin', 'Admin role''s description goes here'),
        (4, 'Other', 'Other role''s description goes here');


2. In the "user_roles" table, you need to create 1 row per user role. Note that 1 user can have several rows (1 per role), ex:
Code:
-- assigning role #3 to user #1.
        INSERT INTO `users_roles` (`userID`, `rolesID`) VALUES ('1', '3');
    -- assigning roles #1 and #2 to user #2.
        INSERT INTO `users_roles` (`userID`, `rolesID`) VALUES ('2', '1'), ('2', '2');
    -- assigning roles #2 and #3 to user #10.
        INSERT INTO `users_roles` (`userID`, `rolesID`) VALUES ('10', '2'), ('10', '3');


3. In your controller, check user role by giving role name (case sensitive) to the method, ex:
Code:
if ($this->tank_auth->check_roles('Purchasing'))
      // user has the role
    else
      // user does NOT have the role

Note that you'll have to manually set every user's role into your DB, or write your own tank_auth component to manage user's roles.


Thanks to theshiftexchange and the tank_auth author and contributors Wink

[eluser]TheFuteballer[/eluser]
I noticed that Tank_Auth redirects ONLY to the home page once a user logs in. Has anyone found a good solution to redirect to the referring page?

i.e. A user tries to access a protected portion of the side - www.example.com/admin , they go to the login page, but once they log in they get redirected to www.example.com instead of www.example.com/admin

I'd ideally like to avoid having to set a session variable that holds the current URL on each page (controller) that I want to protect.

[eluser]rip_pit[/eluser]
not sure this is the cause but after adding the roles part in tank_auth i suddenly got an error that "cookies data" were different from "session datas" and that broken my app.
I had to switch back without roles. any idea ?

[quote author="TheFuteballer" date="1270329503"]I noticed that Tank_Auth redirects ONLY to the home page once a user logs in. Has anyone found a good solution to redirect to the referring page?
[/quote]

no. but you can change it in
\system\application\controllers\auth.php

replacing the 2nd empty redirect from the login function :
redirect('');//not the 1st

with a new one :
redirect('myapp/admin);

[eluser]TheFuteballer[/eluser]
[quote author="rip_pit" date="1270353874"][quote author="TheFuteballer" date="1270329503"]I noticed that Tank_Auth redirects ONLY to the home page once a user logs in. Has anyone found a good solution to redirect to the referring page?

i.e. A user tries to access a protected portion of the side - www.example.com/admin , they go to the login page, but once they log in they get redirected to www.example.com instead of www.example.com/admin

I'd ideally like to avoid having to set a session variable that holds the current URL on each page (controller) that I want to protect.[/quote]

no. but you can change it in
\system\application\controllers\auth.php

replacing the 2nd empty redirect from the login function :
redirect('');//not the 1st

with a new one :
redirect('myapp/admin);[/quote]

The only issue being that you are not redirecting to the referring page, it'll always go to myapp/admin... anyways here's my temporary fix:

In each of my controllers that require to be password protected, I set the flashdata to the current URL:
Code:
if (!$this->tank_auth->is_logged_in()) {
            $this->session->set_flashdata('current_url', current_url());
            redirect('/auth/login/');
        } else {
            $this->example();
        }


In my login form view, I create a hidden variable that grabs that flashdata:
Code:
<?php     $referring_url = $this->session->flashdata('current_url');
        $data = array('referring_url' => $referring_url);?>
<?php echo form_open($this->uri->uri_string(), '', $data); ?>

And finally in the \system\application\controllers\auth.php, I changed the redirect to:
Code:
redirect($this->input->post('referring_url'));



This works, it's not elegant and instead of flashdata I could've probably just used a single session but it works until I find a better solution.

[eluser]theshiftexchange[/eluser]
[quote author="rip_pit" date="1270353874"]not sure this is the cause but after adding the roles part in tank_auth i suddenly got an error that "cookies data" were different from "session datas" and that broken my app.
I had to switch back without roles. any idea ?
[/quote]

I've been using it for a few weeks now - no errors.

I'm wondering how you are updating the session data with the new roles - sounds like it is there somewhere?

edit: maybe its related to this? http://ellislab.com/forums/viewthread/149102/




Theme © iAndrew 2016 - Forum software by © MyBB