add: full multi-tenancy control
This commit is contained in:
156
app/Http/Controllers/Api/LeadController.php
Normal file
156
app/Http/Controllers/Api/LeadController.php
Normal file
@@ -0,0 +1,156 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Api;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
class LeadController extends Controller
|
||||
{
|
||||
public function store(Request $request)
|
||||
{
|
||||
try {
|
||||
// Validação
|
||||
$validated = $request->validate([
|
||||
'title' => 'required|string|max:255',
|
||||
'person_name' => 'required|string|max:255',
|
||||
'person_email' => 'nullable|email',
|
||||
'person_phone' => 'nullable|string',
|
||||
'lead_value' => 'nullable|numeric',
|
||||
'description' => 'nullable|string',
|
||||
'lead_pipeline_stage_id' => 'nullable|integer|exists:lead_pipeline_stages,id', // Nova validação
|
||||
]);
|
||||
|
||||
// Inicia transação
|
||||
DB::beginTransaction();
|
||||
|
||||
// 1. Busca ou cria a pessoa
|
||||
$personId = null;
|
||||
|
||||
if (!empty($validated['person_email'])) {
|
||||
// Busca pessoa existente pelo email
|
||||
$existingPerson = DB::table('persons')
|
||||
->where('emails', 'like', '%' . $validated['person_email'] . '%')
|
||||
->first();
|
||||
|
||||
if ($existingPerson) {
|
||||
$personId = $existingPerson->id;
|
||||
}
|
||||
}
|
||||
|
||||
// Se não encontrou pessoa, cria uma nova
|
||||
if (!$personId) {
|
||||
$personEmails = !empty($validated['person_email'])
|
||||
? json_encode([['value' => $validated['person_email'], 'label' => 'work']])
|
||||
: json_encode([]);
|
||||
|
||||
$personPhones = !empty($validated['person_phone'])
|
||||
? json_encode([['value' => $validated['person_phone'], 'label' => 'work']])
|
||||
: json_encode([]);
|
||||
|
||||
$personId = DB::table('persons')->insertGetId([
|
||||
'name' => $validated['person_name'],
|
||||
'emails' => $personEmails,
|
||||
'contact_numbers' => $personPhones,
|
||||
'created_at' => now(),
|
||||
'updated_at' => now(),
|
||||
]);
|
||||
}
|
||||
|
||||
// 2. Cria o lead
|
||||
$leadId = DB::table('leads')->insertGetId([
|
||||
'title' => $validated['title'],
|
||||
'description' => $validated['description'] ?? '',
|
||||
'lead_value' => $validated['lead_value'] ?? 0,
|
||||
'status' => 1,
|
||||
'person_id' => $personId,
|
||||
'user_id' => 1,
|
||||
'lead_pipeline_id' => 1,
|
||||
'lead_pipeline_stage_id' => $validated['lead_pipeline_stage_id'] ?? 1, // Usa o valor enviado ou padrão (2)
|
||||
'lead_source_id' => 1,
|
||||
'lead_type_id' => 1,
|
||||
'expected_close_date' => null,
|
||||
'created_at' => now(),
|
||||
'updated_at' => now(),
|
||||
]);
|
||||
|
||||
// Commit da transação
|
||||
DB::commit();
|
||||
|
||||
// Busca o lead criado com a pessoa
|
||||
$lead = DB::table('leads')
|
||||
->join('persons', 'leads.person_id', '=', 'persons.id')
|
||||
->where('leads.id', $leadId)
|
||||
->select('leads.*', 'persons.name as person_name', 'persons.emails as person_emails')
|
||||
->first();
|
||||
|
||||
return response()->json([
|
||||
'success' => true,
|
||||
'message' => 'Lead criado com sucesso',
|
||||
'data' => [
|
||||
'lead_id' => $lead->id,
|
||||
'title' => $lead->title,
|
||||
'person_id' => $personId,
|
||||
'person_name' => $lead->person_name,
|
||||
'lead_value' => $lead->lead_value,
|
||||
'lead_pipeline_stage_id' => $lead->lead_pipeline_stage_id,
|
||||
]
|
||||
], 201);
|
||||
|
||||
} catch (\Illuminate\Validation\ValidationException $e) {
|
||||
DB::rollBack();
|
||||
return response()->json([
|
||||
'success' => false,
|
||||
'message' => 'Erro de validação',
|
||||
'errors' => $e->errors()
|
||||
], 422);
|
||||
|
||||
} catch (\Exception $e) {
|
||||
DB::rollBack();
|
||||
|
||||
\Log::error('Erro ao criar lead via API', [
|
||||
'message' => $e->getMessage(),
|
||||
'line' => $e->getLine(),
|
||||
'file' => $e->getFile(),
|
||||
]);
|
||||
|
||||
return response()->json([
|
||||
'success' => false,
|
||||
'message' => 'Erro ao criar lead',
|
||||
'error' => $e->getMessage(),
|
||||
], 500);
|
||||
}
|
||||
}
|
||||
|
||||
public function index()
|
||||
{
|
||||
try {
|
||||
$leads = DB::table('leads')
|
||||
->join('persons', 'leads.person_id', '=', 'persons.id')
|
||||
->select(
|
||||
'leads.id',
|
||||
'leads.title',
|
||||
'leads.lead_value',
|
||||
'leads.created_at',
|
||||
'persons.name as person_name',
|
||||
'persons.emails as person_emails'
|
||||
)
|
||||
->orderBy('leads.created_at', 'desc')
|
||||
->limit(50)
|
||||
->get();
|
||||
|
||||
return response()->json([
|
||||
'success' => true,
|
||||
'count' => $leads->count(),
|
||||
'data' => $leads
|
||||
], 200);
|
||||
|
||||
} catch (\Exception $e) {
|
||||
return response()->json([
|
||||
'success' => false,
|
||||
'message' => 'Erro ao listar leads: ' . $e->getMessage()
|
||||
], 500);
|
||||
}
|
||||
}
|
||||
}
|
||||
13
app/Http/Controllers/Controller.php
Normal file
13
app/Http/Controllers/Controller.php
Normal file
@@ -0,0 +1,13 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
|
||||
use Illuminate\Foundation\Bus\DispatchesJobs;
|
||||
use Illuminate\Foundation\Validation\ValidatesRequests;
|
||||
use Illuminate\Routing\Controller as BaseController;
|
||||
|
||||
class Controller extends BaseController
|
||||
{
|
||||
use AuthorizesRequests, DispatchesJobs, ValidatesRequests;
|
||||
}
|
||||
51
app/Http/Controllers/SuperAdmin/SessionController.php
Normal file
51
app/Http/Controllers/SuperAdmin/SessionController.php
Normal file
@@ -0,0 +1,51 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\SuperAdmin;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
|
||||
class SessionController extends Controller
|
||||
{
|
||||
public function create()
|
||||
{
|
||||
if (Auth::check() && Auth::user()->email === 'admin@example.com') {
|
||||
return redirect()->route('super-admin.tenants.index');
|
||||
}
|
||||
return view('super-admin.session.login');
|
||||
}
|
||||
|
||||
public function store(Request $request)
|
||||
{
|
||||
$credentials = $request->validate([
|
||||
'email' => ['required', 'email'],
|
||||
'password' => ['required'],
|
||||
]);
|
||||
|
||||
if (Auth::attempt($credentials)) {
|
||||
$request->session()->regenerate();
|
||||
|
||||
if (Auth::user()->email !== 'admin@example.com') {
|
||||
Auth::logout();
|
||||
return back()->withErrors([
|
||||
'email' => 'Unauthorized access.',
|
||||
]);
|
||||
}
|
||||
|
||||
return redirect()->route('super-admin.tenants.index');
|
||||
}
|
||||
|
||||
return back()->withErrors([
|
||||
'email' => 'The provided credentials do not match our records.',
|
||||
]);
|
||||
}
|
||||
|
||||
public function destroy(Request $request)
|
||||
{
|
||||
Auth::logout();
|
||||
$request->session()->invalidate();
|
||||
$request->session()->regenerateToken();
|
||||
return redirect()->route('super-admin.session.create');
|
||||
}
|
||||
}
|
||||
52
app/Http/Controllers/SuperAdmin/TenantController.php
Normal file
52
app/Http/Controllers/SuperAdmin/TenantController.php
Normal file
@@ -0,0 +1,52 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\SuperAdmin;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Models\Tenant;
|
||||
use Illuminate\Http\Request;
|
||||
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
|
||||
class TenantController extends Controller
|
||||
{
|
||||
public function index()
|
||||
{
|
||||
$tenants = Tenant::all();
|
||||
return view('super-admin.tenants.index', compact('tenants'));
|
||||
}
|
||||
|
||||
public function create()
|
||||
{
|
||||
return view('super-admin.tenants.create');
|
||||
}
|
||||
|
||||
public function store(Request $request)
|
||||
{
|
||||
$validated = $request->validate([
|
||||
'id' => 'required|string|unique:mysql.tenants',
|
||||
'domain' => 'required|string|unique:mysql.domains,domain',
|
||||
]);
|
||||
|
||||
$tenant = Tenant::create([
|
||||
'id' => $validated['id'],
|
||||
'last_updated_by' => Auth::user()->name ?? 'Super Admin',
|
||||
]);
|
||||
|
||||
$tenant->domains()->create([
|
||||
'domain' => $validated['domain'],
|
||||
]);
|
||||
|
||||
return redirect()->route('super-admin.tenants.index')
|
||||
->with('success', 'Tenant created successfully.');
|
||||
}
|
||||
|
||||
public function destroy($id)
|
||||
{
|
||||
$tenant = Tenant::findOrFail($id);
|
||||
$tenant->delete();
|
||||
|
||||
return redirect()->route('super-admin.tenants.index')
|
||||
->with('success', 'Tenant deleted successfully.');
|
||||
}
|
||||
}
|
||||
69
app/Http/Kernel.php
Normal file
69
app/Http/Kernel.php
Normal file
@@ -0,0 +1,69 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http;
|
||||
|
||||
use Illuminate\Foundation\Http\Kernel as HttpKernel;
|
||||
|
||||
class Kernel extends HttpKernel
|
||||
{
|
||||
/**
|
||||
* The application's global HTTP middleware stack.
|
||||
*
|
||||
* These middleware are run during every request to your application.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $middleware = [
|
||||
// \App\Http\Middleware\TrustHosts::class,
|
||||
\App\Http\Middleware\TrustProxies::class,
|
||||
\Illuminate\Http\Middleware\HandleCors::class,
|
||||
\App\Http\Middleware\PreventRequestsDuringMaintenance::class,
|
||||
\Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
|
||||
\App\Http\Middleware\TrimStrings::class,
|
||||
\Webkul\Installer\Http\Middleware\CanInstall::class,
|
||||
];
|
||||
|
||||
/**
|
||||
* The application's route middleware groups.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $middlewareGroups = [
|
||||
'web' => [
|
||||
\App\Http\Middleware\UniversalTenancy::class,
|
||||
\App\Http\Middleware\EncryptCookies::class,
|
||||
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
|
||||
\Illuminate\Session\Middleware\StartSession::class,
|
||||
// \Illuminate\Session\Middleware\AuthenticateSession::class,
|
||||
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
|
||||
\App\Http\Middleware\VerifyCsrfToken::class,
|
||||
\Illuminate\Routing\Middleware\SubstituteBindings::class,
|
||||
],
|
||||
|
||||
'api' => [
|
||||
\Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
|
||||
'throttle:api',
|
||||
\Illuminate\Routing\Middleware\SubstituteBindings::class,
|
||||
],
|
||||
];
|
||||
|
||||
/**
|
||||
* The application's route middleware.
|
||||
*
|
||||
* These middleware may be assigned to groups or used individually.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $routeMiddleware = [
|
||||
'auth' => \App\Http\Middleware\Authenticate::class,
|
||||
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
|
||||
'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
|
||||
'can' => \Illuminate\Auth\Middleware\Authorize::class,
|
||||
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
|
||||
'password.confirm' => \Illuminate\Auth\Middleware\RequirePassword::class,
|
||||
'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
|
||||
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
|
||||
'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
|
||||
'super_admin' => \App\Http\Middleware\SuperAdminMiddleware::class,
|
||||
];
|
||||
}
|
||||
21
app/Http/Middleware/Authenticate.php
Normal file
21
app/Http/Middleware/Authenticate.php
Normal file
@@ -0,0 +1,21 @@
|
||||
<?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');
|
||||
}
|
||||
}
|
||||
}
|
||||
17
app/Http/Middleware/EncryptCookies.php
Normal file
17
app/Http/Middleware/EncryptCookies.php
Normal file
@@ -0,0 +1,17 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Middleware;
|
||||
|
||||
use Illuminate\Cookie\Middleware\EncryptCookies as Middleware;
|
||||
|
||||
class EncryptCookies extends Middleware
|
||||
{
|
||||
/**
|
||||
* The names of the cookies that should not be encrypted.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $except = [
|
||||
'dark_mode',
|
||||
];
|
||||
}
|
||||
17
app/Http/Middleware/PreventRequestsDuringMaintenance.php
Normal file
17
app/Http/Middleware/PreventRequestsDuringMaintenance.php
Normal file
@@ -0,0 +1,17 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Middleware;
|
||||
|
||||
use Illuminate\Foundation\Http\Middleware\PreventRequestsDuringMaintenance as Middleware;
|
||||
|
||||
class PreventRequestsDuringMaintenance extends Middleware
|
||||
{
|
||||
/**
|
||||
* The URIs that should be reachable while maintenance mode is enabled.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $except = [
|
||||
//
|
||||
];
|
||||
}
|
||||
30
app/Http/Middleware/RedirectIfAuthenticated.php
Normal file
30
app/Http/Middleware/RedirectIfAuthenticated.php
Normal file
@@ -0,0 +1,30 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Middleware;
|
||||
|
||||
use App\Providers\RouteServiceProvider;
|
||||
use Closure;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
|
||||
class RedirectIfAuthenticated
|
||||
{
|
||||
/**
|
||||
* Handle an incoming request.
|
||||
*
|
||||
* @param string|null ...$guards
|
||||
* @return mixed
|
||||
*/
|
||||
public function handle(Request $request, Closure $next, ...$guards)
|
||||
{
|
||||
$guards = empty($guards) ? [null] : $guards;
|
||||
|
||||
foreach ($guards as $guard) {
|
||||
if (Auth::guard($guard)->check()) {
|
||||
return redirect(RouteServiceProvider::HOME);
|
||||
}
|
||||
}
|
||||
|
||||
return $next($request);
|
||||
}
|
||||
}
|
||||
19
app/Http/Middleware/SuperAdminMiddleware.php
Normal file
19
app/Http/Middleware/SuperAdminMiddleware.php
Normal file
@@ -0,0 +1,19 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Middleware;
|
||||
|
||||
use Closure;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
|
||||
class SuperAdminMiddleware
|
||||
{
|
||||
public function handle(Request $request, Closure $next)
|
||||
{
|
||||
if (Auth::check() && Auth::user()->email === 'admin@example.com') {
|
||||
return $next($request);
|
||||
}
|
||||
|
||||
return redirect()->route('super-admin.session.create');
|
||||
}
|
||||
}
|
||||
19
app/Http/Middleware/TrimStrings.php
Normal file
19
app/Http/Middleware/TrimStrings.php
Normal file
@@ -0,0 +1,19 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Middleware;
|
||||
|
||||
use Illuminate\Foundation\Http\Middleware\TrimStrings as Middleware;
|
||||
|
||||
class TrimStrings extends Middleware
|
||||
{
|
||||
/**
|
||||
* The names of the attributes that should not be trimmed.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $except = [
|
||||
'current_password',
|
||||
'password',
|
||||
'password_confirmation',
|
||||
];
|
||||
}
|
||||
20
app/Http/Middleware/TrustHosts.php
Normal file
20
app/Http/Middleware/TrustHosts.php
Normal file
@@ -0,0 +1,20 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Middleware;
|
||||
|
||||
use Illuminate\Http\Middleware\TrustHosts as Middleware;
|
||||
|
||||
class TrustHosts extends Middleware
|
||||
{
|
||||
/**
|
||||
* Get the host patterns that should be trusted.
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public function hosts()
|
||||
{
|
||||
return [
|
||||
$this->allSubdomainsOfApplicationUrl(),
|
||||
];
|
||||
}
|
||||
}
|
||||
13
app/Http/Middleware/TrustProxies.php
Normal file
13
app/Http/Middleware/TrustProxies.php
Normal file
@@ -0,0 +1,13 @@
|
||||
<?php
|
||||
namespace App\Http\Middleware;
|
||||
use Illuminate\Http\Middleware\TrustProxies as Middleware;
|
||||
use Illuminate\Http\Request;
|
||||
class TrustProxies extends Middleware {
|
||||
protected $proxies = '*';
|
||||
protected $headers =
|
||||
Request::HEADER_X_FORWARDED_FOR |
|
||||
Request::HEADER_X_FORWARDED_HOST |
|
||||
Request::HEADER_X_FORWARDED_PORT |
|
||||
Request::HEADER_X_FORWARDED_PROTO |
|
||||
Request::HEADER_X_FORWARDED_AWS_ELB;
|
||||
}
|
||||
22
app/Http/Middleware/UniversalTenancy.php
Normal file
22
app/Http/Middleware/UniversalTenancy.php
Normal file
@@ -0,0 +1,22 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Middleware;
|
||||
|
||||
use Closure;
|
||||
use Illuminate\Http\Request;
|
||||
use Stancl\Tenancy\Middleware\InitializeTenancyByDomain;
|
||||
|
||||
class UniversalTenancy extends InitializeTenancyByDomain
|
||||
{
|
||||
public function handle($request, Closure $next)
|
||||
{
|
||||
// Check if the current host is a central domain
|
||||
if (in_array($request->getHost(), config('tenancy.central_domains'))) {
|
||||
// It's a central domain, skip tenancy initialization
|
||||
return $next($request);
|
||||
}
|
||||
|
||||
// It's a tenant domain, proceed with standard initialization
|
||||
return parent::handle($request, $next);
|
||||
}
|
||||
}
|
||||
18
app/Http/Middleware/VerifyCsrfToken.php
Normal file
18
app/Http/Middleware/VerifyCsrfToken.php
Normal file
@@ -0,0 +1,18 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Middleware;
|
||||
|
||||
use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as Middleware;
|
||||
|
||||
class VerifyCsrfToken extends Middleware
|
||||
{
|
||||
/**
|
||||
* The URIs that should be excluded from CSRF verification.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $except = [
|
||||
'admin/mail/inbound-parse',
|
||||
'admin/web-forms/forms/*',
|
||||
];
|
||||
}
|
||||
Reference in New Issue
Block a user