Where am I going wrong when creating authentication in Laravel? - php

PHP 7.4
Laravel 8
Route 1 (super.com/auth):
Receives email, password data and makes authentication.
$result = Auth::Attempt(['password' => 'superpwd', 'email' => 'super#mail.ru'], true);
Auth::check() // true
Route 2 (super.com/testAuthCheck):
We check the authentication.
Auth::check(); // false
It turns out that the authentication is not saved in the session.
Please tell me where I'm wrong? May be session or some setting, or modules...
Full code:
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Hash;
class AuthUser extends Controller
{
public function register(Request $request)
{
$request->validate([
'name' => 'required|string',
'lastname' => 'required|string',
'secondname' => 'required|string',
'tel' => 'required|numeric',
'password' => 'required|string',
]);
$user = User::create([
'name' => $request->name,
'lastname' => $request->lastname,
'secondname' => $request->secondname,
'tel' => $request->tel,
'password' => Hash::make($request->password),
'email' => '',
]);
$login = Auth::login($user);
return response()->json([
'message' => 'Success!',
'login' => $login
]);
}
public function test(Request $request) {
if(Auth::Attempt(['password' => 111, 'email' => 'a#b.ru'], true)) {
$request->session()->regenerate();
$result = Auth::check();
dump($result); // true
}
}
public function test2(Request $request) {
$result = Auth::check();
dump($result); // false
}

Using dump will most likely cause more problems while debugging this.
public function test(Request $request) {
if(Auth::Attempt(['password' => 111, 'email' => 'a#b.ru'], true)) {
$request->session()->regenerate();
$result = Auth::check();
//dump($result); ***will terminate the request and the session will not be set correctly ***
info($result); // check storage/logs/laravel.log
}
}

Related

Postman failing to send json to PHP api

public function register(Request $request) {
// $user = User::create([
// 'name' => $request->input('name'),
// 'email' => $request->input('email'),
// 'password' => Hash::make($request->input('password'))
// ]);
//
// return $user;
return "test";
}
Hi all,
basically, I'm trying to build a restful API with Laravel and my API is being hit by Postman, but when I send a JSON body my $request is an empty array.
It's the first time I'm touching Laravel so it's probably something obvious so thank you in advance !
Try this one
use Exception;
public function register(Request $request) {
try {
$user = User::create([
'name' => $request->input('name'),
'email' => $request->input('email'),
'password' => Hash::make($request->input('password'))
]);
return response()->json(['status' => true, 'message' => 'You have been register successfully', 'data' => $user]);
} catch (Exception $e) {
return response()->json(['status' => false, 'message' => $e->getMessage(), 'data' => []]);
}
}

Laravel won't send response after a successful create of an account

I can save the data to the database just fine. And then I right after the creation I'll login that current user with the email. But it will always be sending a request. What might be the problem here?
class RegisterController extends Controller
{
use AuthenticatesUsers;
protected $redirectTo = '/home';
private $loginProxy;
public function __construct(LoginProxy $loginProxy)
{
$this->loginProxy = $loginProxy;
$this->middleware('guest')->except('logout');
}
function apiRegisterUser(Request $request)
{
$validator = Validator::make($request->all(), [
'name' => 'string|max:255',
'email' => 'required|string|email|max:255|unique:users',
'password' => 'required|string|min:6',
]);
if ($validator->fails()) {
return response()->json(array('code' => 406, 'error' => $validator->messages()), 406);
} else {
// Log::channel('abuse')->info('user');
$user = User::create(['name' => $request['name'],
'email' => $request['email'],
'password' => Hash::make($request['password']),
'referral_code' => str_random(10)
]);
$user->updateLastRoute(1);
$credentials = $this->loginProxy->attemptLogin($request['email'], $request['password']);
return response()->json($this->successResponse(200, "Login successfull", $credentials), 200);
}
}
protected function validator(array $data)
{
return Validator::make($data, [
'name' => 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:users',
'password' => 'required|string|min:6|confirmed',
]);
}
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
]);
}
}
use auth()->attempt() function i m not sure about loginProxy
but auth()->attempt() this should work
$credentials = [
"email" => $request['email'],
"password" => $request['password']
];
if (auth()->attempt($credentials)) {
return response()->json($this->successResponse(200, "Login successfull", $credentials), 200);
}

Laravel 5 Update Validation email needs to be unique

