How to auto add id on form? - laravel

Add id manually looks like this
{!! Form::text('email', null, ['id' => 'email', 'class' => 'active']) !!}
How to auto add id?
Any example to use macro?

Create your new FromBuilder Class :
class MyFormBuilder extends \Collective\Html\FormBuilder /** Original Form Builder*/{
// Override the text function
public function text($name, $value = null, $options = []){
// If the ID is not explicitly defined in the call
if(!isset($options['id'])){
// Set ID equal to the name
$options['id'] = $name;
}
// Call the original text function with the new ID set
parent::text($name,$value,$options);
}
}
Then Create a new Service Provider
<?php
namespace My\Provider\Space;
use Illuminate\Support\ServiceProvider;
class MyHtmlServiceProvider extends ServiceProvider
{
/**
* Indicates if loading of the provider is deferred.
*
* #var bool
*/
protected $defer = true;
/**
* Register the service provider.
*
* #return void
*/
public function register()
{
$this->registerHtmlBuilder();
$this->registerFormBuilder();
$this->app->alias('html', 'Collective\Html\HtmlBuilder');
$this->app->alias('form', 'My\Class\Space\MyFormBuilder');
}
/**
* Register the HTML builder instance.
*
* #return void
*/
protected function registerHtmlBuilder()
{
$this->app->singleton('html', function ($app) {
return new \Collective\Html\HtmlBuilder($app['url'], $app['view']);
});
}
/**
* Register the form builder instance.
*
* #return void
*/
protected function registerFormBuilder()
{
$this->app->singleton('form', function ($app) {
$form = new \My\Class\Space\MyFormBuilder($app['html'], $app['url'], $app['view'], $app['session.store']->getToken());
return $form->setSessionStore($app['session.store']);
});
}
/**
* Get the services provided by the provider.
*
* #return array
*/
public function provides()
{
return ['html', 'form', 'Collective\Html\HtmlBuilder', 'My\Class\Space\FormBuilder'];
}
}
Then update your config/app.php file and do:
Remove The old \Collective\Html\HtmlServiceProvider::class from the service providers array
Add Your new Service provider in it's place.
A basic explanation of what this does:
A. You move the service provider for the HTML helpers to your own service provider where you register your MyBuilder
B. Next time you call \Form that service provider will point it to your builder.
Check out the vendor files for collective to make sure you get all the variables in the function definitions.
Just filter out any namespace errors etc. as I have not completely tested them all.

Related

Laravel 8 Fortify - 2FA only when the user logs in from a new device

