prevent users from unauthorized access of web pages - php

How can I prevent the users to access my web pages via url browsing. I mean I need to check whether the user is logged in before accessing any web pages. The application should not allow to access the page to user just by url.
Shall I have to check in every controller for authentication or is there any other way?
Suppose I have a controller DistributorController. Now the methods inside this controllers are,
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Session;
use App\Distributor;
class DistributorController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
//
}
function fetchData()
{
$distributors = Distributor::all()->toArray();
return compact('distributors');
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
return view('pages.distributors', $this->fetchData());
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
try{
// code block
}
catch (\Exception $e) {
// code block
}
}
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function edit($id)
{
//
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
//
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy($id)
{
//
}
}

In your web.php file where you define the routes, you can group the routes and surround them using the Auth middleware. You can read more here

I think you may check for the user session for example
if (!$_SESSION['id']){ // if user session is not found
header("location:http://yoursite.index.php"); //redirect anywhere
}
else {
// Your code 'view page'
}
Hope my answer solves it :)

Related

Undefined property: App\Http\Controllers\PermissionController::$permission

there is my controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Spatie\Permission\Models\Permission;
class PermissionController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function _construct(Permission $permission)
{
$this->permission = $permission ;
$this-> middleware("auth") ;
}
public function index()
{
$permissions = $this->permission::all();
return view("permission.index", ['permissions' => $permissions]);
}
public function getAllPermissions(){
$permissions = $this->permission::all();
return response()->json([
'permissions' => $permissions
], 200);
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
//
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
//
}
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function edit($id)
{
//
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
//
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy($id)
{
//
}
}
Your _construct is missing one underscore. It should be __construct.
In your code, the class property $permission was supposed to be set by the constructor, but since you mistyped it, it never happened. That is why you get the undefined property error

Laravel NotFoundHttpException No query results for model

I have error NotFoundHttpException No query results for model [App\ThreadForum]
My web.php :
Route::get('/threads','ThreadForumController#index');
Route::post('/threads','ThreadForumController#store');
Route::get('/threads/create','ThreadForumController#create');
Route::get('/threads/{thread}','ThreadForumController#show')->name('threads.show');
My model:
namespace App;
use Illuminate\Database\Eloquent\Model;
class ThreadForum extends Model
{
protected $fillable = [
'user_id','title','body'
];
public function path(){
return route('threads.show',$this->id);
}
public function replies(){
return $this->hasMany('App\Reply');
}
public function creator(){
return $this->belongsTo('App\User', 'user_id');
}
public function addReply($reply){
$this->replies()->create($reply);
}
}
My controller:
namespace App\Http\Controllers;
use App\ThreadForum;
use Illuminate\Http\Request;
class ThreadForumController extends Controller
{
public function __construct()
{
$this->middleware('auth')->only('store');
}
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$threads = ThreadForum::all();
return view('threads.index', compact('threads'));
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
return view('threads.create');
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
dd('store');
/*$thread = ThreadForum::create([
'user_id'=>auth()->id(),
'title'=>$request['title'],
'body'=>$request['body']
]);
redirect($thread->path());*/
}
/**
* Display the specified resource.
*
* #param \App\ThreadForum $threadForum
* #return \Illuminate\Http\Response
*/
public function show(ThreadForum $thread)
{
return view('threads.show',compact('thread'));
}
/**
* Show the form for editing the specified resource.
*
* #param \App\ThreadForum $threadForum
* #return \Illuminate\Http\Response
*/
public function edit(ThreadForum $threadForum)
{
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param \App\ThreadForum $threadForum
* #return \Illuminate\Http\Response
*/
public function update(Request $request, ThreadForum $threadForum)
{
}
/**
* Remove the specified resource from storage.
*
* #param \App\ThreadForum $threadForum
* #return \Illuminate\Http\Response
*/
public function destroy(ThreadForum $threadForum)
{
//
}
}
All functions work well, but when I run post('/threads') for store new record I get error.
I tried use dd('store') for debugging, but I dont see this text, only error.
How can I fix it?
Thanks.
I cannot comment, but to dump you have to use dd($request) not dd($store)
EDIT: I think that problem is in show method. You use compact, but there's no any variable above it. So you cannot pass anything to view.

Request Validation with Laravel 5.3

