Laravel - How to create authentication for API without database - laravel-5

I'm writing an app at the moment which makes use of web-sockets and therefore needs to keep track of its users somehow.
I don't really want my users to register. Before using the app they should choose a name and will get a JWT-Token for it. I don't want to save anything in a database. As these names can be non-unique I will probaply add an Id.
I'm trying to use tymon/jwt-auth": "^1.0.0-rc.3.
public function login()
{
$token = auth()->tokenById(1234));
return $this->respondWithToken($token);
}
For some reason the tokenById-Function seems to not be available.
Postman says: BadMethodCallException: Method Illuminate\Auth\SessionGuard::tokenById does not exist.

In my case i have clear the cache. Then its working fine

Related

Laravel6 - Email verification customization on multi-login platform

I am new to laravel. I am trying to implement email verification on my laravel6 project.
On my project, there're three user types named 'user' 'vendor' and 'admin'. I have prepared separate directories for each user type in 'Controllers' and each of them has their own Auth files (e.g. Directory 'App/Http/Controllers/Vendor/Auth' has its own VerificationController.php, etc). So far, I've successfully implemented registration and login/logout function for each type with separate table in my DB.
A issue popped up when I tried to implement email verification. When I tried to access to a page where email verification is required, 'Auth\VerificationController#show' method seemed to be called regardless of the user type.
I went over laravel source code and learned that within the process, router calls Illuminate/Routing/Router->emailVerification() method. And the emailVerification() method routes to 'Auth\VerificationController#show' regardless of the user type.
What I wanted to do is to route depending on user type (e.g. if 'vendor' tries to login, I want to call 'Vendor\Auth\VerificationController#show').
I don't come up with any idea how to do for that. Can anyone please give me any advice?
Illuminate\Routing\Router class
public function emailVerification()
{
$this->get('email/verify', 'Auth\VerificationController#show')->name('verification.notice');
$this->get('email/verify/{id}/{hash}', 'Auth\VerificationController#verify')->name('verification.verify');
$this->post('email/resend', 'Auth\VerificationController#resend')->name('verification.resend');
}
Thank you in advance.

Where to check if an User is logged in in a Laravel Application?

I've been using your advice and View::sharing all of my important data to all views. However, there is one issue I have encountered.
This code:
if(!Auth::guest()){
$user=Auth::user()->id;
}
else $user=0;
$temp=DB::select('query');
View::share('cartnumber', count($temp));
View::share('cartitems', $temp);
doesn't work when put in AppServiceProvider. Or better, it always sets $user=0, even if I am logged in. I thought it is because AppServiceProvider's boot function executes before the site checks if someone is logged in.
I then tried to use a BaseController with a construct function but that doesn't work either. The only solution that seems to work correctly is putting the code in every single Controller for every view! That actually works, which kind of confirms my theory.
But is there anywhere I can put this code without having to copy/paste it in every single Controller? Thanks in advance!
You'd likely want to put this code later in the request life cycle to guarantee an auth user because as others have mentioned middleware/session code has not occured during this part of the framework booting up. You could use a service class to call in all your controllers to avoid the copy pasting. Or If you'd like to achieve this using code in your service provider you could use a View Composer instead of a share this allows you to define a callback/or class that will be called right before the view is returned
view()->composer(['/uri-that-needs-data'], function ($view) {
if (Auth::check()) {
$cart = DB::query(...)->get();
$view->with('cartitems', $cart);
}
});
Check out https://laravel.com/docs/5.7/views#view-composers for more details.
Auth::user() will be empty until the session middleware has run.
The reason you can't access the user inside your service provider is because that code is run during the "bootstrapping" phase of the application lifecycle, when it's doing things like loading filesystem or cache drivers, long before the request is sent through response handlers (including middleware).
Once the application has been bootstrapped and all service providers
have been registered, the Request will be handed off to the router
for dispatching. The router will dispatch the request to a route or
controller, as well as run any route specific middleware.
Source: https://laravel.com/docs/5.7/lifecycle
If you don't want to copy/paste that code everywhere, then one place to put it is in custom route middleware. You can list it after the auth middleware to guarantee a logged-in user.
Edit: View composers are another really good option, as suggested by #surgiie. The reason these can be set up inside a service provider (unlike your example) is because the view composer registers a callback, but doesn't execute it until a much later stage in the application lifecycle.