I am implementing two-factor authentication (2FA) in my Laravel 8 application.
The 2FA is applied every time the user logs in. However, I don't really feel that 2FA is necessary every time, I even find it annoying. As a solution I am thinking of applying it only when the user connects from a new device. Is there someone who has already done it or who can give me a hint of the changes that would be necessary?
I have got it. Here are the steps I have followed:
In the config file fortify.php I have added
'pipelines' => [
'login' => [
App\Actions\Fortify\RedirectIfTwoFactorAuthenticatable::class,
Laravel\Fortify\Actions\AttemptToAuthenticate::class,
Laravel\Fortify\Actions\PrepareAuthenticatedSession::class,
]
]
I have added the field two_factor_cookies to the User class.
I have customized the RedirectIfTwoFactorAuthenticatable class of
Fortify:
<?php
namespace App\Actions\Fortify;
use Laravel\Fortify\Actions\RedirectIfTwoFactorAuthenticatable as DefaultRedirectIfTwoFactorAuthenticatable;
use Laravel\Fortify\TwoFactorAuthenticatable;
class RedirectIfTwoFactorAuthenticatable extends DefaultRedirectIfTwoFactorAuthenticatable
{
/**
* Handle the incoming request.
*
* #param \Illuminate\Http\Request $request
* #param callable $next
* #return mixed
*/
public function handle($request, $next)
{
$user = $this->validateCredentials($request);
if (optional($user)->two_factor_secret &&
in_array(TwoFactorAuthenticatable::class, class_uses_recursive($user)) &&
$this->checkIfUserDeviceHasNotCookie($user)) {
return $this->twoFactorChallengeResponse($request, $user);
}
return $next($request);
}
/**
* This checks if the user's device has the cookie stored
* in the database.
*
* #param \App\Models\User\User $user
* #return bool
*/
protected function checkIfUserDeviceHasNotCookie($user)
{
$two_factor_cookies = json_decode($user->two_factor_cookies);
if (!is_array($two_factor_cookies)){
$two_factor_cookies = [];
}
$two_factor_cookie = \Cookie::get('2fa');
return !in_array($two_factor_cookie,$two_factor_cookies);
}
}
In the FortifyServiceProvider I have added a customized TwoFactorLoginResponse.
<?php
namespace App\Providers;
use App\Actions\Fortify\CreateNewUser;
use App\Actions\Fortify\ResetUserPassword;
use App\Actions\Fortify\UpdateUserPassword;
use App\Actions\Fortify\UpdateUserProfileInformation;
use App\Http\Responses\FailedPasswordResetLinkRequestResponse;
use App\Http\Responses\FailedPasswordResetResponse;
use App\Http\Responses\LockoutResponse;
use App\Http\Responses\LoginResponse;
use App\Http\Responses\LogoutResponse;
use App\Http\Responses\PasswordResetResponse;
use App\Http\Responses\RegisterResponse;
use App\Http\Responses\SuccessfulPasswordResetLinkRequestResponse;
use App\Http\Responses\TwoFactorLoginResponse;
use App\Http\Responses\VerifyEmail;
use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\ServiceProvider;
use Laravel\Fortify\Contracts\FailedPasswordResetLinkRequestResponse as FailedPasswordResetLinkRequestResponseContract;
use Laravel\Fortify\Contracts\FailedPasswordResetResponse as FailedPasswordResetResponseContract;
use Laravel\Fortify\Contracts\LockoutResponse as LockoutResponseContract;
use Laravel\Fortify\Contracts\LoginResponse as LoginResponseContract;
use Laravel\Fortify\Contracts\LogoutResponse as LogoutResponseContract;
use Laravel\Fortify\Contracts\PasswordResetResponse as PasswordResetResponseContract;
use Laravel\Fortify\Contracts\RegisterResponse as RegisterResponseContract;
use Laravel\Fortify\Contracts\SuccessfulPasswordResetLinkRequestResponse as SuccessfulPasswordResetLinkRequestResponseContract;
use Laravel\Fortify\Contracts\TwoFactorLoginResponse as TwoFactorLoginResponseContract;
use Laravel\Fortify\Fortify;
class FortifyServiceProvider extends ServiceProvider
{
/**
* Register any application services.
*
* #return void
*/
public function register()
{
$this->registerResponseBindings();
}
/**
* Register the response bindings.
*
* #return void
*/
protected function registerResponseBindings()
{
$this->app->singleton(LoginResponseContract::class, LoginResponse::class);
$this->app->singleton(LogoutResponseContract::class, LogoutResponse::class);
$this->app->singleton(TwoFactorLoginResponseContract::class, TwoFactorLoginResponse::class);
$this->app->singleton(RegisterResponseContract::class, RegisterResponse::class);
$this->app->singleton(LockoutResponseContract::class, LockoutResponse::class);
$this->app->singleton(SuccessfulPasswordResetLinkRequestResponseContract::class, SuccessfulPasswordResetLinkRequestResponse::class);
$this->app->singleton(FailedPasswordResetLinkRequestResponseContract::class, FailedPasswordResetLinkRequestResponse::class);
$this->app->singleton(PasswordResetResponseContract::class, PasswordResetResponse::class);
$this->app->singleton(FailedPasswordResetResponseContract::class, FailedPasswordResetResponse::class);
}
/**
* Bootstrap any application services.
*
* #return void
*/
public function boot()
{
Fortify::ignoreRoutes();
Fortify::loginView(function () {
return view('auth.login');
});
Fortify::twoFactorChallengeView('auth.two-factor-challenge');
Fortify::confirmPasswordView(function (Request $request) {
if ($request->ajax()) {
return view('auth.confirm-password-form');
} else {
return view('auth.confirm-password');
}
});
Fortify::requestPasswordResetLinkView(function () {
return view('auth.forgot-password');
});
Fortify::resetPasswordView(function ($request) {
return view('auth.reset-password', ['request' => $request,'token' => $request->route('token')]);
});
Fortify::registerView(function () {
return view('auth.register');
});
Fortify::verifyEmailView(function () {
return view('auth.verify');
});
Fortify::createUsersUsing(CreateNewUser::class);
Fortify::updateUserProfileInformationUsing(UpdateUserProfileInformation::class);
Fortify::updateUserPasswordsUsing(UpdateUserPassword::class);
Fortify::resetUserPasswordsUsing(ResetUserPassword::class);
/*RateLimiter::for('login', function (Request $request) {
return Limit::perMinute(5)->by($request->email.$request->ip());
});*/
RateLimiter::for('two-factor', function (Request $request) {
return Limit::perMinute(5)->by($request->session()->get('login.id'));
});
}
}
Finally, the TwoFactorLoginResponse:
<?php
namespace App\Http\Responses;
use Illuminate\Http\JsonResponse;
use Laravel\Fortify\Contracts\TwoFactorLoginResponse as TwoFactorLoginResponseContract;
class TwoFactorLoginResponse implements TwoFactorLoginResponseContract
{
/**
* Create an HTTP response that represents the object.
*
* #param \Illuminate\Http\Request $request
* #return \Symfony\Component\HttpFoundation\Response
*/
public function toResponse($request)
{
$user = \Auth::user();
$this->storeCookieIfNotInDB($user);
$role = $user->role;
if ($request->wantsJson()) {
return new JsonResponse('', 204);
}
if ($role == "0") {
return redirect()->route('user.home');
} else {
return redirect()->route('admin.home');
}
}
/**
* Store the cookie if it is not in the database.
*
* #param \App\Models\User\User $user
* #return void
*/
protected function storeCookieIfNotInDB($user)
{
$two_factor_cookies = json_decode($user->two_factor_cookies);
if (!is_array($two_factor_cookies)){
$two_factor_cookies = [];
}
$two_factor_cookie = \Cookie::get('2fa');
if (!in_array($two_factor_cookie,$two_factor_cookies)) {
$two_factor_cookie = md5(now());
$two_factor_cookies[] = $two_factor_cookie;
if (count($two_factor_cookies) > 3) {
array_shift($two_factor_cookies);
}
$user->two_factor_cookies = json_encode($two_factor_cookies);
$user->save();
$lifetime = 60 * 24 * 365; //one year
\Cookie::queue('2fa',$two_factor_cookie,$lifetime);
}
}
}
Upon login, it will look for the cookie 2fa. If its content is stored in the database, it will not be necessary to enter the code again. To prevent unlimited cookie content from being saved in the DB you can add a maximum limit (I have set it 3).
Thanks to Maarten Veerman for the inital help.
According to this line: https://github.com/laravel/fortify/blob/82c99b6999f7e89f402cfd7eb4074e619382b3b7/src/Http/Controllers/AuthenticatedSessionController.php#L80
you can create a pipelines.login entry in your fortify config file.
The solution would be to:
create the config entry
copy the pipeline setup in the above file, line 84.
create a custom AttemptToAuthenticate class, make sure the pipeline config points to your new class.
make the new class extend the default fortify AttemptToAuthenticate class.
overwrite the handle function, add your logic in the new function, where you check for a cookie on the device.

