Laravel Read User id in Controller constructor - authentication

In my controller(s), instead of fetchingAuth::id() in each method, I've set up an $id property in the controller's class and fetched it once in the constructor. then, in the rest of the methods i'm just refering $this->id, is it considered safe or am I doing something wrong?
Code Sample: http://pastebin.com/pvju54eh

What you could do is inject the Guard instance in your controller and then assign the currently logged in user (if there is one) to a class property:
<?php namespace App\Http\Controllers;
use Illuminate\Contracts\Auth\Guard;
class SomeController extends Controller
{
protected $auth;
protected $user;
public function __construct(Guard $auth)
{
$this->auth = $auth;
$this->user = $this->auth->user();
}
public function someMethod()
{
// Get logged in user’s ID
$userId = $this->user->id;
}
}

I do not see any major problems with this approach even though I have not seen approach used often.
Myself I find it easier to get the $request->user() in controller from Request though.

Related

Set & Get session variable value

I am setting session variable in function of a controller like below.
use Illuminate\Support\Facades\Session;
class UserController extends Controller
{
public function store(Request $request)
{
session(['user_name' => $user_name]);
}
}
I am trying to access that session variable in another function of another controller.
use Illuminate\Support\Facades\Session;
class DashboardController extends Controller
{
public function __construct()
{
dd(session('user_name')); // I am not getting value here
}
}
I am not getting value from Session Variable.
You can do it like this
use Illuminate\Support\Facades\Session;
class UserController extends Controller
{
public function store(Request $request)
{
session()->put('user_name', $user_name);
}
}
And you can get it another controller or anywhere like this
session()->get('user_name');
Hope this will help you, thanks..

ASP.NET MVC 4 Custom Authorize filter on Controller class and Method

I did see this stackoverflowQuestion but this revolves around using the, Authorize attribute. I am using a custom authorize attribute, by extending AuthorizeAttribute.
I want to be able to place this custom filter at the top level of the controller class, but for a couple of methods enforce only a specific role, not both the top level and action method role.
so,
[AuthorizeUser("Transact")]
public class HomeController : Controller
{
//
// GET: /Search/Home/
public ActionResult Index()
{
return View();
}
[AuthorizeUser("Search")]
public ActionResult Search()
{
return View();
}
}
Doing this, the framework will check to see if a user has both the Transact, and Search role.. I just want to check for the search role in this scenario.
I am reusing this search functionality and partialview in another Area.
Going back to the link I posted: stackoverflowQuestion I was able to make it work in my situation. What seems to be happening is the call to my action first looks at the attribute from the Controller level, but using filterContext.ActionDescriptor.IsDefined inside the OnAuthroization method will tell me if the called action has my override attribute attached. If it does it skips calling the base.OnAuthorization method, then the override attribute will be invoked.
So, what I had to do was create the override class and extend my custom authorization class. I have a flag declared in the parent and set in the override class's constructor to tell me if the override authorization method is calling the authorization methods of my custom authorization class.
Here is the example to make sense of it all.
public class AuthorizeUserAttribute : AuthorizeAttribute
{
protected bool isOverrideAuthorize = false;
public AuthorizeUserAttribute(params...)
{
}
public AuthorizeUserAttribute(MenuItems...)
{
}
public override void OnAuthorization(AuthorizationContext filterContext)
{
var action = filterContext.ActionDescriptor;
if (action.IsDefined(typeof(OverrideAuthorizeUserAttribute), true) && !isOverrideAuthorize)
{
return;
}
base.OnAuthorization(filterContext);
}
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
}
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
}
}
The override class:
public class OverrideAuthorizeUserAttribute : AuthorizeUserAttribute
{
public OverrideAuthorizeUserAttribute(params...) : base(roles)
{
base.isOverrideAuthorize = true;
}
public OverrideAuthorizeUserAttribute(MenuItems...) : base(item)
{
base.isOverrideAuthorize = true;
}
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
return base.AuthorizeCore(httpContext);
}
}
This allowed me to do authorization on the action solely on the authorization attribute declared on that action, rather than the authorization attribute on the controller AND action method, as defaulted by the framework.
Also, MVC5 seems to have this problem covered by including a, "OverrideAuthorization" attribute.. Unfortunately I am still on MVC4.
You can try at the top of controller like bellow this will support multiple role for single controller or you can use same Authorize(Roles = "Admin") filter top of every action....
[Authorize(Roles = "Admin,HRManager,Finance")]
Public class MyController:Controller{
// inside controller action methods
}

