Laravel dual authentication types - php

I am developing an application using Laravel 4, where I need to have 2 authentication types.
Type 1: Users - which are administators / back-office workers of the system.
Type 2: Customers - which are the visitors of the website who can do certain things (like purchase services) if they are authenticated.
The Type 1 Users are authenticated using username/password, so that fits nicely within the Laravel authentication model.
The Type 2 Customers will be authenticated either using OAuth style (with Google / Facebook) or manual authentication if the customer prefers. I do not want to mix the two together, so if you are authenticated as a customer I don't want the authentication filter to think you can access the admin pages, and vice-versa.
The two types will have their own tables (Users and Customers respectively). Is there a way to have a different Auth model running concurrently in some way? Or do I have to write my own thing for customers? What is the recommended approach in this scenario?

If I understand your question correctly this should set you on the right path.
You can simply set an account_level indicator in each table and wrap your admin routes in a filter that checks that the user's account_level is correct. For example:
in routes.php
Route::group(array('before' => 'admin_only'), function() {
Route::get('my-admin-route', 'AdminController#adminAction');
});
in filters.php
Route::filter('admin_only', function() {
if (!Auth::check() || Auth::user()->account_level !== Config::get('constants.ADMIN_ACCOUNT_LEVEL') {
return App::abort(404);
}
});
In order to log a user in that does not have a username and password in your system you would need to handle the OAuth connection separately and once you have a valid user you may use the Auth::login($user) method to get the user back into your usual application flow.
http://laravel.com/docs/4.2/security#manually

Related

Laravel Protecting Routes from other System Request

We have this system that our students access to get access to other platforms that we provide, such as Office 365 with student license and other programs...
We have access to create this access links, create an route and add some availables TAGS that they provide, such as student email, student unique code, student cellphone...
This links work as a bridge to our Laravel 6.0 application, that link should send the student to an internal page that they can create their office 365 account (if they dont already have) and redefine their passwords, but the problem is, I cannot garantee that this logged user will not change manually (from dev inspector) the data that is passed from the route parameter, and access other student data and change their Office password.
The point is, I can control that this page can be only accessed from this previous URL (this system that the student is logged), and It works, but I cannot do a Middleware from my application that check's if the user is logged in other application, and we don't have any API to check authentication from this system..
Is there any way to protect our routes from this other system?
Controller method that receive this parameters coming from the other system and verify the previous URL:
public function index($ra, $email){
if(url()->previous() != "https://other.system/" ){
return view('errors.503');
}
$usuario = UsuariosMicrosoft::where('login', '=', $ra)->get();
return view('portaloffice.pagina', compact('ra', 'email', 'usuario'));
}
This is my route:
Route::get('office365/{ra}/{email}', 'PortalOffice\PortalOfficeController#index')->name('portaloffice.usuario');
It's generally a pretty bad idea to secure things by keeping URLs secret. They're fairly easily sniffed or guessed.
The way projects usually protect from unauthorised access is to use the Auth guard, and with a relationship between the model you're trying to protect and the User model.
After setting up the models, relationships and guards you end up with something like this in your controller:
$user = Auth::user();
$user->UsuariosMicrosoft->get()
return $user;

Handling different types of user roles in Laravel

I have got a web project which has 3 types of users, say root admin, a super admin and kitchen admin. Each user or role has different functionalities: root admin will create super admin and other small functionalities, same way super admin would be creating kitchen admin and other functionalities and kitchen admin has its own functionalities say handling orders.
I wanted to know whether would it be a good idea to make separate laravel setup for each users or all these users can be developed in one laravel setup?
A small lead on this would be a great help since I am new at laravel.
You could make separate setups for each users. That would work. But would also be difficult to maintain and you might have to write some functions 3 times (login, logout, CRUD, etc.).
However, you could create a single project using Authorizations. Out of the box, Laravel gives you an easy way to authorize and restrict some actions via Gate or restrict models via Policy. You could also restrict URLs via Middleware. See you have 3 different ways of restricting actions.
My personal preference is Policy because it's bound to the model. You have a list of permissions and give each role their permissions, eg.: 'create_sys_admin'. Then link this permission to the 'root_admin' role. so in your policy you can write:
public function createSysAdmin(User $user) {
return $user->role->permissions->contains('create_sys_admin');
}
With the policy defined, we can check for propser permission in the controller. In any function in your controller you can always check for proper permissions
if ( Auth::user()->cant('create_sys_admin', User::class) ) {
return redirect()->back()->withErrors(['authorization' => 'You are not authorized to perform that action']);
}
That was just one way. As I previously said, you have Gates and Middlewares as well. Read more here: https://laravel.com/docs/5.4/authorization
If you want something already made, you can use this package: https://github.com/Zizaco/entrust.

Multiple Authentication Laravel - Socialite Plugin

I've implemented multiple authentication in my Laravel application and I have two different tables to accomplish this task (users and clients).
Everything works fine, the the only issue I've met is related to social authentication. I've followed all the configuration about Socialite-plugin but I don't know how to set up the redirect URL depending on wich type of user (users or clients) is trying to log in.
Any suggestions?
How you check if user is user or client?
You can add extra parameter to redirect route
Route::get('auth/{type}/{provider}', 'SocialAuthController#redirect')
(where {type} is user type)

Laravel - How to authenticate admin and users separately

I have 2 separate controls for my website.
Operators
Users
I want to authenticate users from 2 different tables for my application. Like if user if on myapplication.com/admin it should be authenticated from tbl_operators and if the user if on myapplication.com it should be authenticated from tbl_users
How to achieve this functionality in Laravel 5.2
If you plan to use the Auth built in with Laravel then this may not be possible. However if you wanna build your own authentication specifically for the admin then this may be possible.
You could also look into storing in an entirely new database using
DB::connection('name')

Multiple authentication systems

I've 2 tables, Users and Customers and 2 different actions for them. so I need 2 authentication system. Users login with username and password, and customers login with and id and password.
I know cake default AuthComponent can handle just 1 model, User model. because 'userModel' can be string not array (isn't it?).
How can I use it with 2 models (and tables) with 2 login pages and 2 .... .
(note: I can't combine the 2 tables. they have different schemas)
Instead of trying to maintain 2 different Auth systems, I highly recommend you look into ACLs and AROs. This will allow you to associate users with different access groups - in your case you could have groups like 'Internal'1 and 'Customers', and each new user account is a member of one group or the other.
You can then grant permissions at a group level. Customer users have access to their content, Internal users have access to different content.
There is a good tutorial in the new CakePHP book: Simple Acl controlled Application
1 I assume when you refer to 'users' generically you mean internal users, but feel free to adapt the terminology and group names to your particular situation.
I would presume 2 separate logins areas or a radio button to suggest which login they are attempting.
Use that input as which table to auth against then your code should follow the same path.
if (customer) {
do customer stuff;
} elseif (user) {
do user stuff;
} else {
you didn't login;
}
When you create the registration forms for them try to get their data into different databases. So that you can treat them differently. For this purpose check the submit button ids and direct the data to appropriate tables. When inserting put id's as auto increments.
I would advise against discriminating users from customers in this situation. These issues can be resolved using roles. Before jumping to design, please read about Authentication, Authorization and Audit and Role-Based Access Control.
From my understanding, this is an overview of the authentication process (note that I am not a security expert):
The identification phase is concerned with obtaining user credentials. A simple form that retreives user's name and password would suffice.
The authentication phase represents the process that maps user credentials to an user. Basically, it identifies a identity provider and uses it to obtain an user id for the user credentials provided.
Viewed like services, they look something like this:
// You can have many IdentityProviders. This mecanism allows you to extend your
// authentication system so you can use any mechanism (WebDav, Kerberos, etc).
IIdentityProvider
{
// Returns a pozitive id if the user is found and the credentials are valid
// or zero if user credentials are invalid (or negative numbers that represent
// error codes).
UserID GetUser(UserCredentials)
}
IAuthenticationService
{
Session SignIn(UserCredentials)
void SignOut(Session)
}
DefaultIdentityProvider : IIdentityProvider
{
// Search the user in your database.
UserID GetUser(UserCredentials credentials)
}
AuthenticationService : IAuthenticationService
{
IIdentityProvider[] identityProviders
Session SignIn(UserCredentials credentials)
{
IIdentityProvider provider = identityProviders[credentials.Type]
Session session = null
if (provider)
{
UserID userID = provider.GetUser(credentials)
if (userID > 0)
{
session = new Session
session.UserID = userID
}
}
return session
}
void SignOut(Session session)
{
delete session
}
}
The autorization system says what can a user do with a resource. Resources can be any entity that your application manages. They have a type and an ID. Optionally, they can be part of one or more categories. Users can execute certain operations on a resource, depending on its type and categories. This is defined by a permission. Permissions are grouped in roles. You can assign zero or more roles to an user.
In your example, a customer is a role. A resource is, for example, a product. A product is represented by the Product type, it has an ID and can have some categories associated ("Electronics" and "Dangerous"). Operations can be viewed as variations of Create/Read/Update/Delete verbs. Now, the Customer role would contain a set of permissions that explicitely states what a user having this role can do with the managed resources. For example, a Customer can only Read certain informations about the product, but cannot Create, Update or Delete a product. Note that if a user has more than one role associated, it gains all the permissions from that roles (an union operation, not an intersection).
This only scratches the surface. For further reading, you can find on the Internet more articles that explain these concepts alot better. This is meant to point you in the right direction.

Categories