"Class 'Swift_Mailer' not found"

I got this error, but class Swift_Mailer exists in MailServiceProvider.php
"Class 'Swift_Mailer' not found" on line 95 of /home1/phloxmar/phloxcms/vendor/laravel/framework/src/Illuminate/Mail/MailServiceProvider.php
here's my MailServiceProvider.php
<?php
namespace Illuminate\Mail;
use Swift_Mailer;
use Illuminate\Support\Arr;
use Illuminate\Support\Str;
use Illuminate\Support\ServiceProvider;
class MailServiceProvider extends ServiceProvider
{
/**
* Indicates if loading of the provider is deferred.
*
* #var bool
*/
protected $defer = true;
/**
* Register the service provider.
*
* #return void
*/
public function register()
{
$this->registerSwiftMailer();
$this->registerIlluminateMailer();
$this->registerMarkdownRenderer();
}
/**
* Register the Illuminate mailer instance.
*
* #return void
*/
protected function registerIlluminateMailer()
{
$this->app->singleton('mailer', function ($app) {
$config = $app->make('config')->get('mail');
// Once we have create the mailer instance, we will set a container instance
// on the mailer. This allows us to resolve mailer classes via containers
// for maximum testability on said classes instead of passing Closures.
$mailer = new Mailer(
$app['view'], $app['swift.mailer'], $app['events']
);
if ($app->bound('queue')) {
$mailer->setQueue($app['queue']);
}
// Next we will set all of the global addresses on this mailer, which allows
// for easy unification of all "from" addresses as well as easy debugging
// of sent messages since they get be sent into a single email address.
foreach (['from', 'reply_to', 'to'] as $type) {
$this->setGlobalAddress($mailer, $config, $type);
}
return $mailer;
});
}
/**
* Set a global address on the mailer by type.
*
* #param \Illuminate\Mail\Mailer $mailer
* #param array $config
* #param string $type
* #return void
*/
protected function setGlobalAddress($mailer, array $config, $type)
{
$address = Arr::get($config, $type);
if (is_array($address) && isset($address['address'])) {
$mailer->{'always'.Str::studly($type)}($address['address'], $address['name']);
}
}
/**
* Register the Swift Mailer instance.
*
* #return void
*/
public function registerSwiftMailer()
{
$this->registerSwiftTransport();
// Once we have the transporter registered, we will register the actual Swift
// mailer instance, passing in the transport instances, which allows us to
// override this transporter instances during app start-up if necessary.
$this->app->singleton('swift.mailer', function ($app) {
return new Swift_Mailer($app['swift.transport']->driver());
});
}
/**
* Register the Swift Transport instance.
*
* #return void
*/
protected function registerSwiftTransport()
{
$this->app->singleton('swift.transport', function ($app) {
return new TransportManager($app);
});
}
/**
* Register the Markdown renderer instance.
*
* #return void
*/
protected function registerMarkdownRenderer()
{
if ($this->app->runningInConsole()) {
$this->publishes([
__DIR__.'/resources/views' => $this->app->resourcePath('views/vendor/mail'),
], 'laravel-mail');
}
$this->app->singleton(Markdown::class, function ($app) {
$config = $app->make('config');
return new Markdown($app->make('view'), [
'theme' => $config->get('mail.markdown.theme', 'default'),
'paths' => $config->get('mail.markdown.paths', []),
]);
});
}
/**
* Get the services provided by the provider.
*
* #return array
*/
public function provides()
{
return [
'mailer', 'swift.mailer', 'swift.transport', Markdown::class,
];
}
}
I already tried composer dumpautoload but error still exists.
Check if you are importing the class properly you should check in your autoload if you are requiring something like this:
require_once __DIR__.'/../vendor/swiftmailer/lib/classes/Swift.php';
Swift::registerAutoload(__DIR__.'/../vendor/swiftmailer/lib/swift_init.php');
If you do not have these try to add them and run
composer dump-autoload

