Merge pull request 'subhajit_changes_06_07' (#9) from subhajit_changes_06_07 into main

Reviewed-on: #9
This commit is contained in:
subhajit.pal 2026-07-16 12:12:50 +00:00
commit 0d0500b39c
22 changed files with 1183 additions and 32 deletions

74
DEPLOYMENT.md Normal file
View File

@ -0,0 +1,74 @@
# Production Deployment & Data Persistence Guide
To ensure that user data (and other settings/services) is not lost when you deploy updates to the application, follow these guidelines.
---
## 1. Do Not Use SQLite in Ephemeral Environments
By default, the application is configured to use **SQLite** (`database/database.sqlite`).
SQLite is a file-based database. In modern hosting environments—such as **Heroku**, **AWS ECS**, **Docker containers**, or **digital ocean app platform**—the local container storage is ephemeral (destroyed and recreated on every deployment or restart).
### Recommended: Switch to a Managed Database (MySQL / PostgreSQL)
For production deployments, change your database connection in your server's `.env` file to a persistent RDBMS like MySQL or PostgreSQL:
```ini
DB_CONNECTION=mysql
DB_HOST=your-production-db-host.com
DB_PORT=3306
DB_DATABASE=singlelogin
DB_USERNAME=admin
DB_PASSWORD=your_secure_password
```
---
## 2. If You Must Use SQLite in Production
If you deploy to a Virtual Private Server (VPS) like **DigitalOcean Droplet**, **Linode**, or **AWS EC2**, or if you use Docker with persistent volumes, you can continue using SQLite securely:
### Step A: Move the SQLite Database File to a Shared/Persistent Directory
Do not leave the `database.sqlite` file inside the deployment root directory (which gets overwritten/cleaned on deployment). Instead, place it in a persistent folder (e.g. `/var/www/shared/` or `/data/`):
1. On your production server, create a directory for persistent data:
```bash
mkdir -p /var/www/shared
```
2. Move your existing database file there (so you don't lose current users):
```bash
mv /var/www/singlelogin/database/database.sqlite /var/www/shared/database.sqlite
```
3. Set the correct permissions so the web server can read and write to the database and its parent folder:
```bash
chown -R www-data:www-data /var/www/shared
chmod -R 775 /var/www/shared
```
### Step B: Configure the Absolute Path in `.env`
Update the `DB_DATABASE` environment variable in your production `.env` file to point to this absolute persistent path:
```ini
DB_CONNECTION=sqlite
DB_DATABASE=/var/www/shared/database.sqlite
```
---
## 3. Safe Migration Commands on Deployment
When deploying updates, make sure your deployment scripts run migrations safely:
* **DO RUN**:
```bash
php artisan migrate --force
```
This command runs only new, pending migration files and keeps all existing data safe. The `--force` flag allows it to run in production without prompting.
* **NEVER RUN**:
```bash
php artisan migrate:fresh --seed
```
This command drops all database tables, destroying all registered users and data, and then rebuilds the schema from scratch. Do not use this in production.
---
## 4. Git Configurations
The SQLite database file `database.sqlite` is already ignored in git (`database/.gitignore`). Do not force-add or commit database files to your git repository, as doing so would cause your local database to overwrite your production database during deployment.

View File

@ -49,6 +49,10 @@ ## Code of Conduct
In order to ensure that the Laravel community is welcoming to all, please review and abide by the [Code of Conduct](https://laravel.com/docs/contributions#code-of-conduct). In order to ensure that the Laravel community is welcoming to all, please review and abide by the [Code of Conduct](https://laravel.com/docs/contributions#code-of-conduct).
## Deployment & Persistence
To configure the application for production and ensure that no user data is lost during deployment, please refer to the [DEPLOYMENT.md](file:///D:/projects/singlelogin/DEPLOYMENT.md) guide.
## Security Vulnerabilities ## Security Vulnerabilities
If you discover a security vulnerability within Laravel, please send an e-mail to Taylor Otwell via [taylor@laravel.com](mailto:taylor@laravel.com). All security vulnerabilities will be promptly addressed. If you discover a security vulnerability within Laravel, please send an e-mail to Taylor Otwell via [taylor@laravel.com](mailto:taylor@laravel.com). All security vulnerabilities will be promptly addressed.

View File

@ -39,7 +39,9 @@ public function index()
'roles_count' => Role::count(), 'roles_count' => Role::count(),
]; ];
return view('admin.dashboard', compact('admin', 'users', 'apps', 'roles', 'overrides', 'stats')); $defaultRoleName = \App\Models\Setting::get('default_role', 'Developer');
return view('admin.dashboard', compact('admin', 'users', 'apps', 'roles', 'overrides', 'stats', 'defaultRoleName'));
} }
/** /**
@ -269,4 +271,56 @@ public function toggleBlockUser(Request $request, $id)
$status = $user->is_blocked ? 'blocked' : 'unblocked'; $status = $user->is_blocked ? 'blocked' : 'unblocked';
return redirect()->route('admin.dashboard')->with('success', "User account has been {$status} successfully."); return redirect()->route('admin.dashboard')->with('success', "User account has been {$status} successfully.");
} }
/**
* Update the default role for new users.
*/
public function updateDefaultRole(Request $request)
{
$request->validate([
'default_role' => 'required|string|exists:roles,name',
]);
\App\Models\Setting::set('default_role', $request->default_role);
return redirect()->route('admin.dashboard')->with('success', 'Default role for new users updated successfully.');
}
/**
* Toggle the admin privilege of a user.
*/
public function toggleAdminPrivilege(Request $request, $id)
{
$user = User::findOrFail($id);
// Security: Prevent modifying own admin privileges
if ($user->id === Auth::id()) {
return redirect()->route('admin.dashboard')->with('error', 'Security violation: You cannot modify your own administrator privilege.');
}
if ($user->role === 'admin') {
$user->role = 'user';
// Detach Admin role from pivot if it exists
$adminRole = Role::where('name', 'Admin')->first();
if ($adminRole) {
$user->roles()->detach($adminRole->id);
}
$user->save();
$status = 'revoked';
} else {
$user->role = 'admin';
// Attach Admin role to pivot (create if missing)
$adminRole = Role::firstOrCreate(
['name' => 'Admin'],
['description' => 'Administrator access role.']
);
$user->roles()->syncWithoutDetaching([$adminRole->id]);
$user->save();
$status = 'granted';
}
return redirect()->route('admin.dashboard')->with('success', "Admin privilege has been {$status} for {$user->name} successfully.");
}
} }

View File

