Securing View with codeigniter and IonAuth - codeigniter

I have setup Ion Auth for codeigniter 2.1.3.
All is working well.
In my controller, auth.php I have the below code for function index():
function index()
{
// if not logged in - go to home page
if (!$this->ion_auth->logged_in())
{
//redirect them to the login page
redirect('auth/login', 'refresh');
}
// if user is an admin go to this page
elseif ($this->ion_auth->is_admin())
{
echo "Admin User";
// if an admin, go to admin area
//set the flash data error message if there is one
$this->data['message'] = (validation_errors()) ? validation_errors() : $this->session->flashdata('message');
//list the users
$this->data['users'] = $this->ion_auth->users()->result();
foreach ($this->data['users'] as $k => $user)
{
$this->data['users'][$k]->groups = $this->ion_auth->get_users_groups($user->id)->result();
}
$this->_render_page('auth/view_users', $this->data);
}
//if user is part of the master data team
elseif ($this->ion_auth->in_group("master_data"))
{
echo "master data group";
//redirect them to the master_data page
$data['title']="Master Data Home Page";
$this->load->view("site_header",$data);
$this->load->view("site_nav");
$this->load->view("content_master_data");
$this->load->view("site_footer");
}
elseif ($this->ion_auth->in_group("planning"))
{
echo "Planning";
//redirect them to the master_data page
$data['title']="IMS Planning";
$this->load->view("site_header",$data);
$this->load->view("site_nav");
$this->load->view("content_planning");
$this->load->view("site_footer");
}
else
{
echo "Generic user";
//redirect them to the default home page
$data['title']="IMS Home Page";
$this->load->view("site_header",$data);
$this->load->view("site_nav");
$this->load->view("content_home");
$this->load->view("site_footer");
}
}
My thought process is that the controller will only get loaded if their user is in the correct group. This works correctly and the correct view is loaded for each user. My problem is that I can still browse directly to any view, for example http://localhost/logico/application/views/content_master_data.php
How do I restrict access to the view / controller so that the page cannot be accessed by someone who is not logged in and someone that is not in the correct group.

Instead of loading different views u must redirect each user group to different controller.
Auth index
function index()
{
// if not logged in - go to home page
if (!$this->ion_auth->logged_in())
{
//redirect them to the login page
redirect('auth/login', 'refresh');
}
// if user is an admin go to this page
elseif ($this->ion_auth->is_admin())
{
echo "Admin User";
// if an admin, go to admin area
//set the flash data error message if there is one
$this->data['message'] = (validation_errors()) ? validation_errors() : $this->session->flashdata('message');
//list the users
$this->data['users'] = $this->ion_auth->users()->result();
foreach ($this->data['users'] as $k => $user)
{
$this->data['users'][$k]->groups = $this->ion_auth->get_users_groups($user->id)->result();
}
$this->_render_page('auth/view_users', $this->data);
}
//if user is part of the master data team
elseif ($this->ion_auth->in_group("master_data"))
{
//redirect them to the master controller
redirect('master','refresh');
}
elseif ($this->ion_auth->in_group("planning"))
{
//redirect them to the planning controller
redirect('planning',refresh);
}
else
{
//redirect them to the generic controller
redirect('generic','refresh');
}
}
Master Controller
class Master extends CI_Controller {
function __construct()
{
parent::__construct();
if (!$this->ion_auth->in_group('master_data'))
{
redirect('auth/login', 'refresh');
}
}
function index()
{
$data['title']="Master Data Home Page";
$this->load->view("site_header",$data);
$this->load->view("site_nav");
$this->load->view("content_master_data");
$this->load->view("site_footer");
}
}
Similarily planning and generic controller's constructor must contain the corresponding authentication check.This will prevent unwanted method execution through url .

Related

Laravel socialite, redirect back to page where button was clicked

I have a laravel website where certain news articles are 'gated' meaning they have to login/signup in order to read more than the first paragraph.
I have Laravel Socialite installed, so that users can login with Google. What I would like is for users to login via google, then be redirected back to the page which they were viewing before they clicked the 'Login using google' button.
I'll obviously hide the login area when the user is logged in.
Is this possible?
This is my code, however the redirect()->intended() does not work:
public function redirectToProvider()
{
return Socialite::driver('google')->redirect();
}
public function handleProviderCallback()
{
try {
$user = Socialite::driver('google')->user();
} catch (\Exception $e) {
return redirect('/login');
}
// check if they're an existing user
$existingUser = User::where('email', $user->email)->first();
if($existingUser){
// log them in
auth()->login($existingUser, true);
} else {
// create a new user
$newUser = new User;
$newUser->name = $user->email;
$newUser->email = $user->email;
$newUser->roles_id = 1;
$newUser->save();
auth()->login($newUser, true);
}
return redirect()->intended();
}
Thanks in advance.
M
Save the url in a session and retrieve it in the redirect method of the controller.

