Laravel RESTful and multi-subdomain - laravel

there are 2 sumbdomains in my laravel app. One api another storage. I login by api.exm.com/login but when I want to sotre a file by storage.exm.com/image I get 403. How can I solve it?
Here is a section of my RouteServiceProvider:
protected function mapApiRoutes()
{
Route::middleware(['api', 'return.json'])
->domain(subdomain(env('API_SUBDOMAIN', 'api')))
->namespace($this->namespace . '\Api')
->group(base_path('routes/api.php'));
}
protected function mapStorageRoutes()
{
Route::middleware(['api', 'return.json'])
->domain(subdomain(env('STORAGE_SUBDOMAIN', 'storage')))
->namespace($this->namespace . '\Storage')
->group(base_path('routes/storage.php'));
}

I found my problem. My authorize function in StoreImageRequest always returned false. :))
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return false;
}

Related

Custom Guard Authentication Exception

I created a custom guard (admin) in my application, and everything looks good following this tutorial online (https://pusher.com/tutorials/multiple-authentication-guards-laravel). The only problem is when i try to access a view that is protected by the admin guard, instead of giving me a exception NotAuthenticate, is giving me a "InvalidArgumentException
Route [login] not defined.".
My Dashboard controller custom guard is:
public function __construct()
{
$this->middleware('auth:admin');
}
But the strange thing that i cant understand whats going on is that when i add in my web.php routes the "Auth::routes();", it works fine, the Exception NotAuthenticate gets fired.
Is there a reason why my custom only works has expected with i add the Auth::routes() ?
Admin Login Controller:
namespace App\Http\Controllers\Admin\Auth;
use Auth;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Validation\ValidationException;
class LoginController extends Controller
{
use AuthenticatesUsers;
/**
* Where to redirect users after login.
*
* #var string
*/
protected $redirectTo = '/admin/dashboard';
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest:admin')->except('logout');
}
public function login(Request $request)
{
$this->validateLogin($request);
// If the class is using the ThrottlesLogins trait, we can automatically throttle
// the login attempts for this application. We'll key this by the username and
// the IP address of the client making these requests into this application.
if ($this->hasTooManyLoginAttempts($request)) {
$this->fireLockoutEvent($request);
return $this->sendLockoutResponse($request);
}
if ($this->attemptLogin($request)) {
return $this->sendLoginResponse($request);
}
// If the login attempt was unsuccessful we will increment the number of attempts
// to login and redirect the user back to the login form. Of course, when this
// user surpasses their maximum number of attempts they will get locked out.
$this->incrementLoginAttempts($request);
return $this->sendFailedLoginResponse($request);
}
public function showLoginForm()
{
return view('admin.auth.login');
}
/**
* Log the user out of the application.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function logout(Request $request)
{
$this->guard()->logout();
$request->session()->invalidate();
return $this->loggedOut($request) ?: redirect('/admin');
}
/**
* Get the guard to be used during authentication.
*
* #return \Illuminate\Contracts\Auth\StatefulGuard
*/
protected function guard()
{
return Auth::guard('admin');
}
}
Try following the following tutorial, it did the trick for me.
On a side note: Avoid modifying the existing controller that laravel ships with, instead extend it and implement your own functionality. This practice will take you the long way.
https://www.codementor.io/okoroaforchukwuemeka/9-tips-to-set-up-multiple-authentication-in-laravel-ak3gtwjvt

Download file with php after login with php code