@ -5,6 +5,7 @@
use Illuminate\Http\Request; use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Auth;
use App\Models\PersonalApp;
use Laravel\Socialite\Facades\Socialite; use Laravel\Socialite\Facades\Socialite;
class DashboardController extends Controller class DashboardController extends Controller
@ -19,7 +20,10 @@ public function index()
// Get authorized apps for this user // Get authorized apps for this user
$services = $user->authorizedApps(); $services = $user->authorizedApps();
return view('dashboard', compact('user', 'services')); // Get personal custom apps for this user
$personalApps = $user->personalApps()->orderBy('name', 'asc')->get();
return view('dashboard', compact('user', 'services', 'personalApps'));
} }
/** /**
@ -36,10 +40,14 @@ public function launchSSO($id)
return redirect()->route('dashboard')->with('error', 'Access denied. You do not have permission to access this service.'); return redirect()->route('dashboard')->with('error', 'Access denied. You do not have permission to access this service.');
} }
$url = $app->url;
if (str_contains(strtolower($url), 'convexcrm.convexsol.co')) {
$url = rtrim($url, '/') . '/admin/authentication/microsoft_login';
}
if ($user->microsoft_id) { if ($user->microsoft_id) {
// Save target app URL in session so callback knows where to redirect // Save target app URL in session so callback knows where to redirect
session(['sso_target_url' => $app->url]); session(['sso_target_url' => $url]);
try { try {
// Determine domain hint based on user's email domain to skip account type prompt // Determine domain hint based on user's email domain to skip account type prompt
@ -148,4 +156,135 @@ public function launchApp(Request $request)
return view('sso.launch-app', compact('name', 'url', 'protocol')); return view('sso.launch-app', compact('name', 'url', 'protocol'));
} }
/**
* Store a new user custom personal app.
*/
public function storePersonalApp(Request $request)
{
$request->validate([
'name' => 'required|string|max:255',
'url' => 'required|url|max:255',
'logo' => 'nullable|file|mimes:jpg,jpeg,png,webp,svg|max:2048',
'color' => 'nullable|string|max:20',
'desc' => 'nullable|string',
'tag' => 'nullable|string|max:255',
]);
$logoPath = null;
if ($request->hasFile('logo')) {
$file = $request->file('logo');
$filename = time() . '_' . uniqid() . '.' . $file->getClientOriginalExtension();
$file->move(public_path('uploads/logos'), $filename);
$logoPath = 'uploads/logos/' . $filename;
}
Auth::user()->personalApps()->create([
'name' => $request->name,
'url' => $request->url,
'logo' => $logoPath,
'color' => $request->color ?? '#4f46e5',
'desc' => $request->desc,
'tag' => $request->tag ?? 'Personal',
]);
return redirect()->route('dashboard')->with('success', 'Custom app added successfully.');
}
/**
* Update an existing user custom personal app.
*/
public function updatePersonalApp(Request $request, $id)
{
$app = Auth::user()->personalApps()->findOrFail($id);
$request->validate([
'name' => 'required|string|max:255',
'url' => 'required|url|max:255',
'logo' => 'nullable|file|mimes:jpg,jpeg,png,webp,svg|max:2048',
'color' => 'nullable|string|max:20',
'desc' => 'nullable|string',
'tag' => 'nullable|string|max:255',
]);
$logoPath = $app->logo;
if ($request->hasFile('logo')) {
// Delete old file
if ($app->logo && file_exists(public_path($app->logo))) {
@unlink(public_path($app->logo));
}
$file = $request->file('logo');
$filename = time() . '_' . uniqid() . '.' . $file->getClientOriginalExtension();
$file->move(public_path('uploads/logos'), $filename);
$logoPath = 'uploads/logos/' . $filename;
}
$app->update([
'name' => $request->name,
'url' => $request->url,
'logo' => $logoPath,
'color' => $request->color ?? '#4f46e5',
'desc' => $request->desc,
'tag' => $request->tag ?? 'Personal',
]);
return redirect()->route('dashboard')->with('success', 'Custom app updated successfully.');
}
/**
* Delete a user custom personal app.
*/
public function destroyPersonalApp($id)
{
$app = Auth::user()->personalApps()->findOrFail($id);
if ($app->logo && file_exists(public_path($app->logo))) {
@unlink(public_path($app->logo));
}
$app->delete();
return redirect()->route('dashboard')->with('success', 'Custom app deleted successfully.');
}
/**
* Launch a personal app using SSO.
*/
public function launchPersonalSSO($id)
{
$user = Auth::user();
$pApp = $user->personalApps()->findOrFail($id);
$url = $pApp->url;
if (str_contains(strtolower($url), 'convexcrm.convexsol.co')) {
$url = rtrim($url, '/') . '/admin/authentication/microsoft_login';
}
if ($user->microsoft_id) {
// Save target app URL in session so callback knows where to redirect
session(['sso_target_url' => $url]);
try {
// Determine domain hint based on user's email domain to skip account type prompt
$domainHint = (str_ends_with($user->email, '.onmicrosoft.com') || (str_contains($user->email, '@') && !str_ends_with($user->email, 'outlook.com') && !str_ends_with($user->email, 'hotmail.com') && !str_ends_with($user->email, 'live.com')))
? 'organizations'
: 'consumers';
// Redirect to Microsoft OAuth authorize page with login_hint, domain_hint, prompt=none and custom callback
return Socialite::driver('microsoft')
->redirectUrl(route('sso.callback'))
->with([
'login_hint' => $user->email,
'domain_hint' => $domainHint,
'prompt' => 'none'
])
->redirect();
} catch (\Exception $e) {
return redirect($url);
}
}
// For non-Microsoft or non-Microsoft-linked users, redirect directly
return redirect($url);
}
} }

View File

@ -124,6 +124,16 @@ public function handleMicrosoftCallback(Request $request)
'microsoft_refresh_token' => $microsoftUser->refreshToken ?? $user->microsoft_refresh_token, 'microsoft_refresh_token' => $microsoftUser->refreshToken ?? $user->microsoft_refresh_token,
'avatar' => $microsoftUser->getAvatar() ?? $user->avatar, 'avatar' => $microsoftUser->getAvatar() ?? $user->avatar,
]); ]);
// Assign default role if they have no roles assigned
if ($user->roles()->count() === 0) {
$defaultRoleName = \App\Models\Setting::get('default_role', 'Developer');
$defaultRole = \App\Models\Role::firstOrCreate(
['name' => $defaultRoleName],
['description' => 'Default application role.']
);
$user->roles()->sync([$defaultRole->id]);
}
} else { } else {
// Block registration if domain is not allowed // Block registration if domain is not allowed
if (!$isSentientGeeks) { if (!$isSentientGeeks) {
@ -140,6 +150,14 @@ public function handleMicrosoftCallback(Request $request)
'avatar' => $microsoftUser->getAvatar(), 'avatar' => $microsoftUser->getAvatar(),
'role' => 'user', 'role' => 'user',
]); ]);
// Assign configured default role
$defaultRoleName = \App\Models\Setting::get('default_role', 'Developer');
$defaultRole = \App\Models\Role::firstOrCreate(
['name' => $defaultRoleName],
['description' => 'Default application role.']
);
$user->roles()->sync([$defaultRole->id]);
} }
Auth::login($user, true); Auth::login($user, true);

View File