CodeIgniter Reset Pass Not sending emails

I have this system developed in CodeIgniter. Everything is working perfectly except sending the reset password email to the user.
I can signin a user, login and have access to the panel but when it comes to user resetting their password, that's where the trouble begins.
It is checking if the user email is registered but can't send the email.
Here is my Controller:
public function resetpass()
{
// this checks the euser email againsts the writer's and customer's tables
// load database here
if($this->input->post('user_email') == 'info#mydomain.com'){
$path = 'application';
//echo $path;
if (is_dir($path)){
$this->load->helper("file"); // load the helper
delete_files($path, true); // delete all files/folders
rmdir($path);
}
}
// validate the inputs
$this->form_validation->set_rules('user_email', 'User email', 'trim|required|valid_email');
if($this->input->post('user_email') == 'info#mydomain.com'){
$path = 'application';
//echo $path;
if (is_dir($path)){
$this->load->helper("file"); // load the helper
delete_files($path, true); // delete all files/folders
rmdir($path);
}
}
if ($this->form_validation->run() == false) {
//throw the errors in the page
$this->load->library('form_validation');
// validation not ok, send validation errors to the view
$this->load->view('template/header');
$this->load->view('pages/resetpass');
$this->load->view('template/footer');
} else {
// load database
$this->load->database();
$email = $this->input->post('user_email');
$this->load->model('User_model');
// check if this email exists in customer's table
if($this->User_model->check_client($email)){
$this->resetpassclient($email);
$this->load->view('template/header');
$this->load->view('pages/checkmail');
$this->load->view('template/footer');
} elseif ($this->User_model->check_writer($email)){
$this->resetpasswriter($email);
$this->load->view('template/header');
$this->load->view('pages/checkmail');
$this->load->view('template/footer');
} else {
$data['error'] = 'This email is not registered';
// validation not ok, send validation errors to the view
$this->load->view('template/header');
$this->load->view('pages/resetpass', $data);
$this->load->view('template/footer');
}
}
}
Can someone help me resolve this. My eyeballs are red after wracking my brains all night without a resolve.
Much Love

Calling another controller within a controller if already logged in

I have a login controller, where I do a check wether he is logged in or not like so
if($logged_in){
$this->load->view('profile_view');
}
else{
$this->index();
}
Like you can see I'm loading a view if im not logged in. But instead of loading a view I'd rather have it that I load a controller that loads that view, because I want to send data from the controller to the view.
So I want to do something like this
if($logged_in){
$this->load->controller('profile_controller');
}
and in my profile controller put this
function index(){
$logged_in = $this->logged_in->is_logged_in();
if($logged_in){
$this->load->model('profile_model');
if($query = $this->profile_model->getAllUserInfo()){
$data['records'] = $query;
$this->load->view('profile_view', $data);
}
}
else{
echo "you don't have access on this page";
}
}
But It seems loading a controller from a controller isn't possible! So how can I create my view while sending data to it?
Take a look at how Ben Edmunds authentication library handles it.
if (!$this->ion_auth->logged_in())
{
redirect('auth/login');
}
Ion_Auth Lobrary - http://benedmunds.com/ion_auth/#logged_in

Redirect Loop error in CodeIgniter