Is it possible to get Laravel user data from Vue JS?

i have a Laravel 5.4 application where i do all Authentication based logic through PHP and then redirect the user to a catchAll route when they are authenticated, and let VueRouter take it from there...
I'd like to also use Entrust because my app will have several types of users and some elements (like an Edit User button) will only be visible to some user Roles.
I might also want to implement specific permissions, like some Admins can edit user Permissions, while others do not.
The issue is, alright i'm in Javascript territory now, so how do i know what my current Auth user is? Setting a global JS variable for Auth::user doesn't seem like a good idea to me.
Perhaps i would instead pass just an ID, but how exactly without making it globally visible as a window variable?
I think you may create an auth/check API call, like this:
protected function check()
{
if(Auth::guard('api')->check()) {
return Auth::guard('api')->user();
}
return ['success' => false];;
}
And then get current user with this call.

Laravel 5 - Is there a way to use built-in authentication but disable registration?

I am building an administrative back-end and thus need to hide public user registration. It appears that if you want to use the built-in Illuminate authentication you need to add
use AuthenticatesAndRegistersUsers to your controller definition. This trait is defined here.
It appears as if it is impossible to disable registration if you want to use the built-in auth handlers... can someone show me wrong?
I'm using Laravel 5.2+ and I found that if you remove the Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers and use just Illuminate\Foundation\Auth\AuthenticatesUsers does the trick too.
Though /register is still accessible and will throw a fatal error.
This page talks about overriding the auth controller. Its worth a read, at a basic level it seems you can add the following lines to app\Http\Controllers\Auth\AuthController.php :
public function getRegister() {
return redirect('/');
}
public function postRegister() {
return redirect('/');
}
So if a user accesses the registration url it will redirect them away to a place of your choosing.
You can have your own form of registration. The only thing Laravel does is make it easy to authenticate on a users table because they create the model, build the db schema for users and provide helper methods to authenticate on that model/table.
You don't have to have a view hitting the registration page... But if you want to use the built in auth you still need to use (or set) a Model and a driver for database connections.
You can just remove that view and/or controller method from the route that links to the registration view and create your own (or seed the database manually).
But, no, you cannot forgo using Eloquent, and the User model and expect to use built in auth. Built in authentication requires that you specify settings in /config/auth.php. You may specific a different model (other than User) and you may specify a different table, but you cannot forgo the configuration completely.
Laravel is very customizable though, so you can achieve what you are looking to do... plus why not use Eloquent, it's nice.
Based on #shoo's answer, working with Laravel 5.2
Add the following lines to app\Http\Controllers\Auth\AuthController.php :
public function showRegistrationForm() {
return redirect('/');
}
public function register() {
return redirect('/');
}

codeigniter php native sessions without using cookies or URL session id, but matching browserfingerprints in database

Because of european privacy law being harsly applied in the Netherlands and to keep my company's site user friendly without nagging the users with questions if it's okay to store a cookie on their computer that allows me to access their client data.
What I need is a way to "overwrite" the native php sessions class so that at the point where the native class requests the cookie that stores the phpsessid, that I can place my own code there that checks the browsers fingerprint and matches that to a session id which I can use to return the normal working of the native class.
My idea is:
table sess_fingerprints
Fields: fingerprint - phpsessid
function getsessionid()
{
$result = $this->db->query("SELECT phpsessid
FROM `sessiondatabase`.`sess_fingerprints`
WHERE `sess_fingerprints`.`fingerprint` = '$userfingerprint'");
if($result->num_rows() != 0)
{
return $result->row->phpsessid;
}
}
and at that point the native php session code just works as it would normally do.
So, my question is: is it possible to overwrite only the "cookie" part of the phpsession class? if so, how? because I haven't found that yet.
I'm aware of being able to pass along the session variable via urls etc, but that's not secure enough for my web applications.
PHP provides support for custom session handlers:
http://php.net/manual/en/session.customhandler.php
I think I have found the solution to my problem.
I'm going to override the functions related to cookies by using http://php.net/manual/en/function.override-function.php
Thank you all for thinking along.

Resources