@ -26,11 +26,16 @@ public function handle(Request $request, Closure $next, string $role): Response
return redirect()->route('login')->with('error', 'Your account has been blocked. Please contact the administrator.'); return redirect()->route('login')->with('error', 'Your account has been blocked. Please contact the administrator.');
} }
if (auth()->user()->role !== $role) { $user = auth()->user();
if (auth()->user()->role === 'admin') { $hasRole = ($user->role === $role) || $user->hasRole($role);
if ($role === 'user') {
if (!$hasRole) {
$isAdmin = ($user->role === 'admin') || $user->hasRole('admin');
if ($role === 'user' && $isAdmin) {
return $next($request); return $next($request);
} }
if ($isAdmin) {
return redirect()->route('admin.dashboard'); return redirect()->route('admin.dashboard');
} }
return redirect()->route('dashboard')->with('error', 'Unauthorized access.'); return redirect()->route('dashboard')->with('error', 'Unauthorized access.');

View File

@ -0,0 +1,18 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Attributes\Fillable;
#[Fillable(['user_id', 'name', 'url', 'logo', 'color', 'desc', 'tag'])]
class PersonalApp extends Model
{
/**
* Get the user that owns the custom app.
*/
public function user()
{
return $this->belongsTo(User::class);
}
}

38
app/Models/Setting.php Normal file
View File

@ -0,0 +1,38 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Attributes\Fillable;
#[Fillable(['key', 'value'])]
class Setting extends Model
{
/**
* Get a setting value by key.
*
* @param string $key
* @param mixed $default
* @return mixed
*/
public static function get(string $key, $default = null)
{
$setting = self::where('key', $key)->first();
return $setting ? $setting->value : $default;
}
/**
* Set a setting value.
*
* @param string $key
* @param mixed $value
* @return \App\Models\Setting
*/
public static function set(string $key, $value)
{
return self::updateOrCreate(
['key' => $key],
['value' => $value]
);
}
}

View File

@ -22,7 +22,22 @@ class User extends Authenticatable
*/ */
public function isAdmin(): bool public function isAdmin(): bool
{ {
return $this->role === 'admin'; return $this->role === 'admin' || $this->hasRole('admin');
}
/**
* Check if the user has a specific role by name.
*/
public function hasRole(string $roleName): bool
{
if ($this->roles->isEmpty()) {
$defaultRoleName = \App\Models\Setting::get('default_role', 'Developer');
return strtolower($roleName) === strtolower($defaultRoleName);
}
return $this->roles->contains(function ($r) use ($roleName) {
return strtolower($r->name) === strtolower($roleName);
});
} }
/** /**
@ -41,6 +56,14 @@ public function overrides()
return $this->hasMany(UserAppOverride::class); return $this->hasMany(UserAppOverride::class);
} }
/**
* Get the personal custom apps for this user.
*/
public function personalApps()
{
return $this->hasMany(PersonalApp::class);
}
/** /**
* Get the authorized apps for this user, computed from roles and overrides. * Get the authorized apps for this user, computed from roles and overrides.
*/ */
@ -52,14 +75,23 @@ public function authorizedApps()
$roleIds = $this->roles()->pluck('roles.id')->toArray(); $roleIds = $this->roles()->pluck('roles.id')->toArray();
// If no roles are assigned, fallback to configured default role first
if (empty($roleIds)) {
$defaultRoleName = \App\Models\Setting::get('default_role', 'Developer');
$defaultRole = \App\Models\Role::where('name', $defaultRoleName)->first();
if ($defaultRole) {
$roleIds = [$defaultRole->id];
}
}
// Get apps associated with user's roles // Get apps associated with user's roles
$roleAppIds = \DB::table('app_role') $roleAppIds = \DB::table('app_role')
->whereIn('role_id', $roleIds) ->whereIn('role_id', $roleIds)
->pluck('app_id') ->pluck('app_id')
->toArray(); ->toArray();
// If no roles are assigned, user gets default access to Outlook email and Drive apps if registered // If still no roles/apps resolved, user gets default access to Outlook email and Drive apps if registered
if (empty($roleIds)) { if (empty($roleAppIds)) {
$defaultAppIds = App::where(function ($query) { $defaultAppIds = App::where(function ($query) {
$query->whereRaw('LOWER(name) LIKE ?', ['%outlook%']) $query->whereRaw('LOWER(name) LIKE ?', ['%outlook%'])
->orWhereRaw('LOWER(name) LIKE ?', ['%mail%']) ->orWhereRaw('LOWER(name) LIKE ?', ['%mail%'])

View File

@ -0,0 +1,29 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('settings', function (Blueprint $table) {
$table->id();
$table->string('key')->unique();
$table->text('value')->nullable();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('settings');
}
};

View File

@ -0,0 +1,34 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('personal_apps', function (Blueprint $table) {
$table->id();
$table->foreignId('user_id')->constrained('users')->onDelete('cascade');
$table->string('name');
$table->string('url');
$table->string('logo')->nullable();
$table->string('color')->default('#4f46e5');
$table->text('desc')->nullable();
$table->string('tag')->nullable();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('personal_apps');
}
};

View File

@ -149,5 +149,11 @@ public function run(): void
['user_id' => $user1->id, 'app_id' => $keka->id], ['user_id' => $user1->id, 'app_id' => $keka->id],
['type' => 'allow'] ['type' => 'allow']
); );
// Seed default role setting
\App\Models\Setting::updateOrCreate(
['key' => 'default_role'],
['value' => 'Developer']
);
} }
} }

BIN
public/Screenshot_10.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 287 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 473 KiB

After

Width:  |  Height:  |  Size: 252 KiB

BIN
public/Screenshot_9.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 143 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.2 KiB

View File

@ -9,6 +9,9 @@
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&family=Outfit:wght@400;600;700;800&display=swap" rel="stylesheet"> <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&family=Outfit:wght@400;600;700;800&display=swap" rel="stylesheet">
<!-- SweetAlert2 -->
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<style> <style>
:root { :root {
--bg-color: #0b0f19; --bg-color: #0b0f19;
@ -681,11 +684,28 @@
</table> </table>
</div> </div>
</div> </div>
<!-- Role Management Card --> <!-- Role Management Card -->
<div class="admin-card" style="background-color: var(--card-bg); border: 1px solid var(--card-border); border-radius: 20px; padding: 30px; backdrop-filter: blur(16px); box-shadow: 0 10px 25px rgba(0, 0, 0, 0.2);"> <div class="admin-card" style="background-color: var(--card-bg); border: 1px solid var(--card-border); border-radius: 20px; padding: 30px; backdrop-filter: blur(16px); box-shadow: 0 10px 25px rgba(0, 0, 0, 0.2);">
<h3 style="font-family: 'Outfit', sans-serif; font-size: 1.25rem; font-weight: 600; margin-bottom: 16px; color: #a5b4fc;">Manage Roles & Services</h3> <h3 style="font-family: 'Outfit', sans-serif; font-size: 1.25rem; font-weight: 600; margin-bottom: 16px; color: #a5b4fc;">Manage Roles & Services</h3>
<!-- Default Role Configuration Form -->
<form action="{{ route('admin.settings.default-role') }}" method="POST" style="margin-bottom: 30px; padding-bottom: 20px; border-bottom: 1px solid rgba(255, 255, 255, 0.1);">
@csrf
<div style="margin-bottom: 12px;">
<label style="display:block; font-size:0.75rem; color:var(--text-muted); margin-bottom:6px; font-weight:500;">Default Role for New Users</label>
<div style="display: flex; gap: 8px;">
<select name="default_role" required class="form-input" style="flex: 1; padding:10px; background:rgba(255,255,255,0.03); border:1px solid var(--card-border); border-radius:8px; color:white; outline: none; font-size: 0.85rem;">
@foreach($roles as $role)
<option value="{{ $role->name }}" {{ $defaultRoleName === $role->name ? 'selected' : '' }} style="background-color: #1e1e38; color: white;">
{{ $role->name }}
</option>
@endforeach
</select>
<button type="submit" class="btn" style="background-color: var(--accent-primary); color: white; font-size:0.85rem; border-radius:8px; padding:10px 16px; border:none; cursor:pointer; font-weight:600; white-space: nowrap;">Save Default</button>
</div>
</div>
</form>
<!-- Add Role Form --> <!-- Add Role Form -->
<form action="{{ route('admin.roles.store') }}" method="POST" style="margin-bottom: 30px;"> <form action="{{ route('admin.roles.store') }}" method="POST" style="margin-bottom: 30px;">
@csrf @csrf
@ -915,6 +935,10 @@
<span class="badge" style="background-color:rgba(99,102,241,0.1); color:#818cf8; border:1px solid rgba(99,102,241,0.25); font-size:0.65rem;">{{ $role->name }}</span> <span class="badge" style="background-color:rgba(99,102,241,0.1); color:#818cf8; border:1px solid rgba(99,102,241,0.25); font-size:0.65rem;">{{ $role->name }}</span>
@endforeach @endforeach
</div> </div>
@elseif($usr->role !== 'admin')
<div style="display:flex; flex-wrap:wrap; gap:4px; margin-top:6px;">
<span class="badge" style="background-color:rgba(99,102,241,0.1); color:#818cf8; border:1px solid rgba(99,102,241,0.25); font-size:0.65rem;">{{ $defaultRoleName }}</span>
</div>
@endif @endif
</td> </td>
<td> <td>
@ -939,9 +963,20 @@
</td> </td>
<td style="text-align: right; white-space: nowrap;"> <td style="text-align: right; white-space: nowrap;">
@if($usr->id !== $admin->id) @if($usr->id !== $admin->id)
@if(!$usr->isAdmin())
<button class="action-btn" onclick="openAssignRolesModal({{ $usr->id }}, '{{ addslashes($usr->name) }}', {{ json_encode($usr->roles->pluck('id')) }})" style="color:var(--accent-primary); border-color:rgba(99,102,241,0.2); font-size:0.75rem; padding:6px 12px; margin-right:4px;">Assign Roles</button> <button class="action-btn" onclick="openAssignRolesModal({{ $usr->id }}, '{{ addslashes($usr->name) }}', {{ json_encode($usr->roles->pluck('id')) }})" style="color:var(--accent-primary); border-color:rgba(99,102,241,0.2); font-size:0.75rem; padding:6px 12px; margin-right:4px;">Assign Roles</button>
@if($usr->isAdmin())
<button class="action-btn" onclick="confirmAdminToggle({{ $usr->id }}, '{{ addslashes($usr->name) }}', 'revoke')"
style="color:#ef4444; border-color:rgba(239,68,68,0.3); background-color:rgba(239,68,68,0.05); font-size:0.75rem; padding:6px 12px; margin-right:4px; font-weight:600;">
Revoke Admin
</button>
@else
<button class="action-btn" onclick="confirmAdminToggle({{ $usr->id }}, '{{ addslashes($usr->name) }}', 'grant')"
style="color:#f59e0b; border-color:rgba(245,158,11,0.3); background-color:rgba(245,158,11,0.05); font-size:0.75rem; padding:6px 12px; margin-right:4px; font-weight:600; box-shadow: 0 0 10px rgba(245,158,11,0.15);">
Give Admin Privilege
</button>
@endif @endif
<form action="{{ route('admin.users.toggle-block', $usr->id) }}" method="POST" style="display:inline;"> <form action="{{ route('admin.users.toggle-block', $usr->id) }}" method="POST" style="display:inline;">
@csrf @csrf
<button type="submit" class="action-btn" <button type="submit" class="action-btn"
@ -1068,6 +1103,9 @@
<label style="display:block; font-size:0.75rem; color:var(--text-muted); margin-bottom:6px; font-weight:500;">Select Roles for User</label> <label style="display:block; font-size:0.75rem; color:var(--text-muted); margin-bottom:6px; font-weight:500;">Select Roles for User</label>
<div style="background:rgba(0,0,0,0.2); border:1px solid var(--card-border); border-radius:8px; padding:12px; max-height:200px; overflow-y:auto; display:flex; flex-direction:column; gap:8px;"> <div style="background:rgba(0,0,0,0.2); border:1px solid var(--card-border); border-radius:8px; padding:12px; max-height:200px; overflow-y:auto; display:flex; flex-direction:column; gap:8px;">
@foreach($roles as $role) @foreach($roles as $role)
@if(strtolower($role->name) === 'admin')
@continue
@endif
<label class="checkbox-item"> <label class="checkbox-item">
<input type="checkbox" name="roles[]" value="{{ $role->id }}" class="assign-user-role-checkbox" id="assign-user-role-{{ $role->id }}"> <input type="checkbox" name="roles[]" value="{{ $role->id }}" class="assign-user-role-checkbox" id="assign-user-role-{{ $role->id }}">
<div> <div>
@ -1148,6 +1186,43 @@ function openEditAppModal(id, name, url, tag, iconSvg, color, desc, logoPath) {
openModal('edit-app-modal'); openModal('edit-app-modal');
} }
function confirmAdminToggle(userId, userName, actionType) {
const isGrant = actionType === 'grant';
const title = isGrant ? 'Grant Admin Privilege?' : 'Revoke Admin Privilege?';
const text = isGrant
? `Are you sure you want to grant admin privilege to ${userName}? They will be able to access the admin control panel.`
: `Are you sure you want to revoke admin privilege from ${userName}? They will no longer have administrative access.`;
const confirmButtonText = isGrant ? 'Yes, grant it!' : 'Yes, revoke it!';
const confirmButtonColor = isGrant ? '#f59e0b' : '#ef4444';
Swal.fire({
title: title,
text: text,
icon: 'warning',
showCancelButton: true,
confirmButtonColor: confirmButtonColor,
cancelButtonColor: '#374151',
confirmButtonText: confirmButtonText,
background: '#1f2937',
color: '#f3f4f6'
}).then((result) => {
if (result.isConfirmed) {
const form = document.createElement('form');
form.method = 'POST';
form.action = "{{ route('admin.users.toggle-admin', ':id') }}".replace(':id', userId);
const csrfInput = document.createElement('input');
csrfInput.type = 'hidden';
csrfInput.name = '_token';
csrfInput.value = '{{ csrf_token() }}';
form.appendChild(csrfInput);
document.body.appendChild(form);
form.submit();
}
});
}
</script> </script>
<footer style="text-align: center; padding: 40px 0; font-size: 0.75rem; color: var(--text-muted); z-index: 10;"> <footer style="text-align: center; padding: 40px 0; font-size: 0.75rem; color: var(--text-muted); z-index: 10;">

View File

@ -22,6 +22,138 @@
--info-color: #06b6d4; --info-color: #06b6d4;
} }
.personal-app-card:hover .personal-app-actions {
opacity: 1 !important;
pointer-events: auto !important;
}
/* Personal Modal Styling */
.personal-modal {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(11, 15, 25, 0.85);
backdrop-filter: blur(20px);
-webkit-backdrop-filter: blur(20px);
display: flex;
align-items: center;
justify-content: center;
z-index: 1000;
opacity: 0;
pointer-events: none;
transition: all 0.3s ease;
}
.personal-modal.active {
opacity: 1;
pointer-events: all;
}
.personal-modal-content {
background-color: rgba(25, 30, 45, 0.9);
border: 1px solid var(--card-border);
border-radius: 20px;
padding: 30px;
width: 90%;
max-width: 500px;
box-shadow: 0 20px 50px rgba(0, 0, 0, 0.4);
transform: scale(0.9);
transition: transform 0.3s cubic-bezier(0.175, 0.885, 0.32, 1.275);
max-height: 90vh;
overflow-y: auto;
}
.personal-modal.active .personal-modal-content {
transform: scale(1);
}
.modal-header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 20px;
border-bottom: 1px solid rgba(255,255,255,0.08);
padding-bottom: 12px;
}
.modal-title {
font-family: 'Outfit', sans-serif;
font-size: 1.2rem;
font-weight: 700;
color: #a5b4fc;
}
.modal-close {
background: none;
border: none;
color: var(--text-muted);
font-size: 1.5rem;
cursor: pointer;
transition: color 0.2s;
}
.modal-close:hover {
color: white;
}
.form-group {
margin-bottom: 16px;
}
.form-label {
display: block;
font-size: 0.75rem;
color: var(--text-muted);
margin-bottom: 6px;
font-weight: 500;
text-transform: uppercase;
letter-spacing: 0.3px;
}
.form-input {
width: 100%;
padding: 10px 12px;
background: rgba(255, 255, 255, 0.03);
border: 1px solid var(--card-border);
border-radius: 8px;
color: white;
outline: none;
font-size: 0.85rem;
transition: all 0.2s;
}
.form-input:focus {
border-color: var(--accent-primary);
background: rgba(255, 255, 255, 0.06);
}
.modal-footer {
display: flex;
justify-content: flex-end;
gap: 10px;
margin-top: 24px;
border-top: 1px solid rgba(255,255,255,0.08);
padding-top: 16px;
}
.btn-cancel {
padding: 8px 16px;
border-radius: 8px;
border: 1px solid var(--card-border);
background: transparent;
color: var(--text-main);
font-size: 0.8rem;
font-weight: 600;
cursor: pointer;
transition: background 0.2s;
}
.btn-cancel:hover {
background: rgba(255,255,255,0.05);
}
* { * {
box-sizing: border-box; box-sizing: border-box;
margin: 0; margin: 0;
@ -598,12 +730,12 @@
<span class="nav-profile-email">{{ $user->email }}</span> <span class="nav-profile-email">{{ $user->email }}</span>
<span class="meta-dot">&bull;</span> <span class="meta-dot">&bull;</span>
<span class="nav-badge"> <span class="nav-badge">
@if($user->isAdmin()) @if($user->roles->isNotEmpty())
Admin
@elseif($user->roles->isNotEmpty())
{{ $user->roles->pluck('name')->implode(', ') }} {{ $user->roles->pluck('name')->implode(', ') }}
@elseif($user->role === 'admin')
Admin
@else @else
{{ ucfirst($user->role) }} {{ \App\Models\Setting::get('default_role', 'Developer') }}
@endif @endif
</span> </span>
@if($user->microsoft_id) @if($user->microsoft_id)
@ -614,11 +746,16 @@
</div> </div>
</div> </div>
<!-- Right: Actions --> <!-- Right: Actions -->
<div class="nav-actions"> <div class="nav-actions">
@if($user->role === 'admin') @if($user->role === 'admin')
<a href="{{ route('admin.dashboard') }}" class="nav-action-btn admin" title="Admin Panel"> <a href="{{ route('admin.dashboard') }}" class="nav-action-btn admin" title="Admin Panel">
Admin Go to Admin Dashboard
</a>
@elseif($user->hasRole('admin'))
<a href="{{ route('admin.dashboard') }}" target="_blank" class="nav-action-btn admin" title="Admin Panel">
Go to Admin Dashboard
</a> </a>
@endif @endif
<form action="{{ route('logout') }}" method="POST" id="logout-form" style="display: none;"> <form action="{{ route('logout') }}" method="POST" id="logout-form" style="display: none;">
@ -685,6 +822,71 @@
</div> </div>
</section> </section>
<!-- My Custom Apps Section -->
<section class="services-container" style="margin-top: 50px;">
<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 24px; border-bottom: 1px solid rgba(255, 255, 255, 0.08); padding-bottom: 12px;">
<h2 class="section-title" style="margin-bottom: 0; border: none; padding: 0;">My Custom Apps</h2>
<button onclick="openAddPersonalAppModal()" class="nav-action-btn admin" style="background-color: var(--accent-primary); border-color: var(--accent-primary); color: white; display: inline-flex; align-items: center; gap: 6px; cursor: pointer; text-transform: uppercase;">
+ Add Custom App
</button>
</div>
<div class="services-grid">
@forelse($personalApps as $pApp)
<div class="service-card-glass personal-app-card" style="--service-color: {{ $pApp->color ?? '#4f46e5' }};">
<!-- Relative Wrapper for Logo + Actions -->
<div style="position: relative; display: inline-block;">
<!-- Delete & Edit overlay buttons on hover -->
<div class="personal-app-actions" style="position: absolute; top: -6px; right: -6px; display: flex; gap: 6px; z-index: 100; opacity: 0; transition: opacity 0.2s ease; pointer-events: none;">
<button onclick="event.stopPropagation(); openEditPersonalAppModal({{ $pApp->id }}, '{{ addslashes($pApp->name) }}', '{{ addslashes($pApp->url) }}', '{{ addslashes($pApp->color) }}', '{{ addslashes($pApp->tag) }}', '{{ addslashes($pApp->desc) }}', '{{ $pApp->logo }}')"
style="pointer-events: auto; background: #6366f1; border: 1.5px solid rgba(255, 255, 255, 0.2); color: white; border-radius: 50%; width: 26px; height: 26px; display: flex; align-items: center; justify-content: center; cursor: pointer; box-shadow: 0 4px 12px rgba(0,0,0,0.6); transition: transform 0.2s;"
onmouseover="this.style.transform='scale(1.15)'" onmouseout="this.style.transform='scale(1)'" title="Edit App">
<svg viewBox="0 0 24 24" width="12" height="12" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round">
<path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/>
<path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"/>
</svg>
</button>
<form action="{{ route('dashboard.personal-apps.destroy', $pApp->id) }}" method="POST" onsubmit="return confirm('Are you sure you want to delete this custom app?')" style="display: inline;">
@csrf
@method('DELETE')
<button type="submit" onclick="event.stopPropagation();"
style="pointer-events: auto; background: #ef4444; border: 1.5px solid rgba(255, 255, 255, 0.2); color: white; border-radius: 50%; width: 26px; height: 26px; display: flex; align-items: center; justify-content: center; cursor: pointer; box-shadow: 0 4px 12px rgba(0,0,0,0.6); transition: transform 0.2s;"
onmouseover="this.style.transform='scale(1.15)'" onmouseout="this.style.transform='scale(1)'" title="Delete App">
<svg viewBox="0 0 24 24" width="12" height="12" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round">
<polyline points="3 6 5 6 21 6"/>
<path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/>
</svg>
</button>
</form>
</div>
<!-- Logo Wrapper -->
<div class="service-logo-wrapper" onclick="launchSSO('{{ $pApp->name }}', '{{ route('sso.personal-launch', $pApp->id) }}')">
@if($pApp->logo)
<img src="{{ asset($pApp->logo) }}" alt="{{ $pApp->name }}" class="service-logo-img">
@else
<div class="service-logo-fallback" style="background: linear-gradient(135deg, var(--service-color) 20%, rgba(255,255,255,0.05) 100%); width: 100%; height: 100%; display: flex; align-items: center; justify-content: center; border-radius: 8px; font-family: 'Outfit', sans-serif; font-size: 1.1rem; font-weight: 800; color: white; text-shadow: 0 1px 2px rgba(0,0,0,0.2);">
{{ strtoupper(substr($pApp->name, 0, 1)) }}
</div>
@endif
</div>
</div>
<!-- Name -->
<h3 class="service-title" onclick="launchSSO('{{ $pApp->name }}', '{{ route('sso.personal-launch', $pApp->id) }}')">{{ strtoupper($pApp->name) }}</h3>
@if($pApp->tag)
<div style="font-size: 0.65rem; color: var(--text-muted); text-transform: uppercase; margin-top: 4px; letter-spacing: 0.5px;">{{ $pApp->tag }}</div>
@endif
</div>
@empty
<div style="grid-column: 1 / -1; text-align: center; padding: 40px; background: rgba(255,255,255,0.02); border: 1px dashed var(--card-border); border-radius: 16px; color: var(--text-muted); font-size: 0.9rem;">
No custom apps added yet. Click "+ Add Custom App" to add your own shortcuts!
</div>
@endforelse
</div>
</section>
</main> </main>
<!-- SSO Interstitial Loading Modal --> <!-- SSO Interstitial Loading Modal -->
@ -702,6 +904,96 @@
</div> </div>
</div> </div>
<!-- Add Personal App Modal -->
<div id="add-personal-app-modal" class="personal-modal">
<div class="personal-modal-content">
<div class="modal-header">
<h3 class="modal-title">Add Custom Application</h3>
<button class="modal-close" onclick="closePersonalModal('add-personal-app-modal')">&times;</button>
</div>
<form action="{{ route('dashboard.personal-apps.store') }}" method="POST" enctype="multipart/form-data">
@csrf
<div class="form-group">
<label class="form-label">Application Name *</label>
<input type="text" name="name" required placeholder="e.g. My Github, Internal Wiki" class="form-input">
</div>
<div class="form-group">
<label class="form-label">Redirect URL *</label>
<input type="url" name="url" required placeholder="https://github.com" class="form-input">
</div>
<div class="form-group">
<label class="form-label">Custom Logo Image (Optional)</label>
<input type="file" name="logo" class="form-input" style="padding: 6px 12px;">
<div style="font-size:0.65rem; color:var(--text-muted); margin-top:4px;">Supported: PNG, JPG, WEBP, SVG (Max 2MB)</div>
</div>
<div class="form-group">
<label class="form-label">Brand Color (Hex Code)</label>
<div style="display: flex; gap: 8px;">
<input type="color" name="color_picker" id="add-color-picker" value="#4f46e5" oninput="document.getElementById('add-color-input').value = this.value" style="width: 40px; height: 38px; padding: 0; border: none; border-radius: 8px; cursor: pointer; background: transparent;">
<input type="text" name="color" id="add-color-input" value="#4f46e5" oninput="document.getElementById('add-color-picker').value = this.value" class="form-input" style="flex: 1;">
</div>
</div>
<div class="form-group">
<label class="form-label">Category Tag (Optional)</label>
<input type="text" name="tag" placeholder="e.g. Development, HR, Tools" class="form-input">
</div>
<div class="form-group">
<label class="form-label">Description (Optional)</label>
<textarea name="desc" placeholder="Brief note about this shortcut..." class="form-input" style="min-height: 80px; resize: vertical;"></textarea>
</div>
<div class="modal-footer">
<button type="button" class="btn-cancel" onclick="closePersonalModal('add-personal-app-modal')">Cancel</button>
<button type="submit" class="nav-action-btn admin" style="background-color: var(--accent-primary); border-color: var(--accent-primary); color: white; cursor: pointer;">Save Application</button>
</div>
</form>
</div>
</div>
<!-- Edit Personal App Modal -->
<div id="edit-personal-app-modal" class="personal-modal">
<div class="personal-modal-content">
<div class="modal-header">
<h3 class="modal-title">Edit Custom Application</h3>
<button class="modal-close" onclick="closePersonalModal('edit-personal-app-modal')">&times;</button>
</div>
<form id="edit-personal-app-form" method="POST" enctype="multipart/form-data">
@csrf
<div class="form-group">
<label class="form-label">Application Name *</label>
<input type="text" id="edit-papp-name" name="name" required class="form-input">
</div>
<div class="form-group">
<label class="form-label">Redirect URL *</label>
<input type="url" id="edit-papp-url" name="url" required class="form-input">
</div>
<div class="form-group">
<label class="form-label">Custom Logo Image (Optional)</label>
<input type="file" name="logo" class="form-input" style="padding: 6px 12px;">
<div id="edit-papp-logo-status" style="font-size:0.65rem; margin-top:4px;"></div>
</div>
<div class="form-group">
<label class="form-label">Brand Color (Hex Code)</label>
<div style="display: flex; gap: 8px;">
<input type="color" id="edit-papp-color-picker" oninput="document.getElementById('edit-papp-color').value = this.value" style="width: 40px; height: 38px; padding: 0; border: none; border-radius: 8px; cursor: pointer; background: transparent;">
<input type="text" name="color" id="edit-papp-color" oninput="document.getElementById('edit-papp-color-picker').value = this.value" class="form-input" style="flex: 1;">
</div>
</div>
<div class="form-group">
<label class="form-label">Category Tag (Optional)</label>
<input type="text" id="edit-papp-tag" name="tag" class="form-input">
</div>
<div class="form-group">
<label class="form-label">Description (Optional)</label>
<textarea id="edit-papp-desc" name="desc" class="form-input" style="min-height: 80px; resize: vertical;"></textarea>
</div>
<div class="modal-footer">
<button type="button" class="btn-cancel" onclick="closePersonalModal('edit-personal-app-modal')">Cancel</button>
<button type="submit" class="nav-action-btn admin" style="background-color: var(--accent-primary); border-color: var(--accent-primary); color: white; cursor: pointer;">Update Application</button>
</div>
</form>
</div>
</div>
<script> <script>
function launchSSO(serviceName, url) { function launchSSO(serviceName, url) {
const modal = document.getElementById('sso-modal'); const modal = document.getElementById('sso-modal');
@ -717,6 +1009,37 @@ function launchSSO(serviceName, url) {
window.open(url, '_blank'); window.open(url, '_blank');
}, 1200); }, 1200);
} }
function openAddPersonalAppModal() {
document.getElementById('add-personal-app-modal').classList.add('active');
}
function openEditPersonalAppModal(id, name, url, color, tag, desc, logo) {
const form = document.getElementById('edit-personal-app-form');
form.action = `{{ route('dashboard.personal-apps.update', ':id') }}`.replace(':id', id);
document.getElementById('edit-papp-name').value = name;
document.getElementById('edit-papp-url').value = url;
document.getElementById('edit-papp-color').value = color || '#4f46e5';
document.getElementById('edit-papp-color-picker').value = color || '#4f46e5';
document.getElementById('edit-papp-tag').value = tag || '';
document.getElementById('edit-papp-desc').value = desc || '';
const logoStatus = document.getElementById('edit-papp-logo-status');
if (logo) {
logoStatus.innerText = 'Has custom logo uploaded';
logoStatus.style.color = '#10b981';
} else {
logoStatus.innerText = 'No custom logo uploaded (using name fallback)';
logoStatus.style.color = '#9ca3af';
}
document.getElementById('edit-personal-app-modal').classList.add('active');
}
function closePersonalModal(modalId) {
document.getElementById(modalId).classList.remove('active');
}
</script> </script>
</body> </body>
</html> </html>