I'm trying to update a user, as an admin.
I'm changing the username, but it says email must be unique.
How do I fix this.
public function update($id, PutUser $request)
{
if (auth()->id() == $id) {
return redirect()->back()->withFlashDanger('Permission Denied, You can not edit own profile here.');
}
$user = User::find($id);
$user->update((array_merge($request->validated(), ['county' => request('county')])));
//Update model_has_roles model with assignees_roles
return redirect()->route('users.index')->withFlashSuccess(trans("alerts.users.updated"));
}
This is the request class
public function authorize()
{
return true;
}
public function rules()
{
$user_id = $this->input('id');
return [
'name' => 'required|string',
'username' => 'required',
'email' => 'required|email|unique:users,email'.$user_id,
'gender' => 'required',
'phone' => 'sometimes|numeric',
'address' => 'sometimes|string',
'country_id' => 'required',
];
}
}
I keep getting a failed email validation. 'Email has already been taken'. Any idea
You are missing a comma after the email label in your validation:
return [
'name' => 'required|string',
'username' => 'required',
'email' => 'required|email|unique:users,email,'.$user_id,
'gender' => 'required',
'phone' => 'sometimes|numeric',
'address' => 'sometimes|string',
'country_id' => 'required',
];
Since Laravel 5.3 (I believe), you can also use rule builders for more descriptive validation rules. Those are better to read and interpret for humans so it would result in a lower error rate:
use Illuminate\Validation\Rule;
return [
'email' => [
'required',
Rule::unique('users', 'email')->except($user_id),
]
];
https://medium.com/#tomgrohl/why-you-should-be-using-rule-objects-in-laravel-5-5-c2505e729b40

Call to undefined method Query\Builder

I have a protected function that I want to use to check my login validation. However I am getting the error
Call to undefined method Illuminate\Database\Query\Builder::loginValidation
Do I have to write a model for my function?
Login Validation:
protected function loginValidation($data)
{
$rules = array(
'fname' => 'required|max:255',
'lname' => 'required|max:255',
'email' => 'required|email|max:255|unique:users',
'password' => 'required|min:6|confirmed',
);
return Validator::make($data, $rules);
}
getLoginCredentials
protected function getLoginCredentials(Request $request)
{
$validator = User::loginValidation(Request::all());
if($validator->passes())
{
return[
'email' => Request::input('email'),
'password' => Request::input('password'),
'type' => 1
];
return true;
}else{
return redirect()->back()->withErrors();
}
}
I guess the user model can not see your function. Do composer dump-autoload to see if the changes will reflect. if it does not try a new name and see if it will work.

Auth::attempt fails with PHPUnit TESTING

I have a really strange behavior and I do not see where it could come from. I built an authentication system with Laravel documentation. When I save a User and try to login from the application, it works fine. However when I do the same thing in my AuthControllerTest, the Auth::attempt fails.
AuthControllerTest.php
<?php
use tests\helpers\Factory;
class AuthControllerTest extends ApiTester
{
use Factory;
public function setUp()
{
parent::setUp();
Artisan::call('migrate');
Route::enableFilters();
Session::start();
}
/*
This test fails
I have a 401 instead of a 200 HTTP response code
*/
/** #test */
public function it_should_log_in_user()
{
User::create([
'email' => 'testing#testing.com',
'password' => 'testing'
]);
$credentials = [
'email' => 'testing#testing.com',
'password' => 'testing'
];
//dd(User::count() // I have 1 record
$this->getJson('login', 'POST', $credentials);
$this->assertResponseOk();
}
/** #test */
public function it_should_throws_exception_if_login_fails()
{
User::create([
'email' => 'testing#testing.com',
'password' => 'testing'
]);
$this->getJson('login', 'POST', [
'email' => 'testing#testing.com',
'password' => 'test'
]);
$this->assertResponseStatus(401);
}
/** #test */
public function it_should_log_out_user()
{
$user = User::create([
'email' => 'testing#testing.com',
'password' => 'password'
]);
$this->be($user);
$this->getJson('logout', 'POST');
$this->assertResponseStatus(204);
}
/**
* Generate Alert mock
* #return array
*/
protected function getStub()
{
return [
];
}
}
AuthController.php
<?php
use Arato\Transformers\UserTransformer;
use controllers\ApiController;
class AuthController extends ApiController
{
protected $userTransformer;
function __construct(UserTransformer $userTransformer)
{
$this->userTransformer = $userTransformer;
}
public function login()
{
$rules = [
'email' => ['required', 'email'],
'password' => ['required', 'alphaNum']
];
$validator = Validator::make(Input::all(), $rules);
if ($validator->fails()) {
return $this->respondUnauthorized();
}
$userData = [
'email' => Input::get('email'),
'password' => Input::get('password')
];
if (Auth::attempt($userData)) {
return $this->respond([
'data' => $this->userTransformer->transform(Auth::user())
]);
} else {
return $this->respondUnauthorized();
}
}
public function logout()
{
Auth::logout();
return $this->respondNoContent();
}
}
Thank you
Remember that the password is encrypted, so you need to get the password directly from the User instance, like:
$user = User::create([
'email' => 'testing#testing.com',
'password' => Hash::make('testing')
]);
$credentials = [
'email' => $user->email
'password' => $user->password
];

Categories