PHPackages                             dost-tapi/portal-integration - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Authentication &amp; Authorization](/categories/authentication)
4. /
5. dost-tapi/portal-integration

ActiveLibrary[Authentication &amp; Authorization](/categories/authentication)

dost-tapi/portal-integration
============================

Portal SSO and role integration package for DOST-TAPI Laravel applications

v1.0.0(2mo ago)00MITPHPPHP ^8.1

Since Feb 26Pushed 2mo agoCompare

[ Source](https://github.com/faridmcdato12345/portal-integration)[ Packagist](https://packagist.org/packages/dost-tapi/portal-integration)[ RSS](/packages/dost-tapi-portal-integration/feed)WikiDiscussions main Synced 1mo ago

READMEChangelogDependencies (6)Versions (2)Used By (0)

DOST-TAPI Portal Integration Package
====================================

[](#dost-tapi-portal-integration-package)

A Laravel package that provides SSO (Single Sign-On) and role management integration for DOST-TAPI applications using Spatie Laravel Permission.

Features
--------

[](#features)

- **SSO Authentication**: Validate Portal SSO tokens and authenticate users
- **Role Management**: Expose application roles to Portal with permissions
- **User Provisioning**: Create and update users from Portal with role assignment
- **Automatic User Sync**: Keep user data synchronized with Portal
- **Middleware Protection**: Protect routes with Portal API key and SSO validation
- **Artisan Commands**: Sync roles to Portal via command line

Requirements
------------

[](#requirements)

- PHP ^8.1
- Laravel ^11.0
- Spatie Laravel Permission ^6.0

Installation
------------

[](#installation)

Install the package via Composer:

```
composer require dost-tapi/portal-integration
```

### Publish Configuration

[](#publish-configuration)

Publish the configuration file:

```
php artisan vendor:publish --provider="DostTapi\PortalIntegration\PortalIntegrationServiceProvider" --tag="portal-integration-config"
```

This will create a `config/portal-integration.php` file.

### Publish Migrations

[](#publish-migrations)

Publish the migration file:

```
php artisan vendor:publish --provider="DostTapi\PortalIntegration\PortalIntegrationServiceProvider" --tag="portal-integration-migrations"
```

Then run the migration:

```
php artisan migrate
```

This adds the following columns to your `users` table:

- `portal_user_id` (nullable, indexed)
- `department` (nullable)
- `employee_id` (nullable)

Configuration
-------------

[](#configuration)

Add the following environment variables to your `.env` file:

```
# Portal Integration Settings
PORTAL_API_KEY=your-unique-api-key-here
PORTAL_URL=http://portal-app
PORTAL_USER_MODEL=App\Models\User
PORTAL_AUTO_CREATE_USERS=true
PORTAL_DEFAULT_ROLE=viewer
```

### Configuration Options

[](#configuration-options)

VariableDescriptionDefault`PORTAL_API_KEY`Unique API key for authenticating requests from Portal`null` (required)`PORTAL_URL`Base URL of the Portal application`http://portal-app``PORTAL_USER_MODEL`User model class for your application`\App\Models\User``PORTAL_AUTO_CREATE_USERS`Automatically create users during SSO`true``PORTAL_DEFAULT_ROLE`Default role assigned to new SSO users`viewer`Usage
-----

[](#usage)

### API Endpoints

[](#api-endpoints)

The package automatically registers the following API endpoints:

#### 1. Get Roles

[](#1-get-roles)

**Endpoint**: `GET /api/roles`

**Description**: Returns all roles with their permissions for Portal synchronization.

**Authentication**: Requires Portal API key as Bearer token

**Request Example**:

```
curl -X GET https://your-app.com/api/roles \
  -H "Authorization: Bearer your-api-key"
```

**Response Example**:

```
{
  "success": true,
  "application": "Accounting System",
  "roles": [
    {
      "id": 1,
      "key": "admin",
      "display_name": "Admin",
      "description": "",
      "permissions": ["view-dashboard", "manage-users", "manage-roles"]
    },
    {
      "id": 2,
      "key": "viewer",
      "display_name": "Viewer",
      "description": "",
      "permissions": ["view-dashboard"]
    }
  ]
}
```

#### 2. Create/Update User

[](#2-createupdate-user)

**Endpoint**: `POST /api/admin/create-user`

**Description**: Creates or updates a user with role assignment from Portal.

**Authentication**: Requires Portal API key as Bearer token

**Request Body**:

```
{
  "email": "john.doe@example.com",
  "name": "John Doe",
  "portal_user_id": 123,
  "role": "admin",
  "department": "IT",
  "employee_id": "EMP001"
}
```

**Response Example**:

```
{
  "success": true,
  "user_id": 5,
  "email": "john.doe@example.com",
  "role_assigned": "admin"
}
```

**Error Response** (Role not found):

```
{
  "success": false,
  "error": "Role not found",
  "message": "Role 'invalid-role' does not exist in this application"
}
```

#### 3. Update User Role

[](#3-update-user-role)

**Endpoint**: `PUT /api/admin/update-user-role/{portal_user_id}`

**Description**: Updates an existing user's role.

**Authentication**: Requires Portal API key as Bearer token

**Request Body**:

```
{
  "role": "manager"
}
```

**Response Example**:

```
{
  "success": true,
  "user_id": 5,
  "email": "john.doe@example.com",
  "old_role": "admin",
  "new_role": "manager"
}
```

**Error Response** (User not found):

```
{
  "success": false,
  "error": "User not found",
  "message": "User with portal_user_id 999 not found"
}
```

### SSO Middleware

[](#sso-middleware)

Protect routes with SSO authentication using the `portal.sso` middleware:

```
// In your routes/web.php
Route::middleware(['portal.sso'])->group(function () {
    Route::get('/dashboard', [DashboardController::class, 'index']);
    Route::get('/profile', [ProfileController::class, 'show']);
});
```

The middleware will:

1. Extract the SSO token from query parameter (`?token=...`) or Bearer token
2. Validate the token with the Portal API
3. Create or update the user in your application
4. Authenticate the user
5. Continue the request

**SSO Flow Example**:

```
User clicks "Login with Portal"
  ↓
Redirected to Portal login
  ↓
Portal authenticates user
  ↓
Portal redirects to: https://your-app.com/dashboard?token=sso-token-here
  ↓
SSO middleware validates token
  ↓
User is authenticated and sees dashboard

```

### API Key Middleware

[](#api-key-middleware)

The `portal.api` middleware is automatically applied to all package routes. You can also use it on custom routes:

```
Route::middleware(['portal.api'])->group(function () {
    Route::post('/custom-endpoint', [CustomController::class, 'handle']);
});
```

### Artisan Commands

[](#artisan-commands)

#### Sync Roles to Portal

[](#sync-roles-to-portal)

Synchronize your application's roles and permissions to the Portal:

```
php artisan portal:sync-roles
```

**Output Example**:

```
Syncing roles to Portal...
Sending 5 roles to Portal...
✓ Roles synced successfully

```

This command:

- Fetches all roles with permissions from your application
- Sends them to the Portal API (`POST /api/applications/sync-roles`)
- Logs the sync operation

You can run this command:

- After creating new roles
- After updating role permissions
- As part of deployment scripts
- Via scheduled task for automatic synchronization

Testing
-------

[](#testing)

The package includes comprehensive tests. To run tests:

```
composer install
vendor/bin/phpunit
```

### Test Coverage

[](#test-coverage)

The package includes tests for:

- ✅ Role endpoint with API key validation
- ✅ User creation and update endpoints
- ✅ Role assignment and validation
- ✅ SSO token validation and user authentication
- ✅ Middleware authentication and authorization
- ✅ Error handling and edge cases

API Reference
-------------

[](#api-reference)

### Response Format

[](#response-format)

All endpoints return JSON responses with consistent format:

**Success Response**:

```
{
  "success": true,
  // ... additional data
}
```

**Error Response**:

```
{
  "success": false,
  "error": "Error type",
  "message": "Detailed error message"
}
```

### HTTP Status Codes

[](#http-status-codes)

CodeDescription`200`Success (GET, PUT)`201`Created (POST)`400`Bad Request (Invalid role, etc.)`401`Unauthorized (Invalid API key)`404`Not Found (User not found)`422`Validation Error`500`Server Error### Authentication

[](#authentication)

All API endpoints require authentication via Bearer token:

```
Authorization: Bearer your-api-key

```

The API key is configured in `PORTAL_API_KEY` environment variable.

Security
--------

[](#security)

- **API Key**: Each application should have a unique API key
- **HTTPS**: Always use HTTPS in production
- **Token Validation**: SSO tokens are validated with the Portal API
- **Role Verification**: All role assignments verify role existence
- **Input Validation**: All endpoints validate input data
- **Error Logging**: Failed authentication attempts are logged

Troubleshooting
---------------

[](#troubleshooting)

### Common Issues

[](#common-issues)

**Issue**: API key authentication fails

**Solution**:

- Verify `PORTAL_API_KEY` is set in `.env`
- Check Bearer token is included in request headers
- Ensure API key matches between applications

---

**Issue**: SSO token validation fails

**Solution**:

- Verify `PORTAL_URL` points to correct Portal instance
- Check network connectivity between applications
- Ensure Portal API is accessible
- Review logs in `storage/logs/laravel.log`

---

**Issue**: Role not found error

**Solution**:

- Verify role exists in application using: `php artisan permission:show`
- Check role name matches exactly (case-sensitive)
- Run `php artisan cache:clear` to clear permission cache

---

**Issue**: Migration fails

**Solution**:

- Ensure `users` table exists before running migration
- Check database connection
- Verify you haven't already run the migration

---

**Issue**: Users not being created via SSO

**Solution**:

- Verify `PORTAL_AUTO_CREATE_USERS=true` in `.env`
- Check that default role exists (configured in `PORTAL_DEFAULT_ROLE`)
- Review logs for validation errors

Docker Integration
------------------

[](#docker-integration)

When using Docker, use internal container URLs for `PORTAL_URL`:

```
# For Docker internal communication
PORTAL_URL=http://portal-app

# Not external URL like:
# PORTAL_URL=https://portal.dost-tapi.gov.ph
```

Package Installation Methods
----------------------------

[](#package-installation-methods)

### Via GitHub Repository

[](#via-github-repository)

Add to `composer.json`:

```
{
  "repositories": [
    {
      "type": "vcs",
      "url": "https://github.com/dost-tapi/portal-integration"
    }
  ],
  "require": {
    "dost-tapi/portal-integration": "^1.0"
  }
}
```

### Via Local Path (Development)

[](#via-local-path-development)

Add to `composer.json`:

```
{
  "repositories": [
    {
      "type": "path",
      "url": "../portal-integration"
    }
  ],
  "require": {
    "dost-tapi/portal-integration": "*"
  }
}
```

Then run:

```
composer install
```

Logging
-------

[](#logging)

The package logs important events:

- User creation/update from Portal
- Role assignment changes
- SSO authentication success/failure
- Token validation errors
- Role sync operations

Logs are written to Laravel's default log channel (`storage/logs/laravel.log`).

Support
-------

[](#support)

For issues, questions, or contributions:

- Email:
- Create an issue in the package repository

License
-------

[](#license)

MIT License. See [LICENSE](LICENSE) file for details.

Credits
-------

[](#credits)

Developed by the DOST-TAPI Development Team.

Changelog
---------

[](#changelog)

### Version 1.0.0

[](#version-100)

- Initial release
- SSO authentication middleware
- Role management API endpoints
- User provisioning from Portal
- Role synchronization command
- Comprehensive test coverage

###  Health Score

35

—

LowBetter than 80% of packages

Maintenance86

Actively maintained with recent releases

Popularity0

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity42

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Unknown

Total

1

Last Release

74d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/ca05af41eed5045c2e93d9f72817e5ab9dd3b30ae55de8ac89b16a3054ecad7c?d=identicon)[faridmcdato12345](/maintainers/faridmcdato12345)

---

Top Contributors

[![faridmcdato12345](https://avatars.githubusercontent.com/u/19249628?v=4)](https://github.com/faridmcdato12345 "faridmcdato12345 (5 commits)")

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/dost-tapi-portal-integration/health.svg)

```
[![Health](https://phpackages.com/badges/dost-tapi-portal-integration/health.svg)](https://phpackages.com/packages/dost-tapi-portal-integration)
```

###  Alternatives

[bezhansalleh/filament-shield

Filament support for `spatie/laravel-permission`.

2.8k2.9M88](/packages/bezhansalleh-filament-shield)[laragear/two-factor

On-premises 2FA Authentication for out-of-the-box.

339785.3k8](/packages/laragear-two-factor)[illuminate/auth

The Illuminate Auth package.

9327.3M1.0k](/packages/illuminate-auth)[scaler-tech/laravel-saml2

SAML2 Service Provider integration for Laravel applications, based on OneLogin toolkit

2737.5k](/packages/scaler-tech-laravel-saml2)[alajusticia/laravel-logins

Session management in Laravel apps, user notifications on new access, support for multiple separate remember tokens, IP geolocation, User-Agent parser

2011.0k](/packages/alajusticia-laravel-logins)[aedart/athenaeum

Athenaeum is a mono repository; a collection of various PHP packages

255.2k](/packages/aedart-athenaeum)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
