How to set Yii::app()->user->name - yii

I tried
public function getName()
{
return 'TEST';
}
in UserIdentity.php but it doesn't seem to change the value of Yii::app()->user->name

In the class UserIdentity that you defined you'll need to set a new state by using setState(name, value) method.
For example in the method authenticate if the user is good:
//if the user is good (good login and good password)
$this->_id=$record->id;
$this->setState('name', $record->name);
$this->errorCode=self::ERROR_NONE;
Then you will be able to call Yii::app()->user->name
A complete example in the Yii guide
The setState() documentation

Related

Get authentication data inside of Constructor issue in Laravel5.3.19

I have upgrade Laravel from 4.2 to laravel5.3 but I can't access Authentication data inside of Constructor of Controller
I have as below Middleware but it never work for me
use App\Http\Controllers\BaseController;
use Closure;
use Illuminate\Contracts\Auth\Guard;
use Redirect;
use Auth;
use App\User;
class DashboardController extends BaseController
{
public $user;
public function __construct(Guard $guard, User $user)
{
$this->middleware(function ($request, $next) {
$this->user = Auth::user();
return $next($request);
});
//$this->userID = Auth::user()?Auth::user()->id:null;
dd($user);// Result attributes: []
dd($guard);
dd($this->user);
}
}
The result after DD()
dd($guard);
DD($this->user);
NULL
It will return Null when I dd user property.
This is to be expected. The reason you have to assign the user inside the middleware closure is because the session middleware hasn't run yet. So, the closure you have above won't actually be called until later in the execution process.
If you move the dd($this->user) to inside the middleware closure or in to your one of you route methods in that controller it should be working absolutely fine.
Also, just FYI, in your middleware closure you can get the user instance from the request i.e. $request->user() will give you the authenticated user.
Hope this help!

Overriding Login Error Messages

I have an AuthController, where I have extended the getCredentials method so the user needs to be both existant and active to be able to login. This is the method:
protected function getCredentials(Request $request) {
$credentials = $request->only($this->loginUsername(), 'password');
return array_add($credentials, 'status', '1');
}
I would also like the failed login messages to be different, depending on whether or not the user is active, so the user knows if he is failing his username / password, or just because he hasn't activated his account yet.
I could override the login method of the AuthenticatesUser trait, but it seems overkill to duplicate all the logic just to change that.
Can I extend the sendFailedLoginResponse method to make some sort of validation there, based on the previous Auth::guard->attempt() call? I mean, does that method leave any information behind that allows me to know, after the call has been made, what made the attempt return false?
Or how would I approach this, without having to override a method completely just to make a simple validation?
Thank you.
public function authenticated(Request $request, User $user ) {
// The user was authenticated check if it the active column is true or not
if($user->active == false){
//Store some flash message here saying he's not account is not active
//Log him out after.
Auth::logout();
}
return redirect()->intended( $this->redirectPath() );
}

Laravel 5.2 : Login "attempt" Event Handling

In Laravel 5.2, i need to do something while the authentication process is being triggered. (Not "after" the login.)
Here are what i have done.
In EventServiceProvider.php:
protected $listen = [
'Illuminate\Auth\Events\Attempting' => ['App\Listeners\UserLoginAttempt#handle'],
];
In app/Listeners/UserLoginAttempt.php:
<?php
namespace App\Listeners;
use Illuminate\Http\Request;
use Illuminate\Auth\Events\Login;
use Carbon\Carbon;
use Auth;
class UserLoginAttempt
{
public function __construct()
{
}
public function handle($event)
{
dd(Auth::user());
exit;
}
}
This always returns null.
** In fact, i have one "custom" field in the Login form, of which i need to capture from the above Event Handler. (I need to check something before actual Login event is done.)
How do i capture the Auth::user() from this (Illuminate\Auth\Events\Attempting) Handler please?
(In other words) How do i talk with the Login Form from the (Illuminate\Auth\Events\Attempting) Handler?
OR ----- Is the Auth::user() object created ONLY AFTER the login is fully processed? Which means i can not get it while in "attempting" stage?
Because i need to capture the login elements first, and if it is something "unauthorized" (after some calculations done in Handler), then i need to terminate the login attempt and route back to the login form from here.. by carrying the Failing Message along.
Please let me know what i'm missing here. Thank you.
According to documentation you are right that Auth::user() object is only created when user is authenticated.
Inside the Illuminate\Auth\Events\Attempting listener;
you can capture the form field by
public function handle(Attempting $event)
{
//return dd($event); // will echo all fields
$event->credentials['email']; // capturing the email field
}
you can also use the User model and then access the user table in DB, to get / check a user field in DB...

LARAVEL 5: Need to keep query string after auth redirects

I have a link I am sending via email. For example, www.swings.com/worker?id=3382&tok=jfli3uf
In this case I want the person to click the link, get sent to the login page(which it does) and then be directed to a controller method WITH the $id and $tok variables. I can't get that part to work. Any ideas? I am only using the RedirectIfAuthenticated class and this is what it looks like:
public function handle($request, Closure $next)
{
$user = $request->user();
if ($this->auth->check()) {
if($user && $user->hasRole('worker'))
{
return redirect('worker');
}
return redirect('home');
}
return $next($request);
}
hasRole is a method I created in the User model that checks the role of the logged in user
You can flash data to the session when redirecting by chaining the with() method:
// in your handle() method:
return redirect('home')->with($request->only('id', 'tok'));
// then in home controller method:
$id = session('id');
$tok = session('tok');
AFTER SOME HOURS I WAS ABLE TO HAVE A SOLUTION:
ReturnIfAuthenticated wasn't changed. I just added the following within my controller that this link should go to:
for instance, the route would be:
Route::get('worker', 'WorkerController#methodINeed');
Within this method:
public function methodINeed() {
$id = Input::get('id');
$tok = Input::get('tok');
// Do what I need this variables to do
}
What I didn't understand and what could not be properly understood is that the auth controller in Laravel 5 is triggered when a user is a guest it will still redirect to the actual method with all its original data once auth is successful. Hope this is helpful.

ExtendedMembershipProvider and WebSecutiry.Login, where does persistCookie go?

Ok, so I have implemented a custom ExtendedMembershipProvider for use with an MVC4 application, all of this is wired up and working ok however I have been having an issue with the forms authentication cookie.
I am creating my own cookie which is fine when calling my login process directly however if I use the WebSecurity.Login function I can't seem to control the cookie myself.
So this leads me to my question, WebSecurity.Login takes three parameters (one of which is optional):
public static bool Login(
string userName,
string password,
bool persistCookie (optional)
)
Now this function invokes the ValidateUser function on the ExtendedMembershipProvider which only takes two parameters:
public abstract bool ValidateUser(
string username,
string password
)
Where does the persistCookie parameter go? Does WebSecurity.Login handle the cookie generation itself and if so how can I override this?
Any help is much appreciated guys!!
WebSecurity.Login probably executes following code:
static bool Login(string userName, string password, bool persistCookie)
{
if(System.Web.Security.Membership.Provider.ValidateUser(userName, password))
{
System.Web.Security.FormsAuthentication.SetAuthCookie(userName, persistCookie);
return true;
}
return false;
}
If you want to change behavior, change this snippet in accordance with the guidelines from following answer.