Laravel Socialite initiate credentials - laravel

I would like to integrate Socialite in a Laravel based CMS and I try to figure out how would I initiate Socialite to send requests if client_id and client secret are saved in database?
from the docs basic usage
return Socialize::with('github')->redirect();
and credentials are saved in config/services.php
/**
* Create an instance of the specified driver.
*
* #return \Laravel\Socialite\Two\AbstractProvider
*/
protected function createGithubDriver()
{
$config = $this->app['config']['services.github'];
return $this->buildProvider(
'Laravel\Socialite\Two\GithubProvider', $config
);
}
I would like to define $this->app['config'] on Factory calling

can you not just create a middleware class, apply it to the relevant route then just set the Config using:
$v = Auth::user()->github // or however you work it out, not sure how you've got it stored
Config::set('services.github', $v);
Setting config like this sets it for the current request only

Related

Laravel 7 force user to enter password

I want to know how can I force user to re-enter his password on certain route action?
Let say if user wants to edit product before save process happens he has to input his password and if it was correct then saving is allowed.
Is there any default middleware for password in laravel 7? or should i make myself?
What do you suggest?
Update
I've found this but it's only work on web routes, i need same thing to work on API routes.
Problem with this middleware is that it except sessions which is only available on web middlewares. I tried to add \Illuminate\Session\Middleware\StartSession::class, into api middleware but still getting this error
RuntimeException: Session store not set on request.
Why not just rewrite shouldConfirmPassword() method?
Session is only used to check when was the password confirmed at. If you are requiring password confirmation every time, just rewrite the method to return true:
/**
* Determine if the confirmation timeout has expired.
*
* #param \Illuminate\Http\Request $request
* #return bool
*/
protected function shouldConfirmPassword($request)
{
return true;
//$confirmedAt = time() - $request->session()->get('auth.password_confirmed_at', 0);
//return $confirmedAt > config('auth.password_timeout', 10800);
}
For those who stumble on this, the solution is setting config('password_timeout') to 1 i.e 1 second.
'password_timeout' => 1,
You might think that setting it to 0 should work but it doesn't and that's because of this line in the constructor of the Illuminate\Auth\Middleware\RequirePassword class
$this->passwordTimeout = $passwordTimeout ?: 10800;
which defaults $this->passwordTimeout to 3 hours when config('password_timeout') is not set (null) or 0.
The RequirePassword middleware is being bound to the application container in the registerRequirePassword method of the Illuminate\Auth\AuthServiceProvider class

Dynamic Configuration with Laravel Horizon

I am trying to change the mail driver's username and password on the fly like the following.
/**
* Execute the job.
*
* #return void
*/
public function handle()
{
config(['mail.username' => $this->username]);
config(['mail.password' => $this->password]);
Mail::to('me#me.com')->send(new OrderShipped());
}
The dynamic config setting was inside the queue job. For queue processing, I am using the Laravel horizon. But, when I execute the queue job. It's still using the default config. Not the config I set dynamically.
Note: when I log right after config set it was showing the dynamic value.
How can I set the config dynamically and make Laravel horizon to use dynamic configuration?
From Laravel version 7.x onwards you can now state the mail driver to use while sending an email. All you need to configure all your connections & credentials properly in app/config/mail.php. Once configured, you can specify the name of the driver via mailer() function as below:
Mail::mailer('postmark')
->to($request->user())
->send(new OrderShipped($order));
public function handle()
{
config([
'mail.username' => $this->username,
'mail.password' => $this->password,
]);
}
I did it like that. I think the important part is that you get the data you will use in the Job class from outside.
public function __construct($username,$password)
{
$this->username= $username;
$this->receiver = $password;
}

Authentication check for non auth url in laravel passport api

