By default Laravel Vapor requires the user be authenticated to perform an upload. I need to allow an unauthenticated perform an upload. How can I do this?
Thanks
I think if you add something like this in your UserPolicy, vapor should work
public function before($user)
{
if (Auth::guest()) {
return true;
}
}
We handled this by overriding the default vapor/signed-storage-url route's handling.
In routes/web.php.
Route::post('vapor/signed-storage-url', [Controllers\SignedStorageUrlController::class, 'store']);
In our SignedStorageUrlController, we use the store function with this check removed:
Gate::authorize('uploadFiles', [
$request->user(),
$bucket = $request->input('bucket') ?: $_ENV['AWS_BUCKET'],
]);
resulting in:
<?php
namespace App\Http\Controllers;
use Illuminate\Support\Str;
use Illuminate\Http\Request;
use Laravel\Vapor\Http\Controllers\SignedStorageUrlController as VaporSignedStorageUrlController;
class SignedStorageUrlController extends VaporSignedStorageUrlController
{
public function store(Request $request)
{
$this->ensureEnvironmentVariablesAreAvailable($request);
$bucket = $request->input('bucket') ?: $_ENV['AWS_BUCKET'];
$client = $this->storageClient();
$uuid = (string) Str::uuid();
$signedRequest = $client->createPresignedRequest(
$this->createCommand($request, $client, $bucket, $key = ('tmp/'.$uuid)),
'+5 minutes'
);
$uri = $signedRequest->getUri();
return response()->json([
'uuid' => $uuid,
'bucket' => $bucket,
'key' => $key,
'url' => 'https://'.$uri->getHost().$uri->getPath().'?'.$uri->getQuery(),
'headers' => $this->headers($request, $signedRequest),
], 201);
}
}
Related
I'm trying to make a register page with role as a radio button(consumer, supplier, Admin)
but it show me this error when I test the query in postman
Error: Class "App\Http\Models\Role" not found in file
my controller:
public function register(Request $request)
{
$request->validate([
'first_name'=>'required|string',
'last_name'=>'required|string',
'email'=>'required|string|unique:users',
'password'=>'required|string|min:6',
'phone_number'=>'required|string|min:10',
'role_name'=>'required|string'
]);
$role_a = $request->role_name;
if ($role_a == 'صاحب متجر'){
$role=Role::select('role_id')->where('role_name','صاحب متجر')->first();
$user->roles()->attach($role);
return response()->json($user);
}
elseif ($role_a == 'مشتري'){
$role=Role::select('role_id')->where('role_name','مشتري')->first();
$user->roles()->attach($role);
return response()->json($user);
}
$user=User::create([
'first_name' => $request->first_name,
'last_name' => $request->last_name,
'email' => $request->email,
'password' => Hash::make($request->password),
'phone_number' => $request->phone_number,
]);
And my use statement:
use Illuminate\Http\Request;
use App\Http\Models\User;
use App\Http\Models\Role;
use Illuminate\Support\Facades\Hash;
And my route:
Route::post('/register','App\Http\Controllers\AuthController#register');
and this what I have in tables:
Note: I didn't use custom packages like spatie for example
Thank you for trying to help!
You miss adding the Request class as an argument into your method. Your method should look like this:
public function register(Request $request)
{
//after validation
$data = $request->validated();
}
Dont forget to add use Illuminate\Http\Request; in your use statement.
Let's take an example.
https://www.example.net/xyz?page=2
Route File
Route::get('/xyz', 'controller#getpages');
Controller
public function getpages(Request $request) {
dd($request->all());
}
Showing result as
array:1 [▼
"/xyz" => null
]
instead of
array:1 [▼
"page" => "2"
]
try:
public function getpages(Request $request) {
print_r($request->page);
}
Also make sure you use : use Illuminate\Http\Request;
try
$query = $request->query();
$page = $request->query('page');
In your code there is a mistake. you missed $ symbol
public function getpages(Request $request) {
dd($request->all());
}
use Illuminate\Http\Request;
use App\Http\Requests;
public function getpages(Request $request) {
$request = $request->only('page');
dd($request);
}
There is no array. just only one parameter "$page"
Try below code:
This is user register controller:
use Illuminate\Http\Request;
use App\User;
public function register(Request $request){
$data = $this->validate($request, [
'name' => 'required',
'email' => 'required|email|unique:users',
'password' => 'required'
]);
$data['password'] = app('hash')->make($data['password']);
User::create($data);
$credentials = $request->only('email', 'password');
if ($token = $this->guard()->attempt($credentials)) {
return $this->respondWithToken($token);
}
return response()->json(['error' => 'Unauthorized'], 401);
}
The Problem was in .htaccess file, so i retrieve the old .htaccess and putted it.
I am using Laravel for my application and I am trying to redirect to contact page after an email form. The email is sent to my mailtrap successfully though.
I have to use the "return view('contact')" rather than use redirect instance.
I want to use redirect but everytime i use the redirect instance i get an error:
Method Illuminate\Routing\Redirector::url does not exist.
My code is as below:
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use App\Http\Requests;
use Session;
use Mail;
class PagesController extends Controller{
public function getIndex(){
return view('welcome');
}
public function getAbout() {
return view('about');
}
public function getContact() {
return view('contact');
}
public function postContact(Request $request) {
$data = [];
$this->validate($request, [
'email' => 'required|email',
'subject' => 'min:3',
'message' => 'min:10']);
$data = array(
'email' => $request->email,
'subject' => $request->subject,
'bodyMessage' => $request->message
);
Mail::send('emails.contact', $data, function($message) use
($data){
$message->from($data['email']);
$message->to('zulfadhli.tom#gmail.com');
$message->subject($data['subject']);
});
Session::flash('success', 'Your email is successfully sent!');
return redirect()->url('/');
}
}
use
public function postContact(Request $request) {
...
return redirect('/')->with('success', 'Your email is successfully sent!');
}
read more here : https://itsolutionstuff.com/post/laravel-5-redirect-to-url-using-redirect-helperexample.html
If you are sending the user back to the page (contact page) then you may want to use this:
return redirect()->back()->with('success', 'Your email is successfully sent!');
The first auth system works very fine its code is below and needed to have to different users using two different tables am using laravel 5.5
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\User;
use Illuminate\Support\Facades\Auth;
class StudentController extends Controller
{
public function Register(Request $request)
{
$firstname = $request['firstname'];
$othername = $request['othername'];
$email = $request['email'];
$password = $request['password'];
$user = new User();
$user->firstname = $firstname;
$user->othername = $othername;
$user->email = $email;
$user->password = $password;
$user->save();
Auth::login($user);
return redirect()->route('studentDashboard');
}
public function Login(Request $request)
{
if(Auth::attempt(['email'=> $request['email'], 'password'=>
$request['password']]))
{
return redirect()->route('studentDashboard');
}
return redirect()->back();
}
}
i duplicated the above to create auth for a different user.The registration works but the login does not work even if the login data is right it returns the redirect back after the if statement
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Employer;
use Illuminate\Support\Facades\Auth;
class EmployerController extends Controller
{
public function createEmployerAccount(Request $request)
{
$companyName = $request['companyname'];
$companyEmail = $request['email'];
$companyPasword = $request['password'];
$Employer = new Employer();
$Employer->companyname = $companyName;
$Employer->email = $companyEmail;
$Employer->password = $companyPasword;
$Employer->save();
Auth::login($Employer);
return redirect()->route('employersDashboard');
}
public function signInEmployer(Request $request)
{
if(Auth::attempt(['email'=>$request['email'],
'password'=>$request['password']]))
{
return redirect()->route('employersDashboard');
}
return redirect()->back();
}
}
when i try to change the 'email' to 'emails' an error is shown->the select query is from the users table not employers table that i need to get data from and also when i change 'password' to 'passwords' an error "undefined index password" is shown
this is the route file content
Route::get('/',function(){
return view('pages.index');
})->name('home');
Route::post('/signup',[
'uses'=>'StudentController#Register',
'as'=> 'signup'
]);
Route::post('/signin',[
'uses'=>'StudentController#Login',
'as'=>'signin'
]);
Route::get('/employers',[
'uses'=>'PageController#employersPage',
'as'=>'employers'
]);
Route::get('/studentDashboard',[
'uses'=>'PageController#getStudentDashboard',
'as'=> 'studentDashboard'
]);
Route::post('/createcompany',[
'uses'=>'EmployerController#createEmployerAccount',
'as'=>'createcompany'
]);
Route::post('/signInEmployer',[
'uses'=>'EmployerController#signInEmployer',
'as'=>'signInEmployer'
]);
Route::get('/employersDashboard',[
'uses'=>'PageController#getEmployersDashboard',
'as'=> 'employersDashboard',
'middleware'=>'auth:employer'
]);
Route::post('/createPost',[
'uses'=>'PostController#postCreatePost',
'as'=> 'createPost'
]);
You need to tell Auth to use different Guard for authentication at time of Employer login. To define guards for Employer change like this in your config/auth.php.
Look for guards section in auth.php and add your new guard
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'employer' => [
'driver' => 'session',
'provider' => 'employers',
],
'api' => [
'driver' => 'passport',
'provider' => 'users',
],
],
Now in the same file there is a providers section. You need to add employers provider
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\Models\User::class,
],
//Employer provider
'employers' => [
'driver' => 'eloquent',
'model' => App\Employer::class,
],
],
Create a custom Auth middleware
namespace App\Http\Middleware;
use Closure;
use Auth;
class AuthenticateEmployer
{
public function handle($request, Closure $next)
{
//If request does not comes from logged in employer
//then he shall be redirected to employer Login page
if (!Auth::guard('employer')->check()) {
return redirect('/signInEmployer');
}
return $next($request);
}
}
Register custom auth middleware in Kernal.php in routeMiddleware
'employerAuth' => \App\Http\Middleware\AuthenticateEmployer::class,
Now we have setup our custom guard and custom middleware employerAuth
EmployerController
class EmployerController extends Controller
{
//either you have to define this or you can use `Auth::guard('employer')->attempt($credentials)` in login
protected function guard()
{
return Auth::guard('employer');
}
public function signInEmployer(Request $request)
{
if(Auth::attempt(['email'=>$request['email'],
'password'=>$request['password']]))
{
return redirect()->route('employersDashboard');
}
return redirect()->back();
}
}
For all the routes protected by Employer auth, you either need to add middleware employerAuth in routes or add employerAuth in each controller construct like this
public function __construct()
{
$this->middleware('employerAuth');
}
Hope it may help you. For details you can check this https://laravel.com/docs/5.6/authentication#authenticating-users
Check this nice sample app for multi auth application https://github.com/yskoverride/Various2.0/tree/master/app
I have installed socialite package in my application but its not working properly.
In my login with linkedin button i have given url like below
href="{{ url('auth/linkedin') }}"
My route file is
Route::get('auth/linkedin', 'LinkedInController#redirectToLinkedin');
Route::get('/linkedin/callback', 'LinkedInController#handleLinkedinCallback');
LinkedInController.php is
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\User;
use Validator;
use App\Http\Controllers\Controller;
use Auth;
use Socialite;
use Exception;
class LinkedInController extends Controller {
protected $redirectTo = '/';
//use Illuminate\Foundation\Auth\AuthenticatesUsers;
public function __construct()
{
//$this->middleware('guest', ['except' => 'logout']);
}
protected function validator(array $data) {
return Validator::make($data, [
'name' => 'required|max:255',
'email' => 'required|email|max:255|unique:users',
'password' => 'required|confirmed|min:6',
]);
}
protected function create(array $data) {
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
]);
}
public function redirectToLinkedin() {
return Socialite::driver('linkedin')->redirect();
}
public function handleLinkedinCallback() {
try {
$user = Socialite::driver('linkedin')->user();
$create['name'] = $user->name;
$create['email'] = $user->email;
$create['linkedin_id'] = $user->id;
$userModel = new User;
$createdUser = $userModel->addNew($create);
Auth::loginUsingId($createdUser->id);
return redirect('/index');
} catch (Exception $e) {
return redirect('auth/linkedin');
}
}
}
After i clicking login with linkedin it will comes to redirectToLinkedin() function but i got error like
This page isn’t working
localhost redirected you too many times.
Try clearing your cookies.
ERR_TOO_MANY_REDIRECTS
Whats a problem with my code?