test if user is logged in laravel 5.7 - php

I am making a test but it fails when it tries to check if a user is logged in:
<?php
namespace Tests\Feature;
use Tests\TestCase;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Auth;
use App\User;
class RegisterTest extends TestCase
{
use RefreshDatabase;
/*.....
more test about registering
....*/
/** #test */
function redirect_to_home_page_and_logged_in_after_login()
{
$user = factory(User::class)->create([
'name' => 'Test',
'email' => 'test#hotmail.com',
'password' => '123456'
]);
$response = $this->post('login', [
'email' => 'test#hotmail.com',
'password' => '123456'
]);
//this works
$response->assertRedirect('/');
//this fails
$this->assertTrue(Auth::check());
}
}
And this is my controller HomeController:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class HomeController extends Controller
{
public function index()
{
if (Auth::check()){
return view('home');
}
return view('welcome');
}
}
And this is my routes/web.php
Route::get('/', 'HomeController#index');
Auth::routes();
I am not sure what I am doing wrong. What can I do?. I am using laravel 5.7 and phpunit 5.7.1
Also in my app/Htpp/Auth/LoginController.php I did this:
protected $redirectTo = '/';
Thank you.

In addition to hashing your password you could also just post to the register route and create a new account.
/** #test */
function redirect_to_home_page_and_logged_in_after_register()
{
$response = $this->post('register', [
'name' => 'Test',
'email' => 'test#hotmail.com',
'password' => '123456'
]);
//this works
$response->assertRedirect('/');
//this fails
$this->assertTrue(Auth::check());
}
I guess you may also have a requirement to do it both ways:
/** #test */
function redirect_to_home_page_and_logged_in_after_login()
{
$user = factory(User::class)->create([
'name' => 'Test',
'email' => 'test#hotmail.com',
// note you need to use the bcrypt function here to hash your password
'password' => bcrypt('123456')
]);
$response = $this->post('login', [
'name' => 'Test',
'email' => 'test#hotmail.com',
'password' => '123456'
]);
//this works
$response->assertRedirect('/');
//this fails
$this->assertTrue(Auth::check());
}

Creating a user requires you to take care of the hashing of the password.
You can simply do it by using php's password_hash function. And use Auth::login($user); to login.
Like so:
$user = User::create(['email' => 'r#o.b', 'password' => password_hash('123456', 1)]);
Auth::login($user); //You should be logged in :)

Related

Why Method App\Http\Controllers\RegisterController::guard does not exist and MemberExtra table not fill with data in laravel

