I have two roles, the admin and the teacher. The admin and teacher accounts can login however when I logged in the teacher account it will redirect to admin page. I don't know if my code is right as well. I'm a newbie at using codeigniter so please bear with me.
So here's my controller:
public function login_validation(){
$this->load->library('form_validation');
$this->form_validation->set_rules('idnum', 'ID Number', 'required|trim|xss_clean|callback_validate_credentials');
$this->form_validation->set_rules('password', 'Password', 'required|md5|trim');
if ($this->form_validation->run()){
//$this->load->model('model_users');
$this->load->model('model_role');
$data = array(
'login_id' => $this->input->post('idnum'),
'is_logged_in' => 1,
'role' => $this->model_role->scalar('user_account','role')
);
$this->session->set_userdata($data);
redirect('site/members');
} else {
$data['title'] = "Outcome-based Education";
$this->load->view("index/header", $data);
$this->load->view("index/view_home");
$this->load->view("index/footer");
}
}
public function members(){
if($this->session->userdata('is_logged_in') && $this->session->userdata('role', 'admin')){
$this->load->view('login/admin');
} elseif($this->session->userdata('is_logged_in') && $this->session->userdata('role', 'teacher')){
$this->load->view('login/members');
}
else{
redirect('site/restricted');
}
}
And this is my model:
public function can_log_in(){
$this->db->where('login_id', $this->input->post('idnum'));
$this->db->where('password', md5($this->input->post('password')));
$query = $this->db->get('user_account');
if($query->num_rows() == 1){
return true;
} else{
return false;
}
}
In your members function you are not actually checking the value of the role session data, you are just checking that it exists. You need to change :
if($this->session->userdata('is_logged_in') && $this->session->userdata('role', 'admin')){
to:
if($this->session->userdata('is_logged_in') && $this->session->userdata('role') == 'admin'){
As you will see, there is only 1 parameter that can be passed into the $this->session->userdata() function:
/**
* Fetch a specific item from the session array
*
* #access public
* #param string
* #return string
*/
function userdata($item)
{
return ( ! isset($this->userdata[$item])) ? FALSE : $this->userdata[$item];
}
when you perform login action , From where you are calling can_log_in() method of model , Even you load the model but you are calling only $this->model_role->scalar('user_account','role') method which you give only "admin" parameter results in response .
Related
I use this code in my controller LOGIN and they are role type in my database: $users->isAdmin() $users->isOwner() $users->isMember()
public function dologin(Request $request){
$users = new Users;
$email = $request->input('u_email');
$password = $users->setPasswordAttribute($request->input('pwd1'));
//get user id from email
$user_id = $users->get_user_from_email($email);
foreach($user_id as $u){
$u_type = $u->u_type;
}
// Check validation
if (auth()->attempt(['u_email' => $email, 'password' => $password] )){
if($users->isAdmin() == $u_type){
return redirect('admin');
}
if($users->isOwner() == $u_type){
}
if($users->isMember() == $u_type){
}
}else{
}
}
Code in Users Model
public function isAdmin(){
return 0 ;
}
public function isOwner(){
return 1 ;
}
public function isMember(){
return 2;
}
My question:
-how to store role in session for logged in dashboard?
-how to declare in controller this role
Thanks you for all help
Note: the role type are integer 0, 1 and 2. I don't use enum type in my database for this role but integer
To use session in pages, make sure at the start of the page you have session_start(); (before any HTML tag).
After that, when he is logging in and everything is allright set $_SESSION["u_type"]=$u_type; and you can refer to it until you destroy your session.
To check in dashboard if he is admin, owner or member just check
//don't forget session_start(); at the begging of your file
if($_SESSION["u_type"]==0)
//admin
else if($_SESSION["u_type"]==1)
//owner
else if($_SESSION["u_type"]==2)
//member
i am currently making this part that can create something to input to database. i used callback function of code igniter to check availability of some item code of a non auto increment table.
i always get the message of the callback '{field} exists.' how do i fix this?
controllers
// CREATE /////////////////////////////////////////////////////////
public function create(){
$this->load->library('form_validation');
$this->form_validation->set_rules('JOB_CODE','Job Code','trim|required|min_length[2]|max_length[5]|callback_check_if_exists');
$this->form_validation->set_rules('JOB_NAME','Job Name','trim|required|max_length[30]');
if($this->form_validation->run() == FALSE){
$this->add_view();
}else{
$input = array(
'JOB_CODE' => $this->input->post('JOB_CODE'),
'JOB_NAME' => $this->input->post('JOB_NAME')
);
$this->Job_Titles_Model->insert($input);
}
}
/////////// FOR TABLES WITH NO AUTO INREMENT
public function check_if_exists($jobcode){
$this->load->model('Job_Titles_Model');
$availability = $this->Job_Titles_Model->check_if_exists($jobcode);
if($availability){
return TRUE;
}else{
return FALSE;
}
}
models
///// CREATE /////////////////////////////////////////////////////////
public function insert($input){
$insert = $this->db->insert('job_titles',$input);
}
/////////// FOR TABLES WITH NO AUTO INREMENT
public function check_if_exists($jobcode){ //CHECK IF JOBODE IS AVAILABLE
$sql = ('SELECT * FROM job_titles WHERE JOB_CODE = ?');
$data = array('JOB_CODE' => $this->input->post('JOB_CODE'));
if($result->num_rows() == 0){
return TRUE;
}else{
return FALSE;
}
}
On my codeigniter login. If user types in incorrect user name it should display error saying Username or Password Incorrect as flash-data. And if user puts in username that does not exist then would throw error Username Not Match Any Records.
Cannot get the form database check errors to display correct way. I can login OK but just not throwing login flash-data errors correct.
How can I get my form database errors to work correct. The main codeigniter form validation are OK just not throwing my database errors.
public function index() {
$this->load->library('form_validation');
$this->form_validation->set_rules('username', 'Username', 'required|trim');
$this->form_validation->set_rules('password', 'Password', 'required');
if ($this->form_validation->run() == FALSE) {
$this->login();
} else {
if ($this->input->post('username') && $this->input->post('password')) {
// Gets the user information from the database.
$user = $this->user_login_model->get('username', $this->input->post('username'));
if ($user) {
// If User Login Success
if ($this->user_login_model->check_password($this->input->post('password'), $user['password']) == TRUE) {
$this->user->login($user['user_id']);
redirect('admin/dashboard');
} else {
$this->session->set_flashdata('error', 'Username or Password Is Does Not Match Any Records!');
$this->login();
}
}
}
}
}
public function login() {
$this->document->setTitle($this->lang->line('heading_title'));
$data['text_login'] = $this->lang->line('text_login');
$data['text_register'] = $this->lang->line('text_register');
$data['entry_username'] = $this->lang->line('entry_username');
$data['entry_password'] = $this->lang->line('entry_password');
$data['action'] = site_url('admin');
$data['button_login'] = $this->lang->line('button_login');
return $this->load->view('common/login', $data);
}
Get User model
/**
* Retrieve a user
*
* #param string where
* #param int value
* #param string user_identification field
*/
public function get($where, $value = FALSE) {
if (!$value) {
$value = $where;
$where = 'user_id';
}
$user = $this->db->where($where, $value)->get($this->table)->row_array();
return $user;
}
Flashdata will only be shown if the user is redirected to another page.
On the failed login action you only load a view to the user's screen. Try altering
$this->login();
to
redirect('controller/login'); //ofc change the controller name first
Right I have set up confide user authentication on my Laravel site.
I have ran everything as exactly as they said on the github page. When I direct myself to the user/create page I am presented with the form that I would normally posy me new info into. When I press submit I get this error on this url: /user.
On inspection these are the errors I get:
Symfony \ Component \ HttpKernel \ Exception \ NotFoundHttpException
Controller method not found.
* Handle calls to missing methods on the controller.
*
* #param array $parameters
* #return mixed
*/
public function missingMethod($parameters)
{
throw new NotFoundHttpException("Controller method not found.");
}
15. Symfony\Component\HttpKernel\Exception\NotFoundHttpException
…/vendor/laravel/framework/src/Illuminate/Routing/Controllers/Controller.php290
14. Illuminate\Routing\Controllers\Controller missingMethod
…/vendor/laravel/framework/src/Illuminate/Routing/Controllers/Controller.php302
13. Illuminate\Routing\Controllers\Controller __call
…/app/controllers/UserController.php42
12. User save
…/app/controllers/UserController.php42
11. UserController store
<#unknown>0
My UserController.php is setup like so:
<?php
/*
|--------------------------------------------------------------------------
| Confide Controller Template
|--------------------------------------------------------------------------
|
| This is the default Confide controller template for controlling user
| authentication. Feel free to change to your needs.
|
*/
class UserController extends BaseController {
/**
* Displays the form for account creation
*
*/
public function create()
{
return View::make(Config::get('confide::signup_form'));
}
/**
* Stores new account
*
*/
public function store()
{
$user = new User;
$user->username = Input::get( 'username' );
$user->email = Input::get( 'email' );
$user->password = Input::get( 'password' );
// The password confirmation will be removed from model
// before saving. This field will be used in Ardent's
// auto validation.
$user->password_confirmation = Input::get( 'password_confirmation' );
// Save if valid. Password field will be hashed before save
$user->save();
if ( $user->id )
{
// Redirect with success message, You may replace "Lang::get(..." for your custom message.
return Redirect::action('UserController#login')
->with( 'notice', Lang::get('confide::confide.alerts.account_created') );
}
else
{
// Get validation errors (see Ardent package)
$error = $user->errors()->all(':message');
return Redirect::action('UserController#create')
->withInput(Input::except('password'))
->with( 'error', $error );
}
}
/**
* Displays the login form
*
*/
public function login()
{
if( Confide::user() )
{
// If user is logged, redirect to internal
// page, change it to '/admin', '/dashboard' or something
return Redirect::to('/admin');
}
else
{
return View::make(Config::get('confide::login_form'));
}
}
public function do_login()
{
$input = array(
'email' => Input::get( 'email' ), // May be the username too
'username' => Input::get( 'email' ), // so we have to pass both
'password' => Input::get( 'password' ),
'remember' => Input::get( 'remember' ),
);
// If you wish to only allow login from confirmed users, call logAttempt
// with the second parameter as true.
// logAttempt will check if the 'email' perhaps is the username.
// Get the value from the config file instead of changing the controller
if ( Confide::logAttempt( $input, Config::get('confide::signup_confirm') ) )
{
// Redirect the user to the URL they were trying to access before
// caught by the authentication filter IE Redirect::guest('user/login').
// Otherwise fallback to '/'
// Fix pull #145
return Redirect::intended('/'); // change it to '/admin', '/dashboard' or something
}
else
{
$user = new User;
// Check if there was too many login attempts
if( Confide::isThrottled( $input ) )
{
$err_msg = Lang::get('confide::confide.alerts.too_many_attempts');
}
elseif( $user->checkUserExists( $input ) and ! $user->isConfirmed( $input ) )
{
$err_msg = Lang::get('confide::confide.alerts.not_confirmed');
}
else
{
$err_msg = Lang::get('confide::confide.alerts.wrong_credentials');
}
return Redirect::action('UserController#login')
->withInput(Input::except('password'))
->with( 'error', $err_msg );
}
}
public function confirm( $code )
{
if ( Confide::confirm( $code ) )
{
$notice_msg = Lang::get('confide::confide.alerts.confirmation');
return Redirect::action('UserController#login')
->with( 'notice', $notice_msg );
}
else
{
$error_msg = Lang::get('confide::confide.alerts.wrong_confirmation');
return Redirect::action('UserController#login')
->with( 'error', $error_msg );
}
}
public function forgot_password()
{
return View::make(Config::get('confide::forgot_password_form'));
}
public function do_forgot_password()
{
if( Confide::forgotPassword( Input::get( 'email' ) ) )
{
$notice_msg = Lang::get('confide::confide.alerts.password_forgot');
return Redirect::action('UserController#login')
->with( 'notice', $notice_msg );
}
else
{
$error_msg = Lang::get('confide::confide.alerts.wrong_password_forgot');
return Redirect::action('UserController#forgot_password')
->withInput()
->with( 'error', $error_msg );
}
}
public function reset_password( $token )
{
return View::make(Config::get('confide::reset_password_form'))
->with('token', $token);
}
public function do_reset_password()
{
$input = array(
'token'=>Input::get( 'token' ),
'password'=>Input::get( 'password' ),
'password_confirmation'=>Input::get( 'password_confirmation' ),
);
// By passing an array with the token, password and confirmation
if( Confide::resetPassword( $input ) )
{
$notice_msg = Lang::get('confide::confide.alerts.password_reset');
return Redirect::action('UserController#login')
->with( 'notice', $notice_msg );
}
else
{
$error_msg = Lang::get('confide::confide.alerts.wrong_password_reset');
return Redirect::action('UserController#reset_password', array('token'=>$input['token']))
->withInput()
->with( 'error', $error_msg );
}
}
public function logout()
{
Confide::logout();
return Redirect::to('/');
}
}
This is what the php artisan confide:controller creates for you and then you can do the same for routes which outputs this in the routes.php file for you:
// Confide routes
Route::get( 'user/create', 'UserController#create');
Route::post('user', 'UserController#store');
Route::get( 'user/login', 'UserController#login');
Route::post('user/login', 'UserController#do_login');
Route::get( 'user/confirm/{code}', 'UserController#confirm');
Route::get( 'user/forgot_password', 'UserController#forgot_password');
Route::post('user/forgot_password', 'UserController#do_forgot_password');
Route::get( 'user/reset_password/{token}', 'UserController#reset_password');
Route::post('user/reset_password', 'UserController#do_reset_password');
Route::get( 'user/logout', 'UserController#logout');
In my User.php model I have this setup which is normal:
<?php namespace App\Models;
use Eloquent;
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableInterface;
use Zizaco\Confide\ConfideUser;
use Zizaco\Entrust\HasRole;
class User extends ConfideUser {
use HasRole;
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'users';
public function getPresenter()
{
return new UserPresenter($this);
}
/**
* Get user by username
* #param $username
* #return mixed
*/
public function getUserByUsername( $username )
{
return $this->where('username', '=', $username)->first();
}
/**
* Get the date the user was created.
*
* #return string
*/
public function joined()
{
return String::date(Carbon::createFromFormat('Y-n-j G:i:s', $this->created_at));
}
/**
* Save roles inputted from multiselect
* #param $inputRoles
*/
public function saveRoles($inputRoles)
{
if(! empty($inputRoles)) {
$this->roles()->sync($inputRoles);
} else {
$this->roles()->detach();
}
}
/**
* Returns user's current role ids only.
* #return array|bool
*/
public function currentRoleIds()
{
$roles = $this->roles;
$roleIds = false;
if( !empty( $roles ) ) {
$roleIds = array();
foreach( $roles as &$role )
{
$roleIds[] = $role->id;
}
}
return $roleIds;
}
/**
* Redirect after auth.
* If ifValid is set to true it will redirect a logged in user.
* #param $redirect
* #param bool $ifValid
* #return mixed
*/
public static function checkAuthAndRedirect($redirect, $ifValid=false)
{
// Get the user information
$user = Auth::user();
$redirectTo = false;
if(empty($user->id) && ! $ifValid) // Not logged in redirect, set session.
{
Session::put('loginRedirect', $redirect);
$redirectTo = Redirect::to('user/login')
->with( 'notice', Lang::get('user/user.login_first') );
}
elseif(!empty($user->id) && $ifValid) // Valid user, we want to redirect.
{
$redirectTo = Redirect::to($redirect);
}
return array($user, $redirectTo);
}
public function currentUser()
{
return (new Confide(new ConfideEloquentRepository()))->user();
}
}
So from this I can go to the form on /user/create and it outputs the form which means that route is working but on submit I get the No method error.
Can anyone shed some light onto this please?
Thanks
Whenever you type composer-dump autoload, composer recreates a bunch of files which tell it what classes should be registered into the autoloader. classmap autoloading requires you to composer dump-autoload whenever you make new files in a directory being autoloaded. psr-0 autoloading requires you to namespace your files but from then on you don't need to composer dump-autoload except for the first time you define the psr-0 autoloading in your composer.json file.
I'm new to codeigniter and php, few days only, so I need a little help.
I'm trying to put some data in my cookie from table so I can check where to redirect user after login. In table users there are two columns named Admin and Company with one or zero if user is or not, and then i wish to insert that information to cookie.
function conformation in user_controler is:
function conformation(){
$this->load->model('user');
$q = $this->user->confr();
if($q){
$data = array(
'username' => $this->input->post('username'),
'Admin' => $this->input->post($a = $this->user->getAdmin), // get 1/0 from users column Admin
'Company' => $this->input->post($c = $this->user->getComp),
'login' => true
);
if( $a == 1 ){ //is admin redirect to admin view
$this->session->set_userdata($data);
redirect('user_controler/useradm');
}
if($c == 1){ //if company redirect to company view
$this->session->set_userdata($data);
redirect('user_controler/usercomp');
}
$this->session->set_userdata($data);// if common user redirect to user view
redirect('user_controler/userpro');
}
else{ // if nothing above redirect to login page
redirect('user_controler/log');
}
}
And in user model:
function getAdmin{
$this->db->where('Admin', 1);
$a = $this->db->get('users');
}
function getComp{
$this->db->where('Company', 1);
$a = $this->db->get('users');
}
function conf(){
$this->db->where('username', $this->input->post('username'));
$this->db->where('password', $this->input->post('password'));
$q = $this->db->get('users');
if($q->num_rows == 1 ){
return TRUE;
}
}
Also have site controller for checking login
class Site extends CI_Controller{
function __construct() {
parent::__construct();
$this->login();
}
function login(){
$login = $this->session->userdata('login');
if(!isset($login) || login != TRUE){
$this->log;
die();
}
}
}
Of course it's not working because i should probably check these column some other way but I don't know how. I Also have enabled table ci_session and it's work perfectly without Admin and Company.
Hello and welcome to Stackoverflow.
Here are my updates to the code (I have annotated my changes):
function conformation(){
$this->load->model('user');
if($this->user->confr()){ //$q wasn't needed, as you are only using this twice
$user = $this->input->post('username'); //I have added this as I will be referring to it a couple of times.
$data = array(
'username' => $user,
'Admin' => $this->user->getAdmin($user), // Your method was questioning the original form looking for data that it would never find - This will question your model.
'Company' => $this->user->getComp($user), //Same as above
'login' => true
);
$this->session->set_userdata($data); //It doesn't matter who the user is, we shall set the data to start with.
if($this->user->getAdmin($user)){ //is admin redirect to admin view
redirect('user_controler/useradm');
}
elseif($this->user->getComp($user)){ //if company redirect to company view
redirect('user_controler/usercomp');
}
else { //Redirect non-privileged users.
redirect('user_controler/userpro');
}
}
else{ // if nothing above redirect to login page
redirect('user_controler/log');
}
}
Users Model:
function getAdmin($user){
$this->db->where('username', $user); //Before you was just returning everyone who is an admin This instead finds the user
$a = $this->db->get('users');
foreach($a as $u) {
if($u["Admin"]==1) { return true; } //This finds if the user is a admin or not, and the function will now return a value (true)
}
}
function getComp($user) {
$this->db->where('username', $user);
$a = $this->db->get('users');
foreach($a as $u) {
if($u["Company"]==1) { return true; }
}
} //Edited similar to the function above
function conf(){
$this->db->where('username', $this->input->post('username'));
$this->db->where('password', $this->input->post('password'));
$q = $this->db->get('users');
if($q->num_rows == 1 ){
return TRUE;
}
}
Lastly your login function:
function login(){
$login = $this->session->userdata('login');
if(!isset($login) || $login != TRUE){ //You weren't referring to your $login variable
$this->log;
die();
}
}
Hopefully this helps with your problems, let me know if you need any amendments.