Method Modules\Auth\Http\Controllers\AuthController::username does not exist Laravel 6 - laravel

When trying to integrate limit login attempts to custom controller in Laravel 6, I got the following error:
Error:
exception: "BadMethodCallException"
file: "D:\\wamp64\\www\\alphabilling\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Controller.php"
line: 68
message: "Method Modules\\Auth\\Http\\Controllers\\AuthController::username does not exist."
This is AuthController:
Code:
<?php
namespace Modules\Auth\Http\Controllers;
use Illuminate\Contracts\Support\Renderable;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Auth;
use Validator;
use Illuminate\Foundation\Auth\ThrottlesLogins;
class AuthController extends Controller
{
use ThrottlesLogins;
protected $maxAttempts = 5;
protected $decayMinutes = 1;
public function login(Request $request)
{
$input = $request->all();
$rules = [
'username' => 'required|email',
'password' => 'required'
];
$validator = Validator::make($input, $rules);
if ($validator->fails()) {
return false;
}
if (method_exists($this, 'hasTooManyLoginAttempts') &&
$this->hasTooManyLoginAttempts($request)) {
$this->fireLockoutEvent($request);
return $this->sendLockoutResponse($request);
}
$authenticated = Auth::attempt([
'email' => $request->input('username'),
'password' => $request->input('password')
]);
if($authenticated){
$this->clearLoginAttempts($request);
} else {
$this->incrementLoginAttempts($request);
}
}
}
Version:
Laravel: 6.20.18

Related

Sending email from 2 different mail classes and laravel throws error

I am sending two different emails. One from VerifyMail and other from ForgetEmail but laravel throws error that VerifyMail does not exits. It was working just fine when i had not added the ForgetMail class.
This is my code where i am using VerifyMail
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use App\User;
use App\VerifyUser;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Carbon;
use App\Mail\VerifyMail;
class UserRegisterController extends Controller
{
public function __construct()
{
$this->middleware('guest:user');
}
public function showRegisterForm() {
return view('user.registerForm');
}
public function register(Request $request) {
$userValidated = $this->validate($request, [
'name' => 'required|string',
'email' => 'required|string|unique:users',
'password' => 'required|string|min:6|confirmed'
]);
$register = [
'name' => $userValidated['name'],
'email' => $userValidated['email'],
'password' => Hash::make($userValidated['password']),
];
$user =User::create($register);
VerifyUser::create([
'token' => str::random(60),
'user_id' => $user->id,
]);
Mail::to($user->email)->send(new VerifyMail($user));
return redirect('user/login')->with('email', 'An email was sent to you for verification');
}
public function verifyEmail($token, $date) {
$dates = date(strtotime($date));
if(time() - $dates > 60 * 60) {
return redirect('/user/login')->with('failed' , 'Oops! Something went wrong');
}
$verifiedUser = VerifyUser::where('token', $token)->first();
if(isset($verifiedUser)) {
$user = $verifiedUser->user;
if($user->email_verified_at == '') {
$user->email_verified_at = carbon::now();
$user->save();
return redirect('/user/login')->with('success', 'Your email was successfully verified');
} else {
return redirect('/user/login')->with('failed' , 'Oops! Something went wrong');
}
}
}
}
This is the code where i am using ForgetEmail
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
// use Symfony\Component\HttpFoundation\Session\Session;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Cookie;
use Illuminate\Support\Facades\Session;
use App\ForgetPassword;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Mail;
use App\Mail\ForgetEmail;
use App\User;
use Illuminate\Support\Facades\Hash;
class UserLoginController extends Controller
{
protected $guard;
use AuthenticatesUsers;
public function __construct()
{
$this->middleware('guest:user')->except('logout');
$this->guard = Auth::guard('user');
}
public function showLoginForm()
{
return view('user.login');
}
public function forgetPasswordForm() {
return view('user.forget');
}
public function passwordResetForm($id) {
$user = User::where('id', $id)->first();
return view('user.resetForm', ['id' => $id]);
}
public function userLogin(Request $request) {
$validated = $this->validate($request, [
'email' => 'required|email',
'password' => 'required|min:6',
]);
if(Auth::guard('user')->attempt(['email' => $validated['email'], 'password' => $validated['password']], $request->remember)) {
$user = Auth::guard('user')->user();
if($user->email_verified_at != null) {
return redirect()->route('user.dashboard');
} else {
$this->logout($msg = 1);
}
}
return redirect()->back();
}
public function forgetPassword(Request $request) {
$email = $this->validate($request, [
'email' => 'required|email|exists:users',
]);
$forgetPass = User::where('email', $email['email'])->first();
$forgetArray = array(
'user_id' => $forgetPass->id,
'token' => str::random(60),
);
$forgetPassword = ForgetPassword::create($forgetArray);
Mail::to($email['email'])->send(new ForgetEmail($forgetPassword->user));
return redirect('user/forgetPassword')->with('email', 'We have sent you an email to reset your password');
}
public function passwordReset($token, $date) {
$checkTime = strtotime($date);
if(time() - $checkTime > 20 * 60) {
return redirect('user/login/')->with('passes', 'Looks like the link has expired');
}
$passReset = ForgetPassword::where('token', $token)->first();
if(isset($passReset)) {
$user = $passReset->user;
if($user->password) {
return redirect('/user/passwordReset'. '/'. $user->id);
}
}
}
public function passwordUpdate(Request $request, $id) {
$validatePass = $this->validate($request, [
'password' => 'required|string|min:6|confirmed',
]);
$pass = User::where('id', $id)->first();
$pass->password = Hash::make($validatePass['password']);
$pass->save();
return redirect('/user/login')->with('reset', 'Your password has been reset');
}
public function logout($msg = 0) {
$cookieName = $this->guard->getRecallerName();
$cookie = Cookie::forget($cookieName);
Auth::logout();
Session::flush();
if($msg == 0) {
return redirect()->route('user.login')->withCookie($cookie);
} else {
return redirect()->route('user.login')->withCookie($cookie)->with('verify', 'Your email is not verified');
}
}
}
All of my code was working fine before when i had not added that ForgetEmail class in Mail. I don't know what's the problem here. Will be glad if you can find it for me.

