I would like to test if a user is logged out,I am using Sanctum with Laravel Breeze, I am trying like this:
public function test_users_can_logout()
{
$this->signIn();
$response = $this->postJson(
'/api/logout'
);
$this->assertGuest();
}
And this is AuthenticatedSessionController .php, This came from Breeze, I modified it:
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\Http\Requests\Auth\LoginRequest;
use App\Providers\RouteServiceProvider;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Auth;
class AuthenticatedSessionController extends Controller
{
/**
* Handle an incoming authentication request.
*
* #param \App\Http\Requests\Auth\LoginRequest $request
* #return \Illuminate\Http\RedirectResponse
*/
public function store(LoginRequest $request)
{
$request->authenticate();
$token = $request->user()->createToken('MyAuthApp')->plainTextToken;
return response()->json(
[
'access_token' => $token,
'token_type' => 'Bearer',
'user' => $request->user()
]
);
}
/**
* Destroy an authenticated session.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\RedirectResponse
*/
public function destroy(Request $request)
{
$request->user()->tokens()->delete();
return response()->json(
[
'message' => 'log out successfully'
]
);
}
}
LoginRequest.php
<?php
namespace App\Http\Requests\Auth;
use Illuminate\Auth\Events\Lockout;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;
class LoginRequest 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 [
'email' => 'required|string|email',
'password' => 'required|string',
];
}
/**
* Attempt to authenticate the request's credentials.
*
* #return void
*
* #throws \Illuminate\Validation\ValidationException
*/
public function authenticate()
{
$this->ensureIsNotRateLimited();
if (! Auth::attempt($this->only('email', 'password'), $this->filled('remember'))) {
RateLimiter::hit($this->throttleKey());
throw ValidationException::withMessages([
'email' => __('auth.failed'),
]);
}
RateLimiter::clear($this->throttleKey());
}
/**
* Ensure the login request is not rate limited.
*
* #return void
*
* #throws \Illuminate\Validation\ValidationException
*/
public function ensureIsNotRateLimited()
{
if (! RateLimiter::tooManyAttempts($this->throttleKey(), 5)) {
return;
}
event(new Lockout($this));
$seconds = RateLimiter::availableIn($this->throttleKey());
throw ValidationException::withMessages([
'email' => trans('auth.throttle', [
'seconds' => $seconds,
'minutes' => ceil($seconds / 60),
]),
]);
}
/**
* Get the rate limiting throttle key for the request.
*
* #return string
*/
public function throttleKey()
{
return Str::lower($this->input('email')).'|'.$this->ip();
}
}
TestCase.php
<?php
namespace Tests;
use Illuminate\Foundation\Testing\TestCase as BaseTestCase;
use Laravel\Sanctum\Sanctum;
use App\Models\User;
abstract class TestCase extends BaseTestCase
{
use CreatesApplication;
protected function signIn($user = null)
{
$user = $user ?: User::factory()->create();
Sanctum::actingAs($user);
return $user;
}
}
EDITED: now I am testing only the logout route, my test fails, maybe because sanctum is using cookies? is it ok use sanctum with breeze?
I would like to test if the token no longer exists, what can I do?
Related
In my laravel project , am implementing another login for agencies, which i want to take from agencies table.Agencies table have email and password fields. But when i try to login it not get logged in and redirecting to same page and prducing validation error.But i provided exact email and password from agencie table
Following is my code in model
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Kyslik\ColumnSortable\Sortable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class Agencie extends Authenticatable
{
use Notifiable;
use Sortable;
protected $guard = 'agencie';
protected $table = 'agencies';
protected $primaryKey = 'agency_id';
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'agency_id', 'agency_name','agency_user_name' ,'agency_password', 'agency_city', 'agency_state', 'agency_zip', 'agency_email','status','created_at','updated_at'
];
}
Following i have addeed to config/auth.php
'guards' => [
'agencie' => [
'driver' => 'session',
'provider' => 'agencies',
],
],
'providers' => [
'agencies' => [
'driver' => 'eloquent',
'model' => App\Agencie::class,
],
],
Following is my code in LoginController
<?php
namespace App\Http\Controllers\Agency\AgencyAuth;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Support\Facades\Auth;
use Hesto\MultiAuth\Traits\LogsoutGuard;
use JsValidator;
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 AuthenticatesUsers, LogsoutGuard {
LogsoutGuard::logout insteadof AuthenticatesUsers;
}
protected $validationRules = [
'email' => 'required|email',
'password' => 'required'
];
/**
* Where to redirect users after login / registration.
*
* #var string
*/
// public $redirectTo = '/user/home';
public $redirectTo = '/user/dashboard-graph';
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest:agencie', ['except' => 'logout']);
// $this->middleware('guest:agency')->except('logout');
}
public function username()
{
return 'agency_email';
}
/**
* Show the application's login form.
*
* #return \Illuminate\Http\Response
*/
public function showLoginForm()
{
$validator = JsValidator::make($this->validationRules,[],[],'#loginform');
return view('agency.auth.login')->with('validator', $validator);
}
/**
* Get the guard to be used during authentication.
*
* #return \Illuminate\Contracts\Auth\StatefulGuard
*/
protected function guard()
{
return Auth::guard('agencie');
}
/**
* Get the needed authorization credentials from the request.
*
* #param \Illuminate\Http\Request $request
* #return array
*/
}
I have added following codes to app/Expecations/Handler.php
protected function unauthenticated($request, AuthenticationException $exception)
{
if ($request->expectsJson()) {
return response()->json(['error' => 'Unauthenticated.'], 401);
}
$middleware = request()->route()->gatherMiddleware();
$guard = config('auth.defaults.guard');
foreach($middleware as $m) {
if(preg_match("/auth:/",$m)) {
list($mid, $guard) = explode(":",$m);
}
}
switch($guard) {
case 'agencie':
$login = 'agency/login';
break;
default:
$login = 'user/login';
break;
}
return redirect()->guest($login);
}
I have also added additonal 2 files in middleware named RedirectifAgency.php & Redirectifnotagency.php
Following is the code
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\Auth;
class RedirectIfAgency
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #param string|null $guard
* #return mixed
*/
public function handle($request, Closure $next, $guard = 'agencie')
{
if (Auth::guard($guard)->check()) {
return redirect('agency/home');
}
return $next($request);
}
}
What is the problem here.Please help
I am working on a simple JWT authentication system. User will get a token from login and when he passes the token, the user information will be given as the response. I have followed the procedure from: https://jwt-auth.readthedocs.io/en/develop/laravel-installation/ .
When I pass email and password to the login method I am able to get a token. But when I pass the token (to the me function) it returns 'Unauthorized'.
User Model:
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Tymon\JWTAuth\Contracts\JWTSubject;
class User extends Authenticatable implements JWTSubject
{
use Notifiable;
/**
* 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',
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
public function getJWTIdentifier()
{
return $this->getKey();
}
/**
* Return a key value array, containing any custom claims to be added to the JWT.
*
* #return array
*/
public function getJWTCustomClaims()
{
return [];
}
}
```````
api.php (Route)
`````
Route::group([
'middleware' => 'api',
'prefix' => 'auth'
], function ($router) {
Route::post('login', 'AuthController#login');
Route::post('logout', 'AuthController#logout');
Route::post('refresh', 'AuthController#refresh');
Route::post('me', 'AuthController#me');
});
````
AuthController
```
<?php
namespace App\Http\Controllers;
use Illuminate\Support\Facades\Auth;
use App\Http\Controllers\Controller;
use App\User;
class AuthController extends Controller
{
/**
* Create a new AuthController instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('auth:api', ['except' => ['login']]);
}
/**
* Get a JWT via given credentials.
*
* #return \Illuminate\Http\JsonResponse
*/
public function login()
{
$credentials = request(['email', 'password']);
if (! $token = auth()->attempt($credentials)) {
return response()->json(['error' => 'Unauthorized'], 401);
}
return $this->respondWithToken($token);
//return response()->json(User::all());
}
/**
* Get the authenticated User.
*
* #return \Illuminate\Http\JsonResponse
*/
public function me()
{
return response()->json(auth()->user());
//return response()->json("hellllo");
}
/**
* Log the user out (Invalidate the token).
*
* #return \Illuminate\Http\JsonResponse
*/
public function logout()
{
auth()->logout();
return response()->json(['message' => 'Successfully logged out']);
}
/**
* Refresh a token.
*
* #return \Illuminate\Http\JsonResponse
*/
public function refresh()
{
return $this->respondWithToken(auth()->refresh());
}
/**
* Get the token array structure.
*
* #param string $token
*
* #return \Illuminate\Http\JsonResponse
*/
protected function respondWithToken($token)
{
return response()->json([
'access_token' => $token,
'token_type' => 'bearer',
'expires_in' => auth()->factory()->getTTL() * 60
]);
}
}
```
how are you ?
i'm new in laravel and i'm working in someone project and i want to register by phone number instate of email so m i can login by phone number only but is there any way to register by phone number only and get SMS verification after register
so any one will help me please
this is register controller code
<?php
namespace App\Http\Controllers\Auth;
use App\Models\Auth\Role\Role;
use App\Notifications\Auth\ConfirmEmail;
use Illuminate\Auth\Events\Registered;
use Illuminate\Http\Request;
use App\Models\Auth\User\User;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Validator;
use Illuminate\Foundation\Auth\RegistersUsers;
use Ramsey\Uuid\Uuid;
class RegisterController extends Controller
{
/*
|--------------------------------------------------------------------------
| Register Controller
|--------------------------------------------------------------------------
|
| This controller handles the registration of new users as well as their
| validation and creation. By default this controller uses a trait to
| provide this functionality without requiring any additional code.
|
*/
use RegistersUsers;
/**
* Where to redirect users after registration.
*
* #var string
*/
protected $redirectTo = '/';
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest');
}
/**
* Get a validator for an incoming registration request.
*
* #param array $data
* #return \Illuminate\Contracts\Validation\Validator
*/
protected function validator(array $data)
{
$rules = [
'name' => 'required|max:255',
'email' => 'required|email|max:255|unique:users',
'password' => 'required|min:6|confirmed',
];
if (config('auth.captcha.registration')) {
$rules['g-recaptcha-response'] = 'required|captcha';
}
return Validator::make($data, $rules);
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return User|\Illuminate\Database\Eloquent\Model
*/
protected function create(array $data)
{
/** #var $user User */
$user = User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
'confirmation_code' => Uuid::uuid4(),
'confirmed' => false
]);
if (config('auth.users.default_role')) {
$user->roles()->attach(Role::firstOrCreate(['name' => config('auth.users.default_role')]));
}
return $user;
}
/**
* Handle a registration request for the application.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function register(Request $request)
{
$this->validator($request->all())->validate();
event(new Registered($user = $this->create($request->all())));
$this->guard()->login($user);
return $this->registered($request, $user)
?: redirect($this->redirectPath());
}
/**
* The user has been registered.
*
* #param \Illuminate\Http\Request $request
* #param mixed $user
* #return mixed
*/
protected function registered(Request $request, $user)
{
if (config('auth.users.confirm_email') && !$user->confirmed) {
$this->guard()->logout();
$user->notify(new ConfirmEmail());
return redirect(route('login'));
}
}
}
this is the api register controller code
<?php
namespace App\Http\Controllers\Api\Auth;
use App\Http\Controllers\Controller;
use App\Http\Requests\RegisterRequest;
use App\Models\Auth\User\User;
use Illuminate\Auth\Events\Registered;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Password;
use Illuminate\Support\Facades\Validator;
class RegisterController extends Controller
{
/*
|--------------------------------------------------------------------------
| Register Controller
|--------------------------------------------------------------------------
|
| This controller handles user registration via REST API
|
*/
/**
* Handle a registration request for the application.
*
* #param RegisterRequest $request
* #return \Illuminate\Http\Response
*/
public function register(RegisterRequest $request)
{
$user = $this->create($request->all());
// attach role
$role = \App\Models\Auth\Role\Role::where('name', 'user')->first();
$user->roles()->attach($role);
event(new Registered($user));
$token = $user->createToken('Default')->accessToken;
return response()->json(["token" => $token, "user" => User::find($user->id)]);
}
/**
* Verifies user's mobile
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function verifyMobile(Request $request)
{
Validator::make($request->all(), [
'mobile_number' => 'required|string|exists:users,mobile_number'
])->validate();
$user = User::where('mobile_number', $request->mobile_number)->first();
$user->mobile_verified = 1;
$user->save();
$token = $user->createToken('Default')->accessToken;
return response()->json(["token" => $token, "user" => $user]);
}
/**
* Send a reset link to the given user.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\RedirectResponse|\Illuminate\Http\JsonResponse
*/
public function sendResetLinkEmail(Request $request)
{
Validator::make($request->all(), [
'email' => 'required|email'
])->validate();
// We will send the password reset link to this user. Once we have attempted
// to send the link, we will examine the response then see the message we
// need to show to the user. Finally, we'll send out a proper response.
$response = Password::broker()->sendResetLink(
$request->only('email')
);
return $response == Password::RESET_LINK_SENT
? response()->json(["message" => "Email Sent"])
: response()->json(["message" => "Email Not Sent"], 400);
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return \App\Models\Auth\User\User
*/
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
'mobile' => $data['mobile'],
]);
}
}
and this is register request code
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class RegisterRequest 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 [
'name' => 'required|max:255',
'email' => 'required|email|max:255|unique:users',
'mobile' => 'required|unique:users',
'password' => 'required|min:6'
];
}
}
and this is login controller code
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;
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 AuthenticatesUsers;
/**
* Where to redirect users after login.
*
* #var string
*/
protected $redirectTo = '/admin';
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest', ['except' => 'logout']);
}
/**
* Log the user out of the application.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function logout(Request $request)
{
$this->guard()->logout();
/*
* Remove the socialite session variable if exists
*/
\Session::forget(config('access.socialite_session_name'));
$request->session()->flush();
$request->session()->regenerate();
return redirect('/');
}
/**
* Get the failed login response instance.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\RedirectResponse
*/
protected function sendFailedLoginResponse(Request $request)
{
$errors = [$this->username() => __('auth.failed')];
if ($request->expectsJson()) {
return response()->json($errors, 422);
}
return redirect()->back()
->withInput($request->only($this->username(), 'remember'))
->withErrors($errors);
}
/**
* The user has been authenticated.
*
* #param \Illuminate\Http\Request $request
* #param mixed $user
* #return mixed
*/
protected function authenticated(Request $request, $user)
{
$errors = [];
if (config('auth.users.confirm_email') && !$user->confirmed) {
$errors = [$this->username() => __('auth.notconfirmed', ['url' => route('confirm.send', [$user->email])])];
}
if (!$user->active) {
$errors = [$this->username() => __('auth.active')];
}
if(!$user->hasRole('administrator')) {
$errors = [$this->username() => 'Only administrator can login'];
}
if ($errors) {
auth()->logout(); //logout
return redirect()->back()
->withInput($request->only($this->username(), 'remember'))
->withErrors($errors);
}
return redirect()->intended($this->redirectPath());
}
}
and this is api login controller code
<?php
namespace App\Http\Controllers\Api\Auth;
use App\Http\Controllers\Controller;
use App\Http\Requests\LoginRequest;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class LoginController extends Controller
{
/*
|--------------------------------------------------------------------------
| Login Controller
|--------------------------------------------------------------------------
|
| This controller handles authenticating users via REST API
|
*/
public function authenticate(LoginRequest $request)
{
$username = filter_var($request->login, FILTER_VALIDATE_EMAIL) ? 'email' : 'mobile';
if (Auth::attempt([$username => $request->login, 'password' => $request->password])) {
$user = Auth::user();
$token = $user->createToken('Default')->accessToken;
return response()->json(["token" => $token, "user" => $user]);
}
return response()->json(["error" => "Invalid Login"], 400);
}
}
I am using JWT Authentication and I am trying to setup a Reset Password api functionality using ResetsPasswords.
I have created my own controller for reseting the password to use ResetsPasswords:
namespace App\Http\Controllers\v1;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use JWTAuth;
use Tymon\JWTAuth\Exceptions\JWTException;
use App\Models\PdTlogin;
use App\Models\PdTprofessional;
use App\Models\PdTpatientPainkiller;
use App\Models\PdTprofessionalQualifcation;
use App\Models\PdTprofessionalSpeciality;
use Config;
use LbTtradesman_login;
use Auth;
use Illuminate\Foundation\Auth\ResetsPasswords;
class ResetPasswordController extends Controller
{
use ResetsPasswords;
public function resetPassword(request $request)
{
return json_encode($this->reset($request));
}
public function __construct()
{
$this->middleware('guest');
}
}
And I am calling the reset function in ResetsPasswords, here is that full controller:
namespace Illuminate\Foundation\Auth;
use Illuminate\Support\Str;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Password;
trait ResetsPasswords
{
use RedirectsUsers;
/**
* Reset the given user's password.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\RedirectResponse
*/
public function reset(Request $request)
{
//$this->validate($request, $this->rules(), $this->validationErrorMessages());
// Here we will attempt to reset the user's password. If it is successful we
// will update the password on an actual user model and persist it to the
// database. Otherwise we will parse the error and return the response.
$response = $this->broker()->reset(
$this->credentials($request), function ($user, $password) {
$this->resetPassword($user, $password);
}
);
// If the password was successfully reset, we will redirect the user back to
// the application's home authenticated view. If there is an error we can
// redirect them back to where they came from with their error message.
return $response == Password::PASSWORD_RESET
? $this->sendResetResponse($response)
: $this->sendResetFailedResponse($request, $response);
}
/**
* Get the password reset validation rules.
*
* #return array
*/
protected function rules()
{
return [
'token' => 'required',
'email' => 'required|email',
'password' => 'required|confirmed|min:6',
];
}
/**
* Get the password reset validation error messages.
*
* #return array
*/
protected function validationErrorMessages()
{
return [];
}
/**
* Get the password reset credentials from the request.
*
* #param \Illuminate\Http\Request $request
* #return array
*/
protected function credentials(Request $request)
{
return $request->only(
'email', 'password', 'password_confirmation', 'token'
);
}
/**
* Reset the given user's password.
*
* #param \Illuminate\Contracts\Auth\CanResetPassword $user
* #param string $password
* #return void
*/
protected function resetPassword($user, $password)
{
$user->forceFill([
'password' => bcrypt($password),
'remember_token' => Str::random(60),
])->save();
$this->guard()->login($user);
}
/**
* Get the response for a successful password reset.
*
* #param string $response
* #return \Illuminate\Http\RedirectResponse
*/
protected function sendResetResponse($response)
{
return trans($response);
}
/**
* Get the response for a failed password reset.
*
* #param \Illuminate\Http\Request
* #param string $response
* #return \Illuminate\Http\RedirectResponse
*/
protected function sendResetFailedResponse(Request $request, $response)
{
return ['email' => trans($response)];
}
/**
* Get the broker to be used during password reset.
*
* #return \Illuminate\Contracts\Auth\PasswordBroker
*/
public function broker()
{
return Password::broker('pd_tlogin');
}
/**
* Get the guard to be used during password reset.
*
* #return \Illuminate\Contracts\Auth\StatefulGuard
*/
protected function guard()
{
return Auth::guard();
}
}
But when I run everything, my password does not get updated. Instead I get this error:
Type error: Argument 1 passed to
App\Http\Controllers\v1\ResetPasswordController::resetPassword() must
be an instance of Illuminate\Http\Request, instance of App\User given,
called in
/var/www/html/my_project/vendor/laravel/framework/src/Illuminate/Foundation/Auth/ResetsPasswords.php
on line 45
I really don't understand this error or what I am doing wrong :( All I know is that my User model is App\Models\PdTlogin with the database table name of pd_tlogin
UPDATE
I have also tried this:
public function resetPassword(request $request)
{
$this->validate($request, [
'token' => 'required',
'email' => 'required|email',
'password' => 'required|confirmed',
]);
$credentials = $request->only(
'email', 'password', 'password_confirmation', 'token'
);
$response = $this->passwords->reset($credentials, function($user, $password) {
$user->password = bcrypt($password);
$user->save();
$this->auth->login($user);
});
return json_encode($response);
}
But I got this error:
Undefined property:
App\Http\Controllers\v1\ResetPasswordController::$passwords',
'/var/www/html/my_project/app/Http/Controllers/v1/ResetPasswordController.php
You are invoking resetPassword of the ResetPasswordController instead of invoking resetPassword of the ResetPasswords trait. Change the resetPassword function name in your controller or use an alias for the trait resetPassword function like this:
use ResetsPasswords
{
resetPassword as protected resetUserPassword;
}
Well, It seems you need a json resonse from the reset method. Modify your ResetPasswordController as,
<?php
namespace App\Http\Controllers\v1;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ResetsPasswords;
//...
class ResetPasswordController extends Controller
{
use ResetsPasswords;
protected function sendResetResponse($response)
{
return response()->json(['success' => trans($response)]);
}
protected function sendResetFailedResponse(Request $request, $response)
{
return response()->json(['error' => trans($response)], 401);
}
// removed min:6 validation
protected function rules()
{
return [
'token' => 'required',
'email' => 'required|email',
'password' => 'required|confirmed',
];
}
public function __construct()
{
$this->middleware('guest');
}
}
And point your reset route to ResetPasswordController#reset.
return response()->json(['message'=> __('labels.password_updated')]);
I would like to count how many times a user has been logged in using the Events in Laravel.
I have this Event defined:
<?php namespace App\Handlers\Events;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldBeQueued;
use App\User;
use Illuminate\Support\Facades\Log;
class AuthLoginEventHandler {
/**
* Create the event handler.
*
* #return void
*/
public function __construct()
{
//
}
/**
* Handle the event.
*
* #param User $user
* #param $remember
* #return void
*/
public function handle(User $user, $remember)
{
Log::info('Logged in');
$user->login_counter = 1;
$user->save();
$user->increment('login_counter');
}
}
and in the EventServiceProvider I have the following:
<?php namespace App\Providers;
use Illuminate\Contracts\Events\Dispatcher as DispatcherContract;
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;
use Illuminate\Support\Facades\Event;
use Illuminate\Support\Facades\Log;
class EventServiceProvider extends ServiceProvider {
/**
* The event handler mappings for the application.
*
* #var array
*/
protected $listen = [
'auth.login' => [
'App\Handlers\Events\AuthLoginEventHandler'
]
];
/**
* Register any other events for your application.
*
* #param \Illuminate\Contracts\Events\Dispatcher $events
* #return void
*/
public function boot(DispatcherContract $events)
{
parent::boot($events);
//
}
}
Update:
I have override the postLogin() from trait to the AuthController as:
<?php namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Contracts\Auth\Guard;
use Illuminate\Contracts\Auth\Registrar;
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;
class AuthController extends Controller {
use AuthenticatesAndRegistersUsers;
/**
* Create a new authentication controller instance.
*
* #param \Illuminate\Contracts\Auth\Guard $auth
* #param \Illuminate\Contracts\Auth\Registrar $registrar
* #return void
*/
public function __construct(Guard $auth, Registrar $registrar)
{
$this->auth = $auth;
$this->registrar = $registrar;
$this->middleware('guest', ['except' => 'getLogout']);
}
public function postLogin(Request $request)
{
$this->validate($request, [
'email' => 'required|email', 'password' => 'required',
]);
$credentials = $request->only('email', 'password');
if ($this->auth->attempt($credentials, $request->has('remember')))
{
Log::info('Logged in User from AuthController');
return redirect()->intended($this->redirectPath());
}
return redirect($this->loginPath())
->withInput($request->only('email', 'remember'))
->withErrors([
'email' => $this->getFailedLoginMessage(),
]);
}
}
This is not working on my Laravel 5.0, I dont know why, is there any other alternative to count the logins of user other than using Events?
I am checking the logs and there is nothing comming in, when I try Log::info('Logged in'); within the boot method, it comes to logs.
First thing, because you have added something up into Provider, you need to clear the previous compiled source (which is cached to speed up loading time).
$ php artisan clear-compiled
Secondly, your code has counting problem,
$user->login_counter = 1; <-- set count to 1 ??
$user->save(); <--- then SAVE?
$user->increment('login_counter'); <--- INCREMENT for what?
Instead, it should be like this
$user->login_counter += 1;
$user->save();
Make sure in the migration you have the default (initial) value for login_counter
$table->integer('login_counter')->unsigned()->default(0);
Then it just works!