i am using passport authentication for my Laravel 5.4 API.here i have a api for company details and it is a non auth api.i need to check logined user liked this company using auth in this url ...how i can do this.
This is my route
Route::get('/company/{company}','Api\V1\CompanyController#show');
Route::group(['middleware' => 'auth:api','prefix'=>'v1'], function(){
//auth urls
}
and this is my controller
class CompanyController extends Controller
{
public function show(Company $company,Request $request)
{
$data = array();
$flag = 0;
$data['status'] = 1;
$data['message'] = 'success';
$data['baseUrl'] = url('/');
$data['is_login'] = Auth::check();
Here is_login always return false,if i added autherization token in headers of api.
What is your default guard set as?
Auth::check() is Auth::guard(null)->check() which uses the current default guard.
If you want to check for an api you probably want to use the api guard just like your auth middleware is using when you use auth:api.
Auth::guard('api')->check() tells it to explicitly use the api guard instead of what the default is, which could be anything since we don't know what you have set.
When the auth middleware is ran it actually will set the default guard for you depending upon what guards are passed to it and which one it can resolve a user from. Which is why you can just call Auth::user() and get the correct user from the correct guard, because the middleware sets the current to the one that resolved the user. (When calling routes that have this middleware)

Laravel - Making Routes in file other than web.php

Making routes of various pages of a website in web.php makes it bulky and unstructured. So my question is is there any way to save it in separate files?
// Calling Registration function
Route::any('/admin-store','AdminUserController#store')->name('admin-reg');
// Redirecting to Registration page
Route::get('/admin-registration','AdminUserController#index')->name('admin-registration');
// Redirecting to login page
Route::get('/admin-login','AdminLoginController#index')->name('admin-login');
// Redirecting to Admin Profile Page
Route::get('/admin-profile','AdminProfileController#index')->name('admin-profile');
// Calling Login function
Route::post('admin-login-result','AdminLoginController#login')->name('admin-log');
// Calling Function to Update Profile
Route::post('admin-edit-profile','AdminEditController#updateProfile')
->name('admin-edit-profile');
// Redirecting to Profile Edit page
Route::get('/admin-edit-profile','AdminEditController#index')->name('admin-edit');
Short answer
Yes, you can store routes in different files.
Expanded answer
1 - Create your new Route file
Create your new route file, for this example I'll name it users.php and store there the related routes:
routes/users.php
Route::get('/my-fancy-route', 'MyCoolController#anAwesomeFunction');
// and the rest of your code.
2 - Add your route file to the RouteServiceProvider
Add here a new method, i'll call it mapUserRoutes:
app/Providers/RouteServiceProvider.php
/**
* Define the User routes of the application.
*
*
* #return void
*/
protected function mapUserRoutes()
{
Route::prefix('v1') // if you need to specify a route prefix
->middleware('auth:api') // specify here your middlewares
->namespace($this->namespace) // leave it as is
/** the name of your route goes here: */
->group(base_path('routes/users.php'));
}
3 - Add it to the map() method
In the same file(RouteServiceProvider.php), go to the top and add your new method inside the map() function:
/**
* Define the routes for the application.
*
* #return void
*/
public function map()
{
// some other mapping actions
$this->mapUserRoutes();
}
4 - Final steps
I'm not fully sure if this is neccesary but never hurts to do:
Stop your server (if runing)
do php artisan config:clear
Start your server.

Dynamic middleware for laravel 5

While building multi-tenancy packages for Laravel 5 I had to find out how to add middleware dynamically from code. In comparison to this question on SO I do not want to touch the Http/Kernel definitions.
During application initialization I check whether the requested hostname is known in the database and whether this hostname requires a redirect to a primary hostname or ssl.
Because you don't want to touch the Http/Kernel as a package, we need to use the service provider.
Requirements:
dynamically add middleware without touching Http/Kernel
use service provider and response object instead of "hacks"
The solution is to dynamically register the middleware in the kernel. First write your middleware, for instance:
<?php namespace HynMe\MultiTenant\Middleware;
use App;
use Closure;
use Illuminate\Contracts\Routing\Middleware;
class HostnameMiddleware implements Middleware
{
public function handle($request, Closure $next)
{
/* #var \HynMe\MultiTenant\Models\Hostname */
$hostname = App::make('HynMe\Tenant\Hostname');
if(!is_null($redirect = $hostname->redirectActionRequired()))
return $redirect;
return $next($request);
}
}
Now in your service provider use the following code in the boot() method to add this middleware to the Kernel:
$this->app->make('Illuminate\Contracts\Http\Kernel')->prependMiddleware('HynMe\MultiTenant\Middleware\HostnameMiddleware');
To answer what redirectActionRequired() method does in the hostname object:
/**
* Identifies whether a redirect is required for this hostname
* #return \Illuminate\Http\RedirectResponse|null
*/
public function redirectActionRequired()
{
// force to new hostname
if($this->redirect_to)
return $this->redirectToHostname->redirectActionRequired();
// #todo also add ssl check once ssl certificates are support
if($this->prefer_https && !Request::secure())
return redirect()->secure(Request::path());
// if default hostname is loaded and this is not the default hostname
if(Request::getHttpHost() != $this->hostname)
return redirect()->away("http://{$this->hostname}/" . (Request::path() == '/' ? null : Request::path()));
return null;
}
If you need to dynamically register routeMiddleware use the following in your service provider;
$this->app['router']->middleware('shortname', Vendor\Some\Class::class);
Please add comments if you have questions about this implementation.

Resources