Files
location/app/Http/Controllers/CitiesController.php
Daeng Deni Mardaeni 53a2c3a38e feat(auth): tambah validasi peran pengguna untuk modul lokasi
- **Autentikasi dan Otorisasi**:
  - Menambah validasi akses berdasarkan peran pengguna menggunakan `Auth::guard('web')->user()`.
  - Menentukan izin seperti `location.read`, `location.create`, `location.update`, `location.delete`, dan `location.export` untuk setiap metode di controller.
  - Menambahkan pesan error khusus untuk user yang tidak memiliki izin akses tertentu.

- **Peningkatan Controller**:
  - Mengubah properti `user` dari publik menjadi `protected`.
  - Menambahkan validasi peran pengguna pada metode di controller berikut:
    - `ProvincesController`: Pembatasan akses untuk operasi CRUD dan export.
    - `CitiesController`: Restriksi yang sama seperti pada `ProvincesController`.
    - `DistrictsController`: Menambahkan pengecekan otorisasi berdasarkan peran.
    - `VillagesController`: Validasi akses CRUD, export, dan data villager.

- **Seeder**:
  - Menambahkan `PermissionSeeder` untuk menghasilkan izin CRUD dengan grup `location`.
  - Memastikan setiap action CRUD (`read`, `create`, `update`, dll.) terdaftar dalam basis data.

- **Perbaikan API Response**:
  - Mengganti penggunaan `echo json_encode` dengan metode `response()->json()`.
  - Penanganan response untuk berbagai metode seperti `destroy`, dan validasi akses lainnya.

Signed-off-by: Daeng Deni Mardaeni <ddeni05@gmail.com>
2025-06-22 19:16:11 +07:00

219 lines
7.7 KiB
PHP

