Problems with login and authentication in Laravel - authentication

I need help with my login and authentication of admin.
In the database I have a table called 'admins' with columns of 'name', 'surname', 'password' in my native language.
Every time I press the login button when I try to log in, I get an error:
"Undefined index: password"
where password is in English in folder:
C:\wamp\www\app\vendor\laravel\framework\src\Illuminate\Auth\EloquentUserProvider.php
and I don't know why.
My custom controller AuthController:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Hash;
use Session;
use App\Models\Admin;
use Illuminate\Support\Facades\Auth;
class AuthController extends Controller
{
public function index()
{
return view('auth.login');
}
public function customLogin(Request $request)
{
$request->validate([
'name' => 'required',
'surname' => 'required',
'passw' => 'required',
]);
$credentials = $request->only('name', 'surname', 'passw');
if (Auth::attempt($credentials)) {
return redirect()->intended('');
}
return redirect("login")->withSuccess('Wrong input data.');
}
public function dashboard()
{
if(Auth::check()){
return view('');
}
return redirect("login")->withSuccess('Wrong input data.');
}
public function signOut() {
Session::flush();
Auth::logout();
return Redirect('');
}
}
My route:
Auth::routes();
Route::post('/login', 'AuthController#customLogin');
I consulted with an acquaintance that specialises in web-programming and she said I should do a custom AuthController, which I did, but the problem is either still not fixed or this is a different error.
And from web sources I used:
https://www.positronx.io/laravel-custom-authentication-login-and-registration-tutorial/

Related

How to make an admin ajax call in prestashop 1.7.6

