Extends basic auth laravel - php

Can i expand the login function in Laravel version 5 and higher without overwriting the standard one. I want to expand the functionality without getting into the vendor folder
enter image description here
class AuthController extends Controller
{
use AuthenticatesAndRegistersUsers, ThrottlesLogins;
/**
* Where to redirect users after login / registration.
*
* #var string
*/
protected $redirectTo = '/'; // home initialement
protected $redirectAfterLogout = '/login'; // Added
/**
* Create a new authentication controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest', ['except' => ['logout', 'getLogout']]);
}
/**
* Get a validator for an incoming registration request.
*
* #param array $data
* #return \Illuminate\Contracts\Validation\Validator
*/
protected function validator(array $data)
{
//
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return User
*/
protected function create(array $data)
{
//
}
protected function login(array $data)
{
// my changes here...
}
}

Related

Authenticated user gets changed after request randomly

I have an issue with laravel's authentication.
After some time, authenticated user changes to random one.
Client is using same internet for 3 devices(users) on a same network to use the site, and this particular bug would appear when they opened two tabs parallelly and used the site - the user on one tab would change to a user that is in those three, or even odder - a user with device that is on a different network and they would get a 419 status code.
I created a cronjob for optimize:clear command to run 2 / hour. Note: this occurs only on production server - i tried to reproduce this locally without success.
Below is my login controller, that is using trait https://laravel.com/api/6.x/Illuminate/Foundation/Auth/AuthenticatesUsers.html
from laravel 6.x, even though my laravel version in project is 7.0.
Only thing i modified from trait is the credentials used in login - instead of email i'm using username.
Since I got no way of solving this one, any help would be appreciated.
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\Providers\RouteServiceProvider;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Foundation\Auth\RedirectsUsers;
use Illuminate\Foundation\Auth\ThrottlesLogins;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Auth;
use Illuminate\Validation\ValidationException;
class LoginController extends Controller
{
/*
|--------------------------------------------------------------------------
| Login Controller
|--------------------------------------------------------------------------
|
| This controller handles authenticating users for the application and
| redirecting them to your home screen. The controller uses a trait
| to conveniently provide its functionality to your applications.
|
*/
use RedirectsUsers, ThrottlesLogins;
/**
* Show the application's login form.
*
* #return \Illuminate\View\View
*/
public function showLoginForm()
{
return view('auth.login');
}
/**
* Handle a login request to the application.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\RedirectResponse|\Illuminate\Http\Response|\Illuminate\Http\JsonResponse
*
* #throws \Illuminate\Validation\ValidationException
*/
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 (method_exists($this, 'hasTooManyLoginAttempts') &&
$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);
}
/**
* Validate the user login request.
*
* #param \Illuminate\Http\Request $request
* #return void
*
* #throws \Illuminate\Validation\ValidationException
*/
protected function validateLogin(Request $request)
{
$request->validate([
$this->username() => 'required|string',
'password' => 'required|string',
]);
}
/**
* Attempt to log the user into the application.
*
* #param \Illuminate\Http\Request $request
* #return bool
*/
protected function attemptLogin(Request $request)
{
return $this->guard()->attempt(
$this->credentials($request), $request->filled('remember')
);
}
/**
* Get the needed authorization credentials from the request.
*
* #param \Illuminate\Http\Request $request
* #return array
*/
protected function credentials(Request $request)
{
return $request->only($this->username(), 'password');
}
/**
* 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);
if ($response = $this->authenticated($request, $this->guard()->user())) {
return $response;
}
return $request->wantsJson()
? new Response('', 204)
: redirect()->intended($this->redirectPath());
}
/**
* The user has been authenticated.
*
* #param \Illuminate\Http\Request $request
* #param mixed $user
* #return mixed
*/
protected function authenticated(Request $request, $user)
{
$mode = $user->viewmode;
return redirect()->route($mode . '-mode');
}
/**
* Get the failed login response instance.
*
* #param \Illuminate\Http\Request $request
* #return \Symfony\Component\HttpFoundation\Response
*
* #throws \Illuminate\Validation\ValidationException
*/
protected function sendFailedLoginResponse(Request $request)
{
throw ValidationException::withMessages([
$this->username() => [trans('auth.failed')],
]);
}
/**
* Get the login username to be used by the controller.
*
* #return string
*/
public function username()
{
return 'username';
}
/**
* 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();
$request->session()->regenerateToken();
if ($response = $this->loggedOut($request)) {
return $response;
}
return $request->wantsJson()
? new Response('', 204)
: redirect('/');
}
/**
* The user has logged out of the application.
*
* #param \Illuminate\Http\Request $request
* #return mixed
*/
protected function loggedOut(Request $request)
{
//
}
/**
* Get the guard to be used during authentication.
*
* #return \Illuminate\Contracts\Auth\StatefulGuard
*/
protected function guard()
{
return Auth::guard();
}
/**
* Where to redirect users after login.
*
* #var string
*/
protected $redirectTo = RouteServiceProvider::HOME;
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest')->except('logout');
}
}

Laravel 7 419 Page Expired error after refresh login's laravel