View File

@ -25,8 +25,14 @@
Route::middleware(['auth', 'role:user'])->group(function () { Route::middleware(['auth', 'role:user'])->group(function () {
Route::get('/sso/launch/{id}', [DashboardController::class, 'launchSSO'])->name('sso.launch'); Route::get('/sso/launch/{id}', [DashboardController::class, 'launchSSO'])->name('sso.launch');
Route::get('/sso/personal-launch/{id}', [DashboardController::class, 'launchPersonalSSO'])->name('sso.personal-launch');
Route::get('/sso/callback', [DashboardController::class, 'handleSSOCallback'])->name('sso.callback'); Route::get('/sso/callback', [DashboardController::class, 'handleSSOCallback'])->name('sso.callback');
Route::get('/sso/launch-app', [DashboardController::class, 'launchApp'])->name('sso.launch-app'); Route::get('/sso/launch-app', [DashboardController::class, 'launchApp'])->name('sso.launch-app');
// Personal custom apps management
Route::post('/dashboard/personal-apps', [DashboardController::class, 'storePersonalApp'])->name('dashboard.personal-apps.store');
Route::post('/dashboard/personal-apps/{id}/update', [DashboardController::class, 'updatePersonalApp'])->name('dashboard.personal-apps.update');
Route::delete('/dashboard/personal-apps/{id}', [DashboardController::class, 'destroyPersonalApp'])->name('dashboard.personal-apps.destroy');
}); });
@ -37,11 +43,13 @@
Route::post('/admin/apps/{id}/update', [AdminController::class, 'updateApp'])->name('admin.apps.update'); Route::post('/admin/apps/{id}/update', [AdminController::class, 'updateApp'])->name('admin.apps.update');
Route::delete('/admin/apps/{id}', [AdminController::class, 'destroyApp'])->name('admin.apps.destroy'); Route::delete('/admin/apps/{id}', [AdminController::class, 'destroyApp'])->name('admin.apps.destroy');
Route::post('/admin/users/{id}/toggle-block', [AdminController::class, 'toggleBlockUser'])->name('admin.users.toggle-block'); Route::post('/admin/users/{id}/toggle-block', [AdminController::class, 'toggleBlockUser'])->name('admin.users.toggle-block');
Route::post('/admin/users/{id}/toggle-admin', [AdminController::class, 'toggleAdminPrivilege'])->name('admin.users.toggle-admin');
// Roles CRUD // Roles CRUD
Route::post('/admin/roles', [AdminController::class, 'storeRole'])->name('admin.roles.store'); Route::post('/admin/roles', [AdminController::class, 'storeRole'])->name('admin.roles.store');
Route::post('/admin/roles/{id}/update', [AdminController::class, 'updateRole'])->name('admin.roles.update'); Route::post('/admin/roles/{id}/update', [AdminController::class, 'updateRole'])->name('admin.roles.update');
Route::delete('/admin/roles/{id}', [AdminController::class, 'destroyRole'])->name('admin.roles.destroy'); Route::delete('/admin/roles/{id}', [AdminController::class, 'destroyRole'])->name('admin.roles.destroy');
Route::post('/admin/settings/default-role', [AdminController::class, 'updateDefaultRole'])->name('admin.settings.default-role');
// User Roles & Overrides // User Roles & Overrides
Route::post('/admin/users/{id}/roles', [AdminController::class, 'updateUserRoles'])->name('admin.users.roles.update'); Route::post('/admin/users/{id}/roles', [AdminController::class, 'updateUserRoles'])->name('admin.users.roles.update');

