Redirect to create method of RegisterController in laravel - laravel

I Wanted to redirect to create method of registerController in laravel after a particular action.
So that the user can login after the registration is complete
the screenshoot of the Corresponding error

Assuming you are using the default RegisterController provided by Laravel.
create is a protected method, so you cannot use it as an action in a Route; you may only use public methods there.
The public methods that are meant as route actions in the default implementation are:
showRegistrationForm
register (this one calls create internally)
So either redirect him to the Route that has showRegistrationForm as action - the user may then fill out the form, submit it, and is registered.
Or programmatically create the user in your particular action using User::create(). You can even use the returned/created User object to programmatically login the user in the current session using Auth::login():
// Creates the record in the database. $newUser returned by the create method is the created User object.
$newUser = \App\User::create([
'email' => 'foo#bar.com',
'password' => bcrypt('thepasswordforthenewuser'),
]);
// Pass to the SessionGuard to log him in.
\Auth::login($newUser);

Related

Auth - get model

After using the Illuminate\Auth\Authenticatable trait on a model, I can now do Auth::id() in places in my app (when the current auth-ed thing is that particular model).
Is there a way to get the class / type of the auth-ed model?
Perhaps something like Auth::model() which might return the model's class name (such as App\Models\User or App\Models\MyCustomAuthCapabaleModel)?
Auth::user(); returns the model of the logged in user.
If you ever wish to change the User model, you can change it in config/auth.php at the key providers.users.model
Auth::user(); returns all the information about the authenticated user

Login stops working after changing the input field name "email" to "login-email"

I am developing a Laravel 6.6.2 project and I came across this problem I can't seem to fix.
In the file login.blade.php view i'm trying to change name="email" in the input fields to name="login-email". But when I do this the login doesn't work anymore. So I think that Laravel uses the name email somewhere to validate the login. I can't find where Laravel looks for the name email instead of login-email and if this even is needed to change?
The reason I need to change this is because javascripts use the name value too. (Because I brought a template). I am still learning Laravel so don't be to harsh. Thanks in Advance.
Laravel has excellent documentation. This is always a good place to start.
# Authenticating
https://laravel.com/docs/6.x/authentication#included-authenticating
Username Customization
By default, Laravel uses the email field for authentication. If you would like to customize this, you may define a username method on your LoginController:
In your case, you would return login-email from the username method.
public function username()
{
return 'login-email';
}
Of course, you will also need to add or rename this field in the database if you haven't already.
Alternatively to renaming the field in the database, you could override the credentials method.
protected function credentials(Request $request)
{
return [
'email' => $request->{$this->username()},
'password' => $request->password,
];
}

Using a single policy method to cover every action on a resource

I have a resource named Post. Every Post is related to a single User, and a User may have several (or zero) Posts.
I'm using Route::resource to map routes for every possible action on the Post resource to a single resource controller, PostController.
Now, I wish to implement a policy for the Post resource. Aiming to keep everything as simple and fool-proof as possible, I'd like to make the policy as follows:
Every user is authorized to make any action that doesn't require an existing Post (e.g. create).
A User is only authorized to access its own Posts for every action that accesses a Post (e.g. edit, update, delete).
What I'm trying to do right now is to create a single policy method called access, which would check that the Post is owned by the User. Then, in my PostController, every method that has a Post object in its parameters (such as edit(Post $post)) would begin with
$this->authorize('access', $post);
However, I don't like that I need to put those lines manually. If I ever forget one of those, I'll have a security hole right there.
On the other hand, I have the authorizeResource method, which makes authorization automatic but requires the policy to have several methods so they are mapped to the each of the controller's methods. Also, I tried to use the Authorize/can middleware, but it didn't work (maybe because I used it on a Route::resource mapping).
The question is: What would be the cleanest and more secure way to achieve the result I described (i.e. authorizing every possible action that accesses a resource with the exact same rule)?
You can use authorizeResource() and override the resourceAbilityMap() method in your controller. The latter method returns a mapping from controller methods to the policy methods that will be called.
https://github.com/laravel/framework/blob/5.7/src/Illuminate/Foundation/Auth/Access/AuthorizesRequests.php#L105
E.g.
class MyController extends Controller
{
// ...
/**
* Get the map of resource methods to ability names.
*
* #return array
*/
protected function resourceAbilityMap()
{
return [
'edit' => 'access',
'update' => 'access',
'destroy' => 'access',
];
}
// ...
}

