When the user login, I do the following:
$remember_me = true;
if(Input::has('remember_me')){
$remember_me = true;
}else{
$remember_me = false;
}
if (Auth::attempt(array('username' => Input::get('username'), 'password' => Input::get('password')), $remember_me))
{
echo Auth::user()->picture;exit;
}
return Redirect::back()->withInput()->withErrors(Input::all())->with(array('errorMessage'=>'Username or password is not correct'));
and as you see, I am printing the value of the picture and it is correct. so the user has signed in and I should be able to call him/her like this in another controller
$user = Auth::user();
echo $user->firstName;exit
but I get :
ErrorException
Trying to get property of non-object
I already set the remember me to true. what should I do to be able to use the authenticated user please?
many thanks
You should never exit a function in Laravel.
It is important you always return something.
The reason is Laravel handles some of the final implementation of your functions, set as setting headers, cookies etc. When you exit, you short circuit this process, so Laravel cant finish some of its functions, and therefore you will get errors.
Related
Im trying to log in a system user without sessions or cookies.
The following code in my middelware works unless the user id is from a system user:
$interface_token = $request->header('token');
if ($interface_token !== 'my_secret') {
return response('Unauthorized', 401);
}
$user_id = 1; // Just for testing. Here I want to login a system user.
$success = Auth::onceUsingId($user_id);
if (!$success)
{
throw new Exception('failed!');
}
I want to log in a system user since this specific routes are going to be call from an internal service not from a "real" user.
If I update the table users setting system_user = 0 of user id 1, it works.
If system_user = 1 then it doesn't authenticate.
This system_user column is just a tinyint added to the user's table that shouldn't affect but apparently it does.
The user model is using the SystemUserTrait.
Any ideas?
I'm using Laravel 5.4
Edit
The SystemUserTrait is adding a global scope which does the following:
public function apply(Builder $builder, Model $model)
{
$builder->where('system_user', '=', 0);
}
So that's why it was not working with the user system. But now the question is if is possible to disable this to authenticate the user.
I tried the following without success:
$user = User::withoutGlobalScope(SystemUser::class)->find(1);
$success = Auth::login($user);
The user is fetched but the login fails anyway.
Is there a way to avoid using the global scope for a function?
The solution was to fetch the user with User::withoutGlobalScope and then to use Auth::setUser function to avoid queries which used the scope.
$interface_token = $request->header('token');
if ($interface_token !== 'my_secret') {
return response('Unauthorized', 401);
}
$user = User::withoutGlobalScope(SystemUser::class)->find(1);
Auth::setUser($user);
I wanted to do custom redirect logic upon logging in to my site. So I wrote this code
public function login()
{
$user = //what do I put here?
$this->guard()->login($user);
$id = Auth::id();
//dd($id);
$rfid = DB::table('users')->where('id', $id)->value('reference_id');
if ($rfid == null){
dd($id);
return redirect()->action('RedirectController#client');
}
else {
//dd($rfid);
return redirect()->action('RedirectController#employee');
}
}
However my problem is that all it does is redirect. Which makes sense. The code I have there only manages the redirect, there is nothing there to actually log anyone in. So I did some researching and found
$this->guard()->login($user);
As a way to log the user in. However I don't know what to define the variable $user as. I know this should work because I use it in a different place on my site, but it the $user variable that I use there wouldn't work here. So under the scenario of simply login in the user, what do put there in order to authorize the user as in our database, and then log them in?
If you look at Laravel 5.3 AuthenticatesUsers traits , you will understand how login works behind the scene.
you need to change your login method to use attempt instead of login as follows to work it accordingly.
public function login(Request $request)
{
$user = //what do I put here?
$this->guard()->attempt($this->credentials($request), $request->has('remember'));
$id = Auth::id();
//dd($id);
$rfid = DB::table('users')->where('id', $id)->value('reference_id');
if ($rfid == null){
dd($id);
return redirect()->action('RedirectController#client');
}
else {
//dd($rfid);
return redirect()->action('RedirectController#employee');
}}
I recommend you to use it as I mentioned. If you still want to get $user value you can try out
$user = $this->guard()->user();
Though I haven't used it like that.
I'm new in laravel
I coded a script that many users may work with
but the problem that I have is this :
when a user like "Helen" signs in she can see her profile
but if next another user like "Maria" logs on , Marias panel will be shown for both of them
I think it means just one session can be active at the same time and the value of session will be for the latest user
and the older users session doesn't expire just the value in the session will be changed , thus she identifies as another user and can see that users profile, and also when a user logs out , because of close of the session , all users will be signed out.
here is my simple code :
public function Login(){
$this->Token();
$pack=Input::all();
try {
$result=DB::table('user')->where('Email','=',$pack['email'])->get();
if (Hash::check($pack['password'], $result[0]->Password)){
session(['there' => $result['0']->Email]);
return redirect('dashboard');
}
return redirect('dashboard')->with('does','wrong password');
}catch(Exception $e){
return redirect('dashboard')->with('does',.$e);
}
}
public function UserType() {
if(!session('there'))
return "Not Logged";
else {
$result = DB::table('user')->where('Email', '=', session('there'))->get();
if($result!=null)
return "User";
}
public function ShowDashboard(){
if($this->UserType()=="Not Logged")
else
return view('pages/dashboard');
}
I am not sure why you are session() to manage user logins... Also, they depend a lot on situations where users are login from the same computer, same browser... cookies... etc etc... and maybe that's why you might be getting 2 different session values at the same time...
In any case.. please try and prefer using Laravel's predefined functions of Auth to handle your login/logout procedures.
public function Login()
{
// What does this do? Check for a CSRF token? If yes, then
// please understand then Laravel automatically checks
// for the CSRF token on POST/PUT requests and therefore
// there is no special need to use the below function...
$this->Token();
$pack = request()->only(['email', 'password']);
// I don't really feel try catch is required here... but completely your choice...
try {
if(auth()->attempt($pack)) {
return redirect('dashboard')
}
return redirect->back()->with('does', 'wrong password');
} catch(Exception $e) {
return redirect->back()->with('does', $e);
}
}
public function ShowDashboard()
{
// You can remove this if/else by adding the 'auth' middleware
// to this route
if(!auth()->check())
return view('pages.dashboard');
else
return redirect(route('login'));
}
I found a lot of problems in your above code...
Please use camelCase for naming functions... (I haven't changed the naming in my code above because I don't really know what rules you are following at your workplace or idk...)
Please don't return strings for a simple true/false situation.
Please try and use Models whenever possible. The raw DB commands are required for very complex and extensive queries
I recently built my first web application using laravel and overall it has been great. I have picked up the framework very easily except for this one issue. I am trying to use the framework's built in authentication. I am able to log in my users for a given request but I am trying to implement the remember me functionality by the Auth::attempt() method passing in true as the second parameter as per the documentation.
I have been trying this method for many hours without any luck. I have seen a video at this url (https://www.youtube.com/watch?v=hYUf6u_txhk#aid=P-a-d6RlOC8) which shows which cookie is set when a user is remembered in the application and this cookie is not being set in my browser when I try to remember my user. The cookie is not being set and my users are not being remembered. Here is my code.
if (Auth::attempt(array('email' => Input::get('email'), 'password' => Input::get('password')), true))
{
$userid = DB::table('users')->where('email', '=', $userdata['email'])->pluck('id');
Auth::login(Auth::user());
if (Auth::check())
{
echo "LOGGGEED IN WOOOOOOO";
}
else {
echo "user not logged in";
}
return Redirect::to('/dashboard/' . $userid);
}
Before the redirect happens here is the page I see
Here is the controller that handles the redirect.
class DashboardController extends BaseController
{
public function showDashboard($userid)
{
if (Auth::viaRemember())
{
echo "WOOOOOOOOOOOOOOOO";
}
else {
echo 'booooooo';
}
if (Auth::check())
{
echo 'YAY LOGGED IN';
}
else {
echo 'BOO AGAIN';
}
$user = User::where('id', '=', $userid)->first();
$subscriptions = $user->subscriptions;
$orders = $user->orders;
return View::make('dashboard', compact('user', 'subscriptions', 'orders'));
}
}
But when the redirect happens and /dashboard/{userid} is loaded you can see in the top left hand corner that my echo statements show the user is not being remembered!
I am so frustrated at this point since this is the last step I need to finish my application and I am embarrassed that the laravel documentation says "Laravel aims to make the implementation simple". I have the entire rest of my application working EXCEPT for this part so I would appreciate any and all help with this issue! If you need anymore information please feel free to ask me.Dashboard page
SOLUTION:
In app/config/session.php in the array my 'driver' key had a value of 'file'. After switching this to 'cookie' everything worked as expected.
I am using zend framework. I have built a simple login screen. when the user logs in, I want to set a session and then in the init function of the member area controller its meant to check for the session and grant access, else, redirect to login screen.
I have set my login controller like so, this check the username and password and sets the session:
if (isset($_POST['loginSubmit']) && $form->isValid($_POST)){
$inputtedUsername = $_POST['username'];
$inputtedPassword = $_POST['password'];
if ($inputtedUsername == $username && $inputtedPassword == $password) {
$loggedIn = new Zend_Session_Namespace('loggedIn');
$loggedIn->success;
$this->_forward('index', 'home');
} else {
echo 'invalid';
}
}
I have a home controller, which only logged in users should be able to see, so in the innit function I have:
$loggedIn = new Zend_Session_Namespace('loggedIn');
if (isset($loggedIn->success)) {
echo 'success';
}else{
$url = $this->view->url(array(
'controller' => 'index',
'action' => 'index'));
header('Location:' . $url);
}
}
when i log in, using the correct credentials, it redirects me to login screen as stated in the else function.
what am i doing wrong?
First your use of Zend_Session_Namespace is incomplete (you never assigned a value to the namespace):
$loggedIn = new Zend_Session_Namespace('loggedIn');//here you created a namespace
$loggedIn->success;//here you created a key in that namespace with no value
The way your code seems to be structured any value assigned to $loggedIn->success would return true, so maybe try :
$loggedIn = new Zend_Session_Namespace('loggedIn');//here you created a namespace
$loggedIn->success = true;
While this might fix your current issue, I want to suggest you take a look at two Zend components that can really help with authentication and authorization.
The first is Zend_Auth, a component that deals with application authentication and will also help handle user session persistence. Rob Allen has a tutorial to help get you started.
The second is Zend_Acl, The Access Control List component, deals with authorization, who has access to what. A place to start with Zend_Acl