Laravel 5: How to add Auth::user()->id through the constructor ?

I can get the ID of the authenticated user like this:
Auth::user()->id = $id;
Great it works, ... but I have a load of methods which need it and I want a cleaner way of adding it to the class as a whole,so I can just reference the $id in each method. I was thinking of putting it into the constructor, but as Auth::user is a static, I am making a mess of things and don't know how to do it.
Many thanks for your help !
Laravel >= 5.3
you can't access the session or authenticated user in your controller's constructor because the middleware has not run yet.
As an alternative, you may define a Closure based middleware directly in your controller's constructor. Before using this feature, make sure that your application is running Laravel 5.3.4 or above:
class UserController extends Controller {
protected $userId;
public function __construct() {
$this->middleware(function (Request $request, $next) {
if (!\Auth::check()) {
return redirect('/login');
}
$this->userId = \Auth::id(); // you can access user id here
return $next($request);
});
}
}
Instead of using the Facade you can inject the contract for the authentication class and then set the user ID on your controller. Like #rotvulpix showed you could put this on your base controller so that all child controllers have access to the user ID too.
<?php
namespace App\Http\Controllers;
use Illuminate\Contracts\Auth\Guard;
class FooController extends Controller
{
/**
* The authenticated user ID.
*
* #var int
*/
protected $userId;
/**
* Construct the controller.
*
* #param \Illuminate\Contracts\Auth\Guard $auth
* #return void
*/
public function __construct(Guard $auth)
{
$this->userId = $auth->id();
}
}
The guard has an id() method which returns void if no user is logged in, which is a little easier than having to go through user()->id.
You can use Auth::user() in the whole application. It doesn't matter where you are. But, in response to your question, you can use the 'Controller' class present in your controllers folder. Add a constructor there and make the reference to the user ID.
<?php namespace App\Http\Controllers;
use Illuminate\Foundation\Bus\DispatchesCommands;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests;
/* Don't forget to add the reference to Auth */
use Auth;
abstract class Controller extends BaseController {
use DispatchesCommands, ValidatesRequests;
function __construct() {
$this->userID = Auth::user()?Auth::user()->id:null;
}
}
Then, in any method of any controller you can use the $this->userID variable.

User scope with Zend Framework

I'm switching a Zend Framework application from mono-user to multi-user.
What is the best approach to include the user scope in the controllers ?
One way would be to add the user id in each methods in every controllers:
/application/controllers/IndexController.php
...
public function indexAction() {
$params['user_id'] = Zend_Auth::getInstance()->getIdentity()->id;
$listHelper->readItems($params);
}
...
An other one would be to create a new User model and fetch his items :
/application/controllers/IndexController.php
...
public function indexAction() {
$userModel = new application_models_user();
$userModel->find(Zend_Auth::getInstance()->getIdentity()->id);
$userModel->readItems();
}
...
I'm wondering what's the best approach that would allow me to write minimal code and if you have another idea to "automagically" add the user scope (db scope, plugin...).
Create an abstract class by extending Zend_Controller_Action
abstract class My_Controller_Action extends Zend_Controller_Action {
private $userModel;
public function getUserModel() {
if(is_null($this->userModel)) $this->userModel = new application_models_user();
return $this->userModel;
}
public function getUserId() {
return $this->getUserModel()->find(Zend_Auth::getInstance()->getIdentity()->id);
}
}
Now use this class as base class for your controllers.

yii - variable available to each controller

I am new to yii.
I am using more than 1 controller in my website and each controller has few actions.
I want to use some variables across each controller (Value of variable will be fixed, I need some constants for a formula). Whats the best place (standard way) to define those variables ?
Should I use session ? (as value is not going to change).
Not sure what you are using your vars for, but you can do it by defining them in your config main.php
'params'=>array(
'someVar1'=>'varValue1',
'someVar2' => 'varValue2',
),
Then you can access them in ANYWHERE by calling
Yii::app()->params['someVar1']
They will be available anywhere in your application.
Or you can extend all your controllers off of a base class and define your constants there
Base Controller:
class Controller extends CController {
const SOME_VAR = 'someValue';
}
Your controller:
class YourController1 extends Controller
{
public function actionIndex()
{
echo parent::SOME_VAR;
}
}
Your other controller:
class YourController2 extends Controller
{
public function actionLogin()
{
echo parent::SOME_VAR;
}
}