<?php
namespace Modules\Location\Http\Controllers;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Maatwebsite\Excel\Facades\Excel;
use Modules\Location\Exports\CitiesExport;
use Modules\Location\Http\Requests\CityRequest;
use Modules\Location\Models\City;
use Modules\Location\Models\Province;
class CitiesController extends Controller
{
protected $user;
public function __construct()
{
$this->user = Auth::guard('web')->user();
}
public function index(){
if (is_null($this->user) || !$this->user->can('location.read')) {
abort(403, 'Sorry! You are not allowed to view cities.');
}
return view('location::cities.index');
}
public function create(){
if (is_null($this->user) || !$this->user->can('location.create')) {
abort(403, 'Sorry! You are not allowed to create cities.');
}
$provinces = Province::all();
return view('location::cities.create',compact('provinces'));
}
public function store(CityRequest $request){
if (is_null($this->user) || !$this->user->can('location.create')) {
abort(403, 'Sorry! You are not allowed to create cities.');
}
$validate = $request->validated();
if($validate){
try {
City::create($validate);
return redirect()->route('locations.cities.index')->with('success', 'City created successfully');
} catch (\Exception $e) {
return redirect()->route('locations.cities.create')->with('error', 'Failed to create city');
}
}
}
public function edit($id){
if (is_null($this->user) || !$this->user->can('location.update')) {
abort(403, 'Sorry! You are not allowed to update cities.');
}
$city = City::find($id);
$provinces = Province::all();
return view('location::cities.create', compact('city', 'provinces'));
}
public function update(CityRequest $request, $id){
if (is_null($this->user) || !$this->user->can('location.update')) {
abort(403, 'Sorry! You are not allowed to update cities.');
}
$validate = $request->validated();
if($validate){
try {
$city = City::find($id);
$city->update($validate);
return redirect()->route('locations.cities.index')->with('success', 'City updated successfully');
} catch (\Exception $e) {
return redirect()->route('locations.cities.edit', $id)->with('error', 'Failed to update city');
}
}
}
public function destroy($id){
if (is_null($this->user) || !$this->user->can('provinces.delete')) {
return response()->json(['success' => false, 'message' => 'Sorry! You are not allowed to delete cities.']);
}
try {
City::destroy($id);
return response()->json(['message' => 'City deleted successfully', 'success' => true]);
} catch (\Exception $e) {
return response()->json(['message' => 'Failed to delete city', 'success' => false]);
}
}
public function dataForDatatables(Request $request){
if (is_null($this->user) || !$this->user->can('location.read')) {
return response()->json(['success' => false, 'message' => 'Sorry! You are not allowed to view cities.'], 403);
}
// Retrieve data from the database
$query = City::query();
// Apply search filter if provided
if ($request->has('search') && !empty($request->get('search'))) {
$search = $request->get('search');
$search = explode('|', $search);
if(isset($search[0]) && !empty($search[0])){
// Define special city codes once
$specialCityCodes = ['92.01', '92.04', '92.05', '92.09', '92.10', '92.71'];
// Handle Papua province special cases
if($search[0] == '92'){
$query->where('province_code', '92')
->whereNotIn('code', $specialCityCodes);
} else if($search[0] == '92.1'){
$query->where('province_code', '92')
->whereIn('code', $specialCityCodes);
} else {
// For all other provinces
$query->where('province_code', $search[0]);
}
}
$query->where(function ($q) use ($search) {
$q->where('code', 'LIKE', "%$search[1]%");
$q->orWhere('name', 'LIKE', "%$search[1]%");
$q->orWhereRelation('province','name', 'LIKE', "%$search[1]%");
});
}
// Apply sorting if provided
if ($request->has('sortOrder') && !empty($request->get('sortOrder'))) {
$order = $request->get('sortOrder');
$column = $request->get('sortField');
$query->orderBy($column, $order);
}
// Get the total count of records
$totalRecords = $query->count();
// Apply pagination if provided
if ($request->has('page') && $request->has('size')) {
$page = $request->get('page');
$size = $request->get('size');
$offset = ($page - 1) * $size; // Calculate the offset
$query->skip($offset)->take($size);
}
// Get the filtered count of records
$filteredRecords = $query->count();
// Get the data for the current page
$data = $query->with('province')->get();
// Calculate the page count
$pageCount = ceil($totalRecords/$request->get('size'));
// Calculate the current page number
$currentPage = 0 + 1;
//maping data for datatables,
//jika city code adalah '92.01', '92.04', '92.05', '92.09', '92.10', '92.71' maka province code yang dipilih adalah 92.1
$data = $data->map(function ($item) {
if (in_array($item->code, ['92.01', '92.04', '92.05', '92.09', '92.10', '92.71'])) {
$item->province_name = Province::where('code', '92.1')->first()->name;
} else {
$item->province_name = $item->province->name;
}
return $item;
});
// Apply the search filter again if there is a search filter
// Return the response data as a JSON object
return response()->json([
'draw' => $request->get('draw'),
'recordsTotal' => $totalRecords,
'recordsFiltered' => $filteredRecords,
'pageCount' => $pageCount,
'page' => $currentPage,
'totalCount' => $totalRecords,
'data' => $data,
]);
}
public function export()
{
if (is_null($this->user) || !$this->user->can('location.read')) {
abort(403, 'Sorry! You are not allowed to export cities.');
}
return Excel::download(new CitiesExport, 'cities.xlsx');
}
public function getCitiesByProvinceId($id)
{
if (is_null($this->user) || !$this->user->can('location.read')) {
return response()->json(['success' => false, 'message' => 'Sorry! You are not allowed to view cities.'], 403);
}
$query = City::query();
$provinceCode = substr($id, 0, 2);
$query->where('province_code', $provinceCode);
if ($id == '92.1') {
$query->whereIn('code', ['92.01', '92.04', '92.05', '92.09', '92.10', '92.71']);
} elseif ($id == '92') {
$query->whereNotIn('code', ['92.01', '92.04', '92.05', '92.09', '92.10', '92.71']);
}
return response()->json($query->get());
}
}