Viewing file: AuthController_limit.php (6.6 KB) -rw-r--r-- Select action/file-type: (+) | (+) | (+) | Code (+) | Session (+) | (+) | SDB (+) | (+) | (+) | (+) | (+) | (+) |
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\User;
use App\Models\Vendor;
use App\Models\UserLogin;
use Illuminate\Support\Facades\Auth;
use Tymon\JWTAuth\Facades\JWTAuth;
use Tymon\JWTAuth\Exceptions\JWTException;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\RateLimiter;
use GuzzleHttp\Client;
class AuthController extends Controller
{
public function __construct() {
$this->middleware('auth', ['except' => ['login', 'register','re_generate','resetPassword' ]]);
}
/**
* Attempt to register a new user to the API.
*
* @param Request $request
* @return Response
*/
public function register(Request $request)
{
// Are the proper fields present?
// $this->validate($request, [
// 'name' => 'required|string|between:2,100',
// 'email' => 'required|string|email|max:100',
// 'phone' => 'required|string|unique:users',
// 'password' => 'required|string|min:6',
// ]);
// try {
// $plainPassword = $request->input('password');
// $user = new User;
// $user->name = $request->input('name');
// $user->email = $request->input('email');
// $user->phone = $request->input('phone');
// $user->password = app('hash')->make($plainPassword);
// $user->save();
// return response()->json(['user' => $user, 'message' => 'CREATED'], 201);
// } catch (\Exception $e) {
// return response()->json(['message' => 'User Registration Failed!'], 409);
// }
}
/**
* Attempt to authenticate the user and retrieve a JWT.
* Note: The API is stateless. This method _only_ returns a JWT. There is not an
* indicator that a user is logged in otherwise (no sessions).
*
* @param Request $request
* @return Response
*/
public function username(){
return 'phone';
}
public function login(Request $request)
{
$key = 'login:' . $request->ip(); // Rate limit based on IP address
$maxAttempts = 2; // Maximum attempts
$decayMinutes = 1; // Lockout duration in minutes
if (RateLimiter::tooManyAttempts($key, $maxAttempts)) {
$retryAfter = RateLimiter::availableIn($key);
return response()->json([
'message' => 'Too many login attempts. Please try again after ' . $retryAfter . ' seconds.',
], 429);
}
$validator = Validator::make($request->all(), [
'phone' => 'required|max:20',
'password' => 'required|string|max:32',
'device_information'=>'required'
], [
'phone.required' => 'User name is required',
'phone.max' => 'Invalid username data type',
'password.required' => 'Password is required',
'password.max' => 'Invalid password size',
'device_information.required' => 'Invalid Login attempt'
]);
if ($validator->fails()==true) {
RateLimiter::hit($key, $decayMinutes * 60);
return response()->json($validator->errors()->all(),400);
}
// $this->validate($request, [
// 'phone' => 'required|max:20',
// 'password' => 'required|string|max:32',
// 'device_information'=>'required'
// ]);
$credentials = $request->only(['phone', 'password'])+ ['active' => 1];
if (! $token = Auth::attempt($credentials)) {
RateLimiter::hit($key, $decayMinutes * 60);
return response()->json(["error"=>"true","message"=>"Invalid phone number or password"],401);
}
RateLimiter::clear($key);
return $this->respondWithToken($token);
}
/**
* Log the user out (Invalidate the token). Requires a login to use as the
* JWT in the Authorization header is what is invalidated
*
* @return \Illuminate\Http\JsonResponse
*/
public function logout() {
auth()->logout();
return response()->json(['message' => 'User successfully signed out']);
}
/**
* Refresh the current token.
*
* @return \Illuminate\Http\JsonResponse
*/
public function rrefresh() {
try{
$token = (string) auth()->refresh();
return $this->respondWithToken($token);
} catch (\Exception $exception) {
return response()->json(['error' => 'true', 'message' =>$exception->getMessage()],500);
}
}
/**
* Helper function to format the response with the token.
*
* @return \Illuminate\Http\JsonResponse
*/
private function respondWithToken($token)
{
$user = auth()->user();
$user->makeHidden(['last_ip_address','fee_group','password', 'is_synced','active','last_country','created_at','updated_at']);
$modifiedUser = $user->toArray();
return response()->json([
'token' => $token,
'token_type' => 'bearer',
'expires_in' => Auth::factory()->getTTL(),
'auth'=>$modifiedUser
], 200);
}
public function re_generate(Request $request) {
try{
$token = JWTAuth::parseToken();
$refreshedToken = $token->refresh();
// return response()->json(['token' => $refreshedToken]);
return response()->json([
'token' => $refreshedToken,
'token_type' => 'bearer',
'expires_in' => Auth::factory()->getTTL(),
], 200);
}catch (JWTException $exception) {
return response()->json(['error' => 'true', 'message' =>$exception->getMessage()], 401);
}
// catch (\Exception $exception) {
// return response()->json(['error' => 'true', 'message' =>$exception->getMessage()],401);
// }
}
function changePassword(Request $req) {
$vendor_id=auth()->user()->id;
$user=Vendor::find($vendor_id);
if (Hash::check($req->input('old_password'), $user->password)) {
$user->password=Hash::make($req->input('new_password'));
$user->save();
return response()->json(["message"=>"Password Changed"]);
} else {
return response()->json(["error"=>"true","message"=>"Old password not matched"]);
}
}
public function resetPassword($phone_no, Request $req)
{
try{
$vendor=Vendor::where('phone',$phone_no)->where('active',1)->first();
if ( $vendor) {
$vendor->password= Hash::make($req->input('password'));
$ven=$vendor->save();
return response()->json(["message" => "Password Updated Successfully"]);
}else {
return response()->json(["message" => "Phone number not found."]);
}
} catch (\Exception $exception) {
return response()->json(['error' => 'true', 'message' =>$exception->getMessage()],500);
}
}
}
|