I'm trying to make an ajax call in Prestashop Admin:
I created a module without a config page. It just add a button in some backoffice page, I'm trying to make an ajax call to my module file without success.
Making an ajax call in frontend is working (I added an ajax.php file in my modules/mymodule/controller/front/ directory), I tried to do the same thing for admin but it's not working at all.
What I've done:
loading the js file from actionAdminControllerSetMedia is ok
adding this in the composer.json file:
"autoload": {
"psr-4": {
"MyModule\\Controller\\": "controllers/admin/"
},
"config": {
"prepend-autoloader": false
},
created the controllers/admin/ajax.php file with this code (based on this documentation code):
namespace MyModule\Controller;
use PrestaShopBundle\Controller\Admin\FrameworkBundleAdminController;
class DemoController extends FrameworkBundleAdminController
{
public $auth = false;
public $ssl = true;
public $ajax = true;
public $errors = false;
public $message;
public function __construct()
{
parent::__construct();
}
public function initContent()
{
parent::initContent();
}
public function postProcess()
{
PrestaShopLogger::addLog("MODULE CONTROLLER OK ", 1);
}
public function displayAjax()
{
$this->ajaxDie(json_encode(array('success'=> !$this->errors, 'message' => $this->message)));
}
}
Then I tried to call the ajax from different way in js but never worked (the post query return is a message from prestashop "page not found" with http 200 response.
the doc isn't very helpful and I only find old messages/ways to do (from Prestashop 1.7.5 I'd be able to create a custom Admin controller but it doesn't work), can someone explain me the steps to follow?
thanks
Assuming it is for a PS1.7+ module, using Symphony:
Declare a link in a method of your admin controller (src/Controller/Admin) e.g
$adminLink = $this->generateUrl()
and return in with:
return $this->render
In your views/js/back.js"
$.ajax({
url: adminLink,
type: 'POST',
async: false,
data: {
},
success: (data) => {
}
});
Note: check the generateUrl and render functions for the necessary arguments.

Redirect to nested controller action

I recently moved my controllers to an Admin directory.
I changed the namespace: namespace App\Http\Controllers\Admin;
I have included the Controller class: use App\Http\Controllers\Controller;
In my controller, I have a redirect to the controller's index() action.
return redirect()->action('ServiceController#index');
Now I get the following error:
InvalidArgumentException Action
App\Http\Controllers\ServiceController#index not defined.
I can't figure out how to declare the new action redirect in the docs so I am posting my question here.
Routes
Route::group(['namespace' => 'Admin', 'prefix' => 'admin'], function () {
Route::resource('projects', 'ProjectController');
Route::resource('services', 'ServiceController');
Route::resource('projectFiles', 'ProjectFileController');
Route::get('seed', 'SeedController#seedDatabase')->name('seed');
});
This is the part of the controller where I am talking about:
class ServiceController extends Controller
{
public function index()
{
return view('admin.services.index', [
'services' => Service::all()
]);
}
public function create()
{
return view('admin.services.create');
}
public function store(Request $request)
{
try {
Service::create([
'name' => $request->name,
'machine_name' => snake_case($request->name),
'description' => $request->description
]);
return redirect()->action('\App\Htpp\Controllers\Admin\ServiceController#index');
} catch (\Throwable $th) {
throw $th;
}
}
}
I think I found the answer, but anyone can correct me if I am wrong.
In RouteServiceProvider the namespace is set to App\Http\Controllers:
protected $namespace = 'App\Http\Controllers';
So I decided to add Admin\ before the name of the controller and now the redirect works:
return redirect()->action('Admin\ServiceController#index');

CakePHP3 Auth redirectURL route broken

I have a controller with a particular method to login:
public function login() {
if ($this->request->is('post')){
$user = $this->Auth->identify();
if ($user) {
$this->Auth->setUser($user);
return $this->redirect($this->Auth->redirectUrl());
}
// not logged
$this->Flash->error('Your username or password is incorrect');
}
}
and default route looks like
Router::scope('/', function (RouteBuilder $routes) {
$routes->fallbacks(DashedRoute::class);
});
after user is logged in CakePHP throws an error
Error: A route matching "/" could not be found.
None of the currently connected routes match the provided parameters.
Add a matching route to config/routes.php
when IMO it should to redirect to the page (based on a related controller) from where login method was executed.
Login code is based on that tutorial.
Any thoughts?
To solve this issue:
Please update the below lines in routes.php file
Router::defaultRouteClass('DashedRoute');
Router::scope('/', function (RouteBuilder $routes) {
$routes->connect('/', ['controller' => 'users', 'action' => 'index']);
$routes->fallbacks('DashedRoute');
});
Plugin::routes();
Please do create index() in users controller.
Let me know if any issue.

user auth Laravel 5.2

in my project I need to protect some views.
I create a router group:
Route::group(['middleware' => ['auth']], function (){
//Spot
Route::get('administrator/spot-new', 'SpotController#create');
Route::post('administrator/spot-new', 'SpotController#store');
}
in my Spot Controller:
public function __construct()
{
$this->middleware('auth');
}
but when I try to access to spot view I can't see the login page.
I have this error:
Sorry, the page you are looking for could not be found.
Laravel 5.2 have added Middleware Groups.
https://laravel.com/docs/5.2/middleware#middleware-groups
Web middleware group is responsible for Start Session / Encrypt Cookies / Verify CSRF Token etc.. see below
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
],
You're required to add when working with sessions and any other stuff
in that group.
So to solve your problem add 'web' to your middleware
Route::group(['middleware' => ['web', 'auth']], function (){
Route::get('administrator/spot-new', 'SpotController#create');
Route::post('administrator/spot-new', 'SpotController#store');
}
And in your controller constructor
public function __construct()
{
//$this->middleware('auth'); (No need for this one)
}

Authenticating a user role in Laravel and protecting a route

I have taken advice from people here and given Laravel a try, I have been trying to create a user authentication system. I am having trouble translating what I know works in PHP to Laravel using Eloquent.
What I am trying to do here is identify a user, their roles, if the user has a role of admin they can access the route /admin
I know I can use a package such as Entrust but that is not really helping me learn.
I have created Models for both User and Role. I also have a lookup table called role_user with a user_id and role_id.
In User.php I have
public function roles(){
return $this->belongsToMany('Role', 'users_roles');
}
In Role.php I have
public function users()
{
return $this->belongsToMany('User', 'users_roles');
}
I know if I used
$roles = user::find(1)->roles;
return ($roles);
It will and does return the correct user id (1) and the roles assigned to that user. Now what I am struggling with is how to pick out the admin role and only if the user has this will it allow access to /admin
The route should essentially be
Route::get('admin', function()
{
return View::make('admin.index');
})->before('auth');
What I can't figure how/where/should I check for the admin role first and how to then apply that to the auth check to only permit an admin access to the route.
Any help appreciated.
Lee
For Laravel 5, use Middleware:
Create new middleware
# php artisan make:middleware RoleMiddleware
Check the user role - redirect if invalid role
// app/Http/Middleware/RoleMiddleware.php
class RoleMiddleware
{
public function handle($request, Closure $next, $role)
{
if (! $request->user()->hasRole($role)) {
// Redirect...
}
return $next($request);
}
}
Add key in order to assign to routes - can also make global
// app/Http/Kernel.php
protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'role' => \App\Http\Middleware\RoleMiddleware::class, // new
];
Protect the routes
// app/Http/routes.php
Route::put('post/{id}', ['middleware' => 'role:editor', function ($id) {
// routes for editor
}]);
You have used auth filter so you should check in the auth filter in app/filters.php file:
Route::filter('auth', function($route, $request)
{
// Login check (Default)
if (Auth::guest()) return Redirect::guest('login');
// Admin check
if(!in_array('admin', Auth::user()->roles->toArray())) {
return Redirect::to('/'); // Redirect home page
}
});
You may use a different filter, for example:
Route::get('admin', function()
{
return View::make('admin.index');
})->before('isAdmin');
Declare the custom isAdmin filter in app/filters.php:
Route::filter('isAdmin', function($route, $request)
{
if(!Auth::check()) return Redirect::guest('login');
if( !in_array('admin', Auth::user()->roles->toArray()) ) {
return Redirect::to('/'); // Redirect home page
}
});