How to disable laravel 5.2 password bcrypt

I want to disable the laravel password bcrypt when I try to log-in like this
Auth::guard('client')->attempt(
'id' => $request['id'],
'password' => $request['password'])
But it seems to be more dificult than I thought, I know I should not do this but I temporally need to work like this, but laravel forces me to use encrypted passwords. I need to be able to use plain passwords on my database.
I been searching on internet but I cant find a solution.
Try extending SessionGuard and overriding function hasValidCredentials()
Create A file by name 'SessionGuardExtended' in App\CoreExtensions
use Illuminate\Auth\SessionGuard;
use Illuminate\Contracts\Auth\Authenticatable;
class SessionGuardExtended extends SessionGuard
{
/**
* Determine if the user matches the credentials.
*
* #param mixed $user
* #param array $credentials
* #return bool
*/
protected function hasValidCredentials($user, $credentials)
{
return ! is_null($user) && $credentials['password'] == $user->getAuthPassword();
}
}
Edit config/auth.php edit the driver and use sessionExtended
'web' => [
'driver' => 'sessionExtended',
'provider' => 'users',
],
In AppServiceProvider Write Code in boot function
/**
* Bootstrap any application services.
*
* #return void
*/
public function boot()
{
Auth::extend(
'sessionExtended',
function ($app) {
$provider = new EloquentUserProvider($app['hash'], config('auth.providers.users.model'));
return new SessionGuardExtended('sessionExtended', $provider, app()->make('session.store'), request());
}
);
}
Reference: Extending Laravel 5.2 SessionGuard
You can extend Illuminate\Auth\EloquentUserProvider, ie:
<?php
namespace App\Services\Auth;
use Illuminate\Auth\EloquentUserProvider as BaseUserProvider;
use Illuminate\Contracts\Auth\Authenticatable as UserContract;
class UserProvider extends BaseUserProvider {
/**
* Create a new database user provider.
*
* #param string $model
*
* #return void
*/
public function __construct($model)
{
$this->model = $model;
}
/**
* Validate a user against the given credentials.
*
* #param \Illuminate\Contracts\Auth\Authenticatable $user
* #param array $credentials
*
* #return bool
*/
public function validateCredentials(UserContract $user, array $credentials)
{
$plain = $credentials['password'];
// $matches = some method of matching $plain with $user->getAuthPassword();
return $matches;
}
}
Then register this in the IoC in a service provider like so:
<?php // ...
/**
* Register the service provider.
*
* #return void
*/
public function register()
{
// ...
$this->app['auth']->extend(
'legacy',
function () {
return new \Illuminate\Auth\Guard(
new \App\Services\Auth\UserProvider(
$this->app['config']['auth.model']
),
$this->app['session.store']
);
}
);
// ...
}
Then set your current driver to legacy in config/auth.php.
PS: You may want to include the classes in the provider,
You can use
Auth::guard('client')->login($user);
In this $user is an instance of Model which is implemented Illuminate\Contracts\Auth\Authenticatable contract.
In user model it is already implemented.
Maybe it will helpful