I'm using auth system, and after user logged in if I refresh the page I get the 419 page expired error. I overrided authenticated method to redirect to profile after login. Here's my controller:
use AuthenticatesUsers;
/**
* Where to redirect users after login.
*
* #var string
*/
protected $redirectTo = RouteServiceProvider::HOME;
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest')->except('logout');
}
protected function authenticated()
{
return view("user.profile");
}
And here's my User model:
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $guarded = [];
const UPDATED_AT = null;
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
Try editing the render function in app\Exceptions\Handler.php by adding the code below.
if ($exception instanceof \Illuminate\Session\TokenMismatchException) {
return redirect('/login');
}

Class 'App\users' not found in Laravel when i create users.blade.php

I am getting the following error:
FatalErrorException in usercontroller.php line 21: Class 'APP\User' not found
usercontroller.php:
<?php
namespace App\Http\Controllers;
use APP\User;
use Illuminate\Http\Request;
use App\Http\Requests;
class usercontroller extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$user = User::all();
return view('admin/users', compct('user'));
}
/**
* 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)
{
//
}
}
User.php (it's in App/User.php):
<?php
namespace App;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
}
I create to users.blade.php to listing user in Admin Panel but at last then i m click to a user then they have an error on screen please say what can i do
Typo
Change use APP\User; to use App\User;
It's case sensitive so they are not the same thing.
please use User class in UserController with this namespace App/User NOT APP/user
Change use APP\User; to use App\User;
Change also compct to compact
public function index()
{
$user = User::all();
return view('admin/users', compact('user'));
}

activation link in laravel

I am trying to send activation link to registered user with the help of laravel. I have made some changes in User.php but
"Declaration of User::setRememberToken() must be compatible with
Illuminate\Auth\UserInterface::setRememberToken($value)"
this error is coming.
my User.php is as follows:
<?php
use Illuminate\Auth\UserTrait;
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableTrait;
use Illuminate\Auth\Reminders\RemindableInterface;
class User extends Eloquent implements UserInterface, RemindableInterface {
//use UserTrait, RemindableTrait;
protected $fillable =array('email','username','password','password_temp','code','active');
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'users';
/**
* The attributes excluded from the model's JSON form.
*
* #var array
*/
protected $hidden = array('password');
/**
* get the identifier for user
*
* #return mixed
*/
public function getAuthIdentifier()
{
return $this->getKey();
}
/**
* get the password for user
*
* #return string
*/
public function getAuthPassword()
{
return $this->password;
}
/**
* get the email add where password is sent
*
* #return string
*/
public function getRemainderEmail()
{
return $this->email;
}
public function getRememberToken(){}
public function setRememberToken(){}
public function getReminderEmail(){}
}
If you look at the docs for setRememberToken, you can see that it has a signature of void setRememberToken(string $value). So, your code change
public function setRememberToken(){}
to
public function setRememberToken($value){}

Zend Framework issue with accessing a method from another controller

I have been trying to use the _forward method to access a method in my IndexController from another controller, but it won't seem to work. I have tried:
$this->_forward('permissions', 'Index')
$this->_forward('permissions', 'index')
$this->_forward('permissions', 'IndexController')
$this->_forward('permissions', 'indexcontroller')
None of which have worked. Here is my code.
Controller
class IndexController extends Zend_Controller_Action
{
/**
* facebookConfig
*
* #var mixed
* #access protected
*/
protected $facebookConfig;
/**
* signed_request
*
* #var mixed
* #access protected
*/
protected $signed_request;
/**
* facebookConfig
*
* #var mixed
* #access protected
*/
protected $permissions;
/**
* init function.
*
* #access public
* #return void
*/
public function init()
{
// get the model
$this->app = new Application_Model_Admin();
// get config data
$this->facebookConfig = $this->app->configData();
// get the apps permissions
$this->permissions = $this->permissions();
// get the data for the head
$data = $this->app->configData();
if(empty($data->ogimage))
$data->ogimage = '';
// set the page title
$this->view->headTitle($data->title, 'PREPEND');
// set the meta data
$this->view->headMeta()->setName('fb:app_id', $data->appid);
$this->view->headMeta()->setName('og:type', $data->ogtype);
$this->view->headMeta()->setName('og:title', $data->ogtitle);
$this->view->headMeta()->setName('og:description', $data->ogdesc);
$this->view->headMeta()->setName('og:url', $data->applink);
$this->view->headMeta()->setName('og:image', $data->ogimage);
}
/**
* permissions function.
*
* #access public
* #return void
*/
public function permissions(){
// return the permissions
return 'publish_stream, read_stream, friends_likes';
}
}
Second Controller
<?php
class ThanksController extends Zend_Controller_Action
{
/**
* facebookConfig
*
* #var mixed
* #access protected
*/
protected $permissions;
/**
* init function.
*
* #access public
* #return void
*/
public function init()
{
// get the model
// get the permissions
$this->permissions = $this->_forward('permissions', 'index');
print_r('<pre>');var_dump($this->_forward('permissions', 'index'));print_r('</pre>');die;
}
}
_forward is used only to call controller actions, not regular methods
_forward('index') actually refers to method indexAction()
Change this:
public function permissions(){
// return the permissions
return 'publish_stream, read_stream, friends_likes';
}
to this:
public function permissionsAction(){
// return the permissions
return 'publish_stream, read_stream, friends_likes';
}
I wasn't thinking particularly clearly, instead I just put the code in a model and accessed the data from their.

Categories