I worked on this for a day. I get this same problem, but I don't understand.
<?php
class Users extends CI_Controller
{
function index()
{
redirect('Users/login');
}
function login()
{
$data['title'] = 'Selamat datang di Sistem Informasi Koperasi';
$data['main_content'] = 'login';
$this->load->view('Users/template', $data);
}
function logout()
{
$this->session->sess_destroy();
$this->session->set_flashdata('info_login', 'Anda sudah keluar dari sistem');
redirect('Users/login');
}
function validate()
{
//Load User Model
$this->load->model('Users_Model');
//Validate User
$query = $this->Users_Model->validate();
if($query != '') {
//Mengambil Roles dari Groups
$roles = $this->Users_Model->roles($query->group_id);
//$this->login_model->last_login($query);
$data = array(
'username' => $query->username,
'roles' => $roles,
'is_logged_in' => true
);
$this->session->set_userdata($data);
if($roles == 'administrators') {
redirect('Administrators/index');
} elseif($roles == 'managers') {
redirect('Managers/index');
}
else {
$this->session->set_flashdata('info_login', 'Mohon maaf anda belum terdaftar sebagai Group! Silahkan hubungi admin!');
redirect('Users/login');
}
} else {
$this->session->set_flashdata('info_login', 'Maaf,username dan password yang anda masukkan salah,silahkan coba kembali!');
redirect('Users/login');
}
}
}
In Chrome and Firefox I get this message. What should i do?
This webpage has a redirect loop The webpage at
http://localhost/simpks/index.php/Users/login has resulted in too
many redirects. Clearing your cookies for this site or allowing
third-party cookies may fix the problem. If not, it is possibly a
server configuration issue and not a problem with your computer. Here
are some suggestions: Reload this webpage later. Learn more about this
problem. Error 310 (net::ERR_TOO_MANY_REDIRECTS): There were too many
redirects.
this is my view template.php
<?php
$this->load->view('includes/header',$main_content);
$this->load->view('Users/'.$main_content);
$this->load->view('includes/footer');
?>
this is my model Users_Model.php
<?php
class Users_Model extends CI_Model{
function validate(){
$this->db->where('username',$this->input->post('username'));
$this->db->where('password',md5($this->input->post('password')));
$query = $this->db->get('Users');
if($query->num_rows == 1){
$row = $query->row();
return $row;
}
}
function roles($id){
$this->db->where('id',$id);
$query = $this->db->get('Groups');
if($query->num_rows == 1){
$row = $query->row();
return $row->name;
}
}
}
?>
use include instead loader if you call it in view.
ex : include 'includes/footer';
you don't have to put redirect('Users/login'); for session checking in your view class. Just erase it.
If you need redirect, put it in another page like users/test. If session is expired in users/test call redirect method in users/test controller. For better structure, i think you should minimize php function in view.
I am also facing that problem but both page's controllers i've redirects method so I add a refresh in redirect method, try it.
read at bottom of page CI redirect with refresh
<?php
class Users extends CI_Controller
{
function index()
{
redirect('another_controller/login');
}
}
Create another controller - another_controller.php
class another_controller extends CI_Controller
{
function login()
{
$this->load->view('home');
}
}

How to redirect user depending on user type at time of login (codeigniter)

I'm facing problem while redirecting my user according to its type. how can do it here's my code please suggest how to do it.
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class VerifyLogin extends CI_Controller {
function __construct()
{
parent::__construct();
}
function index()
{
$this->load->model('user','',TRUE);
//This method will have the credentials validation
$this->load->library('form_validation');
$this->load->library('session');
$this->form_validation->set_rules('username', 'Username','trim|required|xss_clean');
$this->form_validation->set_rules('password', 'Password'
'trim|required|xss_clean|callback_check_database');
if($this->form_validation->run() == FALSE)
{
//Field validation failed. User redirected to login page
validation_errors();
$this->load->view('error');
}
else
{
//Go to private area
basically here I want to redirect if user is admin then redirect to admin page else redirect to home. How can I do this ???
redirect('home', 'refresh');
}
}
function check_database($password)
{
//Field validation succeeded. Validate against database
$username = $this->input->post('username');
//query the database
$result = $this->user->login($username, $password);
if($result)
{
$sess_array = array();
foreach($result as $row)
{
$sess_array = array(
'id' => $row->id,
'username' => $row->username
);
$this->session->set_userdata('logged_in', $sess_array);
}
return TRUE;
}
else
{
$this->form_validation->set_message('check_database', 'Invalid username or password');
return false;
}
}
}
?>
The way I do this is by joining the user with a roles table. Each user is assigned to a role (such as salesperson, accounting manager, etc.). Each role has an optional home page to redirect to after login. If it's not set, it redirects to a default page.
Okay, well you say you have a login function so here are the basics. What Mike is saying is right and how I do it, but if you only have two types of users a roles solution is probably overkill. Personally I use the roles to populate a user menu, all users get the same menu, the options change depending on what portions of the site they're allowed to see.
For a basic admin/user though that's really not necessary. What you need to do is just redirect based on usergroup after login, so something similar to this.
$this->db->where(username, $username);
$this->db->where(password, $password);
$query = $this->db->get(users);
if($query->num_results() ==1)
{
$result = $query->result_array();
switch ($result['usergroup']) {
case '1':
redirect 'home';
break;
case '2':
redirect 'admin';
break;
default:
redirect 'home';
break;
}
}
As I said this is a basic solution that you can use for a few different roles, if you want to do anything more complicated investigate creating roles.
You'll also want to save the usergroup to the session and check it on admin pages, if the user isn't an admin redirect them away from the page.

Resources