Authentication from custom user table - php

I got a project where I will have two login interfaces, one for Employees and the other one for external people.
The login for employees works like a charm since they are stored in the standard users table provided by laravel.
Right now I am trying to get to work that external accounts get logged in, the registration works and all their user data is stored inside the "portal_users" database, but the login doesn't work. It seems like that it tries to use the standard users database for verification.
Is there a way to make it check a specific database?
public function store(Request $request) {
$this->validate($request, [
'email' => 'required|email',
'password' => 'required',
]);
if(!auth()->attempt($request->only('email', 'password'), $request->remember)) {
return back()->with('status', 'Falsche Login Daten');
}
return redirect()->route('home');
}
This is my function for the users table login process.
And is it possible to give the default user table different roles within or should I create a new auth for each role?

Related

using laravel guard in laravel breeze and multi authentication

I'm using laravel 8 and laravel breeze for authentication and now want to use guard for authenticating different users like "admin users" and others using different tables (users, admins, so on) or even in a same table and model.
how can I do that?
some information:
I changed LoginRequest:
if (! Auth::guard('admin')->attempt($this->only('email', 'password'), $this->boolean('remember'))) {
RateLimiter::hit($this->throttleKey());
throw ValidationException::withMessages([
'email' => trans('auth.failed'),
]);
}
I created Admin model and it's table.
I changed auth.php for adding provider and guard
when I try to login, it redirects to login page without any error.

Validating user access inside of controller

I just started learning Laravel 5.7 and was wondering if there is an easier way to validate if a specific user has the rights to edit, delete or view a page.
Scenario
A user has many companies, and can view, edit and delete them. So if they try to access a company name (id) they don't belong to, they would get "access dined" or something. My problem is that i keep repeating my code over and over, and it seems very unproductive.
Example code:
public function edit($id)
{
// Check if the company ID exists
if(!Company::whereId($id)->first() || !Company::whereId($id)->where('user_group',Auth::user()->user_group)->first())
{
return abort(404);
}
return view('company/edit');
}
So in my example, I check if the ID of the company exists, and If the company and user_group has the same ID. However, I would need to repeat this code for the "show" method, and any other methods having the same scenario (including other controllers).
How can I make my life easier with this? What's the best practice? A example would be nice.
There are many ways to do this, I believe the best way for your problem is the use of policies. Policies can be seen as a link between the User and the Model (company in your case). You can specify create, show, update and delete methods and specify if a user should be able to perform the specific action.
Policies shine through their general usage, you don't have to check if a user can view a specific company anywhere else in your code, just the once and Eloquent handles the rest.
The clean way is to use Laravel Validator
public function store(Request $request)
{
$validator = Validator::make($request->all(), [
'title' => 'required|unique:posts|max:255',
'body' => 'required',
]);
if ($validator->fails()) {
return redirect('post/create')
->withErrors($validator)
->withInput();
}
// Store the blog post...
}
We did this thru a middleware. You can create an user access table on the database and make a middleware that checks it if the user has the access. then allow if the access exist on the table or redirect if not. However, this approach only works on user type level and not on a specific user.

Laravel registration and login pages on a subdomain