Laravel5 extend Facade

I want to extend Laravel5 Cookies functionality.
I want to make it this way:
I will create file App\Support\Facades\Cookie.php and than file App\Libraries\CookieJar.php. In app.php I will change row for Cookie to this:
'Cookie' => 'App\Support\Facades\Cookie',
Anyway, when I try to use it like this:
Cookie::test()
it returns:
Call to undefined method Illuminate\Cookie\CookieJar::test()
Do you have any idea, why it do this? And is the way, how I want to extend Cookie functionality good?
Thank you for your help.
Here is content of files:
Cookie.php:
<?php namespace App\Support\Facades;
/**
* #see \App\Libraries\CookieJar
*/
class Cookie extends \Illuminate\Support\Facades\Facade
{
/**
* Determine if a cookie exists on the request.
*
* #param string $key
* #return bool
*/
public static function has($key)
{
return !is_null(static::$app['request']->cookie($key, null));
}
/**
* Retrieve a cookie from the request.
*
* #param string $key
* #param mixed $default
* #return string
*/
public static function get($key = null, $default = null)
{
return static::$app['request']->cookie($key, $default);
}
/**
* Get the registered name of the component.
*
* #return string
*/
protected static function getFacadeAccessor()
{
return 'cookie';
}
}
CookieJar.php:
<?php namespace App\Libraries;
class CookieJar extends \Illuminate\Cookie\CookieJar
{
public function test() {
return 'shit';
}
}
The class with all your new cookie functions need to extend Illuminate\CookieJar\CookieJar
<?php
namespace App\Support\Cookie;
class CookieJar extends \Illuminate\Cookie\CookieJar
{
/**
* Determine if a cookie exists on the request.
*
* #param string $key
* #return bool
*/
public static function has($key)
{
return !is_null(static::$app['request']->cookie($key, null));
}
/**
* Retrieve a cookie from the request.
*
* #param string $key
* #param mixed $default
* #return string
*/
public static function get($key = null, $default = null)
{
return static::$app['request']->cookie($key, $default);
}
}
Then make a new facade:
namespace App\Support\Facades;
class CookieFacade extends \Illuminate\Support\Facades\Facade
{
protected static function getFacadeAccessor()
{
/*
* You can't call it cookie or else it will clash with
* the original cookie class in the container.
*/
return 'NewCookie';
}
}
Now bing it in the container:
$this->app->bind("NewCookie", function() {
$this->app->make("App\\Support\\Cookie\\CookieJar");
});
Finally add the alias in your app.php config:
'NewCookie' => App\Support\Facades\CookieFacade::class
Now you can use NewCookie::get('cookie') and NewCookie::has('cookie').
I hope this helps.

Laravel 4 - Extend Pagination Class

Is there a way to extend the Pagination Class of Laravel 4 ?
I tried some things but nothing good...
I'm here :
PaginationServiceProvider.php
class PaginationServiceProvider extends \Illuminate\Pagination\PaginationServiceProvider {
/**
* Indicates if loading of the provider is deferred.
* #var bool
*/
protected $defer = false;
/**
* Bootstrap the application events.
* #return void
*/
public function boot(){
$this->package('thujohn/pagination');
}
/**
* Register the service provider.
* #return void
*/
public function register(){
$this->app['paginator'] = $this->app->share(function($app){
$paginator = new Environment($app['request'], $app['view'], $app['translator']);
$paginator->setViewName($app['config']['view.pagination']);
return $paginator;
});
}
/**
* Get the services provided by the provider.
* #return array
*/
public function provides(){
return array();
}
}
Environment.php
class Environment extends \Illuminate\Pagination\Environment {
public function hello(){
return 'hello';
}
}
I replaced 'Illuminate\Pagination\PaginationServiceProvider', by 'Thujohn\Pagination\PaginationServiceProvider',
When I call $test->links() it's ok
When I call $test->hello() it fails
When I call Paginator::hello() it's ok
Any idea ?
Everyting is fine except that Paginator::make() returns Paginator instance, not Environment.
You should move Your method to Paginator class.
Today I've posted on GH my extension for Paginator. You can check it as a reference desmart/pagination

Resources