Laravel 5.8 and VueJS2 authentication in SPA - php

I'm building a SPA with Laravel in backend and VueJS2 as frontend provider.
The application will handle users with 3 kind of roles: UserRole1, UserRole2 and Admin.
When a user signup to the application, he select if he wants to be a user with Role1 or a user with Role2 (admin-user is set by me directly in the mysql database).
So in the database there is a table "users" with a field called "role":
UserRole1 => "role"=1;
UserRole2 => "role"=2;
Admin => "role"=7.
When an user login, I want to redirect him to his role-based dashboard, so I have 3 different Vue components and 3 routes, and I want to prevent an user with Role1 (or Role2) from access to Role2 or Admin dashboard. Obviously, if a guest try to access to the dashboard, it will be redirected to the login page, and if an authenticated user try to access guest pages (like the Register page), it will be redirected to the dashboard page.
I would like to set a "userRole" parameter for each route, as below:
{
path: '/app/userRole1/Dashboard',
component: DashboardUserRole1,
name: 'dashboardRole1',
meta: {
title: 'Dashboard Role1',
userRole: 1
},
},
{
path: '/app/userRole2/Dashboard',
component: DashboardUserRole2,
name: 'dashboardRole2',
meta: {
title: 'Dashboard Role2',
userRole: 2
},
},
{
path: '/app/Admin/Dashboard',
component: DashboardAdmin,
name: 'dashboardAdmin',
meta: {
title: 'Dashboard Admin',
userRole: 7
},
},
I've tried with Laravel Passport API and now I'm trying with JWT and websanova/vue-auth, so in the "Login" component there is a post request to the "api/auth/loign" route, that pass the data to the AuthController#authenticate method, that return a json response. But the vue-auth package is not so suitable for my needs, so I think that there could be a more efficient solution but actually I can't figure out how to write an appropriate code. I would like to know if you have some ideas.

A simple solution is to define an api route for retrieving information about the authenticated user. Laravel's default api.php routes file contains this route:
Route::middleware('auth:api')->get('/user', function (Request $request) {
return $request->user();
});
You could modify it to include whatever information that your application needs to know about a user in order to handle routing logic:
Route::middleware('auth:api')->get('/user', function (Request $request) {
return $request->user()->load('roles');
});
Then your flow looks like this:
Log in normally.
Immediately call /api/user, and store the response.
Use the stored roles to route to the correct view in your SPA.
If the confusion is around Step 3, then this stackoverflow question might help.

Related

Get user which is authenticated by Fortify in API routes Laravel 8

I have a Laravel 8 application that uses Fortify with custom views to login and register users. I have some API routes that I want to get the logged-in user details on them as well. The problem is that I don't want to use Passport and other packages to make the job hard to generate tokens and so on because most of the routes are in the web.php and just some routes are on api.php, so what I have tried is like below :
dd(auth()->guard('api')->user());
However, it returns null and...
dd(Auth::user());
Again returns null. Is there any way to get the authenticated user in the API routes?
In your controller method, you can retrieve the user with these two methods:
public function render(Request $request) {
$user = $request->user(); // 1
$user = auth()->user(); // 2
}

Laravel 5.6 Multi User Type Auth API

I have a site providing APIs for 2 different websites.
Example:
merchant.mywebsite.com (merchant)
mywebsite.com (normal users)
My User Model:
I'm using polymorph for different type of users, userable_id determines the type of users, will have Admin, Merchant and Normal users, all have access to 3 different sites.
class User extends Authenticatable implements Auditable
{
public function userable()
{
return $this->morphTo();
}
}
API route:
Route::namespace('Api\V1')->prefix('v1')->group(function () {
Route::post('login', 'LoginController#login');
Route::post('signup', 'LoginController#signup');
Route::group(['middleware' => 'auth:api'], function() {
Route::get('user', 'LoginController#user');
Route::get('logout', 'LoginController#logout');
});
});
I would like to share the same auth functions for API call to Merchant and Normal Users, is there any way to do that?
For example, they will all need to auth in the same route:
mywebsite.com/api/v1/login but gets directed to their respective sites upon login and token.
Do i need to specify or make a custom column to identify the user type in oauth?
**I'm using Laravel Passport btw and all 3 sites are in different repos.

Get to work with the authenticated guard in laravel API

I have a session login system for a few guards. I'm using Vue a lot and I came to the point where I need authentication in Vue in order to fetch and post data properly. The question is how could I get the authenticated session user to work with API. So in api.php I want to use a controller whose Middleware the authenticated user. I don't want to use Passport because I only have logins over the webpage and not API.
vue supports component also there is something called props which they are data that you can pass to your vue component what I would usually do is pass the authenticated user id to my vue component and then when I ever fire a request from vue component I will pass the current authenticated user to the backend and there I check if the id received with request is the same as the current authenticated user.
check the example below I will use the regular guard
loading vue component from blade
//loading vue test-component and pass the authenticated user
<test-component :authuser="{{Auth::(user)->id}}"></test-component>
vue component
<script>
export default {
props : ['authuser'], //should be the same name as you passed it
data(){
return {
}
},
created(){
axios.post('/api/test' , {
'authuser' : this.authuser
})
.then(res => {
console.log(res);
})
.catch(err => {
});
}
}
Api route
use Auth;
Route::post('api/test' , function($request){
if(Auth::user()->id == $request->authuser)
return 'you are authenticated';
else
return 'you are not authenticated';
});
Hope you find this helpful , Good luck.

Filters login before using website - Laravel Framework

same as title, i want to all people when using trang web of me, must be login (look like FB or Twitter, ...) with some of the required as follows:
If such as the current URL is the '/' (home page), systems display the interfaces registered. (display the rather than the redirect)
If such as a different URL '/' (home page), systems redirection to login page.
somebody can help me? I'm using laravel framework.
Laravel uses power thing called filter.
You can use them in any Route::action you want.
But a little exemple may helps you.
Following your request :
// Check manualy if user is logged. If so, redirect to the dashboard.
// If not, redirect to the login page
Route::get('/', function()
{
if (Auth::check()) // If user is logged
return View::make('dashboard')
return View::make('/login');
}
// Each routes inside this Route::group will check if the user is logged
// Here, /example will only be accessible if you are logged
Route::group(array('before'=>'auth', function()
{
// All your routes will be here
Route::get('/example', function()
{
return View::make('contents.example');
}
});
Of course, the filter auth is built in Laravel. You can find this file in app/filters.php
and modifying it to your needs.
As follow:
Route::filter('auth', function()
{
if (Auth::guest()) return Redirect::guest('/login');
});

Laravel Package Authentication

I have a Laravel 4 web application where users can login and edit their profile.
I've created an API package that allows the user to login with their username/password and get a json dump of their profile.
Now, I don't want the API users to use their username/password but instead to use an app_id / app_key from another table in the database.
How to accomplish this with Laravel 4? It would be fantastic if I can create an Auth driver that works the same way Auth:attempt() would so I don't have to change any of my business logic, but I don't know how to inject a new Auth service provider that ONLY works inside of the API package.
You can change your Auth settings at where you want. You can create a filter in filters.php like that:
Route::filter('api_auth', function()
{
Config::set('auth.table', 'api_table');
// you can even change your model
// Config::set('auth.model', 'Apiuser');
});
And use before any route in routes.php like that:
Route::get('user', array('before' => 'api_auth', function()
{
// some stuff
}));
So that, you can use different settings and do what you want.
BTW, I tried this method at Laravel 3, it worked. I looked docs of laravel 4, I couldn't see anything prevent this work.

Categories