initial commit
This commit is contained in:
@@ -0,0 +1,56 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use Illuminate\Http\Request;
|
||||
use App\Models\User;
|
||||
use App\Models\HealthData;
|
||||
use DB;
|
||||
|
||||
class AdminController extends Controller
|
||||
{
|
||||
public function dashboard(Request $request)
|
||||
{
|
||||
$userRoleCounts = User::groupBy('user_role')
|
||||
->select('user_role', DB::raw('count(*) as count'))
|
||||
->get();
|
||||
|
||||
$doctorCount = User::where('user_role', 'doctor')->count();
|
||||
$patientCount = User::where('user_role', 'user')->count();
|
||||
$maleCount = User::where('user_role', 'user')->where('gender', 'Male')->count();
|
||||
$femaleCount = User::where('user_role', 'user')->where('gender', 'Female')->count();
|
||||
|
||||
$normalCount = HealthData::where('obesity_status', 'Normal')->count();
|
||||
$obesityCount = HealthData::where('obesity_status', 'Obesity')->count();
|
||||
|
||||
return view('dashboardAdmin',
|
||||
compact('userRoleCounts', 'doctorCount', 'patientCount', 'maleCount', 'femaleCount', 'normalCount', 'obesityCount'));
|
||||
}
|
||||
|
||||
public function showDoctor(Request $request){
|
||||
return view('doctor-list', ["data" => User::where('user_role', 'doctor')->get()]);
|
||||
}
|
||||
|
||||
public function showPatient(Request $request)
|
||||
{
|
||||
$data = User::where('user_role', 'user')->get();
|
||||
return view('patient-list')->with('data', $data);
|
||||
}
|
||||
|
||||
public function showUserDetail($id){
|
||||
$data = User::find($id);
|
||||
return view('update-user', compact('data'));
|
||||
}
|
||||
|
||||
public function updateData(Request $request, $id){
|
||||
$data = User::find($id);
|
||||
$data -> update($request -> all());
|
||||
return redirect()->route('showPatient');
|
||||
}
|
||||
|
||||
public function delete($id){
|
||||
$data = User::find($id);
|
||||
$data -> delete();
|
||||
return redirect()->route('showPatient');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Api;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Models\HealthData;
|
||||
use Illuminate\Http\Request;
|
||||
|
||||
class HealthDataAPIController extends Controller
|
||||
{
|
||||
public function getHealthData($userId)
|
||||
{
|
||||
$healthData = HealthData::where('users_id', $userId)->first();
|
||||
|
||||
if (!$healthData) {
|
||||
return response()->json(['error' => 'Health data not found'], 404);
|
||||
}
|
||||
|
||||
return response()->json($healthData);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Api;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Models\User;
|
||||
use Illuminate\Http\Request;
|
||||
|
||||
class UserAPIController extends Controller
|
||||
{
|
||||
public function getUser($id)
|
||||
{
|
||||
$user = User::find($id);
|
||||
|
||||
if (!$user) {
|
||||
return response()->json(['error' => 'User not found'], 404);
|
||||
}
|
||||
|
||||
return response()->json($user);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Auth;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Http\Requests\Auth\LoginRequest;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use Illuminate\View\View;
|
||||
use App\Models\User;
|
||||
|
||||
class AuthenticatedSessionController extends Controller
|
||||
{
|
||||
/**
|
||||
* Display the login view.
|
||||
*/
|
||||
public function create(): View
|
||||
{
|
||||
return view('auth.login');
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle an incoming authentication request.
|
||||
*/
|
||||
public function store(LoginRequest $request): RedirectResponse
|
||||
{
|
||||
$request->authenticate();
|
||||
$request->session()->regenerate();
|
||||
|
||||
$role = Auth::user()->user_role;
|
||||
|
||||
if ($role == 'user') {
|
||||
return redirect()->intended(route('dashboard'));
|
||||
} else if ($role == 'doctor') {
|
||||
// return redirect()->intended(route('doctor.dashboard'));
|
||||
} else {
|
||||
return redirect()->intended(route('admin.dashboard'));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Destroy an authenticated session.
|
||||
*/
|
||||
public function destroy(Request $request): RedirectResponse
|
||||
{
|
||||
Auth::guard('web')->logout();
|
||||
|
||||
$request->session()->invalidate();
|
||||
|
||||
$request->session()->regenerateToken();
|
||||
|
||||
if ($request->session()->has('remember_token')) {
|
||||
$request->session()->forget('remember_token');
|
||||
}
|
||||
|
||||
return redirect('/');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Auth;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
use Illuminate\View\View;
|
||||
|
||||
class ConfirmablePasswordController extends Controller
|
||||
{
|
||||
/**
|
||||
* Show the confirm password view.
|
||||
*/
|
||||
public function show(): View
|
||||
{
|
||||
return view('auth.confirm-password');
|
||||
}
|
||||
|
||||
/**
|
||||
* Confirm the user's password.
|
||||
*/
|
||||
public function store(Request $request): RedirectResponse
|
||||
{
|
||||
if (! Auth::guard('web')->validate([
|
||||
'email' => $request->user()->email,
|
||||
'password' => $request->password,
|
||||
])) {
|
||||
throw ValidationException::withMessages([
|
||||
'password' => __('auth.password'),
|
||||
]);
|
||||
}
|
||||
|
||||
$request->session()->put('auth.password_confirmed_at', time());
|
||||
|
||||
return redirect()->intended(route('dashboard', absolute: false));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Auth;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
use Illuminate\Http\Request;
|
||||
|
||||
class EmailVerificationNotificationController extends Controller
|
||||
{
|
||||
/**
|
||||
* Send a new email verification notification.
|
||||
*/
|
||||
public function store(Request $request): RedirectResponse
|
||||
{
|
||||
if ($request->user()->hasVerifiedEmail()) {
|
||||
return redirect()->intended(route('dashboard', absolute: false));
|
||||
}
|
||||
|
||||
$request->user()->sendEmailVerificationNotification();
|
||||
|
||||
return back()->with('status', 'verification-link-sent');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Auth;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\View\View;
|
||||
|
||||
class EmailVerificationPromptController extends Controller
|
||||
{
|
||||
/**
|
||||
* Display the email verification prompt.
|
||||
*/
|
||||
public function __invoke(Request $request): RedirectResponse|View
|
||||
{
|
||||
return $request->user()->hasVerifiedEmail()
|
||||
? redirect()->intended(route('dashboard', absolute: false))
|
||||
: view('auth.verify-email');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Auth;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use Illuminate\Auth\Events\PasswordReset;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Hash;
|
||||
use Illuminate\Support\Facades\Password;
|
||||
use Illuminate\Support\Str;
|
||||
use Illuminate\Validation\Rules;
|
||||
use Illuminate\View\View;
|
||||
|
||||
class NewPasswordController extends Controller
|
||||
{
|
||||
/**
|
||||
* Display the password reset view.
|
||||
*/
|
||||
public function create(Request $request): View
|
||||
{
|
||||
return view('auth.reset-password', ['request' => $request]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle an incoming new password request.
|
||||
*
|
||||
* @throws \Illuminate\Validation\ValidationException
|
||||
*/
|
||||
public function store(Request $request): RedirectResponse
|
||||
{
|
||||
$request->validate([
|
||||
'token' => ['required'],
|
||||
'email' => ['required', 'email'],
|
||||
'password' => ['required', 'confirmed', Rules\Password::defaults()],
|
||||
]);
|
||||
|
||||
// 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.
|
||||
$status = Password::reset(
|
||||
$request->only('email', 'password', 'password_confirmation', 'token'),
|
||||
function ($user) use ($request) {
|
||||
$user->forceFill([
|
||||
'password' => Hash::make($request->password),
|
||||
'remember_token' => Str::random(60),
|
||||
])->save();
|
||||
|
||||
event(new PasswordReset($user));
|
||||
}
|
||||
);
|
||||
|
||||
// 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 $status == Password::PASSWORD_RESET
|
||||
? redirect()->route('login')->with('status', __($status))
|
||||
: back()->withInput($request->only('email'))
|
||||
->withErrors(['email' => __($status)]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Auth;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Hash;
|
||||
use Illuminate\Validation\Rules\Password;
|
||||
|
||||
class PasswordController extends Controller
|
||||
{
|
||||
/**
|
||||
* Update the user's password.
|
||||
*/
|
||||
public function update(Request $request): RedirectResponse
|
||||
{
|
||||
$validated = $request->validateWithBag('updatePassword', [
|
||||
'current_password' => ['required', 'current_password'],
|
||||
'password' => ['required', Password::defaults(), 'confirmed'],
|
||||
]);
|
||||
|
||||
$request->user()->update([
|
||||
'password' => Hash::make($validated['password']),
|
||||
]);
|
||||
|
||||
return back()->with('status', 'password-updated');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Auth;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Password;
|
||||
use Illuminate\View\View;
|
||||
|
||||
class PasswordResetLinkController extends Controller
|
||||
{
|
||||
/**
|
||||
* Display the password reset link request view.
|
||||
*/
|
||||
public function create(): View
|
||||
{
|
||||
return view('auth.forgot-password');
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle an incoming password reset link request.
|
||||
*
|
||||
* @throws \Illuminate\Validation\ValidationException
|
||||
*/
|
||||
public function store(Request $request): RedirectResponse
|
||||
{
|
||||
$request->validate([
|
||||
'email' => ['required', 'email'],
|
||||
]);
|
||||
|
||||
// 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.
|
||||
$status = Password::sendResetLink(
|
||||
$request->only('email')
|
||||
);
|
||||
|
||||
return $status == Password::RESET_LINK_SENT
|
||||
? back()->with('status', __($status))
|
||||
: back()->withInput($request->only('email'))
|
||||
->withErrors(['email' => __($status)]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Auth;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Models\User;
|
||||
use Illuminate\Auth\Events\Registered;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use Illuminate\Support\Facades\Hash;
|
||||
use Illuminate\Validation\Rules;
|
||||
use Illuminate\View\View;
|
||||
|
||||
class RegisteredUserController extends Controller
|
||||
{
|
||||
/**
|
||||
* Display the registration view.
|
||||
*/
|
||||
public function create(): View
|
||||
{
|
||||
return view('auth.register');
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle an incoming registration request.
|
||||
*
|
||||
* @throws \Illuminate\Validation\ValidationException
|
||||
*/
|
||||
public function store(Request $request): RedirectResponse
|
||||
{
|
||||
$request->validate([
|
||||
'username' => 'required|string|unique:users',
|
||||
'password' => ['required', 'confirmed', Rules\Password::defaults()],
|
||||
'name' => ['required', 'string', 'max:255'],
|
||||
'email' => ['required', 'string', 'lowercase', 'email', 'max:255', 'unique:'.User::class],
|
||||
'telepon' => 'required|string',
|
||||
'alamat' => 'string',
|
||||
'gender' => 'required|string',
|
||||
]);
|
||||
|
||||
$user = User::create([
|
||||
'user_role' => 'user',
|
||||
'username' => $request->username,
|
||||
'password' => bcrypt($request->password),
|
||||
'name' => $request->name,
|
||||
'email' => $request->email,
|
||||
'telepon' => $request->telepon,
|
||||
'alamat' => $request->alamat,
|
||||
'gender' => $request->gender,
|
||||
]);
|
||||
|
||||
event(new Registered($user));
|
||||
|
||||
//Auth::login($user);
|
||||
|
||||
return redirect(route('login', absolute: false));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Auth;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use Illuminate\Auth\Events\Verified;
|
||||
use Illuminate\Foundation\Auth\EmailVerificationRequest;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
|
||||
class VerifyEmailController extends Controller
|
||||
{
|
||||
/**
|
||||
* Mark the authenticated user's email address as verified.
|
||||
*/
|
||||
public function __invoke(EmailVerificationRequest $request): RedirectResponse
|
||||
{
|
||||
if ($request->user()->hasVerifiedEmail()) {
|
||||
return redirect()->intended(route('dashboard', absolute: false).'?verified=1');
|
||||
}
|
||||
|
||||
if ($request->user()->markEmailAsVerified()) {
|
||||
event(new Verified($request->user()));
|
||||
}
|
||||
|
||||
return redirect()->intended(route('dashboard', absolute: false).'?verified=1');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use App\Models\HealthData;
|
||||
use App\Models\User;
|
||||
use App\Models\Consultation;
|
||||
use Illuminate\Http\Request;
|
||||
use Carbon\Carbon;
|
||||
|
||||
class ConsultationController extends Controller
|
||||
{
|
||||
public function showHealthDataForm()
|
||||
{
|
||||
$user = auth()->user();
|
||||
$healthData = HealthData::where('users_id', $user->id)->get()->last();
|
||||
return view('health-data', compact('healthData'));
|
||||
}
|
||||
|
||||
public function storeHealthDataForm(Request $request)
|
||||
{
|
||||
$validatedData = $request->validate([
|
||||
'birthdate' => 'required|date',
|
||||
'weight' => 'required|numeric',
|
||||
'height' => 'required|numeric',
|
||||
'sleeptime' => 'required|integer',
|
||||
'disease' => 'required|string',
|
||||
'food' => 'required|string',
|
||||
'alergi_makanan' => 'required|string',
|
||||
]);
|
||||
|
||||
$user = auth()->user();
|
||||
|
||||
$data = HealthData::create(
|
||||
[
|
||||
'users_id' => $user->id,
|
||||
'birthdate' => Carbon::parse($validatedData['birthdate'])->format('Y-m-d'),
|
||||
'weight' => $validatedData['weight'],
|
||||
'height' => $validatedData['height'],
|
||||
'sleeptime' => $validatedData['sleeptime'],
|
||||
'disease' => $validatedData['disease'],
|
||||
'food' => $validatedData['food'],
|
||||
'alergi_makanan' => $validatedData['alergi_makanan'],
|
||||
]
|
||||
);
|
||||
|
||||
return redirect()->route('jadwal.show');
|
||||
}
|
||||
|
||||
|
||||
public function showJadwalForm()
|
||||
{
|
||||
$user = auth()->user();
|
||||
$doctors = User::where('user_role', 'doctor')->get();
|
||||
return view('jadwal-konsultasi', compact('doctors'));
|
||||
}
|
||||
|
||||
// ConsultationController.php
|
||||
public function storeConsultation(Request $request)
|
||||
{
|
||||
$validatedData = $request->validate([
|
||||
'doctor_id' => 'required|exists:users,id',
|
||||
'consultation_date' => 'required|date',
|
||||
'consultation_time' => 'required',
|
||||
'location' => 'required|string',
|
||||
]);
|
||||
|
||||
$user = auth()->user();
|
||||
|
||||
$data = Consultation::create([
|
||||
'patient_id' => $user->id,
|
||||
'doctor_id' => $validatedData['doctor_id'],
|
||||
'consultation_date' => Carbon::parse($validatedData['consultation_date'])->format('Y-m-d'),
|
||||
'consultation_time' => $validatedData['consultation_time'],
|
||||
'location' => $validatedData['location'],
|
||||
'consultation_status' => 'pending',
|
||||
]);
|
||||
|
||||
return redirect()->route('dashboard');
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
abstract class Controller
|
||||
{
|
||||
//
|
||||
}
|
||||
@@ -0,0 +1,217 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use Illuminate\Http\Request;
|
||||
use App\Http\Controllers\StravaController;
|
||||
use App\Http\Controllers\ConsultationController;
|
||||
use App\Models\PhysicalActivity;
|
||||
use App\Models\HealthData;
|
||||
use App\Models\Result;
|
||||
use App\Models\Notification;
|
||||
use App\Models\Consultation;
|
||||
use Carbon\Carbon;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
|
||||
class DashboardController extends Controller
|
||||
{
|
||||
|
||||
public function dashboardClient()
|
||||
{
|
||||
$user = auth()->user();
|
||||
|
||||
$activities = PhysicalActivity::where('users_id', $user->id)->get();
|
||||
$healthData = HealthData::where('users_id', $user->id)->get()->last();
|
||||
|
||||
$activities->transform(function ($activity) {
|
||||
$activity->date = Carbon::parse($activity->date)->format('d M Y');
|
||||
$activity->calories_burned = $activity->calculateCaloriesBurned();
|
||||
return $activity;
|
||||
});
|
||||
|
||||
// Loop through activities and print out the values
|
||||
|
||||
$totalDistance = $activities->sum('distance');
|
||||
|
||||
if ($healthData) {
|
||||
// Check if obesity_status is null
|
||||
if (!$healthData->obesity_status) {
|
||||
// Call prediction method only if obesity_status is null
|
||||
$obesityPrediction = $this->predictObesity($healthData, $user);
|
||||
$healthData->obesity_status = $obesityPrediction;
|
||||
$healthData->save();
|
||||
}
|
||||
|
||||
// Check if calorie_recommendation is null
|
||||
if (!$healthData->calorie_recommendation) {
|
||||
// Call calorie prediction method only if calorie_recommendation is null
|
||||
$calorieRecommendation = $this->predictCalories($healthData, $user);
|
||||
$healthData->calorie_recommendation = $calorieRecommendation;
|
||||
$healthData->save();
|
||||
}
|
||||
}
|
||||
|
||||
return view('dashboardClient', compact('activities', 'healthData', 'totalDistance'));
|
||||
}
|
||||
|
||||
private function predictObesity($healthData, $user)
|
||||
{
|
||||
$data = [
|
||||
'height' => $healthData->height ?? 0,
|
||||
'weight' => $healthData->weight ?? 0,
|
||||
'age' => now()->diffInYears($healthData->birthdate ?? '2000-03-25'),
|
||||
'gender' => ($user->gender === 'male') ? 'M' : 'F',
|
||||
'activity_level' => 1,
|
||||
];
|
||||
|
||||
$obesityPrediction = Http::post('https://aigoo.humicprototypingapi.online/api/predict/obesity', $data)->json();
|
||||
$predictedCategory = $obesityPrediction['predicted_category'] ?? null;
|
||||
return $predictedCategory;
|
||||
}
|
||||
|
||||
private function predictCalories($healthData, $user)
|
||||
{
|
||||
$data = [
|
||||
'height' => $healthData->height ?? 0,
|
||||
'weight' => $healthData->weight ?? 0,
|
||||
'age' => now()->diffInYears($healthData->birthdate ?? '2000-03-25'),
|
||||
'gender' => ($user->gender === 'male') ? 'M' : 'F',
|
||||
];
|
||||
|
||||
$response = Http::post('https://aigoo.humicprototypingapi.online/api/predict/calorie', $data);
|
||||
$predictedCalories = ceil($response->json()['predicted_calories']);
|
||||
|
||||
return $predictedCalories;
|
||||
}
|
||||
|
||||
public function activityReport()
|
||||
{
|
||||
$currentMonth = now()->format('m');
|
||||
$currentYear = now()->format('Y');
|
||||
|
||||
$user = auth()->user();
|
||||
$healthData = HealthData::where('users_id', $user->id)
|
||||
->orderBy('updated_at', 'desc')
|
||||
->get();
|
||||
|
||||
$healthData->transform(function ($item) {
|
||||
$item->formatted_created_at = Carbon::parse($item->created_at)->format('d F Y');
|
||||
$item->time = Carbon::parse($item->created_at)->format('h:i A');
|
||||
return $item;
|
||||
});
|
||||
|
||||
$activities = PhysicalActivity::whereYear('date', $currentYear)
|
||||
->whereMonth('date', $currentMonth)
|
||||
->where('users_id', $user->id)
|
||||
->get();
|
||||
|
||||
$totalSteps = $activities->sum('avg_steps');
|
||||
$totalDistance = $activities->sum('distance');
|
||||
$totalDuration = $activities->sum('duration');
|
||||
|
||||
if ($totalDuration < 60) {
|
||||
$durationValue = $totalDuration;
|
||||
$durationUnit = 'seconds';
|
||||
} elseif ($totalDuration < 3600) {
|
||||
$durationValue = floor($totalDuration / 60);
|
||||
$durationUnit = 'minutes';
|
||||
} else {
|
||||
$durationValue = floor($totalDuration / 3600);
|
||||
$durationUnit = 'hours';
|
||||
}
|
||||
|
||||
$filteredHealthData = collect();
|
||||
foreach ($healthData as $index => $data) {
|
||||
if ($index < $healthData->count() - 1) {
|
||||
$nextWeight = $healthData[$index + 1]->weight;
|
||||
$data->weight_difference = $data->weight - $nextWeight;
|
||||
if ($data->weight_difference != 0) {
|
||||
$filteredHealthData->push($data);
|
||||
}
|
||||
} else {
|
||||
$data->weight_difference = 0;
|
||||
$filteredHealthData->push($data);
|
||||
}
|
||||
}
|
||||
|
||||
$totalSleepTime = $healthData->sum('sleeptime');
|
||||
if ($healthData->count() > 0) {
|
||||
$averageSleepTime = number_format($totalSleepTime / $healthData->count(), 2);
|
||||
} else {
|
||||
$averageSleepTime = 0;
|
||||
}
|
||||
|
||||
$latestHealthData = $healthData->last();
|
||||
if ($latestHealthData) {
|
||||
$predictedCalories = $this->predictCalories($latestHealthData, $user);
|
||||
} else {
|
||||
$predictedCalories = 0;
|
||||
}
|
||||
|
||||
$recommended_distance = Result::where('patient_id', $user->id)->get()->last()->jarak_lari ?? 0;
|
||||
|
||||
|
||||
$chartData = PhysicalActivity::whereYear('date', $currentYear)
|
||||
->whereMonth('date', $currentMonth)
|
||||
->where('users_id', $user->id)
|
||||
->orderBy('date')
|
||||
->get();
|
||||
|
||||
$labels = $chartData->map(function ($activity) {
|
||||
return Carbon::parse($activity->date)->format('d F');
|
||||
});
|
||||
|
||||
$distances = $chartData->map(function ($activity) {
|
||||
return intval($activity->distance);
|
||||
});
|
||||
|
||||
$durations = $chartData->map(function ($activity) {
|
||||
return intval($activity->duration);
|
||||
});
|
||||
|
||||
return view('activity-report', compact(
|
||||
'totalSteps', 'totalDistance', 'durationValue', 'durationUnit',
|
||||
'averageSleepTime', 'filteredHealthData', 'activities', 'predictedCalories',
|
||||
'recommended_distance', 'labels', 'distances', 'durations'
|
||||
));
|
||||
}
|
||||
|
||||
public function schedule()
|
||||
{
|
||||
$user = auth()->user();
|
||||
|
||||
$approvedConsultations = Consultation::where('patient_id', $user->id)
|
||||
->where('consultation_status', 'approved')
|
||||
->with('doctor')
|
||||
->get();
|
||||
|
||||
return view('customer-schedule', compact('approvedConsultations'));
|
||||
}
|
||||
|
||||
public function notifications()
|
||||
{
|
||||
$patient = auth()->user();
|
||||
$notifications = Notification::where('user_id', $patient->id)->orderBy('created_at', 'desc')->get();
|
||||
|
||||
return view('patient-notifications', compact('notifications'));
|
||||
}
|
||||
|
||||
public function consultation()
|
||||
{
|
||||
return view('health-data');
|
||||
}
|
||||
|
||||
|
||||
public function consultationResults()
|
||||
{
|
||||
$patient = auth()->user();
|
||||
$consultations = Consultation::where('patient_id', $patient->id)
|
||||
->where('consultation_status', 'finished')
|
||||
->with('doctor', 'result')
|
||||
->orderBy('consultation_date', 'desc')
|
||||
->get();
|
||||
|
||||
return view('customer-result', compact('consultations'));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,162 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use Illuminate\Http\Request;
|
||||
use App\Models\Consultation;
|
||||
use App\Models\Result;
|
||||
use App\Models\User;
|
||||
use App\Models\HealthData;
|
||||
use App\Models\Notification;
|
||||
|
||||
class DoctorController extends Controller
|
||||
{
|
||||
public function dashboard()
|
||||
{
|
||||
$normalWeightCount = HealthData::where('obesity_status', 'Normal weight')->count();
|
||||
$overweightCount = HealthData::where('obesity_status', 'Overweight')->count();
|
||||
$unknownCount = HealthData::whereNotIn('obesity_status', ['Normal weight', 'Overweight'])->count();
|
||||
|
||||
$doctor = auth()->user();
|
||||
|
||||
$totalAppointments = Consultation::where('doctor_id', $doctor->id)->count();
|
||||
$pendingAppointments = Consultation::where('doctor_id', $doctor->id)
|
||||
->where('consultation_status', 'pending')
|
||||
->count();
|
||||
|
||||
$malePatients = User::where('user_role', 'user')
|
||||
->where('gender', 'male')
|
||||
->count();
|
||||
$femalePatients = User::where('user_role', 'user')
|
||||
->where('gender', 'female')
|
||||
->count();
|
||||
|
||||
|
||||
$latestAppointments = Consultation::where('doctor_id', $doctor->id)
|
||||
->orderBy('consultation_date', 'desc')
|
||||
->take(5)
|
||||
->get();
|
||||
|
||||
return view('dashboardDoctor', compact(
|
||||
'normalWeightCount',
|
||||
'overweightCount',
|
||||
'unknownCount',
|
||||
'totalAppointments',
|
||||
'pendingAppointments',
|
||||
'malePatients',
|
||||
'femalePatients',
|
||||
'latestAppointments'
|
||||
));
|
||||
}
|
||||
|
||||
public function notifications()
|
||||
{
|
||||
$doctor = auth()->user();
|
||||
$notifications = Notification::where('user_id', $doctor->id)->orderBy('created_at', 'desc')->get();
|
||||
|
||||
return view('doctor-notifications', compact('notifications'));
|
||||
}
|
||||
|
||||
public function patientAcceptance()
|
||||
{
|
||||
$doctor = auth()->user();
|
||||
$consultations = Consultation::with('patient')
|
||||
->where('doctor_id', $doctor->id)
|
||||
->where('consultation_status', 'pending')
|
||||
->get();
|
||||
|
||||
return view('acceptance-patients', compact('consultations'));
|
||||
}
|
||||
|
||||
public function approveConsultation($consultationId)
|
||||
{
|
||||
$consultation = Consultation::findOrFail($consultationId);
|
||||
$consultation->consultation_status = 'approved';
|
||||
$consultation->save();
|
||||
|
||||
// Create notification for the patient
|
||||
$patientNotification = new Notification();
|
||||
$patientNotification->user_id = $consultation->patient_id;
|
||||
$patientNotification->consultation_id = $consultation->id;
|
||||
$patientNotification->message = 'Your consultation request has been approved by Dr. ' . $consultation->doctor->name . '.';
|
||||
$patientNotification->save();
|
||||
|
||||
// Create notification for the doctor
|
||||
$doctorNotification = new Notification();
|
||||
$doctorNotification->user_id = $consultation->doctor_id;
|
||||
$doctorNotification->consultation_id = $consultation->id;
|
||||
$doctorNotification->message = 'You have approved the consultation request from ' . $consultation->patient->name . '.';
|
||||
$doctorNotification->save();
|
||||
|
||||
return redirect()->back()->with('success', 'Consultation approved successfully.');
|
||||
}
|
||||
|
||||
public function declineConsultation($consultationId)
|
||||
{
|
||||
$consultation = Consultation::findOrFail($consultationId);
|
||||
$consultation->consultation_status = 'declined';
|
||||
$consultation->save();
|
||||
|
||||
// Create notification for the patient
|
||||
$patientNotification = new Notification();
|
||||
$patientNotification->user_id = $consultation->patient_id;
|
||||
$patientNotification->consultation_id = $consultation->id;
|
||||
$patientNotification->message = 'Your consultation request has been declined by Dr. ' . $consultation->doctor->name . '.';
|
||||
$patientNotification->save();
|
||||
|
||||
// Create notification for the doctor
|
||||
$doctorNotification = new Notification();
|
||||
$doctorNotification->user_id = $consultation->doctor_id;
|
||||
$doctorNotification->consultation_id = $consultation->id;
|
||||
$doctorNotification->message = 'You have declined the consultation request from ' . $consultation->patient->name . '.';
|
||||
$doctorNotification->save();
|
||||
|
||||
return redirect()->back()->with('success', 'Consultation declined successfully.');
|
||||
}
|
||||
|
||||
public function schedule()
|
||||
{
|
||||
$doctor = auth()->user();
|
||||
$approvedConsultations = Consultation::where('doctor_id', $doctor->id)
|
||||
->where('consultation_status', 'approved')
|
||||
->with('patient.healthDatas')
|
||||
->get();
|
||||
|
||||
return view('doctor-schedule', compact('approvedConsultations'));
|
||||
}
|
||||
|
||||
public function showConsultationResultForm($patientId)
|
||||
{
|
||||
return view('doctor-result-form', compact('patientId'));
|
||||
}
|
||||
|
||||
public function storeConsultationResult(Request $request)
|
||||
{
|
||||
$validatedData = $request->validate([
|
||||
'doctor_id' => 'required|exists:users,id',
|
||||
'patient_id' => 'required|exists:users,id',
|
||||
'jarak_lari' => 'required|integer',
|
||||
'sleeptime' => 'required|numeric',
|
||||
'food' => 'required|string',
|
||||
'unrecommended_food' => 'required|string',
|
||||
'notes' => 'required|string',
|
||||
]);
|
||||
|
||||
$consultation = Consultation::where('doctor_id', $validatedData['doctor_id'])
|
||||
->where('patient_id', $validatedData['patient_id'])
|
||||
->where('consultation_status', 'approved')
|
||||
->first();
|
||||
|
||||
if ($consultation) {
|
||||
$validatedData['consultation_id'] = $consultation->id;
|
||||
Result::create($validatedData);
|
||||
|
||||
$consultation->consultation_status = 'finished';
|
||||
$consultation->save();
|
||||
|
||||
return redirect()->route('doctor.schedule')->with('success', 'Consultation result submitted successfully.');
|
||||
}
|
||||
|
||||
return redirect()->back()->with('error', 'Consultation not found or already finished.');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use App\Http\Requests\ProfileUpdateRequest;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use Illuminate\Support\Facades\Redirect;
|
||||
use Illuminate\View\View;
|
||||
|
||||
class ProfileController extends Controller
|
||||
{
|
||||
/**
|
||||
* Display the user's profile form.
|
||||
*/
|
||||
public function edit(Request $request): View
|
||||
{
|
||||
return view('profile.edit', [
|
||||
'user' => $request->user(),
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Update the user's profile information.
|
||||
*/
|
||||
public function update(ProfileUpdateRequest $request): RedirectResponse
|
||||
{
|
||||
$request->user()->fill($request->validated());
|
||||
|
||||
if ($request->user()->isDirty('email')) {
|
||||
$request->user()->email_verified_at = null;
|
||||
}
|
||||
|
||||
$request->user()->save();
|
||||
|
||||
return Redirect::route('profile.edit')->with('status', 'profile-updated');
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete the user's account.
|
||||
*/
|
||||
public function destroy(Request $request): RedirectResponse
|
||||
{
|
||||
$request->validateWithBag('userDeletion', [
|
||||
'password' => ['required', 'current_password'],
|
||||
]);
|
||||
|
||||
$user = $request->user();
|
||||
|
||||
Auth::logout();
|
||||
|
||||
$user->delete();
|
||||
|
||||
$request->session()->invalidate();
|
||||
$request->session()->regenerateToken();
|
||||
|
||||
return Redirect::to('/');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use App\Models\PhysicalActivity;
|
||||
|
||||
|
||||
class StravaController extends Controller
|
||||
{
|
||||
|
||||
public function authorize(Request $request)
|
||||
{
|
||||
$request->validate([
|
||||
'email' => 'required|email',
|
||||
'password' => 'required',
|
||||
]);
|
||||
|
||||
if (Auth::attempt($request->only('email', 'password'), $request->filled('remember'))) {
|
||||
if (Auth::user()->user_role == 'user') {
|
||||
$clientId = "124405";
|
||||
$redirectUri = route('strava.callback');
|
||||
$authUrl = "https://www.strava.com/oauth/authorize?client_id={$clientId}&redirect_uri={$redirectUri}&response_type=code&scope=activity:read_all";
|
||||
|
||||
return redirect()->away($authUrl);
|
||||
} elseif (Auth::user()->user_role == 'doctor') {
|
||||
return redirect()->route('doctor.dashboard');
|
||||
} else {
|
||||
return redirect()->route('admin.dashboard');
|
||||
}
|
||||
}
|
||||
|
||||
return back()->withErrors([
|
||||
'email' => 'The provided credentials do not match our records.',
|
||||
]);
|
||||
}
|
||||
|
||||
public function handleCallback(Request $request)
|
||||
{
|
||||
$authorizationCode = $request->input('code');
|
||||
if ($authorizationCode) {
|
||||
$tokenEndpoint = "https://www.strava.com/oauth/token";
|
||||
$clientId = "124405";
|
||||
$clientSecret = "2df5d622c326215c290841fb0ffcdd894274803e";
|
||||
|
||||
$response = Http::post($tokenEndpoint, [
|
||||
'client_id' => $clientId,
|
||||
'client_secret' => $clientSecret,
|
||||
'code' => $authorizationCode,
|
||||
'grant_type' => 'authorization_code',
|
||||
]);
|
||||
|
||||
$data = $response->json();
|
||||
//dd($data);
|
||||
$accessToken = $data['access_token'];
|
||||
|
||||
|
||||
// Store the access token in the session or database for future API requests
|
||||
session(['strava_access_token' => $accessToken]);
|
||||
// Redirect the user to the desired page after successful authorization
|
||||
|
||||
if (auth()->user()->user_role == 'user') {
|
||||
$this->fetchAthleteActivities($data['access_token']);
|
||||
return redirect()->intended(route('dashboard'));
|
||||
} else if (auth()->user()->user_role == 'doctor') {
|
||||
// redirect to doctor dashboard (TODO)
|
||||
} else {
|
||||
return redirect()->intended(route('admin.dashboard'));
|
||||
}
|
||||
}
|
||||
|
||||
// Handle the case when the authorization code is missing
|
||||
return view('auth.login');
|
||||
}
|
||||
|
||||
public function fetchAthleteActivities($accessToken)
|
||||
{
|
||||
$accessToken = session('strava_access_token');
|
||||
|
||||
if ($accessToken) {
|
||||
$activitiesEndpoint = "https://www.strava.com/api/v3/athlete/activities";
|
||||
|
||||
$response = Http::withHeaders([
|
||||
'Authorization' => 'Bearer ' . $accessToken,
|
||||
])->get($activitiesEndpoint);
|
||||
|
||||
$activities = $response->json();
|
||||
//dd($activities);
|
||||
foreach ($activities as $activity) {
|
||||
$existingActivity = PhysicalActivity::where('id', $activity['id'])->first();
|
||||
|
||||
if (!$existingActivity) {
|
||||
$startDate = new \DateTime($activity['start_date_local']);
|
||||
$formattedDate = $startDate->format('Y-m-d H:i:s');
|
||||
|
||||
PhysicalActivity::create([
|
||||
'users_id' => auth()->user()->id,
|
||||
//'id' => $activity['id'],
|
||||
'date' => $formattedDate,
|
||||
'type' => $activity['type'],
|
||||
'distance' => $activity['distance'],
|
||||
'duration' => $activity['moving_time'],
|
||||
'avg_speed' => $activity['average_speed'],
|
||||
'avg_steps' => $activity['average_cadence'] ?? 0,
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
return $activities;
|
||||
}
|
||||
|
||||
// Handle the case when the access token is missing
|
||||
return redirect()->route('login')->with('error', 'Strava access token not found.');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use Illuminate\Http\Request;
|
||||
|
||||
class UserController extends Controller
|
||||
{
|
||||
public function index()
|
||||
{
|
||||
return view('welcome');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,400 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\vendor\Chatify\Api;
|
||||
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Routing\Controller;
|
||||
use Illuminate\Support\Facades\Response;
|
||||
use App\Models\ChMessage as Message;
|
||||
use App\Models\ChFavorite as Favorite;
|
||||
use Chatify\Facades\ChatifyMessenger as Chatify;
|
||||
use App\Models\User;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
|
||||
class ApiMessagesController extends Controller
|
||||
{
|
||||
protected $perPage = 30;
|
||||
|
||||
/**
|
||||
* Authinticate the connection for pusher
|
||||
*
|
||||
* @param Request $request
|
||||
* @return void
|
||||
*/
|
||||
public function pusherAuth(Request $request)
|
||||
{
|
||||
return Chatify::pusherAuth(
|
||||
$request->user(),
|
||||
Auth::user(),
|
||||
$request['channel_name'],
|
||||
$request['socket_id']
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch data by id for (user/group)
|
||||
*
|
||||
* @param Request $request
|
||||
* @return \Illuminate\Http\JsonResponse
|
||||
*/
|
||||
public function idFetchData(Request $request)
|
||||
{
|
||||
return auth()->user();
|
||||
// Favorite
|
||||
$favorite = Chatify::inFavorite($request['id']);
|
||||
|
||||
// User data
|
||||
if ($request['type'] == 'user') {
|
||||
$fetch = User::where('id', $request['id'])->first();
|
||||
if($fetch){
|
||||
$userAvatar = Chatify::getUserWithAvatar($fetch)->avatar;
|
||||
}
|
||||
}
|
||||
|
||||
// send the response
|
||||
return Response::json([
|
||||
'favorite' => $favorite,
|
||||
'fetch' => $fetch ?? null,
|
||||
'user_avatar' => $userAvatar ?? null,
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* This method to make a links for the attachments
|
||||
* to be downloadable.
|
||||
*
|
||||
* @param string $fileName
|
||||
* @return \Illuminate\Http\JsonResponse
|
||||
*/
|
||||
public function download($fileName)
|
||||
{
|
||||
$path = config('chatify.attachments.folder') . '/' . $fileName;
|
||||
if (Chatify::storage()->exists($path)) {
|
||||
return response()->json([
|
||||
'file_name' => $fileName,
|
||||
'download_path' => Chatify::storage()->url($path)
|
||||
], 200);
|
||||
} else {
|
||||
return response()->json([
|
||||
'message'=>"Sorry, File does not exist in our server or may have been deleted!"
|
||||
], 404);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Send a message to database
|
||||
*
|
||||
* @param Request $request
|
||||
* @return JSON response
|
||||
*/
|
||||
public function send(Request $request)
|
||||
{
|
||||
// default variables
|
||||
$error = (object)[
|
||||
'status' => 0,
|
||||
'message' => null
|
||||
];
|
||||
$attachment = null;
|
||||
$attachment_title = null;
|
||||
|
||||
// if there is attachment [file]
|
||||
if ($request->hasFile('file')) {
|
||||
// allowed extensions
|
||||
$allowed_images = Chatify::getAllowedImages();
|
||||
$allowed_files = Chatify::getAllowedFiles();
|
||||
$allowed = array_merge($allowed_images, $allowed_files);
|
||||
|
||||
$file = $request->file('file');
|
||||
// check file size
|
||||
if ($file->getSize() < Chatify::getMaxUploadSize()) {
|
||||
if (in_array(strtolower($file->extension()), $allowed)) {
|
||||
// get attachment name
|
||||
$attachment_title = $file->getClientOriginalName();
|
||||
// upload attachment and store the new name
|
||||
$attachment = Str::uuid() . "." . $file->extension();
|
||||
$file->storeAs(config('chatify.attachments.folder'), $attachment, config('chatify.storage_disk_name'));
|
||||
} else {
|
||||
$error->status = 1;
|
||||
$error->message = "File extension not allowed!";
|
||||
}
|
||||
} else {
|
||||
$error->status = 1;
|
||||
$error->message = "File size you are trying to upload is too large!";
|
||||
}
|
||||
}
|
||||
|
||||
if (!$error->status) {
|
||||
// send to database
|
||||
$message = Chatify::newMessage([
|
||||
'type' => $request['type'],
|
||||
'from_id' => Auth::user()->id,
|
||||
'to_id' => $request['id'],
|
||||
'body' => htmlentities(trim($request['message']), ENT_QUOTES, 'UTF-8'),
|
||||
'attachment' => ($attachment) ? json_encode((object)[
|
||||
'new_name' => $attachment,
|
||||
'old_name' => htmlentities(trim($attachment_title), ENT_QUOTES, 'UTF-8'),
|
||||
]) : null,
|
||||
]);
|
||||
|
||||
// fetch message to send it with the response
|
||||
$messageData = Chatify::parseMessage($message);
|
||||
|
||||
// send to user using pusher
|
||||
if (Auth::user()->id != $request['id']) {
|
||||
Chatify::push("private-chatify.".$request['id'], 'messaging', [
|
||||
'from_id' => Auth::user()->id,
|
||||
'to_id' => $request['id'],
|
||||
'message' => $messageData
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
// send the response
|
||||
return Response::json([
|
||||
'status' => '200',
|
||||
'error' => $error,
|
||||
'message' => $messageData ?? [],
|
||||
'tempID' => $request['temporaryMsgId'],
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* fetch [user/group] messages from database
|
||||
*
|
||||
* @param Request $request
|
||||
* @return JSON response
|
||||
*/
|
||||
public function fetch(Request $request)
|
||||
{
|
||||
$query = Chatify::fetchMessagesQuery($request['id'])->latest();
|
||||
$messages = $query->paginate($request->per_page ?? $this->perPage);
|
||||
$totalMessages = $messages->total();
|
||||
$lastPage = $messages->lastPage();
|
||||
$response = [
|
||||
'total' => $totalMessages,
|
||||
'last_page' => $lastPage,
|
||||
'last_message_id' => collect($messages->items())->last()->id ?? null,
|
||||
'messages' => $messages->items(),
|
||||
];
|
||||
return Response::json($response);
|
||||
}
|
||||
|
||||
/**
|
||||
* Make messages as seen
|
||||
*
|
||||
* @param Request $request
|
||||
* @return void
|
||||
*/
|
||||
public function seen(Request $request)
|
||||
{
|
||||
// make as seen
|
||||
$seen = Chatify::makeSeen($request['id']);
|
||||
// send the response
|
||||
return Response::json([
|
||||
'status' => $seen,
|
||||
], 200);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get contacts list
|
||||
*
|
||||
* @param Request $request
|
||||
* @return \Illuminate\Http\JsonResponse response
|
||||
*/
|
||||
public function getContacts(Request $request)
|
||||
{
|
||||
// get all users that received/sent message from/to [Auth user]
|
||||
$users = Message::join('users', function ($join) {
|
||||
$join->on('ch_messages.from_id', '=', 'users.id')
|
||||
->orOn('ch_messages.to_id', '=', 'users.id');
|
||||
})
|
||||
->where(function ($q) {
|
||||
$q->where('ch_messages.from_id', Auth::user()->id)
|
||||
->orWhere('ch_messages.to_id', Auth::user()->id);
|
||||
})
|
||||
->where('users.id','!=',Auth::user()->id)
|
||||
->select('users.*',DB::raw('MAX(ch_messages.created_at) max_created_at'))
|
||||
->orderBy('max_created_at', 'desc')
|
||||
->groupBy('users.id')
|
||||
->paginate($request->per_page ?? $this->perPage);
|
||||
|
||||
return response()->json([
|
||||
'contacts' => $users->items(),
|
||||
'total' => $users->total() ?? 0,
|
||||
'last_page' => $users->lastPage() ?? 1,
|
||||
], 200);
|
||||
}
|
||||
|
||||
/**
|
||||
* Put a user in the favorites list
|
||||
*
|
||||
* @param Request $request
|
||||
* @return void
|
||||
*/
|
||||
public function favorite(Request $request)
|
||||
{
|
||||
$userId = $request['user_id'];
|
||||
// check action [star/unstar]
|
||||
$favoriteStatus = Chatify::inFavorite($userId) ? 0 : 1;
|
||||
Chatify::makeInFavorite($userId, $favoriteStatus);
|
||||
|
||||
// send the response
|
||||
return Response::json([
|
||||
'status' => @$favoriteStatus,
|
||||
], 200);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get favorites list
|
||||
*
|
||||
* @param Request $request
|
||||
* @return void
|
||||
*/
|
||||
public function getFavorites(Request $request)
|
||||
{
|
||||
$favorites = Favorite::where('user_id', Auth::user()->id)->get();
|
||||
foreach ($favorites as $favorite) {
|
||||
$favorite->user = User::where('id', $favorite->favorite_id)->first();
|
||||
}
|
||||
return Response::json([
|
||||
'total' => count($favorites),
|
||||
'favorites' => $favorites ?? [],
|
||||
], 200);
|
||||
}
|
||||
|
||||
/**
|
||||
* Search in messenger
|
||||
*
|
||||
* @param Request $request
|
||||
* @return \Illuminate\Http\JsonResponse
|
||||
*/
|
||||
public function search(Request $request)
|
||||
{
|
||||
$input = trim(filter_var($request['input']));
|
||||
$records = User::where('id','!=',Auth::user()->id)
|
||||
->where('name', 'LIKE', "%{$input}%")
|
||||
->paginate($request->per_page ?? $this->perPage);
|
||||
|
||||
foreach ($records->items() as $index => $record) {
|
||||
$records[$index] += Chatify::getUserWithAvatar($record);
|
||||
}
|
||||
|
||||
return Response::json([
|
||||
'records' => $records->items(),
|
||||
'total' => $records->total(),
|
||||
'last_page' => $records->lastPage()
|
||||
], 200);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get shared photos
|
||||
*
|
||||
* @param Request $request
|
||||
* @return \Illuminate\Http\JsonResponse
|
||||
*/
|
||||
public function sharedPhotos(Request $request)
|
||||
{
|
||||
$images = Chatify::getSharedPhotos($request['user_id']);
|
||||
|
||||
foreach ($images as $image) {
|
||||
$image = asset(config('chatify.attachments.folder') . $image);
|
||||
}
|
||||
// send the response
|
||||
return Response::json([
|
||||
'shared' => $images ?? [],
|
||||
], 200);
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete conversation
|
||||
*
|
||||
* @param Request $request
|
||||
* @return void
|
||||
*/
|
||||
public function deleteConversation(Request $request)
|
||||
{
|
||||
// delete
|
||||
$delete = Chatify::deleteConversation($request['id']);
|
||||
|
||||
// send the response
|
||||
return Response::json([
|
||||
'deleted' => $delete ? 1 : 0,
|
||||
], 200);
|
||||
}
|
||||
|
||||
public function updateSettings(Request $request)
|
||||
{
|
||||
$msg = null;
|
||||
$error = $success = 0;
|
||||
|
||||
// dark mode
|
||||
if ($request['dark_mode']) {
|
||||
$request['dark_mode'] == "dark"
|
||||
? User::where('id', Auth::user()->id)->update(['dark_mode' => 1]) // Make Dark
|
||||
: User::where('id', Auth::user()->id)->update(['dark_mode' => 0]); // Make Light
|
||||
}
|
||||
|
||||
// If messenger color selected
|
||||
if ($request['messengerColor']) {
|
||||
$messenger_color = trim(filter_var($request['messengerColor']));
|
||||
User::where('id', Auth::user()->id)
|
||||
->update(['messenger_color' => $messenger_color]);
|
||||
}
|
||||
// if there is a [file]
|
||||
if ($request->hasFile('avatar')) {
|
||||
// allowed extensions
|
||||
$allowed_images = Chatify::getAllowedImages();
|
||||
|
||||
$file = $request->file('avatar');
|
||||
// check file size
|
||||
if ($file->getSize() < Chatify::getMaxUploadSize()) {
|
||||
if (in_array(strtolower($file->extension()), $allowed_images)) {
|
||||
// delete the older one
|
||||
if (Auth::user()->avatar != config('chatify.user_avatar.default')) {
|
||||
$path = Chatify::getUserAvatarUrl(Auth::user()->avatar);
|
||||
if (Chatify::storage()->exists($path)) {
|
||||
Chatify::storage()->delete($path);
|
||||
}
|
||||
}
|
||||
// upload
|
||||
$avatar = Str::uuid() . "." . $file->extension();
|
||||
$update = User::where('id', Auth::user()->id)->update(['avatar' => $avatar]);
|
||||
$file->storeAs(config('chatify.user_avatar.folder'), $avatar, config('chatify.storage_disk_name'));
|
||||
$success = $update ? 1 : 0;
|
||||
} else {
|
||||
$msg = "File extension not allowed!";
|
||||
$error = 1;
|
||||
}
|
||||
} else {
|
||||
$msg = "File size you are trying to upload is too large!";
|
||||
$error = 1;
|
||||
}
|
||||
}
|
||||
|
||||
// send the response
|
||||
return Response::json([
|
||||
'status' => $success ? 1 : 0,
|
||||
'error' => $error ? 1 : 0,
|
||||
'message' => $error ? $msg : 0,
|
||||
], 200);
|
||||
}
|
||||
|
||||
/**
|
||||
* Set user's active status
|
||||
*
|
||||
* @param Request $request
|
||||
* @return void
|
||||
*/
|
||||
public function setActiveStatus(Request $request)
|
||||
{
|
||||
$activeStatus = $request['status'] > 0 ? 1 : 0;
|
||||
$status = User::where('id', Auth::user()->id)->update(['active_status' => $activeStatus]);
|
||||
return Response::json([
|
||||
'status' => $status,
|
||||
], 200);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,483 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\vendor\Chatify;
|
||||
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Routing\Controller;
|
||||
use Illuminate\Support\Facades\Response;
|
||||
use App\Models\User;
|
||||
use App\Models\ChMessage as Message;
|
||||
use App\Models\ChFavorite as Favorite;
|
||||
use Chatify\Facades\ChatifyMessenger as Chatify;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Request as FacadesRequest;
|
||||
use Illuminate\Support\Str;
|
||||
class MessagesController extends Controller
|
||||
{
|
||||
protected $perPage = 30;
|
||||
|
||||
/**
|
||||
* Authenticate the connection for pusher
|
||||
*
|
||||
* @param Request $request
|
||||
* @return JsonResponse
|
||||
*/
|
||||
public function pusherAuth(Request $request)
|
||||
{
|
||||
return Chatify::pusherAuth(
|
||||
$request->user(),
|
||||
Auth::user(),
|
||||
$request['channel_name'],
|
||||
$request['socket_id']
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returning the view of the app with the required data.
|
||||
*
|
||||
* @param int $id
|
||||
* @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View
|
||||
*/
|
||||
public function index( $id = null)
|
||||
{
|
||||
$messenger_color = Auth::user()->messenger_color;
|
||||
return view('Chatify::pages.app', [
|
||||
'id' => $id ?? 0,
|
||||
'messengerColor' => $messenger_color ? $messenger_color : Chatify::getFallbackColor(),
|
||||
'dark_mode' => Auth::user()->dark_mode < 1 ? 'light' : 'dark',
|
||||
]);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Fetch data (user, favorite.. etc).
|
||||
*
|
||||
* @param Request $request
|
||||
* @return JsonResponse
|
||||
*/
|
||||
public function idFetchData(Request $request)
|
||||
{
|
||||
$favorite = Chatify::inFavorite($request['id']);
|
||||
$fetch = User::where('id', $request['id'])->first();
|
||||
if($fetch){
|
||||
$userAvatar = Chatify::getUserWithAvatar($fetch)->avatar;
|
||||
}
|
||||
return Response::json([
|
||||
'favorite' => $favorite,
|
||||
'fetch' => $fetch ?? null,
|
||||
'user_avatar' => $userAvatar ?? null,
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* This method to make a links for the attachments
|
||||
* to be downloadable.
|
||||
*
|
||||
* @param string $fileName
|
||||
* @return \Symfony\Component\HttpFoundation\StreamedResponse|void
|
||||
*/
|
||||
public function download($fileName)
|
||||
{
|
||||
$filePath = config('chatify.attachments.folder') . '/' . $fileName;
|
||||
if (Chatify::storage()->exists($filePath)) {
|
||||
return Chatify::storage()->download($filePath);
|
||||
}
|
||||
return abort(404, "Sorry, File does not exist in our server or may have been deleted!");
|
||||
}
|
||||
|
||||
/**
|
||||
* Send a message to database
|
||||
*
|
||||
* @param Request $request
|
||||
* @return JsonResponse
|
||||
*/
|
||||
public function send(Request $request)
|
||||
{
|
||||
// default variables
|
||||
$error = (object)[
|
||||
'status' => 0,
|
||||
'message' => null
|
||||
];
|
||||
$attachment = null;
|
||||
$attachment_title = null;
|
||||
|
||||
// if there is attachment [file]
|
||||
if ($request->hasFile('file')) {
|
||||
// allowed extensions
|
||||
$allowed_images = Chatify::getAllowedImages();
|
||||
$allowed_files = Chatify::getAllowedFiles();
|
||||
$allowed = array_merge($allowed_images, $allowed_files);
|
||||
|
||||
$file = $request->file('file');
|
||||
// check file size
|
||||
if ($file->getSize() < Chatify::getMaxUploadSize()) {
|
||||
if (in_array(strtolower($file->extension()), $allowed)) {
|
||||
// get attachment name
|
||||
$attachment_title = $file->getClientOriginalName();
|
||||
// upload attachment and store the new name
|
||||
$attachment = Str::uuid() . "." . $file->extension();
|
||||
$file->storeAs(config('chatify.attachments.folder'), $attachment, config('chatify.storage_disk_name'));
|
||||
} else {
|
||||
$error->status = 1;
|
||||
$error->message = "File extension not allowed!";
|
||||
}
|
||||
} else {
|
||||
$error->status = 1;
|
||||
$error->message = "File size you are trying to upload is too large!";
|
||||
}
|
||||
}
|
||||
|
||||
if (!$error->status) {
|
||||
$message = Chatify::newMessage([
|
||||
'from_id' => Auth::user()->id,
|
||||
'to_id' => $request['id'],
|
||||
'body' => htmlentities(trim($request['message']), ENT_QUOTES, 'UTF-8'),
|
||||
'attachment' => ($attachment) ? json_encode((object)[
|
||||
'new_name' => $attachment,
|
||||
'old_name' => htmlentities(trim($attachment_title), ENT_QUOTES, 'UTF-8'),
|
||||
]) : null,
|
||||
]);
|
||||
$messageData = Chatify::parseMessage($message);
|
||||
if (Auth::user()->id != $request['id']) {
|
||||
Chatify::push("private-chatify.".$request['id'], 'messaging', [
|
||||
'from_id' => Auth::user()->id,
|
||||
'to_id' => $request['id'],
|
||||
'message' => Chatify::messageCard($messageData, true)
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
// send the response
|
||||
return Response::json([
|
||||
'status' => '200',
|
||||
'error' => $error,
|
||||
'message' => Chatify::messageCard(@$messageData),
|
||||
'tempID' => $request['temporaryMsgId'],
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* fetch [user/group] messages from database
|
||||
*
|
||||
* @param Request $request
|
||||
* @return JsonResponse
|
||||
*/
|
||||
public function fetch(Request $request)
|
||||
{
|
||||
$query = Chatify::fetchMessagesQuery($request['id'])->latest();
|
||||
$messages = $query->paginate($request->per_page ?? $this->perPage);
|
||||
$totalMessages = $messages->total();
|
||||
$lastPage = $messages->lastPage();
|
||||
$response = [
|
||||
'total' => $totalMessages,
|
||||
'last_page' => $lastPage,
|
||||
'last_message_id' => collect($messages->items())->last()->id ?? null,
|
||||
'messages' => '',
|
||||
];
|
||||
|
||||
// if there is no messages yet.
|
||||
if ($totalMessages < 1) {
|
||||
$response['messages'] ='<p class="message-hint center-el"><span>Say \'hi\' and start messaging</span></p>';
|
||||
return Response::json($response);
|
||||
}
|
||||
if (count($messages->items()) < 1) {
|
||||
$response['messages'] = '';
|
||||
return Response::json($response);
|
||||
}
|
||||
$allMessages = null;
|
||||
foreach ($messages->reverse() as $message) {
|
||||
$allMessages .= Chatify::messageCard(
|
||||
Chatify::parseMessage($message)
|
||||
);
|
||||
}
|
||||
$response['messages'] = $allMessages;
|
||||
return Response::json($response);
|
||||
}
|
||||
|
||||
/**
|
||||
* Make messages as seen
|
||||
*
|
||||
* @param Request $request
|
||||
* @return JsonResponse|void
|
||||
*/
|
||||
public function seen(Request $request)
|
||||
{
|
||||
// make as seen
|
||||
$seen = Chatify::makeSeen($request['id']);
|
||||
// send the response
|
||||
return Response::json([
|
||||
'status' => $seen,
|
||||
], 200);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get contacts list
|
||||
*
|
||||
* @param Request $request
|
||||
* @return JsonResponse
|
||||
*/
|
||||
public function getContacts(Request $request)
|
||||
{
|
||||
// get all users that received/sent message from/to [Auth user]
|
||||
$users = Message::join('users', function ($join) {
|
||||
$join->on('ch_messages.from_id', '=', 'users.id')
|
||||
->orOn('ch_messages.to_id', '=', 'users.id');
|
||||
})
|
||||
->where(function ($q) {
|
||||
$q->where('ch_messages.from_id', Auth::user()->id)
|
||||
->orWhere('ch_messages.to_id', Auth::user()->id);
|
||||
})
|
||||
->where('users.id','!=',Auth::user()->id)
|
||||
->select('users.*',DB::raw('MAX(ch_messages.created_at) max_created_at'))
|
||||
->orderBy('max_created_at', 'desc')
|
||||
->groupBy('users.id')
|
||||
->paginate($request->per_page ?? $this->perPage);
|
||||
|
||||
$usersList = $users->items();
|
||||
|
||||
if (count($usersList) > 0) {
|
||||
$contacts = '';
|
||||
foreach ($usersList as $user) {
|
||||
$contacts .= Chatify::getContactItem($user);
|
||||
}
|
||||
} else {
|
||||
$contacts = '<p class="message-hint center-el"><span>Your contact list is empty</span></p>';
|
||||
}
|
||||
|
||||
return Response::json([
|
||||
'contacts' => $contacts,
|
||||
'total' => $users->total() ?? 0,
|
||||
'last_page' => $users->lastPage() ?? 1,
|
||||
], 200);
|
||||
}
|
||||
|
||||
/**
|
||||
* Update user's list item data
|
||||
*
|
||||
* @param Request $request
|
||||
* @return JsonResponse
|
||||
*/
|
||||
public function updateContactItem(Request $request)
|
||||
{
|
||||
// Get user data
|
||||
$user = User::where('id', $request['user_id'])->first();
|
||||
if(!$user){
|
||||
return Response::json([
|
||||
'message' => 'User not found!',
|
||||
], 401);
|
||||
}
|
||||
$contactItem = Chatify::getContactItem($user);
|
||||
|
||||
// send the response
|
||||
return Response::json([
|
||||
'contactItem' => $contactItem,
|
||||
], 200);
|
||||
}
|
||||
|
||||
/**
|
||||
* Put a user in the favorites list
|
||||
*
|
||||
* @param Request $request
|
||||
* @return JsonResponse|void
|
||||
*/
|
||||
public function favorite(Request $request)
|
||||
{
|
||||
$userId = $request['user_id'];
|
||||
// check action [star/unstar]
|
||||
$favoriteStatus = Chatify::inFavorite($userId) ? 0 : 1;
|
||||
Chatify::makeInFavorite($userId, $favoriteStatus);
|
||||
|
||||
// send the response
|
||||
return Response::json([
|
||||
'status' => @$favoriteStatus,
|
||||
], 200);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get favorites list
|
||||
*
|
||||
* @param Request $request
|
||||
* @return JsonResponse|void
|
||||
*/
|
||||
public function getFavorites(Request $request)
|
||||
{
|
||||
$favoritesList = null;
|
||||
$favorites = Favorite::where('user_id', Auth::user()->id);
|
||||
foreach ($favorites->get() as $favorite) {
|
||||
// get user data
|
||||
$user = User::where('id', $favorite->favorite_id)->first();
|
||||
$favoritesList .= view('Chatify::layouts.favorite', [
|
||||
'user' => $user,
|
||||
]);
|
||||
}
|
||||
// send the response
|
||||
return Response::json([
|
||||
'count' => $favorites->count(),
|
||||
'favorites' => $favorites->count() > 0
|
||||
? $favoritesList
|
||||
: 0,
|
||||
], 200);
|
||||
}
|
||||
|
||||
/**
|
||||
* Search in messenger
|
||||
*
|
||||
* @param Request $request
|
||||
* @return JsonResponse|void
|
||||
*/
|
||||
public function search(Request $request)
|
||||
{
|
||||
$getRecords = null;
|
||||
$input = trim(filter_var($request['input']));
|
||||
$records = User::where('id','!=',Auth::user()->id)
|
||||
->where('name', 'LIKE', "%{$input}%")
|
||||
->paginate($request->per_page ?? $this->perPage);
|
||||
foreach ($records->items() as $record) {
|
||||
$getRecords .= view('Chatify::layouts.listItem', [
|
||||
'get' => 'search_item',
|
||||
'user' => Chatify::getUserWithAvatar($record),
|
||||
])->render();
|
||||
}
|
||||
if($records->total() < 1){
|
||||
$getRecords = '<p class="message-hint center-el"><span>Nothing to show.</span></p>';
|
||||
}
|
||||
// send the response
|
||||
return Response::json([
|
||||
'records' => $getRecords,
|
||||
'total' => $records->total(),
|
||||
'last_page' => $records->lastPage()
|
||||
], 200);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get shared photos
|
||||
*
|
||||
* @param Request $request
|
||||
* @return JsonResponse|void
|
||||
*/
|
||||
public function sharedPhotos(Request $request)
|
||||
{
|
||||
$shared = Chatify::getSharedPhotos($request['user_id']);
|
||||
$sharedPhotos = null;
|
||||
|
||||
// shared with its template
|
||||
for ($i = 0; $i < count($shared); $i++) {
|
||||
$sharedPhotos .= view('Chatify::layouts.listItem', [
|
||||
'get' => 'sharedPhoto',
|
||||
'image' => Chatify::getAttachmentUrl($shared[$i]),
|
||||
])->render();
|
||||
}
|
||||
// send the response
|
||||
return Response::json([
|
||||
'shared' => count($shared) > 0 ? $sharedPhotos : '<p class="message-hint"><span>Nothing shared yet</span></p>',
|
||||
], 200);
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete conversation
|
||||
*
|
||||
* @param Request $request
|
||||
* @return JsonResponse
|
||||
*/
|
||||
public function deleteConversation(Request $request)
|
||||
{
|
||||
// delete
|
||||
$delete = Chatify::deleteConversation($request['id']);
|
||||
|
||||
// send the response
|
||||
return Response::json([
|
||||
'deleted' => $delete ? 1 : 0,
|
||||
], 200);
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete message
|
||||
*
|
||||
* @param Request $request
|
||||
* @return JsonResponse
|
||||
*/
|
||||
public function deleteMessage(Request $request)
|
||||
{
|
||||
// delete
|
||||
$delete = Chatify::deleteMessage($request['id']);
|
||||
|
||||
// send the response
|
||||
return Response::json([
|
||||
'deleted' => $delete ? 1 : 0,
|
||||
], 200);
|
||||
}
|
||||
|
||||
public function updateSettings(Request $request)
|
||||
{
|
||||
$msg = null;
|
||||
$error = $success = 0;
|
||||
|
||||
// dark mode
|
||||
if ($request['dark_mode']) {
|
||||
$request['dark_mode'] == "dark"
|
||||
? User::where('id', Auth::user()->id)->update(['dark_mode' => 1]) // Make Dark
|
||||
: User::where('id', Auth::user()->id)->update(['dark_mode' => 0]); // Make Light
|
||||
}
|
||||
|
||||
// If messenger color selected
|
||||
if ($request['messengerColor']) {
|
||||
$messenger_color = trim(filter_var($request['messengerColor']));
|
||||
User::where('id', Auth::user()->id)
|
||||
->update(['messenger_color' => $messenger_color]);
|
||||
}
|
||||
// if there is a [file]
|
||||
if ($request->hasFile('avatar')) {
|
||||
// allowed extensions
|
||||
$allowed_images = Chatify::getAllowedImages();
|
||||
|
||||
$file = $request->file('avatar');
|
||||
// check file size
|
||||
if ($file->getSize() < Chatify::getMaxUploadSize()) {
|
||||
if (in_array(strtolower($file->extension()), $allowed_images)) {
|
||||
// delete the older one
|
||||
if (Auth::user()->avatar != config('chatify.user_avatar.default')) {
|
||||
$avatar = Auth::user()->avatar;
|
||||
if (Chatify::storage()->exists($avatar)) {
|
||||
Chatify::storage()->delete($avatar);
|
||||
}
|
||||
}
|
||||
// upload
|
||||
$avatar = Str::uuid() . "." . $file->extension();
|
||||
$update = User::where('id', Auth::user()->id)->update(['avatar' => $avatar]);
|
||||
$file->storeAs(config('chatify.user_avatar.folder'), $avatar, config('chatify.storage_disk_name'));
|
||||
$success = $update ? 1 : 0;
|
||||
} else {
|
||||
$msg = "File extension not allowed!";
|
||||
$error = 1;
|
||||
}
|
||||
} else {
|
||||
$msg = "File size you are trying to upload is too large!";
|
||||
$error = 1;
|
||||
}
|
||||
}
|
||||
|
||||
// send the response
|
||||
return Response::json([
|
||||
'status' => $success ? 1 : 0,
|
||||
'error' => $error ? 1 : 0,
|
||||
'message' => $error ? $msg : 0,
|
||||
], 200);
|
||||
}
|
||||
|
||||
/**
|
||||
* Set user's active status
|
||||
*
|
||||
* @param Request $request
|
||||
* @return JsonResponse
|
||||
*/
|
||||
public function setActiveStatus(Request $request)
|
||||
{
|
||||
$activeStatus = $request['status'] > 0 ? 1 : 0;
|
||||
$status = User::where('id', Auth::user()->id)->update(['active_status' => $activeStatus]);
|
||||
return Response::json([
|
||||
'status' => $status,
|
||||
], 200);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Middleware;
|
||||
|
||||
use Closure;
|
||||
use Illuminate\Http\Request;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
|
||||
class RedirectBasedOnRole
|
||||
{
|
||||
/**
|
||||
* Handle an incoming request.
|
||||
*
|
||||
* @param \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response) $next
|
||||
*/
|
||||
public function handle($request, Closure $next)
|
||||
{
|
||||
if (Auth::check()) {
|
||||
$user = Auth::user();
|
||||
if ($user->user_role == 'user') {
|
||||
if ($request->route()->getName() !== 'dashboard') {
|
||||
return redirect()->route('dashboard');
|
||||
}
|
||||
} elseif ($user->user_role == 'doctor') {
|
||||
// redirect to doctor dashboard (TODO)
|
||||
// if ($request->route()->getName() !== 'doctor.dashboard') {
|
||||
// return redirect()->route('doctor.dashboard');
|
||||
// }
|
||||
} elseif ($user->user_role == 'admin') {
|
||||
if ($request->route()->getName() !== 'admin.dashboard') {
|
||||
return redirect()->route('admin.dashboard');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $next($request);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
<?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.
|
||||
*/
|
||||
public function authorize(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the validation rules that apply to the request.
|
||||
*
|
||||
* @return array<string, \Illuminate\Contracts\Validation\Rule|array|string>
|
||||
*/
|
||||
public function rules(): array
|
||||
{
|
||||
return [
|
||||
'email' => ['required', 'string', 'email'],
|
||||
'password' => ['required', 'string'],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Attempt to authenticate the request's credentials.
|
||||
*
|
||||
* @throws \Illuminate\Validation\ValidationException
|
||||
*/
|
||||
public function authenticate()
|
||||
{
|
||||
$this->ensureIsNotRateLimited();
|
||||
|
||||
if (! Auth::attempt($this->only('email', 'password'), $this->boolean('remember'))) {
|
||||
RateLimiter::hit($this->throttleKey());
|
||||
|
||||
throw ValidationException::withMessages([
|
||||
'email' => trans('auth.failed'),
|
||||
]);
|
||||
}
|
||||
|
||||
RateLimiter::clear($this->throttleKey());
|
||||
}
|
||||
|
||||
/**
|
||||
* Ensure the login request is not rate limited.
|
||||
*
|
||||
* @throws \Illuminate\Validation\ValidationException
|
||||
*/
|
||||
public function ensureIsNotRateLimited(): void
|
||||
{
|
||||
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.
|
||||
*/
|
||||
public function throttleKey(): string
|
||||
{
|
||||
return Str::transliterate(Str::lower($this->string('email')).'|'.$this->ip());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Requests;
|
||||
|
||||
use App\Models\User;
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
use Illuminate\Validation\Rule;
|
||||
|
||||
class ProfileUpdateRequest extends FormRequest
|
||||
{
|
||||
/**
|
||||
* Get the validation rules that apply to the request.
|
||||
*
|
||||
* @return array<string, \Illuminate\Contracts\Validation\Rule|array|string>
|
||||
*/
|
||||
public function rules(): array
|
||||
{
|
||||
return [
|
||||
'name' => ['required', 'string', 'max:255'],
|
||||
'email' => ['required', 'string', 'lowercase', 'email', 'max:255', Rule::unique(User::class)->ignore($this->user()->id)],
|
||||
];
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user