Shows an error when using the Gate facade - laravel

When writing privileges and rights of a user shows error: 403
Forbidden
Controller code
class IndexController extends AdminController
{
public function __construct(){
parent::__construct();
if (Gate::denies('VIEW_ADMIN')) {
abort(403);
}
$this->template = env('THEME').'.admin.index';
}
AuthServiceProvider code
public function boot()
{
$this->registerPolicies();
Gate::define('VIEW_ADMIN', function($user){
return $user->canDo('VIEW_ADMIN');
});
//
}
Model User code
The User model is associated with the Roles model, and the Roles model is associated with the Permission model.
public function canDo($permission, $require = FALSE){
if (is_array($permission)) {
dump($permission);
}
else{
foreach ($this->roles as $role) {
foreach ($this->permissions as $permission) {
if (str_is($permission,$permission->name)) {
return true;
}
}
}
}
}

You rewrite input $permission on line foreach ($this->permissions as $permission) { so your if (str_is($permission,$permission->name)) is always FALSE because
str_is(array(), 'VIEW_ADMIN') === FALSE
You should do this
public function canDo($permission, $require = FALSE){
if (is_array($permission)) {
dump($permission);
}
else{
foreach ($this->roles as $role) {
foreach ($this->permissions as $permissionObject) {
if (str_is($permission,$permissionObject->name)) {
return true;
}
}
}
}
}
Also you should add return FALSE because return type is boolean in this case.

Related

Can't do pagination in laravel

I need to do a pagination of the data I retrieve from the DB but I get this error:
Call to undefined method App\Models\DataFromRasp::table()
I followed the Laravel documentation but I still getting this error
My controller is this:
class DeviceController extends Controller
{
public function index()
{
$data=Device::all();
return view('backend.auth.user.device', compact("data"));
}
public function create()
{
}
public function store(Request $request)
{
}
public function show(Device $deviceID)
{
$device = Device::firstWhere('id', $deviceID);
return view('backend.auth.user.singleDevice', compact("device"));
}
public function edit(Device $device)
{
//
}
public function update(Request $request, Device $device)
{
//
}
public function destroy(Device $device)
{
//
}
public function visualizeData()
{
$data=DataFromRasp::table('data_from_rasp')->simplePaginate(10);
return view('backend.auth.user.dictionary', compact("data"));
}
public function getData(Request $request)
{
$m_data = $request->get('m_data');
$r_data = $request->get('r_data');
DataFromRasp::create(['MAC' => $m_data, 'RSSI' => $r_data]);
if(($m_data == 'C4:A5:DF:24:05:7E' or $m_data == '70:1C:E7:E4:71:DA') and Device::where('MAC_ADDR', $request->m_data)->doesntExist()){
Device::create(['MAC_ADDR' => $m_data]);
}
}
public function scan()
{
$process = new Process(['python2','C:\Simone\Università\Smart IoT Devices\Lab_Raspy\Bluetooth\prova.py']);
$process->run();
if (!$process->isSuccessful()) { throw new ProcessFailedException($process); }
return redirect()->route('dict');
}
}
The route is:
Route::get('dict', [DeviceController::class, 'visualizeData'])->name('dict');
Can someone help me?
try $data = DataFromRasp::paginate(10)

How to differentiate the multiple panels with login and session?

It create the session but does not go to index2 and index3 always redirect with else and go to index method but i want to go index2 and index3 to handle other panels also.
Session is created successfully for all just comming else condition all the time.
My form data and array is also showing when i using the print_r for my code to view if the data is comming or not.
Problem is it is showing no any error just redirect with file of index method.
My Controller
class Main extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->model('Main_Model');
$this->load->helper('url');
$this->load->library('session');
$method = $this->router->fetch_method();
$methods = array('index','index2','index3');
if(in_array($method,$methods))
{
if(!$this->session->has_userdata('signup_email'))
{
redirect(base_url('Main/login'));
}
}
}
public function index()
{
if($this->session->has_userdata('signup_email'))
{
$this->load->view('BKO/index');
}
}
public function index2()
{
if($this->session->has_userdata('signup_email'))
{
$this->load->view('Admin/index');
}
}
public function index3()
{
if($this->session->has_userdata('signup_email'))
{
$this->load->view('Owner/index');
}
}
public function login()
{
//$data['select'] = $this->Main_Model->get_select();
$this->load->view('login');
}
public function login_process()
{
//$roll = $this->input->post('select');
echo $email = $this->input->post('email');
echo $pass = $this->input->post('upass');
$query = $this->Main_Model->login_process($email,$pass);
if($query == TRUE)
{
$this->session->set_userdata('signup_email');
$session = array(
'signup_email' => $email
);
$this->session->set_userdata($session);
redirect(base_url('Main/check_login'));
}
else
{
$this->session->set_flashdata('error','Invalid Email or Password');
redirect(base_url('Main/login'));
}
}
public function check_login()
{
if($this->session->userdata() == 'admin#gmail.com')
{
echo "Welcome - <h2>".$this->session->userdata('username')."</h2>";
redirect(base_url('Main/index2'));
}
elseif($this->session->userdata() == 'owner#gmail.com')
{
echo "Welcome - <h2>".$this->session->userdata('username')."</h2>";
redirect(base_url('Main/index3'));
}
else
{
echo "Welcome - <h2>".$this->session->userdata('username')."</h2>";
redirect(base_url('Main/index'));
}
}
public function logout()
{
$this->session->sess_destroy();
redirect(base_url());
}
My Model
public function login_process($email,$pass)
{
//$this->db->select('*');
//$this->db->where('roll_id',$roll);
$this->db->where('signup_email',$email);
$this->db->where('signup_password',$pass);
$query = $this->db->get('signup');
if($query->num_rows() > 0)
{
$this->session->set_flashdata('signup_email');
return true;
}
else
{
return false;
}
}
You missed the parameter here
if($this->session->userdata() == 'admin#gmail.com')
instead it should be
if($this->session->userdata('signup_email') == 'admin#gmail.com')

middleware not executing after successful login

AdminMiddleware:
public function handle($request, Closure $next)
{
return $next($request);
if (\Auth::user() && \Auth::user()->isAdmin() == 1) {
return view('adminpage');
} else {
return view('homepage');
}
}
}
User.php:
public function isAdmin() {
return $this->is_admin;
}
UserController.php:
public function login(Request $request)
{
$email = $request->email;
$password = $request->password;
if(\Auth::attempt(['email'=>$email, 'password'=>$password])) {
// i dont know what if successfull login, i need to execute the logic written in AdminMiddleware
} else {
return view('login);
}
}
My table contains a boolean field "is_admin" with 1 for xxx#gmail.com

Laravel - Prevent from create empty key in database

I have a table where I keep all the settings that will be used on the website, they are saved in the cache, I'm trying to upload the favicon, however when uploading the image the favicon row is updated and an empty key value with the temp path is created at the same time, how can I solve this?
You can see the empty field in the image...
Route
Route::put('/', ['as' => 'setting.update', 'uses' => 'Admin\AdminConfiguracoesController#update']);
Model
class Setting extends Model
{
protected $table = 'settings';
public $timestamps = false;
protected $fillable = ['value'];
}
Controller
class AdminConfiguracoesController extends AdminBaseController
{
private $repository;
public function __construct(SettingRepository $repository){
parent::__construct();
$this->repository = $repository;
}
public function update(Request $request, Factory $cache)
{
$settings = $request->except('_method', '_token');
$this->repository->update($settings);
$cache->forget('settings');
return redirect()->back();
}
}
Repository
class SettingRepository{
private $settings;
public function __construct(Setting $settings)
{
$this->settings = $settings;
}
public function update($key, $value = null)
{
if (is_array($key))
{
foreach ($key as $name => $value)
{
if( $name == "website_favicon" ){
$imageName = $key['website_favicon']->getClientOriginalName();
$this->update($name, asset('public/images/website/'.$imageName));
$key['website_favicon']->move(
base_path() . '/public/images/website/', $imageName
);
} else{
$this->update($name, $value);
}
}
}
$setting = $this->settings->firstOrCreate(['name' => $key]);
$setting->value = $value;
$setting->save();
}
public function lists()
{
return $this->settings->lists('value', 'name')->all();
}
}
The problem is a missing return statement after the foreach loop in your repository. The code after the loop will be executed. $key is an array and $value is the temp value of the uploaded file, which will be set inside the loop.
As I mentioned in my comment, you shouldn't use the repository to upload files. Do it in your controller instead:
AdminConfiguracoesController.php
class AdminConfiguracoesController extends AdminBaseController
{
private $repository;
public function __construct(SettingRepository $repository)
{
parent::__construct();
$this->repository = $repository;
}
public function update(Request $request, Factory $cache)
{
$settings = $request->except('_method', '_token', 'website_favicon');
if ($request->hasFile('website_favicon'))
{
$this->uploadImage($request->file('website_favicon'), 'website_favicon');
$cache->forget('website_favicon');
}
$this->repository->update($settings);
$cache->forget('settings');
return redirect()->back();
}
private function uploadImage(UploadedFile $image, $key)
{
$image->move(public_path('images/website'), $image->getClientOriginalName());
$this->repository->update($key, $image->getClientOriginalName());
}
}
SettingRepository.php
class SettingRepository
{
private $settings;
public function __construct(Setting $settings)
{
$this->settings = $settings;
}
public function update($key, $value = null)
{
if (is_array($key))
{
foreach ($key as $name => $value)
{
$this->update($name, $value);
}
return; // This was missing!
}
$setting = $this->settings->firstOrCreate(['name' => $key]);
$setting->value = $value;
$setting->save();
}
public function lists()
{
return $this->settings->lists('value', 'name')->all();
}
}
You can refactor this even further to use a Job that uploads the image, but this would be overkill for now.

Fatal error: Call to a member function in the login validation

I have the controller file:- login.php
class Login extends CI_Controller {
function __construct() {
parent::__construct();
}
function success() {
$username = $this->input->post('username');
$password = $this->input->post('password');
$errorMsg ="";
$queryResult = $this->logins->validate($username,$password);
if($queryResult == TRUE) {
redirect ('home');
}
else {
$errorMsg ="Invalid Username or Password";
$this->load->view('login',$errorMsg);
}
}
}
view:- login.php
<script type="text/javascript">
function validatelogin(){
var x=document.forms["login"]["username"].value;
var y=document.forms["login"]["passwrd"].value;
if (x==null || x=="")
{
alert("First name must be filled out");
return false;
}
if (y==null || y=="")
{
alert("Password field must be filled out");
return false;
}
/*if(x!="monisha" && y!="monisha"){
alert("Username and Password incorrect");
return false;
}*/
return true;
}
</script>
the HTML form have:-
<form name="login" id="login" action="<?php echo base_url() ?>login/success" onsubmit="return validatelogin()" method="post">
Model file logins.php is having the function, which describes function validate
class Logins extends CI_Model {
function __construct()
{
parent::__construct();
}
function validate($username,$password){
$this->db->select('username','password');
$this->db->from('logins');
$this->db->where('username', $username);
$query = $this->db->get('logins');
if ($query->num_rows() > 0) {
foreach ($query->result() as $row) {
$passwrd = $row->password;
if($passwrd == $password) {
return TRUE;
}
}
} else {
return FALSE;
}
}
}
but showing the error:-
Fatal error: Call to a member function validate() on a non-object in this line:-
$queryResult = $this->logins->validate($username,$password);
You aren't loading class "logins"
$this->load->library('Logins');
Try like this in your model
public function __construct() {
// Connecting Database
parent::__construct();
$this->load->database();
}
Please Add your model Class name into config\autoload.php file
$autoload['model'] = array('logins');
Its working fine for me,Please try it.
Load the model named Logins before you use it
$this->load->model('logins', '', TRUE);
or in autoload.php

Resources