Laravel - Call to undefined method App\\User::getAvatarUrlAttribute()

I am using Laravel-5.8 as backend for an application. I have written all the Api for the endpoints.
Laravel: ApiController
<?php
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Carbon\Carbon;
use App\User;
use App\Activity;
use Avatar;
use Storage;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Mail;
use Audit;
use Spatie\Permission\Models\Role;
use Spatie\Permission\Models\Permission;
class ApiController extends Controller
{
public $successStatus = 200;
public function __construct() {
}
protected function guard()
{
return Auth::guard();
}
protected function respondWithToken($token)
{
return response()->json([
'access_token' => $token,
'token_type' => 'bearer',
'expires_in' => auth()->factory()->getTTL() * 60,
'user' => auth()->user()->email
], 200);
}
public function returnResponse($success, $data, $errorCode = 0, $message = false) {
$response = array();
$response['success'] = $success;
$response['message'] = isset($message) ? $message : '';
if ($errorCode) {
$response['errorCode'] = isset($errorCode) ? $errorCode : 0;
}
$response['data'] = $data;
return response()->json($response, 200);
}
public function register(Request $request) {
$validator = Validator::make($request->all(), [
'name' => 'required',
'email' => 'required|string|email|max:255|unique:users',
// 'phone' => 'required',
// 'password' => 'required',
'password' => 'required|string|min:6',
// 'password' => 'required|string|min:6|confirmed',
'password_confirmation' => 'required|same:password',
]);
if ($validator->fails()) {
return $this->returnResponse(false, ['error' => $validator->errors()], 1, 'Invalid User Data');
}
$input = $request->all();
// code for check email / username / phone exist or not
if(isset($input['email'])){
$alreadyExist = User::where(function ($query) use ($input) {
$query->where('email', '=', $input['email']);
})->get();
}
if (count($alreadyExist->toArray()) > 0) {
return $this->returnResponse(false, ['error' => 'Email Already Exist'], 1, 'User Data Already Exist');
}
// code for register user
$user = new User();
$user->name = $input['name'];
$user->email = $input['email'];
$user->password = bcrypt($input['password']);
$user->save();
$mainData = array();
$mainData['to'] = $user->toArray()[0]['email'];
$mainData['from'] = "support#tsllimited.com";
$mainData['subject'] = "Successful Signup";
$mainData['content'] = "Your signup was successful, you can login with the credentials.";
$this->mailSend($mainData);
Activity::create([
'user_id' => $user->id,
'owner_id' => $user->client_id,
'type' => "User Registration",
'title' => "Successful Signup of User",
'state' => 2,
'created_at'=> date('Y-m-d H:i:s')
]);
$success = array();
$success['user_id'] = $user->id;
$success['user']=$user;
return $this->returnResponse(true, $success, 0, 'User registered successfully');
}
public function login(Request $request) {
$authenticated = false;
$validator = Validator::make($request->all(), [
'email' => 'required|string|email',
'password' => 'required|string',
'remember' => 'boolean'
]);
if ($validator->fails()) {
return $this->returnResponse(false, ['error' => $validator->errors()], 1, 'Invalid User Data');
}
$remember = request('remember') ? true : false;
if (Auth::guard('web')->attempt(['email' => request('email'), 'password' => request('password')], $remember)) {
$authenticated = true;
}
if ($authenticated == true) {
$user = Auth::guard('web')->user();
$date = date('Y-m-d');
$success['userId'] = $user->id;
$success['avatar'] = url('/storage/user') . '/' . $user->avatar;
$success['email'] = $user->email;
$success['token'] = $user->createToken('MyApp')->accessToken;
return $this->returnResponse(true, $success);
} else {
$success = array();
return $this->returnResponse(false, $success, 1, 'Invalid User Credential');
}
}
}
api.php
Route::group([
], function () {
Route::post('login', 'ApiController#login');
Route::post('register', 'ApiController#register');
Route::post('forgetPassword', 'ApiController#forgetPassword');
Route::group([
'middleware' => 'auth:api'
], function() {
Route::get('logout', 'AuthController#logout');
Route::get('user', 'AuthController#user');
});
});
I stalled and configured Laravel Passport and also Spatie. I have checked the code and don't know what the error really is. When I test the resgister Post Request on the POSTMAN, I got the error shown below:
See the POSTMAN preview side:
What could have caused the error and how do I resolve it?
You do not have the column avatar on your users table.
Maybe you did not use the trait you need in your User class
class User extends Authenticatable {
use HasAvatar;
// ...
}
I eventually solved the problem myself. The issue is that, I forgot to add:
public function getAvatarUrlAttribute()
{
return Storage::url('avatars/'.$this->id.'/'.$this->avatar);
}
to User Model.
Thanks

