Viewing file: AuthController.php (8.72 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 App\Helpers\NotificationHelper;
use DateTime;
use Carbon\Carbon;
use GuzzleHttp\Client;
class AuthController extends Controller
{
public function __construct() {
$this->middleware('auth', ['except' => ['login', 'register','re_generate','resetPassword','logout']]);
}
/**
* 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';
}
private function notification($endpoint,$body) {
register_shutdown_function(function () use ($endpoint,$body) {
try {
$notification=new NotificationHelper();
$notification->send('/login',$body);
}catch (\Exception $e) {
\Log::error('Error API call failed', ['error' => $e->getMessage()]);
}
});
}
public function login(Request $request)
{
$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) {
// return redirect()->back()->withErrors($validator->errors()->all())->withInput();
// return $validator->errors()->all();
return response()->json($validator->errors()->all(),402);
}
$credentials = $request->only(['phone', 'password'])+ ['active' => 1];
$user=User::where("phone",$request->input("phone"))->where("delete_request","!=",2)->first();
if ($user) {
$date = Carbon::now('Asia/Dhaka'); // Example date
$formattedDate = $date->format('M j, Y, \a\t g:i A'); // Jan 2, 2025, at 3:45 PM
$body=["json"=>[
'vendor_id' =>$user->id,
'device_info'=>$request->input("device_information"),
"date_time"=>$formattedDate
]];
if (! $token = Auth::attempt($credentials)) {
$this->notification('/login',$body);
return response()->json(["error"=>"true","message"=>"Invalid Credentials"],401);
}
}
if (! $token = Auth::attempt($credentials)) {
return response()->json(["error"=>"true","message"=>"Invalid Credentials"],401);
}
// UserLogin::create([
// 'user_id' =>auth()->user()->id,
// 'vendor_id' =>auth()->user()->id,
// 'ip_address' =>$request->ip(),
// 'username' =>$request->input('phone'),
// 'device_information'=>$request->input('device_information')
// ]);
// $client = new Client();
// $resp = $client->get("http://ip-api.com/json/{$request->ip()}");
// // Retrieve the response body
// $body = $resp->getBody();
// $location = json_decode($body);
// User::where("id",auth()->user()->id)->update([
// 'last_ip_address' =>$request->ip(),
// 'last_country' => $location->country
// ]);
// return $this->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();
$this->notification('/login',$body);
return response()->json([
'token' => $token,
'token_type' => 'bearer',
'expires_in' => Auth::factory()->getTTL(),
'auth'=>$modifiedUser
], 200);
}
/**
* 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);
return response('Unauthorized.', 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();
$date = Carbon::now('Asia/Dhaka');
$formattedDate = $date->format('M j, Y, \a\t g:i A');
$body=["json"=>[
'vendor_id' =>$vendor_id,
"date_time"=>$formattedDate
]];
$this->notification('/password',$body);
return response()->json(["message"=>"Password Changed"]);
} else {
return response()->json(["error"=>"true","message"=>"Old password not matched"],400);
}
}
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();
$date = Carbon::now('Asia/Dhaka');
$formattedDate = $date->format('M j, Y, \a\t g:i A');
$body=["json"=>[
'vendor_id' =>$vendor->id,
"date_time"=>$formattedDate
]];
$this->notification('/password',$body);
return response()->json(["message" => "Password Updated Successfully"]);
}else {
return response()->json(["error"=>"true","message" => "No account found with your phone number."],400);
}
} catch (\Exception $exception) {
return response()->json(['error' => 'true', 'message' =>$exception->getMessage()],500);
}
}
}
|