I am creating a website in Laravel 5.3 that has two different entry points for registration, these entry points need to be subdomains.
I've setup the two routes but I am a bit lost how I would setup the Auth::routes() for the two subdomains.
One route will be for users who will register and pay a monthly subscription fee while the other route will not have a subscription fee attached to them.
As a site note: the two registration forms are identical at the moment but one could get a few more fields added than the basic username / password fields (think of name, surname, etc).
There is a sub-domain-feature in the routing component:
Route groups may also be used to handle sub-domain routing. Sub-domains may be assigned route parameters just like route URIs, allowing you to capture a portion of the sub-domain for usage in your route or controller. The sub-domain may be specified using the domain key on the group attribute array:
Route::group(['domain' => '{account}.myapp.com'], function () {
Route::get('user/{id}', function ($account, $id) {
// your code
});
});
https://laravel.com/docs/5.3/routing#route-group-sub-domain-routing
If subscribed users and non subscribed users are in the same table you can manually authenticate users (see the docs):
if (Auth::attempt(['email' => $email, 'password' => $password])) {
// The user is logged in
}
This Auth:attempt method has an option to send more parameters:
if (Auth::attempt(['email' => $email, 'password' => $password, 'subscribed' => 1])) {
// The user is a subscriber and logged in
}
You would need an extra field in your database that shows if a user is subscribed or not (subscribed) for this, and you should fill this with 1 or 0 via the two different registration pages.
The name and surname fields should be nullable in your database so filling them is optional.

How can I create an edit form for Laravel's user model?

I want to use the default auth built into laravel 5.2, however my application has no need for letting users register themselves as the users are authorized users of the administrator dashboard. Only currently existing users should be able to create users.
As such, I need to be able to accomplish a few things:
Need to disable registration for public users
Need to allow authenticated users to register new users, access registration form
Need to provide a form to allow authenticated users to edit users, allow for password resets, name changes, etc...
Where would I build the controller methods for these views? Should I build a new userscontroller altogether, or write the create and edit methods directly into the authcontroller? Overall, what's the best practice for building such a system based on Laravel's auth.
For disable registration for public users you can remove all the links in views to register routes, and you can edit the AuthController methods showRegistrationForm() and register(), the first load the view and you can redirect to 'login' route, the second is the POST to save the user.
For the new methods on User's table, i believe that is better make an UserController and put your logic away from the Laravel's auth controller, here the User will be as any resource, but you will need verify if the authenticated user that is trying to add another user has the privilegefor that.
And for this permission to add new users depends on your system, i think that you don't need to make all the "Roles and Permissions" thing if your system needs only a admin user to add new users, you can do it from another column in User's table, but if you will have more permission controled areas or actions, think in this as an ACL will be a lot better.
It sounds like you need to bring in the routes that are being pulled in through the function call into your file itself.
Doing this gives you the ability to disable to routes for registration. So instead of having the Router::auth() in your routes.php pull them in yourself and leave out ones you don't need: https://github.com/laravel/framework/blob/ea9fd03f5c5aef12018812e22e82979d914fef93/src/Illuminate/Routing/Router.php#L367
The rest of the things you will need to code yourself. A good starting point is to take the views for registration and put that into a form for a logged in user. When the user creates the *new user then you run you validation (email => required, password => required, etc) and you would have something like
// this would be in something like public function createUser(Request $request)
$rules = [
'email' => 'required|unique:users,email',
'password' => 'required|confirmed'
];
// validate the request, if it doesn't pass it will redirect back with input and errors
$this->validate($request, $rules);
// create the user now
User::create(['email' => $request->input('email'), 'password' => \Hash::make($request->input('password')]);
and the rest is up to you to code.

After registration using tank_auth user should get logged in for codeigniter

What is the best authentication out there for codeigniter, I decided to use tank_auth.
It seems to be the best authentication for codeigniter.
So how can I, after registration user using tank_auth should be automatically logged in without requiring him/her to activate his/her account.
I have 4 step of registration process in my application so I need to add the user id into multiple tables.
My Logice like at first step I want to I will directly login to user and then session id will be useful to other step.
My Logice like at first step I want to I will directly login to user
and then session id will be useful to other step.
Having never used Tank_auth, I'm not sure how to implement this into their system, however it shouldn't be too difficult.
Here's a quick example I whipped up, just for you...
$data = array(
'username' => $username,
'email' => $email,
'password' => $hashed_password
);
$query = $this->db->insert('users', $data);
// Use this for each table
$user_id = $this->db->insert_id();
Then you can do whatever with the database, linking the user by their id $user_id
The session can be set once you have this ID

Categories