View File

@ -273,4 +273,298 @@ public function test_sso_launch_redirects_to_microsoft_for_all_services_if_user_
$response->assertRedirect('https://login.microsoftonline.com/common/oauth2/v2.0/authorize'); $response->assertRedirect('https://login.microsoftonline.com/common/oauth2/v2.0/authorize');
} }
/**
* Test user with multiple roles including Admin logs in via general route,
* sees user dashboard, displays all roles, and has Go to Admin Dashboard target_blank link.
*/
public function test_user_multiple_roles_admin_link(): void
{
$user = User::create([
'name' => 'Multi Role User',
'email' => 'multi@sentientgeeks.com',
'role' => 'user',
]);
$pmRole = Role::create(['name' => 'Project Manager']);
$adminRole = Role::create(['name' => 'Admin']);
$user->roles()->sync([$pmRole->id, $adminRole->id]);
// User dashboard can be accessed
$response = $this->actingAs($user)
->get('/dashboard');
$response->assertStatus(200);
// At the top they will see other role i.e. admin
$response->assertSee('Project Manager, Admin');
// And they will see a link Go to Admin Dashboard which has target="_blank"
$response->assertSee('href="' . route('admin.dashboard') . '" target="_blank" class="nav-action-btn admin"', false);
$response->assertSee('Go to Admin Dashboard');
// And they can access the Admin Dashboard
$responseAdmin = $this->actingAs($user)
->get('/admin/dashboard');
$responseAdmin->assertStatus(200);
}
/**
* Test that new user registration / login defaults to the configured role.
*/
public function test_new_user_registration_default_role(): void
{
// 1. Initially configuration fallback is Developer
$devRole = Role::create(['name' => 'Developer']);
$otherRole = Role::create(['name' => 'Team Lead']);
// Mock Socialite callback for a brand new user
$mockSocialite = \Mockery::mock('Laravel\Socialite\Contracts\Provider');
$mockUser = \Mockery::mock('Laravel\Socialite\Two\User');
$mockUser->shouldReceive('getId')->andReturn('new-microsoft-id-888');
$mockUser->shouldReceive('getEmail')->andReturn('newuser@sentientgeeks.com');
$mockUser->shouldReceive('getName')->andReturn('New User');
$mockUser->shouldReceive('getAvatar')->andReturn(null);
$mockSocialite->shouldReceive('user')->andReturn($mockUser);
\Laravel\Socialite\Facades\Socialite::shouldReceive('driver')->with('microsoft')->andReturn($mockSocialite);
// Login as new user
$response = $this->get('/auth/microsoft/callback');
$response->assertRedirect(route('dashboard'));
$newUser = User::where('email', 'newuser@sentientgeeks.com')->first();
$this->assertNotNull($newUser);
$this->assertTrue($newUser->hasRole('Developer'));
$this->assertFalse($newUser->hasRole('Team Lead'));
}
/**
* Test that new user registration / login defaults to the custom configured role.
*/
public function test_new_user_registration_custom_default_role(): void
{
$devRole = Role::create(['name' => 'Developer']);
$otherRole = Role::create(['name' => 'Team Lead']);
// Admin updates the configuration
$admin = User::create([
'name' => 'Admin User',
'email' => 'admin@company.com',
'role' => 'admin',
]);
$this->withoutMiddleware(\Illuminate\Foundation\Http\Middleware\PreventRequestForgery::class);
$this->actingAs($admin)
->post(route('admin.settings.default-role'), [
'default_role' => 'Team Lead',
])
->assertRedirect(route('admin.dashboard'));
$this->assertEquals('Team Lead', \App\Models\Setting::get('default_role'));
// Mock Socialite callback for second new user
$mockSocialite2 = \Mockery::mock('Laravel\Socialite\Contracts\Provider');
$mockUser2 = \Mockery::mock('Laravel\Socialite\Two\User');
$mockUser2->shouldReceive('getId')->andReturn('new-microsoft-id-999');
$mockUser2->shouldReceive('getEmail')->andReturn('anotheruser@sentientgeeks.com');
$mockUser2->shouldReceive('getName')->andReturn('Another User');
$mockUser2->shouldReceive('getAvatar')->andReturn(null);
$mockSocialite2->shouldReceive('user')->andReturn($mockUser2);
\Laravel\Socialite\Facades\Socialite::shouldReceive('driver')->with('microsoft')->andReturn($mockSocialite2);
// Login as second new user
$response2 = $this->get('/auth/microsoft/callback');
$response2->assertRedirect(route('dashboard'));
$anotherUser = User::where('email', 'anotheruser@sentientgeeks.com')->first();
$this->assertNotNull($anotherUser);
$this->assertTrue($anotherUser->hasRole('Team Lead'));
$this->assertFalse($anotherUser->hasRole('Developer'));
}
/**
* Test granting and revoking admin privileges to/from other users.
*/
public function test_admin_toggle_privileges(): void
{
$admin = User::create([
'name' => 'Admin User',
'email' => 'admin@company.com',
'role' => 'admin',
]);
$targetUser = User::create([
'name' => 'Regular Dev',
'email' => 'dev@sentientgeeks.com',
'role' => 'user',
]);
$this->withoutMiddleware(\Illuminate\Foundation\Http\Middleware\PreventRequestForgery::class);
// 1. Grant admin privilege
$response = $this->actingAs($admin)
->post(route('admin.users.toggle-admin', $targetUser->id));
$response->assertRedirect(route('admin.dashboard'));
$targetUser = $targetUser->fresh();
$this->assertTrue($targetUser->isAdmin());
$this->assertEquals('admin', $targetUser->role);
$this->assertTrue($targetUser->hasRole('Admin'));
// 2. Revoke admin privilege
$response2 = $this->actingAs($admin)
->post(route('admin.users.toggle-admin', $targetUser->id));
$response2->assertRedirect(route('admin.dashboard'));
$targetUser = $targetUser->fresh();
$this->assertFalse($targetUser->isAdmin());
$this->assertEquals('user', $targetUser->role);
$this->assertFalse($targetUser->hasRole('Admin'));
// 3. Security: Prevent toggling self
$response3 = $this->actingAs($admin)
->post(route('admin.users.toggle-admin', $admin->id));
$response3->assertRedirect(route('admin.dashboard'));
$this->assertTrue($admin->fresh()->isAdmin());
}
/**
* Test user personal custom apps CRUD and isolation.
*/
public function test_user_personal_custom_apps(): void
{
$user1 = User::create([
'name' => 'User One',
'email' => 'user1@sentientgeeks.com',
'role' => 'user',
]);
$user2 = User::create([
'name' => 'User Two',
'email' => 'user2@sentientgeeks.com',
'role' => 'user',
]);
$this->withoutMiddleware(\Illuminate\Foundation\Http\Middleware\PreventRequestForgery::class);
// 1. Create personal app
$response = $this->actingAs($user1)
->post(route('dashboard.personal-apps.store'), [
'name' => 'My Test App',
'url' => 'https://example.com/test',
'color' => '#123456',
'tag' => 'Testing',
'desc' => 'Some description'
]);
$response->assertRedirect(route('dashboard'));
$this->assertDatabaseHas('personal_apps', [
'user_id' => $user1->id,
'name' => 'My Test App',
'url' => 'https://example.com/test',
'color' => '#123456'
]);
$personalApp = \App\Models\PersonalApp::where('name', 'My Test App')->first();
$this->assertNotNull($personalApp);
// 2. View dashboard and see the custom app
$viewResponse = $this->actingAs($user1)->get('/dashboard');
$viewResponse->assertStatus(200);
$viewResponse->assertSee('MY TEST APP'); // Displayed upper case in UI
// 3. Update personal app
$updateResponse = $this->actingAs($user1)
->post(route('dashboard.personal-apps.update', $personalApp->id), [
'name' => 'Updated Test App',
'url' => 'https://example.com/updated',
'color' => '#654321',
'tag' => 'UpdatedTag',
'desc' => 'New description'
]);
$updateResponse->assertRedirect(route('dashboard'));
$this->assertDatabaseHas('personal_apps', [
'id' => $personalApp->id,
'name' => 'Updated Test App',
'url' => 'https://example.com/updated',
'color' => '#654321'
]);
// 4. Security: User 2 cannot update User 1's custom app
$hackerResponse = $this->actingAs($user2)
->post(route('dashboard.personal-apps.update', $personalApp->id), [
'name' => 'Hacked App',
'url' => 'https://hacked.com',
]);
// Let's assert a 404 status because user2 doesn't own it (Auth::user()->personalApps()->findOrFail($id) throws ModelNotFoundException which is rendered as 404)
$hackerResponse->assertStatus(404);
// 5. Delete personal app
$deleteResponse = $this->actingAs($user1)
->delete(route('dashboard.personal-apps.destroy', $personalApp->id));
$deleteResponse->assertRedirect(route('dashboard'));
$this->assertDatabaseMissing('personal_apps', [
'id' => $personalApp->id
]);
}
/**
* Test silent Microsoft SSO redirection for Convex CRM.
*/
public function test_convexcrm_silent_sso_redirection(): void
{
$user = User::create([
'name' => 'Convex CRM User',
'email' => 'convexcrm@sentientgeeks.com',
'role' => 'user',
'microsoft_id' => 'mock-ms-id-777',
]);
$app = \App\Models\App::create([
'name' => 'Convex CRM',
'url' => 'https://demo-convexcrm.convexsol.co/',
'color' => '#123456',
'tag' => 'CRM'
]);
// Enable access to this app
$devRole = Role::firstOrCreate(['name' => 'Developer'], ['description' => 'Developer role']);
$devRole->apps()->syncWithoutDetaching([$app->id]);
$user->roles()->syncWithoutDetaching([$devRole->id]);
// Trigger SSO launch for corporate app
$response = $this->actingAs($user)
->get(route('sso.launch', $app->id));
// It should initiate Microsoft OAuth redirect to refresh the session
// And save rewritten target URL (Convex CRM Microsoft login redirect endpoint) in session
$this->assertEquals(
'https://demo-convexcrm.convexsol.co/admin/authentication/microsoft_login',
session('sso_target_url')
);
// Test personal custom app version
$pApp = $user->personalApps()->create([
'name' => 'My Custom Convex',
'url' => 'https://demo-convexcrm.convexsol.co',
]);
$responsePersonal = $this->actingAs($user)
->get(route('sso.personal-launch', $pApp->id));
$this->assertEquals(
'https://demo-convexcrm.convexsol.co/admin/authentication/microsoft_login',
session('sso_target_url')
);
}
} }