i have two links
one for login (www.xxx/login/)
one for download file (www.xxx/download/)
if already login, link to www.xxx/download/ will download file automatically,
if not the page will redirect to www.xxx/login/
So how can i write the php code? to login first then go to download file
If you are working on Laravel provided login functionality then this is default provided by Laravel.
You can check this here
Illuminate\Foundation\Auth\AuthenticatesUsers
This is the trait and check function sendLoginResponse. Below is the code written in sendLoginResponse function:-
/**
* Send the response after the user was authenticated.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
protected function sendLoginResponse(Request $request)
{
$request->session()->regenerate();
$this->clearLoginAttempts($request);
return $this->authenticated($request, $this->guard()->user())
?: redirect()->intended($this->redirectPath());
}
If you are using custom login functionality follow this.
you just need the middleware
so add the _construct method in top of controller
public function __construct()
{
$this->middleware('auth');
}
public function dowloadMethod($fileName)
{
//your code
}
if You are using the Closure method in route
Route::get('YourdowloadUrl/{fileName}',function($fileName)
{
//yourcode goesrhere
}
)->middleware(['web', 'auth']);

Laravel Nova only access from specific guard

In NovaServiceProvider there is:
protected function gate()
{
Gate::define('viewNova', function ($user) {
return in_array($user->email, [
'example#example.com',
]);
});
}
But what I would like to do is only allow people from the admins guard that I've setup in config/auth to access Nova. All users from the web guard should ideally get a 404 when they access any Nova URL.
This question for Telescope seems to be similar, but I can't seem to figure out where I should define this, and how to generate a 404 for the web guard.
A question that is probably related: what does viewNova in the gate method actually mean?
Can I define that specific action for a specific guard in config/auth? (I think I've seen this somewhere but can't seem to find it)?
There doesn't seem to be a Policy written for Nova?
Checkout vendor/laravel/nova/src/NovaApplicationServiceProvider.php. It has a method called authorization:
/**
* Configure the Nova authorization services.
*
* #return void
*/
protected function authorization()
{
$this->gate();
Nova::auth(function ($request) {
return app()->environment('local') ||
Gate::check('viewNova', [$request->user()]);
});
}
If the environment was local, it allows everyone to access the panel, but if the environment was something else, it checks for the definition on viewNova method and it passes the $request->user() to it.
In the same file, there's gate() method which defined viewNova:
/**
* Register the Nova gate.
*
* This gate determines who can access Nova in non-local environments.
*
* #return void
*/
protected function gate()
{
Gate::define('viewNova', function ($user) {
return in_array($user->email, [
//
]);
});
}
Basically, this method does nothing. You can implement it in app/Providers/NovaServiceProvider.php (which is the default implementation you see in the file and you've mentioned). In your case, you could implement it this way:
/**
* Register the Nova gate.
*
* This gate determines who can access Nova in non-local environments.
*
* #return void
*/
protected function gate()
{
Gate::define('viewNova', function ($user) {
Auth::guard('admin')->check();
});
}
It returns true if the currently authenticated user is in admin guard. Hope I could answer all your questions.

laravel 5.5. how to response a redirect from a action, not the route action

I want to check the auth before run the action. if the user deny, I will response the 403 status.
I use the method function in the __construct to check .
the code is following.
The User Controller:
public function __construct()
{
if (!app()->runningInConsole()) {
$beforeMethod = \Route::getCurrentRoute()->getActionMethod()."before";
if (method_exists($this, $beforeMethod)) {
return $this->$beforeMethod();
}
}
}
/**
* Edit interface.
*
* #param $id
* #return Content
*/
public function edit($id)
{
return "success";
}
/**
* Check user Auth
*
* #return \Illuminate\Http\RedirectResponse
*/
public function editBefore()
{
$id = \request()->route('user');
if (Gate::denies('edit', User::find($id))) {
return redirect("login");
}
}
the above code, don't return to the login.
what code should I use to achieve my purpose? Thanks!
You're really close to what I would do. I would use Policies.
You can add these to the routes or route groups so that you can check the policy before it hits the controller method whatsoever.
Create a new policy class that looks something like:
class UserPolicy
{
public function canEdit(User $user) // this user is the logged in user
{
// Here you return true or false depending on whether they can edit or not.
return $user->isAllowedToEdit();
}
}
Then you make sure the policy is added to AuthServiceProvider.php:
public function boot(GateContract $gate)
{
$gate->define('user.edit', UserPolicy::class.'#canEdit');
// Additional policies
}
Then make sure to add can to your $routeMiddleware in the Kernel.php:
protected $routeMiddleware = [
// other middleware
'can' => \Illuminate\Auth\Middleware\Authorize::class,
];
Finally, you can add it to your route making sure that you use the same name you defined in the AuthServiceProvider:
Route::get('/user/edit')
->uses('UserController#edit')
->middleware('can:user.edit');
I personally like doing it this way because it cleans up the controllers and lets the policies do all the work "behind the scenes". Even better, you can then use that same users.edit policy for multiple routes.

getting err_too_many_redirects in laravel when I use Request for validation for validating unique

it is my error page
I have used customize Request page for geting value from post request.
in that request I am validating
namespace App\Http\Requests;
use App\Http\Requests\Request;
class TaxclassRequest extends Request
{
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return [
"tax_class"=>'unique:taxes,tax_class'
];
}
}
and my controller is
function insert(TaxclassRequest $request)
{
$n=$request->input('number'); //total number of variable that has been created dyanamic
$tax_class=$request->input("tax_class"); // tax_class
.
.
.
other code
I am getting error
ERR_TOO_MANY_REDIRECTS

Resources