Files
backend_vib360_laravel/app/Http/Controllers/APIS/AdminApi/UsersController.php

685 lines
25 KiB
PHP
Raw Normal View History

2025-03-18 16:39:57 +05:30
<?php
namespace App\Http\Controllers\APIS\AdminApi;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Http\Requests\CreateUserRequest;
2025-03-19 19:28:22 +05:30
use App\Mail\Admin\UserCreatedMail;
2025-03-18 16:39:57 +05:30
use App\Models\User;
use App\Services\AdminService;
use Exception;
2025-04-23 12:31:37 +05:30
use Faker\Guesser\Name;
2025-03-18 16:39:57 +05:30
use Illuminate\Database\QueryException;
2025-03-19 19:28:22 +05:30
use Illuminate\Support\Facades\Hash;
2025-03-18 16:39:57 +05:30
use Illuminate\Support\Facades\Log;
2025-03-19 19:28:22 +05:30
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\URL;
2025-03-18 16:39:57 +05:30
use Illuminate\Support\Str;
2025-03-19 19:28:22 +05:30
use Illuminate\Validation\ValidationException;
use Illuminate\Support\Facades\Auth;
2025-03-27 11:43:12 +05:30
use Illuminate\Support\Facades\Validator;
2025-03-18 16:39:57 +05:30
class UsersController extends Controller
{
protected $adminService;
public function __construct(AdminService $adminService)
{
$this->adminService = $adminService;
}
2025-03-27 18:54:06 +05:30
// public function store(Request $request)
// {
// try {
// $userData = [
// 'email' => $request->email,
// 'authority' => $request->authority,
// 'tenantId' => $request->tenant_id,
// 'customerId' => $request->customer_id,
// 'firstName' => $request->first_name,
// 'lastName' => $request->last_name,
// 'phone' => $request->phone,
// 'name' => $request->name,
// 'description' => $request->description,
// 'defaultDashboardId' => $request->default_dashboard_id,
// 'defaultDashboardFullscreen' => $request->default_dashboard_fullscreen,
// 'homeDashboardId' => $request->home_dashboard_id,
// 'homeDashboardHideToolbar' => $request->home_dashboard_hide_toolbar,
// 'userCredentialsEnabled' => $request->user_credentials_enabled,
// 'failedLoginAttempts' => $request->failed_login_attempts,
// 'lastLoginTs' => $request->last_login_ts,
// 'version' => $request->version,
// ];
// $response = $this->adminService->createUser($userData);
// $user = new User();
// $user->id = Str::uuid();
// $user->created_time = now()->timestamp;
// $user->tenant_id = $request->tenant_id;
// $user->customer_id = $request->customer_id;
// $user->email = $request->email;
// $user->authority = $request->authority;
// $user->first_name = $request->first_name;
// $user->last_name = $request->last_name;
// $user->phone = $request->phone;
// $user->version = $request->version;
// $user->name = $request->name;
// $user->description = $request->description;
// $user->default_dashboard_id = $request->default_dashboard_id;
// $user->default_dashboard_fullscreen = $request->default_dashboard_fullscreen;
// $user->home_dashboard_id = $request->home_dashboard_id;
// $user->home_dashboard_hide_toolbar = $request->home_dashboard_hide_toolbar;
// $user->user_credentials_enabled = $request->user_credentials_enabled;
// $user->failed_login_attempts = $request->failed_login_attempts;
// $user->last_login_ts = $request->last_login_ts;
// $user->save();
// $randomToken = Str::random(64);
// $activationLink = url("/apia/activate/{$user->id}?token={$randomToken}");
// $mail = Mail::to($user->email)->send(new UserCreatedMail($user, $activationLink));
// return response()->json([
// 'message' => __('auth.data_fetched_successfully'),
// 'user_id' => $user->id,
// 'activation_link' => $activationLink,
// 'token' => $randomToken,
// 'data' => $response
// ], 200);
// } catch (QueryException $e) {
// Log::error('Error in creating User ' . $e->getMessage());
// return jsonResponseWithErrorMessageApi(__('auth.something went wrong'), 401);
// }
// }
// public function store(Request $request)
// {
// try {
// // Validation rules
// $validator = Validator::make($request->all(), [
// 'email' => 'required|email|unique:users,email',
// 'authority' => 'required|string',
// 'tenant_id' => 'required|uuid',
// 'customer_id' => 'nullable|uuid',
// 'first_name' => 'required|string|max:255',
// 'last_name' => 'required|string|max:255',
// 'phone' => 'nullable|string|max:20',
// 'name' => 'required|string|max:255',
// 'description' => 'nullable|string',
// 'default_dashboard_id' => 'nullable|uuid',
// 'home_dashboard_id' => 'nullable|uuid',
// 'user_credentials_enabled' => 'nullable|boolean',
// 'failed_login_attempts' => 'nullable|integer',
// 'version' => 'nullable|integer',
// ]);
// if ($validator->fails()) {
// return response()->json([
// 'success' => false,
// 'message' => 'Validation failed',
// 'errors' => $validator->errors()
// ], 422);
// }
// // Generate UUID for the user
// $userId = Str::uuid();
// $currentTimestamp = now()->timestamp;
// // Create local user FIRST to ensure all fields are set
// $user = User::create([
// 'id' => $userId,
// 'email' => $request->email,
// 'authority' => $request->authority,
// 'tenant_id' => $request->tenant_id,
// 'customer_id' => $request->customer_id,
// 'first_name' => $request->first_name,
// 'last_name' => $request->last_name,
// 'phone' => $request->phone,
// 'name' => $request->name ?? "{$request->first_name} {$request->last_name}",
// 'description' => $request->description,
// 'created_time' => $currentTimestamp,
// 'created_at' => now(),
// 'updated_at' => now()
// ]);
// // Prepare data for external service
// $serviceData = [
// 'email' => $request->email,
// 'authority' => $request->authority,
// 'first_name' => $request->first_name,
// 'last_name' => $request->last_name,
// 'phone' => $request->phone,
// 'name' => $request->name ?? "{$request->first_name} {$request->last_name}",
// 'description' => $request->description,
// 'tenant_id' => $request->tenant_id,
// 'customer_id' => $request->customer_id
// ];
// // Create user in external service
// $serviceResponse = $this->adminService->createUser($serviceData);
// if (isset($serviceResponse['error'])) {
// // Rollback local creation if service fails
// $user->delete();
// throw new \Exception($serviceResponse['message']);
// }
// // Generate activation token and link
// $randomToken = Str::random(64);
// $activationLink = url("/apia/activate/{$userId}?token={$randomToken}");
// // Send activation email
// Mail::to($user->email)->queue(new UserCreatedMail($user, $activationLink));
// return response()->json([
// 'success' => true,
// 'message' => 'User created successfully',
// 'data' => [
// 'user_id' => $userId,
// 'activation_link' => $activationLink,
// 'external_service_response' => $serviceResponse
// ]
// ], 201);
// } catch (QueryException $e) {
// Log::error('Database error creating user: ' . $e->getMessage());
// return response()->json([
// 'success' => false,
// 'message' => 'Database error creating user',
// 'error' => config('app.debug') ? $e->getMessage() : null
// ], 500);
// } catch (\Exception $e) {
// Log::error('Error creating user: ' . $e->getMessage());
// return response()->json([
// 'success' => false,
// 'message' => 'Failed to create user',
// 'error' => config('app.debug') ? $e->getMessage() : null
// ], 500);
// }
// }
2025-03-18 16:39:57 +05:30
public function store(Request $request)
{
try {
2025-03-27 18:54:06 +05:30
// Validation rules (include all fields)
$validator = Validator::make($request->all(), [
'email' => 'required|email|unique:users,email',
2025-04-23 12:31:37 +05:30
// 'authority' => 'required|string|in:CUSTOMER_USER,TENANT_ADMIN,SYS_ADMIN',
// 'tenant_id' => 'required|uuid',
// 'customer_id' => 'nullable|uuid',
2025-04-23 14:45:29 +05:30
'first_name' => 'required|string|max:255',
'last_name' => 'required|string|max:255',
2025-04-23 12:31:37 +05:30
// 'phone' => 'nullable|string|max:20',
2025-04-23 14:45:29 +05:30
// 'name' => 'nullable|string|max:255',
2025-04-23 12:31:37 +05:30
// 'description' => 'nullable|string',
// 'default_dashboard_id' => 'nullable',
// 'home_dashboard_id' => 'nullable',
// 'version' => 'nullable|integer',
2025-03-27 18:54:06 +05:30
// Add validation for other fields as needed
]);
if ($validator->fails()) {
return response()->json([
'success' => false,
'message' => 'Validation failed',
'errors' => $validator->errors()
], 422);
}
// Generate UUID for the user
$userId = Str::uuid();
$currentTimestamp = now()->timestamp;
// Create user with ALL fields
$user = User::create([
'id' => $userId,
'email' => $request->email,
2025-04-23 12:31:37 +05:30
'authority' => $request->authority ?? 'CUSTOMER_USER',
'tenant_id' => $request->tenant_id ?? null,
'customer_id' => $request->customer_id ?? null,
2025-04-23 14:45:29 +05:30
'first_name' => $request->first_name ?? '',
'last_name' => $request->last_name ?? '',
2025-04-23 12:31:37 +05:30
'phone' => $request->phone ?? null,
2025-04-23 14:45:29 +05:30
'name' => $request->name ?? "{$request->first_name} {$request->last_name}",
2025-04-23 12:31:37 +05:30
'description' => $request->description ?? null,
'default_dashboard_id' => $request->default_dashboard_id ?? null,
2025-03-27 18:54:06 +05:30
'default_dashboard_fullscreen' => $request->default_dashboard_fullscreen ?? false,
2025-04-23 12:31:37 +05:30
'home_dashboard_id' => $request->home_dashboard_id ?? null,
2025-03-27 18:54:06 +05:30
'home_dashboard_hide_toolbar' => $request->home_dashboard_hide_toolbar ?? false,
'user_credentials_enabled' => $request->user_credentials_enabled ?? false,
'failed_login_attempts' => $request->failed_login_attempts ?? 0,
'last_login_ts' => $request->last_login_ts,
'version' => $request->version ?? 0,
'created_time' => $currentTimestamp,
'created_at' => now(),
'updated_at' => now()
]);
$serviceData = [
2025-03-18 16:39:57 +05:30
'email' => $request->email,
2025-04-23 14:45:29 +05:30
'authority' => $request->authority ?? null,
2025-03-18 16:39:57 +05:30
'firstName' => $request->first_name,
'lastName' => $request->last_name,
'phone' => $request->phone,
2025-03-27 18:54:06 +05:30
'name' => $request->name ?? "{$request->first_name} {$request->last_name}",
2025-03-18 16:39:57 +05:30
'description' => $request->description,
2025-04-23 14:45:29 +05:30
'tenant_id' => 'bbab7c17-2f19-4eff-9ce7-63870e02b522',
2025-03-27 18:54:06 +05:30
'customer_id' => $request->customer_id
2025-03-18 16:39:57 +05:30
];
2025-03-27 18:54:06 +05:30
if ($request->filled('customer_id')) {
$serviceData['customerId'] = [
'id' => $request->customer_id,
'entityType' => 'CUSTOMER'
];
}
2025-03-18 16:39:57 +05:30
2025-03-27 18:54:06 +05:30
$serviceResponse = $this->adminService->createUser($serviceData);
2025-03-19 19:28:22 +05:30
2025-03-27 18:54:06 +05:30
if (isset($serviceResponse['error'])) {
$user->delete();
throw new \Exception($serviceResponse['message']);
}
2025-03-19 19:28:22 +05:30
2025-03-27 18:54:06 +05:30
$randomToken = Str::random(64);
$activationLink = url("/apia/activate/{$userId}?token={$randomToken}");
2025-03-19 19:28:22 +05:30
2025-03-27 18:54:06 +05:30
// Send activation email
Mail::to($user->email)->queue(new UserCreatedMail($user, $activationLink));
2025-03-19 19:28:22 +05:30
return response()->json([
2025-03-27 18:54:06 +05:30
'success' => true,
'message' => 'User created successfully',
'data' => [
'user_id' => $userId,
'activation_link' => $activationLink,
'external_service_response' => $serviceResponse
]
], 201);
} catch (QueryException $e) {
2025-03-27 18:54:06 +05:30
Log::error('Database error creating user: ' . $e->getMessage());
return response()->json([
'success' => false,
'message' => 'Database error creating user',
'error' => config('app.debug') ? $e->getMessage() : null
], 500);
} catch (\Exception $e) {
Log::error('Error creating user: ' . $e->getMessage());
return response()->json([
'success' => false,
'message' => 'Failed to create user',
'error' => config('app.debug') ? $e->getMessage() : null
], 500);
2025-03-18 19:28:52 +05:30
}
}
public function list()
{
try {
$users = $this->adminService->listUsers();
if (!empty($users['data'])) {
return response()->json([
'message' => 'Users fetched successfully',
'users' => $users['data']
], 200);
}
return response()->json(['message' => 'No users found'], 404);
} catch (Exception $e) {
return response()->json(['error' => 'Failed to fetch users', 'details' => $e->getMessage()], 500);
}
}
2025-03-27 11:43:12 +05:30
public function delete(Request $request)
2025-03-18 19:28:52 +05:30
{
try {
2025-03-27 11:43:12 +05:30
$validator = Validator::make($request->all(), [
2025-03-27 18:54:06 +05:30
'user_id' => 'required|string|uuid'
2025-03-27 11:43:12 +05:30
]);
if ($validator->fails()) {
return response()->json([
2025-03-27 18:54:06 +05:30
'success' => false,
2025-03-27 11:43:12 +05:30
'error' => $validator->errors()->first()
], 400);
}
$userId = $request->input('user_id');
2025-03-27 18:54:06 +05:30
$errors = [];
$success = true;
2025-03-27 11:43:12 +05:30
// First try to delete from ThingsBoard
2025-03-27 18:54:06 +05:30
$tbResponse = $this->adminService->deleteUser($userId);
2025-03-18 19:28:52 +05:30
$user = User::find($userId);
2025-03-27 18:54:06 +05:30
if ($user) {
try {
$user->delete();
} catch (\Exception $e) {
$errors['local'] = 'Failed to delete from local database';
$success = false;
Log::error("Local user deletion failed: " . $e->getMessage());
}
} else {
$errors['local'] = "User not found in local database";
$success = false;
2025-03-18 19:28:52 +05:30
}
2025-03-27 18:54:06 +05:30
if (!$success) {
return response()->json([
'success' => false,
'message' => 'Partial or complete deletion failed',
'errors' => $errors,
'details' => $tbResponse['details'] ?? null
], count($errors) === 2 ? 500 : 404);
}
2025-03-27 11:43:12 +05:30
2025-03-18 19:28:52 +05:30
return response()->json([
2025-03-27 18:54:06 +05:30
'success' => true,
2025-03-27 11:43:12 +05:30
'message' => 'User deleted successfully from both systems',
2025-03-27 18:54:06 +05:30
'thingsboard_response' => $tbResponse['data'] ?? null
2025-03-18 19:28:52 +05:30
], 200);
2025-03-27 11:43:12 +05:30
} catch (\Exception $e) {
Log::error('User deletion failed: ' . $e->getMessage());
2025-03-18 19:28:52 +05:30
return response()->json([
2025-03-27 18:54:06 +05:30
'success' => false,
2025-03-27 11:43:12 +05:30
'error' => 'Failed to complete deletion process',
'details' => config('app.debug') ? $e->getMessage() : null
2025-03-18 19:28:52 +05:30
], 500);
2025-03-18 16:39:57 +05:30
}
}
2025-03-18 19:28:52 +05:30
2025-03-27 18:54:06 +05:30
2025-03-19 19:28:22 +05:30
public function activate(Request $request, $id)
{
Log::info('Full Request URL: ' . $request->fullUrl());
try {
$user = User::find($id);
if (!$user) {
Log::error("User not found for ID: {$id}");
return response()->json([
'status' => false,
'message' => 'User not found.'
], 404);
}
$token = $request->query('token');
if (!$token) {
Log::error("Token missing for User ID: {$id}");
return response()->json([
'status' => false,
'message' => 'Invalid activation link.'
], 401);
}
2025-03-27 18:54:06 +05:30
// Update password in Laravel
$user->password = Hash::make('password');
2025-03-19 19:28:22 +05:30
$user->save();
2025-03-27 18:54:06 +05:30
Log::info("Password updated for User ID: {$id} in Laravel.");
2025-03-19 19:28:22 +05:30
2025-03-27 18:54:06 +05:30
// Activate user in ThingsBoard
$activateToken = $token;
$password = 'password';
try {
$this->adminService->activateUser($user, $password, $activateToken);
Log::info("User ID: {$id} activated successfully in ThingsBoard.");
return response()->json([
'status' => true,
'message' => 'User activated and password updated successfully!',
'user_id' => $user->id
], 200);
} catch (\Exception $e) {
Log::error("ThingsBoard activation failed: " . $e->getMessage());
// If token is invalid or user is already activated, skip activation
if (str_contains($e->getMessage(), 'Unable to find user credentials')) {
return response()->json([
'status' => true,
'message' => 'User is already activated. Password updated successfully.'
], 200);
}
return response()->json([
'status' => false,
'message' => 'Failed to activate user in ThingsBoard.',
'error' => $e->getMessage()
], 500);
}
2025-03-19 19:28:22 +05:30
} catch (\Exception $e) {
Log::error("Error activating user ID: {$id}. Exception: " . $e->getMessage());
return response()->json([
'status' => false,
'message' => 'An error occurred. Please try again later.',
'error' => $e->getMessage()
], 500);
}
}
2025-03-27 11:43:12 +05:30
2025-03-27 18:54:06 +05:30
2025-03-19 19:28:22 +05:30
// public function autoLogin(Request $request)
// {
// $request->validate([
// 'email' => 'required|email'
// ]);
// $email = $request->email;
// $user = User::where('email', $email)->first();
// if (!$user) {
// return response()->json([
// 'status' => false,
// 'message' => 'User not found in Laravel. Please register or verify your email.'
// ], 404);
// }
// Auth::login($user);
// $thingsboardUser = $this->adminService->getUserByEmail($email);
// if ($thingsboardUser) {
// $tbUserId = $thingsboardUser['id']['id'];
// $thingsboardDashboardUrl = "http://your-thingsboard-domain.com/dashboard/{$tbUserId}";
// } else {
// $thingsboardDashboardUrl = null;
// }
// return response()->json([
// 'status' => true,
// 'message' => 'User found, redirecting to dashboards...',
// 'laravel_dashboard_url' => url("/dashboard/{$user->id}"),
// 'thingsboard_dashboard_url' => $thingsboardDashboardUrl
// ], 200);
// }
// public function loginUser(Request $request)
// {
// $email = $request->input('email');
// if (!$email) {
// return response()->json([
// 'status' => false,
// 'message' => 'Email is required.'
// ], 400);
// }
// $localResponse = null;
// $thingsboardResponse = null;
// // ✅ Check in local database
// $user = User::where('email', $email)->first();
// if ($user) {
// $localResponse = [
// 'status' => true,
// 'message' => 'Login successful (Local). Redirecting to Local dashboard...',
// 'user_id' => $user->id,
// 'email' => $email,
// 'dashboard_url' => url('/dashboard') // Local dashboard URL
// ];
// } else {
// $localResponse = [
// 'status' => false,
// 'message' => 'User not found in Local database.'
// ];
// }
// // ✅ Check in ThingsBoard
// $thingsboardResponse = $this->adminService->getUserByIdThingsBoard($email);
// if ($thingsboardResponse['status']) {
// $thingsboardUser = $thingsboardResponse['user'];
// $thingsboardResponse = [
// 'status' => true,
// 'message' => 'Login successful (ThingsBoard). Redirecting to ThingsBoard dashboard...',
// 'user_id' => $thingsboardUser['id']['id'],
// 'email' => $email,
// 'dashboard_url' => $thingsboardResponse['dashboard_url']
// ];
// } else {
// $thingsboardResponse = [
// 'status' => false,
// 'message' => 'User not found in ThingsBoard.'
// ];
// }
// // ✅ Return both responses
// return response()->json([
// 'local' => $localResponse,
// 'thingsboard' => $thingsboardResponse
// ], 200);
// }
public function loginUser(Request $request)
{
$email = $request->input('email');
if (!$email) {
return response()->json([
'status' => false,
'message' => 'Email is required.'
], 400);
}
$localResponse = null;
$thingsboardResponse = null;
// ✅ Check in Local database
$user = User::where('email', $email)->first();
if ($user) {
$localResponse = [
'status' => true,
'message' => 'Login successful (Local). Redirecting to Local dashboard...',
'user_id' => $user->id,
'email' => $email,
'dashboard_url' => url('/dashboard')
];
} else {
$localResponse = [
'status' => false,
'message' => 'User not found in Local database.'
];
}
$thingsboardResponse = $this->adminService->getUserByEmailThingsBoard($email);
// ✅ Return both responses
return response()->json([
'local' => $localResponse,
'thingsboard' => $thingsboardResponse
], 200);
}
2025-03-27 11:43:12 +05:30
public function userlistCustomer(Request $request)
{
try {
2025-03-27 11:43:12 +05:30
// Validate the request input
$validator = Validator::make($request->all(), [
'customer_id' => 'required|string' // or 'uuid'/'integer' depending on your ID format
]);
if ($validator->fails()) {
return response()->json([
'error' => $validator->errors()->first()
], 400);
}
2025-03-19 19:28:22 +05:30
2025-03-27 11:43:12 +05:30
$customerId = $request->input('customer_id');
$users = User::where('customer_id', $customerId)->get();
2025-03-19 19:28:22 +05:30
if ($users->isEmpty()) {
2025-03-27 11:43:12 +05:30
return response()->json([
'message' => 'No users found for this customer ID'
], 404);
}
2025-03-19 19:28:22 +05:30
2025-03-27 11:43:12 +05:30
return response()->json([
'message' => 'Users fetched successfully',
'users' => $users
], 200);
} catch (\Exception $e) {
Log::error("Customer user listing error: " . $e->getMessage());
return response()->json([
'error' => 'Failed to fetch users',
'details' => config('app.debug') ? $e->getMessage() : null
], 500);
}
}
2025-04-08 13:49:07 +05:30
public function UserByCustomerId($customerId)
{
try {
$users = User::with('customer:id,name')
->where('customer_id', $customerId)
->get()
->map(function ($user) {
$userArray = $user->toArray();
unset($userArray['customer']);
$userArray['customer_name'] = optional($user->customer)->name;
return $userArray;
});
if ($users->isEmpty()) {
return response()->json(['message' => 'No users found for this customer ID'], 404);
}
return jsonResponseWithSuccessMessage('Users fetched successfully', [
'users' => $users
]);
} catch (Exception $e) {
Log::error("An error occurred in fetching users by customer ID: " . $e->getMessage());
return jsonResponseWithErrorMessage($e->getMessage(), 500);
}
}
2025-03-18 16:39:57 +05:30
}