I am stuck with users profile feature, I want only authenticated users to access their own profile only.
User with id: 1 can only access route /applicants/profile/1, otherwise return 404 Not found?
class ApplicantProfileController extends Controller
{
public function show(Applicant $applicant)
{
return view('applicant.show', compact('applicant'));
}
}
route::group(['prefix' => 'applicants', 'middleware' => 'auth:applicant'], function() {
Route::get('/profile/{applicant}', 'Profiles\ApplicantProfileController#show');
});
You can chech whether the logged user and the parameter user are the same by using the Illuminate/Support/Facades/Auth facade like this:
public function show(Applicant $applicant)
{
if (Auth::id() == $applicant->id) {
return view('applicant.show', compact('applicant'));
}
return abort(404);
}
Related
I have two roles in my app admin and users. Both roles are using a middleware called auth. Now in the application, when i login as a admin, i am not able to route to user page (that is perfect).
But when i login as user, i am able to route to admin page but my auth must prevent the user from accessing the admin page. Currently, that is my issue... What am i not doing right?
Below is my code
AuthMiddleWare
if (Auth::check())
{
if(Auth::user()->roles->pluck('name')->first() == "admin")
{
// return $next($request);
return Redirect::to('/admin/dashboard');
}
else if(Auth::user()->roles->pluck('name')->first() == "user")
{
return Redirect::to('/user/dashboard/');
}
else{
return Redirect::to('login');
}
}
Route
Route::group(array('prefix' => 'admin', 'namespace' => 'Admin', 'middleware' => ['auth']), function () {
Route::get('dashboard','Controller#show');
}
Route::group(array('prefix' => 'user', 'namespace' => 'User', 'middleware' => ['auth']), function () {
Route::get('dashboard','Controller#show');
}
Try the following code:
if (Auth::check())
{
if(in_aaray('admin', Auth::user()->roles->pluck('name')->all()))
{
// return $next($request);
return redirect('/admin/dashboard');
}
else if(in_array('user', Auth::user()->roles->pluck('name')->all()))
{
return redirect('/user/dashboard/');
}
else{
return redirect('login');
}
}else{
return redirect('login');
}
you need to make custom auth in laravel and make different table for admin and user
I have this in my database
|username|password|type|
------------------------
|foo |12345 |1 |
|asd |adsdsd |0 |
Here 1 means that the user is an admin, 0 a normal user.
How can I redirect the admin to the admin page and the normal user to normal user page??
if($attempt)
{
$id = User::find($attempt);
$user = $id->type;
if($user === 0)
{
return Redirect::action('LoginUsersController#profile');
}
else
{
return Redirect::to('adminpage');
}
}
I created this in my UsersController page I don’t know if this is the proper way to do this, and my code is not working.
Are you using normal Laravel Authentication?
You will get Object Auth::user(), this will return current user Object.
It should look like this.
Controller (SessionsController#store)
public function store() {
$input = Input::all();
$attempt = Auth::attempt([
'username' => $input['username'],
'password' => $input['password']
]);
if($attempt) {
if(Auth::user()->type == 1) {
return Redirect::admin(); // If admin, redirect to admin
} else {
return Redirect::profile(); // Else, redirect to user profile
}
}
}
Route
Route::resource('sessions', 'SessionsController', ['only' => ['create','store','destroy']]);
Route::get('admin', 'AdminController#dashboard')->before('adminAuth');
Route::get('profile/{id}', 'UsersController#showProfile')->before('auth');
First of all you have to add a new field in your users table to check against, for example 'rank'. If rank for a user is '1' so he is an Admin,
else he is a normal user.
Then define all required routes in your routes file like this:
Route::get('login', 'adminController#login');
Route::post('login', 'adminController#checkuser');
Route::group(array('before' => 'auth'), function() {
Route::resource('admin', 'adminController');
Route::resource('normaluser', 'normaluserController');
} );
Then in your controller you have to define all actions:
public function login()
{
return View::make('loginview');
}
public function checkuser()
{
if (Auth::attempt(array('username'=>Input::get('username'), 'password'=>Input::get('password'))))
{
$user_data = Auth::getUser();
if ($user_data->rank == 1) //if true, so this user is an admin
{return Redirect::to('admin');} //go to adminController index action
else //if not, so he is a normal user
{return Redirect::to('normaluser');} // go to normaluserController index action
}
else
{
//return 'wrong user name or password';
Session::flash('mismatch', "Username and Password mismatch");
return Redirect::to('login'); // go again to login form to relogin
}
}
if any thing is not clear, don't hesitate to ask.
in the if statement use:
if($attempt)
{
$id = User::find($attempt);
$user = $id->type;
if($user === 0)
{
return Redirect::action('LoginUsersController#profile');
header('Location: http://www.example.com/userpahe.php');
}
else
{
return Redirect::to('adminpage');
header('Location: http://www.example.com/admin-page.php');
}
}
The user logs out after redirecting to the homepage after successful login. Even a before filter for auth fails on the route. I am using ollieread/multi-auth plugin.
Auth Controller
public function postLogin()
{
if (\Auth::biz()->attempt(\Input::only(array('email', 'password')), \Input::get('persist', 'no') == 'yes')) {
// dd(Auth::biz()->check()); returns true
return \Redirect::route('main.home');
} else {
return \Redirect::back()->withInput()->with('loginFail', true);
}
}
Route
Route::get('/{verify_token?}', array('as' => 'main.home', 'uses' => 'MainController#getIndex'));
Main Controller
public function getIndex($verify_token = '')
{
dd(\Auth::biz()->check()); // returns bool(false)
return \View::make('main.pages.home', array($emailVerified));
}
I am using laravel 4 and here is my AdminController file :
class AdminController extends BaseController {
protected $layout = "admin.layout";
public function __construct() {
// security for the forms and access
$this->beforeFilter('csrf', array('on'=>'post'));
$this->beforeFilter('auth.admin' , array('except' =>array('getIndex','postSignin')));
// using this one to display user value if login and is admin
if (Auth::check() && Auth::user()->isAdmin()){
$this->user = Auth::getUser();
View::share('user', $this->user);
}
}
// main admin page
public function getIndex(){
$this->layout->content = View::make('admin.login');
}
// get the dashboard page
public function getDashboard() {
$this->layout->content = View::make('admin.dashboard');
}
// missing pages all redirect to dashboard if user is logged in.
public function missingMethod($parameters = array()){
if (Auth::check() && Auth::user()->isAdmin())
$this->getDashboard();
else
$this->getIndex();
}
Here is my filters.php file :
Route::filter('auth.admin', function()
{
if(!Auth::check() && !(Auth::user()->isAdmin())){
return Redirect::guest('admin');
}
});
in my routes.php file I am doing this:
Route::controller('admin', 'AdminController');
here is what I want if you could help me :_
1) . I want to clean up my code where there is not that much checking for if user is logged and isAdmin.
2). right now if you are logged in and you go to "admin/" , it will show you the login page ? how could I fix it in an effective way.
3). also if you are not logged in and you go to "admin/dashboard" it will show you dashboard content ? how to fix
Thank you in advance for all your help :)
You can use route groups and use a single filter to validate them
Check the docs
http://laravel.com/docs/routing#route-groups
Add this in your routes.php file:
Route::group(array('before' => 'auth.admin'), function() {
Route::controller('admin', 'AdminController');
})
Declare filter in filters.php file:
Route::filter('auth.admin', function(){
// Assumed you have a '/login' url
if (Auth::guest() || (Auth::check() && !Auth::user()->isAdmin())) {
return Redirect::guest('login');
}
});
Also make sure you have the user()->isAdmin() method in your User model that you are using and it checks whether the user is an admin or not and returns a Boolean value, TRUE if the user is an admin otherwise FALSE.
I don't want my users to be able to go to the login page if they are logged in. They have to log out first to be able to login. It seems simple enough, am i not understanding something correctly
class UsersController extends AppController {
public function isAuthorized($user) {
if( $this->Auth->login() ){
return false;
} else {
return true;
}
}
public function login() {
if ($this->request->is('post')) {
if ($this->Auth->login()) {
return $this->redirect($this->Auth->redirectUrl());
} else {
$this->Session->setFlash(__('Username or password is incorrect'), 'default', array(), 'auth');
}
}
}
There are also actions like register or lost password etc.
Basically you just check on blacklisted controller/actions and redirect to your home screen or login redirect accordingly
// Do not allow access to these public actions when already logged in
$allowed = array('Account' => array('login', 'lost_password', 'register'));
foreach ($allowed as $controller => $actions) {
if ($this->name === $controller && in_array($this->request->action, $actions)) {
$this->Common->flashMessage('The page you tried to access is not relevant if you are already logged in. Redirected to main page.', 'info');
return $this->redirect($this->Auth->loginRedirect);
}
}
See
https://github.com/dereuromark/cakefest/blob/master/Controller/AppController.php#L66
I use laravel, and in situations like that, my login route is filtered like this.
Route::get('login', array('before' => 'guest', "uses" => "SessionController#create"));
guest is the name of a filter, defined as return !Auth::check();
For CakePHP, I'd imagine it'd be pretty similar. Look for a way that you can filter your routes, based on if your current user is authenticated.