Laravel - user login

I use Laravel 5.4 and need to login user in my system. I have next login.blade.php
where i have email and password field. In my controller I have next
protected function log() {
$email=Input::get('email');
$pass=Input::get('password');
$user = DB::select("SELECT * FROM users where email = '".$email."' and password = '".$pass."'");
foreach($user as $users){
if(Input::get('email') == $users->email){
return redirect('/');
}else{
return view('site.warning');
}
}
}
How can I return logged user in my redirect('/') and show them in my site.
Any idea?
Use the attempt() method:
if (Auth::attempt(['email' => $request->email, 'password' => $request->password])) {
From the docs:
The attempt method accepts an array of key / value pairs as its first argument. The values in the array will be used to find the user in your database table. So, in the example above, the user will be retrieved by the value of the email column. If the user is found, the hashed password stored in the database will be compared with the password value passed to the method via the array.
This method will work for you if you're using bcrypt() or Hash::make() to generate password hash.
Please do not create your own login system!
Now that's out of the way the explanation.
There is (almost) no good reason to create your own login system, as your code already showed. Your current code is very VERY insecure due to storing passwords in plain text. Please read up on resent security advice.
The even better option is using Laravels build-in auth.
https://laravel.com/docs/5.4/authentication
If you do try to use this build-in authentication methods you will be able to get the current authenticated user by using Auth::user() this can be used in your blade files as well as in your controllers.
You cannot (maybe you can) but you certainly should't store user's password unhashed. Laravel has build artisan command: php artisan make:auth. You may use it, and retrieve him in the show method for example (thro the URL, passing id). Or just retrieve him via Auth::user(). Planty of choices.

Laravel 5 - Middleware get user ID and send to controllers

Hello guys !
I'm working on an API that has a middleware authenticating the user with a unique ID. After making sure that this user exists, I want to send his database ID to the controller coming next, whichever it is.
Is that a good idea ? Or should I get that ID somehow after the middleware finished ?
How do I do that ?
Thanks !
Is that a good idea ? Or should I get that ID somehow after the middleware finished ?
It depends on what you want to do and how you routes are declared.
The routing is one of the first thing initialized by Laravel. You cannot pass parameter at run time (correct me if I'm wrong).
Plus, the controllers called after all midlewares has done their work.
I cannot garanty it's the more "beautiful" way to do this, but what i'm use to do is using Session::flash() or Session::put() when I want to pass parameters to my controllers at run time.
I use Session::flash() if the parameter has a one request life time, and Session::put() when I want the variable be more 'consistent' across the whole application.
I don't know if I am clear or not, tell me :)
Well, as long as you don't send that ID passing through the HTTP protocol, you should be fine since the user won't be able to tamper with the data.
That said, if you are using Laravel's built-in Auth module, you should just do an Auth::user() call at the other controller and it will give you the authenticated user.
If that isn't an option, you should create a function in the other controller that accepts $id as a parameter. You can call that function from within the first controlling by constructing the second controller throug $secondController = App->make(SecondController) and then $secondController->receiverFunction($id)
If you want the currently-authenticated user available in your application, just add it your base controller:
<?php namespace App\Http\Controllers;
use Illuminate\Contracts\Auth\Guard;
abstract class Controller {
protected $auth;
protected $currentUser;
public function __construct(Guard $auth)
{
$this->auth = $auth;
$this->currentUser = $this->auth->user();
}
}

Resources