I am trying to validate my api call using laravel built-in request method.
I have used --resource to get make it REST.
OneTimePasswordController
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use DB;
use App\Models\OneTimePassword as Model;
use App\Http\Requests\OneTimePasswordReq;
class OneTimePasswordController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index(UserController $user)
{
//
$otps = Model::get();
return response()->json($otps);
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
//
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(OneTimePasswordReq $request)
{
$insert = Model::create($request->all());
return response()->json($insert);
}
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function edit($id)
{
//
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
//
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy($id)
{
//
$delete = Model::destroy($id);
return response()->json($delete);
}
}
OneTimePasswordReq
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Contracts\Validation\Validator;
class OneTimePasswordReq extends FormRequest
{
/**
* 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 [
'mobile' => 'required',
'code' => 'required',
];
}
protected function formatErrors(Validator $validator)
{
return $validator->errors()->all();
}
/**
* Set custom messages for validator errors.
*
* #return array
*/
public function messages()
{
return [
'mobile.required'=>"Mobile field is required"
];
}
}
If i pass my params, with values, it gets inserted.
Now if i pass a post request with mobile field deleted, i expect a validation errors.
But the call is made to index method which fetches all data from the url.
My understanding is the request is rejected because the params is missing and the question is why its changing to index method and how do i get the errors?
Note : I am aware about $validator->fails() concept, which i don't want to put into my controller as laravel offers this.
As i tested it with postman, it was redirecting to the same route and picking as get.
If called with javascript code, the errors are displayed.
To check with postman, you need add in headers
X-Requested-With: XMLHttpRequest
Thanks to all supporters.

Add Custom Functions to a Class

all i want to do is add a custom method to my controller so that i can reuse them in other methods inside my controller. eg.:
class SampleController extends Controller {
/**
* Display a listing of the resource.
*
* #return Response
*/
public function index()
{
generateCode();
sendEmail();
}
/**
* Show the form for creating a new resource.
*
* #return Response
*/
public function create()
{
//
}
/**
* Store a newly created resource in storage.
*
* #return Response
*/
public function store()
{
//
}
/**
* Display the specified resource.
*
* #param int $id
* #return Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return Response
*/
public function edit($id)
{
//
}
/**
* Update the specified resource in storage.
*
* #param int $id
* #return Response
*/
public function update($id)
{
//
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return Response
*/
public function destroy($id)
{
//
}
/**
* Custom Functions
*/
function sendEmail()
{
}
function generateCode()
{
}
}
Here i just want to be able to call sendEmail() and generateCode() in my index method but i keep getting function not defined.
They are not global functions so you can't use them like that. They are class methods with scope. Note the changes I made for you:
<?php
class SampleController extends Controller {
/**
* Display a listing of the resource.
*
* #return Response
*/
public function index()
{
$this->generateCode();
$this->sendEmail();
}
// . . .
/**
* Custom Functions
*/
private function sendEmail()
{
}
private function generateCode()
{
}
}
You really should do some OOP PHP tutorials, or read some books, or take a course. This is very basic stuff that you should not need to be asking on stack overflow.
http://php.net/manual/en/language.oop5.php

Laravel RESTful Controller Redirects on POST only

I have a RESTful controller that was created. When I attempt to create a new resource (POST) it redirects me to a 404.
/app-container/public/index.php/api/v1 ->
/index.php/api/v1 ->
/api/v1 -> 404
Here is my route for the controller:
Route::resource('restauranthours', 'restaurantHoursController');
Here is my controller:
class restaurantHoursController extends \BaseController {
/**
* Display a listing of the resource.
*
* #return Response
*/
public function index()
{
//
}
/**
* Show the form for creating a new resource.
*
* #return Response
*/
public function create()
{
//
return "Create";
}
/**
* Store a newly created resource in storage.
*
* #return Response
*/
public function store()
{
//
return "Store";
}
/**
* Display the specified resource.
*
* #param int $id
* #return Response
*/
public function show($id)
{
//
$day = $_GET['day'];
return Response::json(DB::select('select * from restaurantHours where restId=? and day=? order by day',array($id, $day)));
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return Response
*/
public function edit($id)
{
//
}
/**
* Update the specified resource in storage.
*
* #param int $id
* #return Response
*/
public function update($id)
{
//
return "Update";
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return Response
*/
public function destroy($id)
{
//
} }
If I use GET or PUT it gives me the values shown. It only redirects on POST.
PUT doesn't create a new resource; it updates an existing resource. POST creates a new resource.

Categories