Redirect too many times when using socialite laravel package in laravel 5.4

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?

Auth::login($user) in laravel not able to login the user

I am using laravel 5.4 and Auth::login($user) is showing Type error:
Argument 1 passed to Illuminate\Auth\SessionGuard::login() must
implement interface Illuminate\Contracts\Auth\Authenticatable,
instance of Illuminate\Database\Eloquent\Builder given, called in
/home/vendor/laravel/framework/src/Illuminate/Auth/AuthManager.php on
line 294
My User.php file is:
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'role', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
}
My AuthController.php is:
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\User;
use Auth;
use Illuminate\Support\Facades\Input;
use \Hash;
class AuthController extends Controller
{
//
public function register(Request $request){
$this->validate($request, [
'name' => 'required|max:30',
'email' => 'required|email|unique:users',
'regpassword' => 'required|alpha_num|confirmed'
]);
/*$user = new User();
$user['name'] = $request['name'];
$user['email'] = $request['email'];
$user['password'] = bcrypt($request['password']);
$user['role'] = 'user';
$user->save();
*/
$user = User::create(array(
'email' => Input::get('email'),
'name' => Input::get('name'),
'password' => Hash::make(Input::get('password')),
'role' => 'user'));
return 'success';
}
public function userLogin(Request $request){
$this->validate($request,[
'email' => 'required|email',
'password' => 'required'
]);
$user = User::where('email', '=', $request['email'])-> where('password' ,'=', Hash::make($request['password']))->where('role','=','user');
if($user){
Auth::login($user);
return $next($request);
}
else{
return redirect()->back();
}
}
}
My web.php
Route::get('/', function () {
return view('welcome');
});
Auth::routes();
Route::get('/home', 'HomeController#index');
Route::post('/register', 'AuthController#register');
Route::post('/UserLogin','AuthController#userLogin');
Your problem is this:
$user = User::where('email', '=', $request['email'])-> where('password' ,'=', Hash::make($request['password']))->where('role','=','user');
Is lacking a call to get the result set back from the query. Add ->first().
What it' saying is:
You gave me an instance of the query Builder
But
I wanted a model that extends the authenticatable class
If you open App\User, you'll see that it does indeed extend this class:
class User extends Authenticatable {
This:
$user = User::where('email', '=', $request['email'])-> where('password' ,'=', Hash::make($request['password']))->where('role','=','user');
is not the way you will get the user.
Instead of
$user = User::where('email', '=', $request['email'])-> where('password' ,'=', Hash::make($request['password']))->where('role','=','user');
if($user){
Auth::login($user);
return $next($request);
}
else{
return redirect()->back();
}
you could use:
$logged = auth()->attempt(
['email' => $request['email'],
'password' => $request['password'],
'role' => 'user']);
if($logged) {
return $next($request); // probably it won't work. This is fine in middleware but not in controller
}
else{
return redirect()->back();
}
Solved my problem as following:
$user = User::where('email', '=' $request['email'])->where('role','=','user')->first();
if(Hash::check($request['password'],$user->password)){
Auth::login($user);
return 'success';
}

How to add extra logic on login condition in Laravel 5.2

I just wanted to say if the user is not active, don't allow to login. I have made the controller as below, I am not sure what I am missing or what else I have to do here to make this work!
<?php
namespace App\Http\Controllers\Auth;
use Illuminate\Auth\Authenticatable;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use App\User;
use Validator;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ThrottlesLogins;
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;
class AuthController extends Controller{
use AuthenticatesAndRegistersUsers, ThrottlesLogins;
protected $redirectTo = '/home';
public function __construct()
{
$this->middleware($this->guestMiddleware(), ['except' => 'logout']);
}
protected function validator(array $data)
{
return Validator::make($data, [
'name' => 'required|max:255',
'email' => 'required|email|max:255|unique:users',
'password' => 'required|min:6|confirmed',
]);
}
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
]);
}
public function authenticate()
{
if (Auth::attempt(['email' => $email, 'password' => $password, 'active' => 1])) {
// Authentication passed...
return redirect()->intended('dashboard');
}
}
}
My thinking was authenticate() method should do the trick!
The below code worked for my case:
protected function getCredentials(Request $request)
{
return [
'email' => $request->input('email'),
'password' => $request->input('password'),
'active' => true
];
}
for Laravel 5.3 need to add following code to LoginController
protected function credentials(Request $request)
{
return [
'email' => $request->input('email'),
'password' => $request->input('password'),
'active' => true
];
}
i think you should create method to check if user passed your credentials, here's my suggestion :
protected function getCredentials(Request $request)
{
return [
'username' => $request->input('email'),
'password' => $request->input('password'),
'active' => true
];
}
and your login method:
public function login(Request $request) {
$this->validate($request,['email' => 'required|email','password' => 'required']);
if (Auth::guard()->attempt($this->getCredentials($request))){
//authentication passed
}
return redirect()->back();
}
hope you get basic idea.
In LoginController.php file write this function
protected function credentials(Request $request) {
$extraFields = [
'user_type'=> 'customer',
'user_entry_status' => 1
];
return array_merge($request->only($this->username(), 'password'), $extraFields);
}
Go to this path :
your-project-folder/vendor/laravel/framework/src/illuminate/Foundation/Auth/AuthenticatesUsers.php
$credentials=$request->only($this->loginUsername(), 'password');
$credentials['status'] = '1';
return $credentials;
Change getCredantials works fine, but it is good practice to let user know, that the account was suspended (credentials are OK, but the account status is not). You can easily override login method in Auth/LoginController.php to your own copy, add your own logic to login process and raise own exception.
in Auth/LoginController.php create login and sendAccountBlocked function
/*load additional classes to LoginController.php*/
use Illuminate\Http\Request;
use Illuminate\Validation\ValidationException;
use Auth;
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)) {
//check user status
if (Auth::user()->user_status == 'A') return $this->sendLoginResponse($request);
// if user_status != 'A' raise exception
else {
$this->guard()->logout();
return $this->sendAccountBlocked($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);
//
}//
protected function sendAccountBlocked(Request $request){
throw ValidationException::withMessages([
$this->username() => ['Your account was suspended.'],
]);
}

Resources