thanks for helping
I have some error when insert data i nto database, that is guard does not exit when I try to register by using this controller
namespace App\Http\Controllers;
use App\Models\MemberExtra;
use App\Models\User;
use App\Http\Controllers\Controller;
use Carbon\Carbon;
use Illuminate\Support\Facades\Validator;
use Illuminate\Foundation\Auth\RegistersUsers;
use Illuminate\Http\Request;
use Illuminate\Auth\Events\Registered;
class RegisterController extends Controller
{
public function __construct()
{
$this->middleware('guest');
}
public function index(){
return view('users.register');
}
protected function validator(array $data)
{
return Validator::make($data, [
'email' => 'required|string|email|max:255|unique:users',
'password' => 'required|string|min:6',
'referrer_id' => 'required',
'position' => 'required',
'username' => 'required',
]);
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return \App\User
*/
protected function create(array $data)
{
$ref_id = $data['referrer_id'];
$poss = $data['position'];
$posid = getLastChildOfLR($ref_id,$poss);
return User::create([
'email' => $data['email'],
'password' => bcrypt($data['password']),
'referrer_id' => $data['referrer_id'],
'position' => $data['position'],
'username' => $data['username'],
'join_date' => Carbon::today(),
'posid' => $posid
]);
}
public function register(Request $request)
{
$this->validator($request->all())->validate();
event(new Registered($user = $this->create($request->all())));
$this->guard()->login($user);
MemberExtra::create([
'user_id' => $user['id'],
'left_paid' => 0,
'right_paid' => 0,
'left_free' => 0,
'right_free' => 0,
'left_bv' => 0,
'right_bv' => 0,
]);
updateMemberBelow($user['id'], 'FREE');
return $this->registered($request, $user) ?: redirect()->route('home');
}
}
when register , show this error
and I refresh the page , user data is inserted into database but MemberExtra data still not insert
And this guard does not exist error happen again and again whenever register.
How can fix this error
Can someone help me
In your controller I didn't see the RegistersUsers trait which have guard function.
You have missed to write below in your controller. By default this function exist in RegistersUsers this trait
/**
* Get the guard to be used during registration.
*
* #return \Illuminate\Contracts\Auth\StatefulGuard
*/
protected function guard()
{
return Auth::guard('your guard name');
}

Auth::attempt always return false even with proper input

Here are the facades I used
namespace App\Http\Controllers;
use App\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
I've successfully created user signup page with hashed password using bcrypt.
//Get singnup view
public function getSignup()
{
return view('user.signup');
}
//Process signup
public function postSignup(Request $request)
{
$this->validate($request, [
'email' => 'email|required|unique:users',
'password' => 'required|min:4'
]);
$user = new User([
'email' => $request->input('email'),
'password' => bcrypt($request->input('password')),
]);
$user->save();
return redirect()->route('product.index');
}
And now I'm stuck at the signin page. The Auth::attempt always return false. I even tried to store a plain password in my database and signin without bcrypt but it still returned false. I have no idea where I'm wrong right now.
//Get signin view
public function getSignin()
{
return view('user.signin');
}
//Process signin
public function postSignin(Request $request)
{
$this->validate($request, [
'email' => 'email|required',
'password' => 'required|min:4'
]);
$credentials = array(
'email' => $request->input('email'),
'password' => bcrypt($request->input('password'))
);
if(Auth::attempt($credentials))
{
return redirect()->route('user.profile');
}
return redirect()->route('product.index');
}
You don't need bcrypt() in Auth::attempt(). Remove it and try again.
In config\auth, change guard driver setting is set to api.
'defaults' => [
'guards' => 'api',
'passwords' => 'users'
]
But Laravel doesn't support attempt() function with guard api. Thus, you should use some packages like Passport (You can reference here)
Or simplier, just configure you guard driver with Auth::guard('api')->attempt($credentials)
Hope this solve your problem.

Laravel - Auth, route is not logged

I've a problem when route call a method of Controller after login successfull.
In the new method user seems to be not logged.
I can't understand why.
Steps are: Log-in with
Route::post('login', 'UserController#login')->name('login');
and than check if user is logged with:
Route::get('check-login', 'UserController#checklogged');
Controller is this one:
<?php
namespace App\Http\Controllers;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Faker\Generator as Faker;
class UserController extends Controller
{
// regole per FormValidator
protected $rulesLogin = [
'email' => 'bail|required|email',
'password' => 'required',
];
// Effettuo il login
/**
* Method: POST
* #Parameters: email, password
* return: Authenticated User.
*/
public function login(Request $request)
{
//dd($request->all());
$validator = Validator::make($request->all(),$this->rulesLogin);
// login fallito
if ($validator->failed()) {
return response([
'status' => 'ko',
'message' => $validator->errors()->first(),
], 422);
}
// login errato
if (!Auth::attempt([
'email' => $request->email,
'password' => $request->password,
'status' => ['active'],
])) {
return response(
[
'status' => 'ko',
'message' => 'Invalid email or password',
], 422);
}
return (Auth::user());
}
public function checklogged()
{
return dd(Auth::id());
}
checklogged() return always false. I expect it return a user logged Id
I think the problem is u havent used web midlleware in route.If you are following HMVC pattern make sure to use web middleware like this.
Route::group([
'middleware' => ['web'],
], function () {
});
or please check your RouteServiceProvider.php file weather it has web middleware in mapWebRoutes() function
protected function mapWebRoutes()
{
Route::middleware('web')
->namespace($this->namespace)
->group(base_path('routes/web.php'));
}
problem was middleware as guest.
Route::post('login', 'UserController#login')->name('login')->middleware('guest');
Try this sintaxe:
public function checklogged()
{
return dd(Auth::user()->id);
}

No hashing on Password field in Laravel seeder

I've recently inherited a project from a Laravel developer to look at. Unfortunately, when I migrate and seed the user table, the password ciphering is not working, as follows:
public function run()
{
DB::table('users')->insert([
'email' => 'admin#site.co.uk',
'first_name' => 'Site',
'last_name' => 'Admin',
'username' => 'admin',
'password' => 'localhostPassword'
]);
}
When I run php artisan migrate --seed the password field is the string literal as above, and when I try to sign in it tells me that my password credentials are incorrect.
As I'm not an Artisan Laravel developer I'm not sure where to start, but I'm expecting the password field to be hashed like this $2y$10$u/FcKFPKsgRs8whJZ6ODAO90qllmGjqROnkmuQnxcpynG6WaIbX8e, which is what is generated when I use the register form in the current code base.
You need to hash it before storing it:
use Illuminate\Support\Facades\Hash; // <-- import it at the top
//
public function run()
{
DB::table('users')->insert([
'email' => 'admin#site.co.uk',
'first_name' => 'Site',
'last_name' => 'Admin',
'username' => 'admin',
'password' => Hash::make('localhostPassword') // <---- check this
]);
}
Note: An alternative is to use the bcrypt() helper instead of the Hash::make() method.
Chech the documentation regarding this aspect:
Basic Usage
You may hash a password by calling the make method on the Hash
facade:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use App\Http\Controllers\Controller;
class UpdatePasswordController extends Controller
{
/**
* Update the password for the user.
*
* #param Request $request
* #return Response
*/
public function update(Request $request)
{
// Validate the new password length...
$request->user()->fill([
'password' => Hash::make($request->newPassword)
])->save();
}
}
You have to manually bcrypt the password like below
public function run()
{
DB::table('users')->insert([
'email' => 'admin#site.co.uk',
'first_name' => 'Site',
'last_name' => 'Admin',
'username' => 'admin',
'password' => bcrypt('localhostPassword')
]);
}

Login Fail in laravel 5.2 using AuthenticatesUsers trait

I'm using the AuthenticatesUsers trait to handle logins in my web site.
When I register a new user on the site it can login and logout successfully, but when I login through the login form it fails every time even though I'm providing the right data. I don't understand why this is happening. What did I do wrong? Here is my auth controller.
<?php
namespace App\Http\Controllers\Auth;
use App\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Validator;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ThrottlesLogins;
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;
class AuthController extends Controller
{
use AuthenticatesAndRegistersUsers, ThrottlesLogins;
protected $redirectTo = '/home';
protected $guard = 'user';
public function __construct()
{
$this->middleware($this->guestMiddleware(), ['except' => 'logout']);
}
protected function validator(array $data)
{
return Validator::make($data, [
'email' => 'required|email|max:255|unique:users',
'password' => 'required|min:6|confirmed',
]);
}
protected function create(array $data)
{
return User::create([
'first_name' => $data['firstName'],
'last_name' => $data['lastName'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
]);
}
}
Route.php
<?php
Route::group(['middleware' => ['web']], function () {
// Your route here
// // Authentication routes...
Route::get('customer/login', 'Customer\Auth\AuthController#getLogin');
Route::post('customer/login', 'Customer\Auth\AuthController#postLogin');
Route::get('customer/logout', 'Customer\Auth\AuthController#getLogout');
//
// // Registration routes...
Route::get('customer/register', 'Customer\Auth\AuthController#getRegister');
Route::post('customer/register', 'Customer\Auth\AuthController#postRegister');
Route::auth();
Route::get('/home', function (){
return view('welcome');
});
});
Route::get('/home', 'HomeController#index');

Categories