I have created function in laravel helper class to check Authentication in app/lib/Auth.php
class Auto extends \BaseController {
public static function logged() {
if(Auth::check()) {
return true;
} else {
$message = array('type'=>'error','message'=>'You must be logged in to view this page!');
return Redirect::to('login')->with('notification',$message);
}
}
}
In my controller
class DashboardController extends \BaseController {
/**
* Display a listing of the resource.
*
* #return Response
*/
public function index()
{
Auto::logged();
return View::make('dashboard.index');
}
I expect it redirect to login route if not logged, but it load dashboard.index view with message 'You must be logged in to view this page!'.
How can I redirect to login route with this message?
Why you want to create new helper function for that. Laravel already handle it for you. See app/filters.php. You will be see authentication filter like the following
Route::filter('auth', function()
{
if (Auth::guest())
{
if (Request::ajax())
{
return Response::make('Unauthorized', 401);
}
else
{
return Redirect::guest('/')->with('message', 'Your error message here');
}
}
});
You can determine if user is Authenticated or not like the following
if (Auth::check())
{
// The user is logged in...
}
Read more about Authentication on Laravel doc.
this should be work :
/**
* Display a listing of the resource.
*
* #return Response
*/
public function index()
{
if(Auto::logged()) {
return View::make('dashboard.index');
}
}
Related
I keep having this issue that whenever I log-in, I get my jwt token, but whenever I try to use that token to make other requests on differents route that are binded with the auth:api middleware, it keeps returning unauthenticated. hence, I can't make any request.
can anybody please help
Route looks like
Route::prefix('auth')->group(function () {
Route::post('login', [LoginController::class, 'login'])->name('login');
Route::post('refresh', [LoginController::class, 'handleRefreshToken'])->name('refresh');
Route::post('me', [LoginController::class, 'userDetails'])->name("user_details");
});
why my controller looks like
<?PHP
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\Http\Requests\Auth\LoginController\LoginValidator;
use App\Traits\SendsApiResponse;
use Illuminate\Http\Response;
class LoginController extends Controller
{
use SendsApiResponse;
/**
* Create a new AuthController instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('auth:api', ['except' => ['login', 'refresh']]);
}
/**
* Handles User Login
* #param LoginValidator $request
* #return \Illuminate\Http\JsonResponse|mixed
*/
public function login(LoginValidator $request)
{
try {
$login_cred = $request->validated();
$token = auth()->attempt($login_cred);
if (!$token) {
return $this->failureResponse("Incorrect UserName and/or Password", Response::HTTP_UNAUTHORIZED);
}
return $this->successResponse($this->returnToken($token));
} catch (\Exception $e) {
return $this->failureResponse($e->getMessage(), $e->getCode());
}
}
public function returnToken($token)
{
return [
"token" => $token
];
}
/**
* Handle The Refreshing Of Users Token
* #return \Illuminate\Http\JsonResponse|mixed
*/
public function handleRefreshToken()
{
try {
return $this->successResponse($this->returnToken(auth()->refresh($forceForever = true)));
} catch (\Exception $e) {
return $this->failureResponse($e->getMessage(), 440);
}
}
public function userDetails()
{
return $this->successResponse(auth()->user());
}
}
of all the method above, only login works, the rest don't
Depending on how you're sending the token:
This package will always return Unauthenticated when the token is missing, expired, or wrong.
Add the Authorization header with Bearer [your token] to the request and send it again, then check if it still returns Unauthenticated.
The code that handles this logic is contained in the auth:api middleware, but it only works if you configured it correctly in the config/auth.php file.
I have multiple users with multiple permissions. A user can belong to the only single role but that role can have multiple permissions like create, read, update, delete. And I have a RoleMiddleware. I am authenticating the user in roleMiddleware. But how can I protect routes in RoleMiddleware against a specific user?
For Example, I have a route create-case which can only be accessed by the operator or by Admin else everyone redirects to 404 error how Can I deal with it in RoleMiddleware.
I have written basic code for authentication where every user with their roles is authenticated but I am getting how can I code in middleware so ever route when a user hits it may go to the RoleMiddleware where middleware Authenticate route to the Role and then give him the access.
Role Middleware
class RoleMiddleware
{
public function handle($request, Closure $next, $permission = null)
{
if (Auth::check() === false)
{
return redirect('login');
}
elseif (Auth::check() === true)
{
$roles = Role::all()->pluck('slug');
if (is_null($request->user()) )
{
abort(404);
}
if (!$request->user()->hasRole($roles))
{
abort(404);
}
if ($request->user())
{
if ($request->user()->hasRole($roles))
{
return $next($request);
}
}
}
}
}
Case Controller:
<?php
namespace App\Http\Controllers\Cases;
use App\Http\Controllers\Controller;
use App\Http\Requests\CaseStoreRequest;
use Illuminate\Support\Facades\Auth;
use Session;
class CaseController extends Controller
{
use DropzoneFileUploadTraits;
public function __construct()
{
$this->middleware('role');
}
public function index()
{
$data['portal'] = Portal::all();
$data['operators'] = Operator::all();
return view('case', $data);
}
public function caseList()
{
$user = new User();
$isAdmin = $user->isAdmin();
$loggedIn = Auth::id();
$cases = Cases::with('patients', 'portal')
->when(!$isAdmin, function ($query) use ($loggedIn) {
return $query->where('user_id', $loggedIn);
})->orderBy('created_at', 'desc')->get();
$data['cases'] = $cases;
return view('case_list', $data);
}
}
Route:
Route::get('create-case', 'Cases\CaseController#index')->name('create-case');
Route::post('case-submit', 'Cases\CaseController#caseSubmit')->name('case-submit');
Route::post('edit-patient-case-submit', 'Cases\CaseController#editPatientCaseSubmit')->name('edit-patient-case-submit');
Route::get('case-list', 'Cases\CaseController#caseList')->name('case-list');
Best way to do that in a clean manner would be to create policies on the targeted entities.
Laravel policies allow you to :
Bind a route authorization logic to a policy action
Easily call a policy action result from anywhere else in the project (views, controllers and so on).
The subject is well covered in Laravel documentation so I suggest you go there and take a look. Do not forget to register the policy and bind it to your model.
Apart from that this should do the trick.
class CasePolicy
{
use HandlesAuthorization;
public function create(User $user){
$roles = ['operator','Admin']
return $user->hasRole($roles);
}
}
Then in your route file :
Route::get('create-case', 'Cases\CaseController#index')->name('create-case')->middleware('can:create,App\Case');
I haved just learned and implement Gate and Policy hope this is correct Because its working for me. Great concept thanks.
Route::get('create-case', 'Cases\CaseController#index')->name('create-case')->middleware('can:create-case,App\Model\Case');
Gate:
class AuthServiceProvider extends ServiceProvider
{
/**
* The policy mappings for the application.
*
* #var array
*/
protected $policies = [
// 'App\Model' => 'App\Policies\ModelPolicy',
User::class => CreateCase::class
];
/**
* Register any authentication / authorization services.
*
* #return void
*/
public function boot()
{
$this->registerPolicies();
Gate::define('create-case','App\Policies\CreateCase#create_case');
}
}
Policy
class CreateCase
{
use HandlesAuthorization;
/**
* Create a new policy instance.
*
* #return void
*/
public function __construct()
{
//
}
public function create_case(User $user){
if($user->hasRole(['admin']) ||$user->hasRole(['operator']) && $user->hasPermissionTo('create')){
return true;
}else
return false;
}
}
I want to stop the controller action when a block code is complete.
This some example code.
class Controller extends \Phalcon\Mvc\Controller {
/**
* Check if user have access
*
*/
protected function isAllowed($perm = false)
{
/**
* Always allowed if $perm not defined
*/
if (!$perm) {
return false;
}
/**
* if user not login
*/
if (!$this->authentication->isLoggedin()) {
/* Redir to login */
$this->response->redirect( $this->url->get('authentication/login') );
return false;
} else {
/* Check for user access */
if ($this->authorization->isAllowed($perm)) {
return true;
} else {
/* if not have access, it will be redir to index */
$this->flash->warning("U not have permission to access page");
return $this->response->redirect( $this->url->get('administrator/') );
}
}
}
}
and the another controller that extend from base is
class postController extends Controller {
/**
* Add group
*
*/
public function addAction()
{
/*
Check user access
this must redirect to login and stop exe script
*/
$this->isAllowed('group_add');
/*
But when i check with `Postman`
without auth i redirect to login.
but when i use post method and fill the header body like bellow.
i still redir to login but this code execute. why? and how to stop it.
*/
/* If request is POST */
if ($this->request->isPost()) {
/* Get all inputs from form */
$inputs = $this->request->getPost();
$name = $this->request->getPost('name', ['trim', 'striptags', 'string']);
$definition = $this->request->getPost('definition', ['trim', 'striptags', 'string']);
/* Filter validation */
if (!Validation::make($inputs, $this->rules())) {
$this->flash->error('...');
... redirect to page
return false;
}
/* Get from database */
$model = new AauthGroups;
$group = $model->findFirst([
'name = :name:',
'bind' => [
'name' => $name
]
]);
/* If cant find group then add it */
if (!$group) {
/* Set & save data */
$model->name = $name;
$model->definition = $definition;
$model->save();
$this->flash->success('Yay!! We found that name in database, do u want to change it?');
return;
}
/* If it finded than set flash error */
else {
$this->flash->error('Oops!! We found that name in database, do u want to change it?');
return;
}
}
}
}
I tried to use exit; but the view will not render. Can you explain it?
Can you try send()-ing the response like this?
/* Redir to login */
$this->response->redirect( $this->url->get('authentication/login') )->send();
return false;
If this does not work, you may have to use beforeExecuteRoute in your "BaseController".
class Controller extends \Phalcon\Mvc\Controller {
public function beforeExecuteRoute()
{
// Check if logged
if (!$notLogged) {
$this->response->redirect('....')->send();
return false;
}
}
I will be able to check those later. Hope it works for you by then.
Hello their i am using laravel 5.1 and i have problem with redirecting the path of user. i have a roles table, a users table and role_user table means pivot table. Every thing is fine nice but i failed to redirect the page of different user. . This is my User Model. I have not created any middleware
public function roles()
{
return $this->belongsToMany('my\role');
}
public function hasRole($role)
{
if (is_string($role)){
return $this->roles->contains('name', $role);
}
return !! $role->intersect($this->roles)->count();
}
This is my AuthController:
public function redirectPath()
{
// Logic that determines where to send the user
if (\Auth::user()->hasRole('GlobalAdmin', 'SuperAdmin', 'CompanyAdmin', 'GroupAdmin'))
{
return '/adminpanel';
}
return '/dashboard';
}
When I login as role globleadmin It works fine and redirect to adminpanel but when i login as another assigned role it redirect to dashboard. I didn't get it perhaps I passed arguments in AuthController as:
if (\Auth::user()->hasRole('GlobalAdmin', 'SuperAdmin', 'CompanyAdmin', 'GroupAdmin'))
is incorrect. Please help me.
This is my route:
Route::get('/adminpanel', 'Admin\adminscontroller#index');
And This is my adminscontroller:
class adminscontroller extends Controller
{
public function __construct()
{
$this->middleware('auth');
}
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
return view('Admin.AdminPanel');
}
}
Thanks in advance.
Hello friends i am beginner in yii framework and i wanna to create login form with authentication but i have this error:
Fatal error: Call to undefined method User::model() in C:\xampp\htdocs\pro_c\protected\components\UserIdentity.php on line 47
UserIdentity.php
public function authenticate()
{
$users = User::model()->findByAttributes(array('username'=>$this->username));
if(!isset($users[$this->username]))
$this->errorCode=self::ERROR_USERNAME_INVALID;
elseif($users[$this->username]!==$this->password)
$this->errorCode=self::ERROR_PASSWORD_INVALID;
else
$this->errorCode=self::ERROR_NONE;
return !$this->errorCode;
}
}
?>
UserController.php
class UserController extends Controller
{
public function actionIndex()
{
// renders the view file 'protected/views/site/index.php'
// using the default layout 'protected/views/layouts/main.php'
$this->render('index');
}
public function actionLogin()
{
$model=new User;
if(isset($_POST['User']))
{
$model->attributes=$_POST['User'];
// validate user input and redirect to the previous page if valid
if($model->validate() && $model->login())
$this->redirect(Yii::app()->user->returnUrl);
}
// display the login form
$this->render('login',array('model'=>$model));
}
public function actionLogout()
{
Yii::app()->user->logout();
$this->redirect(Yii::app()->homeUrl);
}
}
?>
User.php
/**
* LoginForm class.
* LoginForm is the data structure for keeping
* user login form data. It is used by the 'login' action of 'SiteController'.
*/
class User extends CFormModel
{
public $username;
public $password;
public $rememberMe;
private $_identity;
/**
* Declares the validation rules.
* The rules state that username and password are required,
* and password needs to be authenticated.
*/
public function rules()
{
return array(
// username and password are required
array('username, password', 'required'),
// rememberMe needs to be a boolean
array('rememberMe', 'boolean'),
// password needs to be authenticated
array('password', 'authenticate'),
);
}
/**
* Declares attribute labels.
*/
public function attributeLabels()
{
return array(
'rememberMe'=>'Remember me next time',
);
}
/**
* Authenticates the password.
* This is the 'authenticate' validator as declared in rules().
*/
public function authenticate($attribute,$params)
{
if(!$this->hasErrors())
{
$this->_identity=new UserIdentity($this->username,$this->password);
if(!$this->_identity->authenticate())
$this->addError('password','Incorrect username or password.');
}
}
/**
* Logs in the user using the given username and password in the model.
* #return boolean whether login is successful
*/
public function login()
{
if($this->_identity===null)
{
$this->_identity=new UserIdentity($this->username,$this->password);
$this->_identity->authenticate();
}
if($this->_identity->errorCode===UserIdentity::ERROR_NONE)
{
$duration=$this->rememberMe ? 3600*24*30 : 0; // 30 days
Yii::app()->user->login($this->_identity,$duration);
return true;
}
else
return false;
}
}
?>
when i use this code in UserIdentity
$users=array(
// username => password
'demo'=>'demo',
'admin'=>'admin',
);
return true
but when i using
$users = Pi::model()->findByAttributes(array('username'=>$this->username));
return me this error
Fatal error: Call to undefined method Pi::model() in C:\xampp\htdocs\pro_c\protected\components\UserIdentity.php on line 47
please help me
Well, you have a model called User that is of the type CFormModel (it is a form model). But you are trying to access User::model()->findByAttributes (a database model) that is used for the type CActiveModel. You should rename your class User to something else. Here for example, your User class is called UserIdentity.
http://www.yiiframework.com/doc/guide/1.1/en/topics.auth
You have to make quite a few changes to your code to work. Just see the Yii blog demo to get you to the right track.
Your code looks to be on the right path, but Yii seems to be unable to find the User class.
You could manually import the class, or better still, automatically load this using the 'import' directive in the file protected/config/main.
This tells yii to load all models in protected/models/ directory, assuming that is where the User.php class file resides.
// autoloading model and component classes
'import'=>array(
'application.models.*',
'application.components.*',
),