I am using Nova just as the backend for a SAAS application so basically going to app.mydoain.com just pops up the Nova login form. I want Laravel 5.7 Email Verification that comes standard in use for this (so when I add a user they have to verify the email before the can login).
In config/nova.php I added the middleware:
'middleware' => [
'verified',
'web',
Authenticate::class,
DispatchServingNovaEvent::class,
BootTools::class,
Authorize::class,
],
In User.php model I implemented it (which is done differently than there webiste docs?)
<?php
namespace App;
use Illuminate\Auth\MustVerifyEmail;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Contracts\Auth\MustVerifyEmail as MustVerifyEmailContract;
class User extends Authenticatable implements MustVerifyEmailContract
{
use MustVerifyEmail, Notifiable;
....
I added some routes in web.php for just verification (dont need any other auth)
Route::get('email/verify', 'Auth\VerificationController#show')->name('verification.notice');
Route::get('email/verify/{id}', 'Auth\VerificationController#verify')->name('verification.verify');
Route::get('email/resend', 'Auth\VerificationController#resend')->name('verification.resend');
After I login it just stalls out and either goes to /email/verify or /. In my db I have already added a timestamp so it shouldn't go to /email/verify at all and when it goes to / it times-out.
If i remove verified from the middleware in the config it works fine, but no email verification check.
Change the order of the middlewares.
'middleware' => [
'web',
Authenticate::class,
'verified',
DispatchServingNovaEvent::class,
BootTools::class,
Authorize::class,
],
Your request must go through web first. Most likely you are getting the timeout because of a redirect loop.
Related
So I just started a Laravel Project with Breeze, and I wanted to change the default table users , the problem is it didn't work, I did my research for days and I didn't get any successful result
I will try to explain what is the problem and what have I tried so far.
First, I created a new table called users_data, and this table, is completely different than the users table.
The fields that users_data has, are for example: name_value, password_value, age_value, email_value, etc. (I have to mention too that for the table users_data, it doesn't use a migration, because I already have an sql file, and added it directly to the db (I already have tables created, with primary keys, and foreign key, so i couldn't do the migration because it would take me a lot of time), and without the migration I can still get the data, so I don't think it could be this the problem).
Actually I'am using Breeze, however, I used Auth scaffolding (PHP artisan make: Auth) too
What have I tried:
After several days of search, first I have created a new Model, called UsersModel, the content of this is the same as User Model however what I change is:
protected $table = 'users_data';
protected $fillable = [
*name_value*,
*password_value*,
];
and an extra function to override the default password of breeze or Auth (I guess):
public function getAuthPassword()
{
return $this->password_value;
}
next I went to conf/auth.php
there I specified the Model:
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\Models\UsersModel::class,
],
and the table to use:
/*
|--------------------------------------------------------------------------
| Authentication Table
|--------------------------------------------------------------------------
|
| When using the "Database" authentication driver, we need to know which
| table should be used to retrieve your users. We have chosen a basic
| default value but you may easily change it to any table you like.
|
*/
'table' => 'users_data',
after this I went to the view login.blade.php, and changed only the email input (for what I read on different pages, changing the password input will cause different problems, because I would need to make a lot of changes to make it work so the best idea is to override it with getAuthPassword, specified in the model):
new name input:
x-input id="email" class="block mt-1 w-full" type="text" name="name_value" :value="old('name_value')" required autofocus />
After all this I went to LoginRequest (the validation for the login), where I replaced email for name_value
I tried to debug this:
dd(Auth::attempt($this->only('name_value', 'password'), $this->boolean('remember')));
and returns false
I noticed that there's a function in vendor/laravel/ui/auth-back/AuthenticatesUsers
called username(), that returns 'email'
when I saw that I remembered a page that said that this function could override too, so I changed the return value to name_value, and it doesn't do nothing
last, just to clarify,
I don't need the Register site I only need the login page, so for that in the $fillable I didn't add all the columns of the database, just the ones that I need to log in (name_value, password_value)
If anyone could help me and guide me it will be great, because I'am running out of ideas (I could do it with PHP alone, however, I need the ->middleware ['Auth], is there a way to activate the middlware if the user exists?)
So you might have a model named users_data.php. Go inside it and change the code to something like that.
STEP:1
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Foundation\Auth\users_data as Authenticatable; //Add this line for Auth.
class users_data extends Authenticatable //Extends child from Authenticatable parent class obj.
{
use HasFactory;
protected $fillable = ['column1', 'column2', 'column3', .....];
}
STEP:2
Go to config/auth.php. You may found something like this below.
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\Models\User::class,
],
// 'users' => [
// 'driver' => 'database',
// 'table' => 'users',
// ],
],
Change the 'model' => App\Models\User::class, to 'model' => App\Models\users_data::class,
This is the main character in this drama that putting your application to users table by default.
STEP:3
Comment off the User.php so that no future conflict create.
Now your application has been diverted to your desired table and ready to login.
I don't think it's good practice to be editing vendor files. We don't push them to version control so other developers won't have your changes. Also, Laravel already has a way to override the username value without editing the vendor files.
Just use the trait in your auth controller like this:
public class MyLoginController {
use AuthenticatesUsers; // or you can also use ThrottlesLogins trait
// then override the username function here
public function username() {
return 'name_value';
}
}
To override the password you can define this on your User model:
public function getPasswordAttribute() {
return $this->attributes['password_value'];
}
public function getAuthPassword() {
return $this->password_value;
}
I haven't tested this but based on the docs this is how you should do it. Also make sure to read this Laravel doc.
I need to create a login with Laravel 8 and Sanctum. I have a Laravel application without Vue.js / React or Angular and I need to create tokens for api.
When I create a token, authorization on the API works great but doesn't work for the web.
I just need to log in and then create a token that can be used for API and of course let the data be stored in the session or cookies so that he can use the web.
Or can you recommend something to me about how it could be solved?
Laravel Sanctum is a new powerful package that makes authentication easier for different scenarios:
Laravel Sanctum provides a featherweight authentication system for SPAs (single page applications), mobile applications, and simple, token based APIs. Sanctum allows each user of your application to generate multiple API tokens for their account. These tokens may be granted abilities / scopes which specify which actions the tokens are allowed to perform.
The following Controller allows an user to login and create a token via Laravel sanctum:
<?php
namespace App\Http\Controllers;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
class AuthController extends Controller
{
public function store(Request $request)
{
$request->validate([
'email' => 'required|email',
'password' => 'required',
'device_name' => 'required',
]);
$user = User::where('email', $request->email)->first();
if (!$user || !Hash::check($request->password, $user->password)) {
return response('Login invalid', 503);
}
return $user->createToken($request->device_name)->plainTextToken;
}
}
We can register a route that will be managed by the Controller above:
// routes/web.php or routes/api.php
Route::post('/login', [AuthController::class, 'store']);
Route::group(['middleware' => 'auth:sanctum'], function () {
// Route that needs the user to be logged in
/*
Route
::get('/dashboard', [DashboardController::class, 'index'])
->name('dashboard');
*/
});
Therefore, the following POST request with valid credentials will return a token:
curl -d "email=admin&password=123&device_name=test" -X POST https://localhost:8000/login
Which we can then use to make the next authenticated API calls:
curl -i https://localhost:8000/dashboard \
-H "Authorization: Bearer <TOKEN_FROM_PREVIUOS_COMMAND>" \
I moved the User.php in my laravel installation to a different folder and adjusted the namespace accordingly. Still, when I login into the page, laravel is not able to find the class and throws an error.
I ran composer clear-cash and composer dump-autoload but still it is not working as Laravel still searches for App/User.php instead of App/Classes/User/User.php
The User.php looks like this:
namespace App\Classes\User;
use App\Events\EventGenerator;
use App\Events\User\UserRegistered;
use App\Permission;
use App\Role;
use Laratrust\Traits\LaratrustUserTrait;
use \Illuminate\Contracts\Auth\Authenticatable as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Console\Command;
class User extends Model implements Authenticatable {
use EventGenerator;
(...)
You need to change the class the path in auth.php
In your auth.php
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\Classes\User::class,
],
// 'users' => [
// 'driver' => 'database',
// 'table' => 'users',
// ],
],
Idea is to change the path of 'model' => App\Classes\User::class, to your class.
Hope this helps
There is a reference to the user model in auth config, you'll probably need to adjust the namespace there.
File: config/auth.php
Setting: providers -> users -> model
I'm kinda a newbie in Cakephp (3.5) and I'm currently trying to make my first plugin (called Example) which contains several sub-directories. One of them is the UserManager directory which contains a Users MVC standard suit with authentication.
Since I want to add social logins and other stuffs, I created my own auth component as explained in the docs :
plugins/Example/UserManager/src/Controller/AppController.php
<?php
namespace Example\UserManager\Controller;
use App\Controller\AppController as BaseController;
class AppController extends BaseController
{
public function initialize()
{
parent::initialize();
$this->loadComponent('Auth', [
'authenticate' => [
'Example/UserManager.Example' => [
'fields' => ['username' => 'email', 'password' => 'pass'],
'userModel' => 'Users',
],
],
]);
}
}
plugins/Example/UserManager/src/Auth/ExampleAuthenticate.php
<?php
namespace App\Auth;
use Cake\Auth\BaseAuthenticate;
use Cake\Http\ServerRequest;
use Cake\Http\Response;
class ExampleAuthenticate extends BaseAuthenticate
{
// The same as Form authentication, since I'm testing
}
The problem is that I can't make the authentication component find the ExampleAuthenticate class. I already tried by setting the authenticate config param like
Example
ExampleAuthenticate
UserManager.Example
Example/UserManager.Example
Example\UserManager.Example
Example/UserManager.ExampleAuthenticate
Example\UserManager.ExampleAuthenticate
but I always get the error Authentication adapter "..." was not found. when visiting http://localhost/Project/example/user-manager/users :(
Does anyone have any clue of what I might be missing?
The problem was that the php function class_exists(...) didn't recognise the custom authentication class, so after digging a bit more I realised that the namespace shown in the docs only works for a custom authentication file defined in the App environment, but not in the Plugin one (silly me).
So I changed namespace App\Auth; to namespace Example\UserManager\Auth; inside ExampleAuthenticate.php and it worked like a charm! now the function class_exists('Example\\UserManager\\Auth\\ExampleAuthenticate') returns true and everything works perfect by defining Example/UserManager.Example in the authenticate config params.
I have read a lot of threads about multi-auth in Laravel, most of the configurations I see are somehow complicated, I have also seen a multi-auth package but it does not support Laravel Socialite.
I am aware that this question is asked multiple times, but if someone can give a better answer. It would be much appreciated!
Things I have tried
I am familiar with Laravel make:auth
I am also familiar with Laravel socialite Facebook , Twitter , Google plus.
Give this a try. But you still need some basic knowledge about Laravel's new multitenancy.
In config/auth.php add something like this to guards array:
'customer' => [
'driver' => 'session',
'provider' => 'customers',
],
Than in the same file add this to providers array:
'customers' => [
'driver' => 'eloquent',
'model' => App\Customer::class,
],
Than create Migration for customers DB table (you can use Laravel's out of the box migration for users table)
Next is Eloquent model App\Customer with these included:
use App\Scopes\AuthorizedScope;
use Illuminate\Foundation\Auth\User as Authenticatable;
These should let you use Laravel's Auth facade in your app with these most used methods:
Auth::guard('customer')->attempt()
Auth::guard('customer')->check()
Auth::guard('customer')->logout()
Auth::guard('customer')->user()
Or use auth middleware like this:
Route::get('customer/dashboard', function () {
// Only authenticated users may enter...
})->middleware('auth:customer');
Also checkout these:
https://laravel.com/docs/5.3/authentication#authenticating-users