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')]);
Related
I am trying to update an old (5.2) laravel installation to the newest one (9.2) and most is working except the authentication part.
I already installed laravel/ui, I have an authentication middleware, route and controller but for some reason I get:
Invalid route action: [App\Http\Controllers\Auth\AuthController].
My Authenticate.php middleware:
<?php
namespace App\Http\Middleware;
use Illuminate\Auth\Middleware\Authenticate as Middleware;
class Authenticate extends Middleware
{
/**
* Get the path the user should be redirected to when they are not authenticated.
*
* #param \Illuminate\Http\Request $request
* #return string|null
*/
protected function redirectTo($request)
{
if (! $request->expectsJson()) {
return route('login');
}
}
}
My route in web.php :
Route::get('/login', 'App\Http\Controllers\Auth\AuthController')->name('login');
And my AuthController:
<?php
namespace App\Http\Controllers\Auth;
use App\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Topsite\Dataroom\Models\LogEntry;
use Validator;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ThrottlesLogins;
use Illuminate\Foundation\Auth\RegistersUsers;
class AuthController extends Controller
{
/*
|--------------------------------------------------------------------------
| Registration & Login Controller
|--------------------------------------------------------------------------
|
| This controller handles the registration of new users, as well as the
| authentication of existing users. By default, this controller uses
| a simple trait to add these behaviors. Why don't you explore it?
|
*/
use RegistersUsers, ThrottlesLogins;
/**
* Where to redirect users after login / registration.
*
* #var string
*/
protected $redirectTo = '/';
/**
* The custom login view.
*
* #var string
*/
protected $loginView = 'pages.login';
/**
* Create a new authentication controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest', ['except' => 'logout']);
}
/**
* Get a validator for an incoming registration request.
*
* #param array $data
* #return \Illuminate\Contracts\Validation\Validator
*/
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',
]);
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return User
*/
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
]);
}
/**
* Send the response after the user was authenticated.
*
* #param \Illuminate\Http\Request $request
* #param bool $throttles
* #return \Illuminate\Http\Response
*/
protected function handleUserWasAuthenticated(Request $request, $throttles)
{
if ($throttles) {
$this->clearLoginAttempts($request);
}
if (method_exists($this, 'authenticated')) {
return $this->authenticated($request, Auth::guard($this->getGuard())->user());
}
LogEntry::create([
'account_id' => Auth::id(),
'message' => 'Ingelogd'
]);
return redirect()->intended($this->redirectPath());
}
}
I thought maybe I need to set a method in the route so I changed the route to:
Route::get('/login', 'App\Http\Controllers\Auth\AuthController#handleUserWasAuthenticated')->name('login');
But this gives:
Too few arguments to function App\Http\Controllers\Auth\AuthController::handleUserWasAuthenticated(), 1 passed in C:\xampp\htdocs\dataroom.website.nl.test\vendor\laravel\framework\src\Illuminate\Routing\Controller.php on line 54 and exactly 2 expected
I think the $throttles variable is empty but what needs to be passed there? Or maybe I am thinking wrong alltogether and the fix is something else?
I have a boolean column in my users table for active. But I can't figure out how to have the column checked during login and only allow login if active has a value of 1. I wish I had examples of code I've tried, but I am literally stuck. I am using Laravel 8 and Breeze. I am assuming that the check would happen inside the AuthenticatedSessionController file in the store function. Below is the file.
AuthenticatedSessionController.php
<?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\Support\Facades\Auth;
class AuthenticatedSessionController extends Controller
{
/**
* Display the login view.
*
* #return \Illuminate\View\View
*/
public function create()
{
return view('auth.login');
}
/**
* Handle an incoming authentication request.
*
* #param \App\Http\Requests\Auth\LoginRequest $request
* #return \Illuminate\Http\RedirectResponse
*/
public function store(LoginRequest $request)
{
$request->authenticate();
$request->session()->regenerate();
return redirect()->intended(RouteServiceProvider::HOME);
}
/**
* Destroy an authenticated session.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\RedirectResponse
*/
public function destroy(Request $request)
{
Auth::guard('web')->logout();
$request->session()->invalidate();
$request->session()->regenerateToken();
return redirect('/');
}
}
Please look at authenticate() function located at app/Http/Requests/LoginRequest.php
/**
* Attempt to authenticate the request's credentials.
*
* #return void
*
* #throws \Illuminate\Validation\ValidationException
*/
public function authenticate()
{
$this->ensureIsNotRateLimited();
//array_merge( $request->only($this->username(), 'password'), ['is_active' => 1 ])
//if (! Auth::attempt($this->only('email', 'password'), $this->filled('remember'))) {
if (! Auth::attempt(array_merge( $this->only('email', 'password'), ['is_active' => 1 ]), $this->filled('remember'))) {
RateLimiter::hit($this->throttleKey());
throw ValidationException::withMessages([
'email' => __('auth.failed'),
]);
}
RateLimiter::clear($this->throttleKey());
}
You have to use AuthenticatesUsers where you doing POST login request
AuthenticatesUsers is Laravel's default authentication trait which provide the Login Related methods.
You have to place below method in your LoginController to override default method and add your column to check if user is active or not.
protected function credentials(Request $request)
{
return array_merge($request->only($this->username(), 'password'), ['active' => 1]);
}
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?
I implemented MustVerifyEmail interface in my user model
class User extends Authenticatable implements MustVerifyEmail
also I made VerificationApi Controller
<?php
namespace App\Http\Controllers;
use App\Models\User;
use Illuminate\Foundation\Auth\VerifiesEmails;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Auth\Events\Verified;
class VerificationApiController extends Controller
{
use VerifiesEmails;
* Mark the authenticated user’s email address as verified.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function verify(Request $request) {
$userID = $request['id'];
$user = User::findOrFail($userID);
$date = date("Y-m-d H:i:s");
$user->email_verified_at = $date; // to enable the “email_verified_at field of that user be a current time stamp by mimicing the must verify email feature
$user->save();
return response()->json('Email verified!');
}
/**
* Resend the email verification notification.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function resend(Request $request)
{
if ($request->user()->hasVerifiedEmail()) {
return response()->json('User already have verified email!', 422);
// return redirect($this->redirectPath());
}
$request->user()->sendEmailVerificationNotification();
return response()->json('The notification has been resubmitted');
}
}
and I made
<?php
namespace App\Notifications;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\URL;
use Illuminate\Auth\Notifications\VerifyEmail as VerifyEmailBase;
class VerifyApiEmail extends VerifyEmailBase
{
/**
* Get the verification URL for the given notifiable.
*
* #param mixed $notifiable
* #return string
*/
protected function verificationUrl($notifiable)
{
return URL::temporarySignedRoute(
'verificationapi.verify', Carbon::now()->addMinutes(60), ['id' => $notifiable->getKey()]
); // this will basically mimic the email endpoint with get request
}
}
in my api.php file I added
Route::get('email/verify/{id}', 'VerificationApiController#verify')->name('verificationapi.verify');
Route::get('email/resend', 'VerificationApiController#resend')->name('verificationapi.resend');
So when i register to my api I get verification email in my mailtrap and when I click the button it says that my email is verified and in my database it changes from null to email_verified_at 2019-05-27 13:04:20 but when I put middleware('verified') on my routes and when I login with user that I have registrated in my postman I get
"message": "Your email address is not verified.",
"exception": "Symfony\\Component\\HttpKernel\\Exception\\HttpException",
my register() and login() functions look like this:
public function register(Request $request, User $user)
{
$phoneRegex = "(06|387)[0-9]{7,8}";
$request->validate([
'first_name' => 'required|string',
'last_name' => 'required|string',
'email' => 'required|string|email|unique:users',
'password' => 'required|string|confirmed',
'phone_number' => 'required|string|min:6',
]);
$user = new User([
'first_name' => $request->first_name,
'last_name' => $request->last_name,
'email' => $request->email,
'password' => bcrypt($request->password),
'phone_number' => $request['phone_number'],
]);
$user->save();
Auth::login($user,true);
$user->sendApiEmailVerificationNotification();
$success['message'] = 'Please confirm yourself by clicking on verify user button sent to you on your email';
return response()->json(['success'=>$success], $this->successStatus);
}
public function login(Request $request)
{
$request->request->add([
'client_id' => env("PASSPORT_CLIENT_ID"),
'client_secret' => env("PASSPORT_CLIENT_SECRET"),
'grant_type' => 'password',
'scope' => '',
]);
$tokenRequest = $request->create('/oauth/token', 'POST', $request->all());
$response = Route::dispatch($tokenRequest);
return $response;
}
can someone help me with this?
I solved this by doing the following:
Create a file
Http > Middleware > EnsureEmailIsVerified.php
with this code
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Contracts\Auth\Factory as Auth;
class EnsureEmailIsVerified
{
/**
* The authentication factory instance.
*
* #var \Illuminate\Contracts\Auth\Factory
*/
protected $auth;
/**
* Create a new middleware instance.
*
* #param \Illuminate\Contracts\Auth\Factory $auth
* #return void
*/
public function __construct(Auth $auth)
{
$this->auth = $auth;
}
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #param string|null $redirectToRoute
* #return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
*/
public function handle($request, Closure $next, $guard = null)
{
if (! $request->user($guard)) {
if($request->expectsJson()) {
return response()->json([
'message' => 'You do not have permission to access this feature.',
'errors' => [
'main' => ['The access token is either missing or incorrect.']
]
], 401);
} else {
return redirect(route('login'));
}
} else if
($request->user($guard) instanceof MustVerifyEmail &&
! $request->user($guard)->hasVerifiedEmail()) {
if($request->expectsJson()) {
return response()->json([
'message' => 'You do not have permission to access this feature.',
'errors' => [
'main' => ['Your email address is not verified.']
]
], 403);
} else {
return redirect(route('verification.notice'));
}
}
$this->auth->shouldUse($guard);
return $next($request);
}
}
In the Kernel.php file, change the value for 'verified'
protected $routeMiddleware = [
...
'verified' => \App\Http\Middleware\EnsureEmailIsVerified::class,
]
In the routes > api.php file use verified:api
Route::group(['middleware' => 'verified:api'], function () {
Route::get('/user', function (Request $request) {
return $request->user();
});
});
This works well for me, as I can use the same middleware for both my API and website while still being as generic as possible.
I just added this to my login() function and now it looks like this
public function login(Request $request)
{
$request->request->add([
'client_id' => env("PASSPORT_CLIENT_ID"),
'client_secret' => env("PASSPORT_CLIENT_SECRET"),
'grant_type' => 'password',
'scope' => '',
]);
$tokenRequest = $request->create('/oauth/token', 'POST', $request->all());
$response = Route::dispatch($tokenRequest);
$user = User::where('email', $request->username)->first();
if($user->email_verified_at !== NULL){
$success['message'] = "Login successfull";
return $response;
}else{
return response()->json(['error'=>'Please Verify Email'], 401);
}
}
and now if you did not verify your email you can't login it does not give you your access and refresh token back but I don't have to use my middleware('verified') on my routes so if someone still have better solution I would appreciate it.
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);
}
}