Laravel user update problems - laravel

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

Related

Laravel 9: Auth::user() / auth()->user() null after successfull login

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.

How to redirect the user back to intended route after social login?

This is my code in LoginController:
public function handleProviderCallback($provider)
{
$socialUser = Socialite::driver($provider)->stateless()->user();
$user = User::where('email', $socialUser->getEmail())->first();
if (!$user) {
$user = User::create([
'name' => $socialUser->getName(),
'email' => $socialUser->getEmail(),
'password' => Hash::make('12345678'),
'social_id' => $socialUser->getId(),
]);
}
Auth::login($user, true);
return redirect()->intended($this->redirectPath());
}
When performing normal login, it redirects to intended. But, in case of social login, it doesn't. What could be the cause?
I had a similar problem. You have to store the path you want to redirect in a session and then redirect the the path intended. I am also using the Socialite. Here is how I solved it.
public function redirect($provider)
{
session()->put('intended_url', url()->previous());
return Socialite::driver($provider)->redirect();
}
public function callback(Request $request, $provider){
$intendedUrl = session('intended_url');
if (!$request->has('code') || $request->has('denied')) {
return redirect('/');
}
$userSocial = Socialite::driver($provider)->stateless()->user();
$users = User::where(['email' => $userSocial->getEmail()])->first();
if($users){
Auth::login($users);
return redirect()->intended($intendedUrl);
}else{
$user = User::create([
'name' => $userSocial->getName(),
'email' => $userSocial->getEmail(),
'provider_id' => $userSocial->getId(),
'provider' => $provider,
]);
Auth::login($user);
return redirect()->intended($intendedUrl);
}
}
Before the redirect I store the previous route and then I use it. So no matter from which URL the user signs in, it will be redirected to the same page.
Check your url()->previous() in my case I actually needed the current url. So I used session()->put('intended_url', url()->full()); in the controller I hit and after lgoin redirect to this url as in the example.
Also you need to use Session::forget('intended_url'); afeter assigning it to variable.

Can't login with the correct credentials of a user created from admin panel

I created a UserController where admin can create a user with special privileges, asides from the Laravel Automatic register page, the issue is user creation works fine via the UserController but I can't sign in with the details I used when creating the account. Would appreciate any help I can find on here.
public function create()
{
//
$privileges = privilege::all();
$courses = course::all();
return view('tutor.create')->with('privileges', $privileges)->with('courses',$courses);
}
public function store(Request $request)
{
//
$this->validate($request,[
'name' => 'required',
'email' => 'required',
'password' => 'required',
]);
$users = new User;
$users->name = $request->input('name');
$users->email = $request->input('email');
$users->password = \Hash::make($request['password']);
$users->privilege_id = $request->input('privilege_id');
$users->save();
$course = $request->get('course');
$users->courses()->attach($course);
return redirect('/tutor')->with('success','User created');
}

Laravel sometimes validation rule not working

I'm trying to implement the sometimes validation rule into one of my projects (Laravel 5.6).
I have a profile page that a user can update their name and password, but i want to make it so that if the user doesnt enter a password, it wont update that field, which is what i thought the sometimes rule was.
The complete update method i am using in my controller is below.
If i leave the password field blank, then it returns a string or min error which it shouldn't be doing.
public function update()
{
$user = Auth::user();
$this->validate(request(), [
'name' => 'required',
'password' => 'sometimes|string|min:6'
]);
$user->name = request('name');
$user->password = bcrypt(request('password'));
$user->save();
return back();
}
Any help would be greatly appreciated.
The problem is that if you leave the password field empty, it is still present in the request. But filled with null
Try this instead:
public function update()
{
$user = Auth::user();
$this->validate(request(), [
'name' => 'required',
'password' => 'nullable|string|min:6'
]);
$user->name = request('name');
if(!is_null(request('password'))) {
$user->password = bcrypt(request('password'));
}
$user->save();
return back();
}
Try to add nullable in validation rule
$this->validate(request(), [
'name' => 'required',
'password' => 'sometimes|nullable|string|min:6'
]);
From Laravel docs:
nullable
The field under validation may be null. This is particularly useful
when validating primitive such as strings and integers that can
contain null values.

Auth Issue when upgrading from Laravel 5.2 to Laravel 5.3

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)

Resources