I have following the official guide to upgrade from laravel 5.2 to laravel 5.3:
https://laravel.com/docs/5.3/upgrade#upgrade-5.3.0
Because I needed some customizations to the default authentication I have copied the login function to Http\Controllers\Auth\AuthController.php.
Now, when I updated, the `AuthController.php' was divided into several other files.
I have copied the login function to Http\Controllers\Auth\LoginController.php
Now, I am getting the following error when trying to login:
BadMethodCallException in Controller.php line 82:
Method [getCredentials] does not exist.
The login functions below (Might not matter):
public function login(Request $request)
{
$this->validate($request, [
'email' => 'required|email',
'password' => 'required',
]);
$credentials = $this->getCredentials($request);
// This section is the only change
if (Auth::validate($credentials)) {
$user = Auth::getLastAttempted();
if ($user->active) {
Auth::login($user, $request->has('remember'));
ActivityLog::add("User has successfully logged in.", $user->id);
return redirect()->intended($this->redirectPath());
} else {
return redirect($this->loginPath) // Change this to redirect elsewhere
->withInput($request->only('email', 'remember'))
->withErrors([
'active' => 'This account has been suspended.'
]);
}
}
return redirect($this->loginPath)
->withInput($request->only('email', 'remember'))
->withErrors([
'email' => $this->getFailedLoginMessage(),
]);
}
How do I fix this?
This method simply returns the login username (which can be username, email or custom field) and the password from the request data. You can replace the getCredentials() call with this:
$request->only($this->username(), 'password');
NOTE
depending on how you merged the code, the method $this->username() can be also used as $this->loginUsername() in the older version.
Anyone else looking here now the call getCredentials(Response $response) was replaced in 5.3 with credentials(Response $response)
Related
I have created a REST API with LARAVEL SANCTUM. I have tested api on postman and it works as expected but when mobile developer uses it on ionic app, it returns for login "TOKEN MISMATCH".
Here is my API route
Route::post('/register', [ApiController::class, 'register']);
Route::post('/login', [ApiController::class, 'login']);
Here is the ApiController for login
public function login(Request $request){
$fields = $request->validate([
'email' => 'required|string|email|max:255',
'password' => 'required|string|min:8'
]);
//validate login parameters
//check email
$user = User::where('email', $fields['email'])->first();
//check password
if(!$user || !Hash::check($fields['password'], $user->password)){
return response([
'message' => 'Invalid Credentials'
], 401);
}
$token = $user->createToken('myapptoken')->plainTextToken;
//return $user->createToken($request->device_name)->plainTextToken;
$response = [
'user' => $user,
'token' =>$token,
];
return response($response, 201);
}
EndPoint: https://findajob.ng/api/login
Email:johndeo1#gmail.com
Password: 12345678
This might not be a problem from backend, but in other-hand, if everything work in postman, you might try to:
Change support_credentials in config\cors to true.
Add withCredential header to front-end.
I made a manual login system in a Laravel 9 API that it's works correctly, but when I try to use Auth::user() in another controller, I get it as null, but when I return the auth->user() to the Vue SPA, I get it correctly. Is there a way to it is setting Auth::user() null after a successfull login? Here's are my api.php (api routes):
route::middleware('auth:sanctum')->get('/user', function (Request $request) {
return $request->user();
});
route::controller(UserController::class)->group(function () {
route::post('/register', 'register');
route::post('/login', 'login');
route::get('/logout', 'logout');
});
route::resource('book', BookController::class);
route::get('/my_books/{user_id}', [BookController::class, 'myBooks']);
As you can see in the image above, I can get the authenticated user after try login it, here's my login method:
public function login(Request $request)
{
$validate = $request->validate([
'email' => 'required|email',
'password' => 'required'
]);
if ($validate) {
$credentials = $request->only('email', 'password');
return Auth::attempt($credentials)
? Auth::user() :
response()->json('No se ha podido iniciar sesiĆ³n', 500);
}
return response()->json($validate->errors, 422);
}
But when I'm going to store a new book, I get the following error:
Here's the error, when I try to use the auth()->user() method to get the logged in user's id:
public function store(Request $request)
{
$validate = $request->validate([
'title' => 'required',
'genre' => 'required'
]);
if ($validate) {
$book = Book::create([
'title' => $request->title,
'author' => $request->author,
'genre' => $request->genre,
'subgenre' => $request->subgenre,
'opinion' => $request->opinion,
]);
$user = User::find(auth()->user()->id);
if ($request->cover) {
$this->uploadImage($request, 'cover', $book);
}
$user->books()->save($book);
return new BooksResource($book);
}
I don't know why it's happening, and I'd like any idea or possible solution. Thanks in advance:
From laravel 9 documentation
// Get the currently authenticated user's ID...
$id = Auth::id();
Also, you should describe your
route::get('/my_books/{user_id}', [BookController::class, 'myBooks']);
route before resource route.
I guess, you dont need this assign $user = User::find(auth()->user()->id); just use auth()->user
To get the Authenticated user, put the book route inside the auth:sanctum middleware.
When a user logs in I want them to be redirected to their profile page instead of homepage. I have a method in another controller that gets a user profile. Not sure what I need to do since the user profile takes a username variable but when user logs in I'm only asking for email and password.
My route file, but the following method is in a different controller from the authentication controller.
Route::get('/user/{username}', [
'uses' => 'ProfileController#getProfile',
'as' => 'profile.index',
'middleware' => ['auth'],
]);
My following method is in my authentication controller.
public function postSignin(Request $request)
{
$this->validate($request, [
'email' => 'required',
'password' => 'required',
]);
if (!Auth::attempt($request->only(['email', 'password']), $request->has('remember'))) {
return redirect()->back()->with('info' , 'Could not sign you in with that info.');
}
$user= User::where('username', $username)->first();
return redirect()->route('profile.index')
->with('info', 'You are now signed in.')
->with('user', $user);
}
The following is in my profile controller..
public function getProfile($username)
{
$user= User::where('username', $username)->first();
if (!$user){
abort(404);
}
return view('profile.index')
->with('user', $user);
}
To correctly build the route, you need to pass the username here:
$user = User::where('username', $username)->first();
return redirect()->route('profile.index', ['username' => $user->username])
->with('info', 'You are now signed in.')
->with('user', $user);
Get the username from the email provided and pass the $username variable to route:
public function postSignin(Request $request)
{
if (!Auth::attempt($request->only(['email', 'password']),$request->has('remember')))
{
return redirect()->back()->with('info' , 'Could not sign you in with that info.');
}
$username=User::where(['email'=>$request->email])->first()->username;
return redirect()->route('profile.index')->with('username', $username);
}
You can use as like below.
if (!Auth::attempt($request->only(['email', 'password']), $request->has('remember'))) {
return redirect('profile.index')->with('info' , 'Could not sign you in with that info.');
Will try make this clear as much as I can.
Im rolled out a make Auth call in order to use the login and registeration function of laravel and later just used the template to provide the needs I wanted that is.
If user is admin he/she can register a new user.
public function openNewUser(){
return view('auth.register');
}
NB. Part for update.
public function registerNewUser(Request $request){
$this->validate($request,[
'email' => 'required|email|unique:users',
'name' => 'required|max:120',
'password' => 'required|min:4|confirmed']);
$user = new User();
$user->name = $request->name;
$user->email = $request->email;
$user->password = encrypt($request->password);
if (Gate::denies('register-user')) {
return redirect()->back();
}
$user->save();
return view('home');
}
Problem 1 - I also want to update user , which is giving problems. The password inputs return empty fields , which i understand. When I try to change it doenst work the confirm password always give a mismatch even though they are the same. When I leave it blank too it doesnt work because the field is required to be filled. I took them off the form and tried if i could edit the email only but only didnt work.
public function userUpdate (Request $request,$user_id) {
$this->validate($request,[
'email' => 'required|email',
'name' => 'required|max:120',
'password' => 'required|min:4|confirmed']);
$user = new User();
$user->name = $request->name;
$user->email = $request->email;
$user->password = encrypt($request->password);
if (Gate::allows('register-user')) {
$user->save();
$user->roles()->attach($request->roles);
return redirect()->route('view_users');
}elseif (Gate::denies('register-user')) {
if (Auth::id() == $user_id) {
$user->save();
$user->roles()->attach($request->roles);
return redirect()->route('view_users');
}else{
return redirect()->back();
}
}
}
Problem 2. I just realized all logins I am doing with my new registration gives These credentials do not match our records.Even though the credentials are there and was registered correctly.
I am using the login provided by laravel but I created my own registration.
Please how can I edit and update my users and also be able to login after registration
What version of Laravel are you using?
Here is my (v5.3) register() method in RegisterController.php, at least part for registration:
public function register(Request $request)
{
...
// save and login user
$user = $this->create($request->all());
$this->guard()->login($user);
...
}
...
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'lastname' => $data['lastname'],
'phone' => $data['phone'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
]);
}
and the login() method from LoginController.php
public function login(Request $request)
{
$credentials = $this->credentials($request);
...
if ($this->guard()->attempt($credentials, $request->has('remember'))) {
return $this->sendLoginResponse($request);
}
}
Hopefully I haven't miss anything.
Keep in mind that things have changed here from version 5.2.
I found out what was wrong , Since I am using Laravel's login my registration had to use bycrypt for the encryption which is what Laravel registration was using , but I was using encrypt when I created my own registration so there was a conflict when logging in. (Remembere I was using Laravels login not my own written Login). I hope this helps someone
When I authorize in Laravel 5.3 I redirect to /home page.
I tried to change this on: protected $redirectTo = '/order'; in file LoginController.
But It does not work, I am redirected on home still.
In my UserController.php , I hope email and passwords are the things you use for user signin.
public function userSignIn(Request $request)
{
$this->validate($request,[
'email' => 'required|email',
'password' => 'required'
]);
if(Auth::attempt(['email'=>$request['email'],'password'=>$request['password']])){
return redirect()->route('order');
}
return redirect()->back();
}
You must have a route for order in your route.php file.