# **Chapter 14: Permissions and Authentication — Roles, Permission Maps, and Menus**
> **Prerequisites:** Chapters 1-4 (Gates and Page Events)
> **Try it:** Tested code from gate `ex09permis`
> (`apps/examples/Ex09permis.gate.php`, registered with a permlist in `reg.php`)
> and the production login flow in `apps/permis/` (`signin.html`).
> Open `http://localhost/SartajPhpDoc/ex09permis.html`.
---
## **14.1 Two Different Questions**
SartajPhp separates **who you are** from **what you may do**:
| Question | API | Source of truth |
|----------|-----|-----------------|
| Who is this visitor? | `getAuthenticate("GUEST,MEMBER,ADMIN")` + session `usertype` | Login (`Signin` Gate) writes session |
| What may they do? | `getAuthenticatePerm()` + `hasPermission('x')` | `registerGate` permlist + profile `lstpermis` |
Roles are coarse (three types); permissions are fine (per gate, per action).
## **14.2 Registering a Gate WITH Permissions**
The 5th argument of `registerGate` is the permission list (`reg.php`, tested):
```php
<?php
registerGate(
"ex09permis",
__DIR__ . "/apps/examples/Ex09permis.gate.php",
"",
"Ex09 Permissions",
array(
array("view", "View"),
array("secret", "Secret Event"),
array("delete", "Delete Demo"),
)
);
```
Permission names are stored as **`{gate}-{perm}`** — here
`ex09permis-view`, `ex09permis-secret`, `ex09permis-delete`.
## **14.3 The Gate Side: Authenticate, Then Load Permissions**
```php
<?php
// apps/examples/Ex09permis.gate.php — onstart (tested)
// 1) Role gate. Demo allows GUEST; a production member Gate omits GUEST
// and often passes a required permission.
$this->getAuthenticate('GUEST,MEMBER,ADMIN');
// 2) Load the permission map.
// null = load only (ADMIN→all registerGate perms; MEMBER→lstpermis).
// "view" would REQUIRE ex09permis-view or getWelcome() + exit.
$this->page->getAuthenticatePerm();
```
Then check permissions anywhere in the Gate:
```php
<?php
$type = $this->page->getAuthenticateType(); // 'GUEST' | 'MEMBER' | 'ADMIN'
$btnDel = $this->frtMain->getComponent('btnDelDemo');
if ($btnDel !== null) {
if ($this->page->hasPermission('delete')) {
$btnDel->fu_setRender(); // fusion: render this component
} else {
$btnDel->fu_unsetRender(); // fusion: never render it
}
}
```
`hasPermission('delete')` checks `ex09permis-delete` for the current Gate —
you pass the short name, the framework prefixes the gate.
## **14.3a Permission-Aware Fusion Methods — Guarding UI Without PHP Branches**
The `hasPermission()` + `fu_setRender()` pattern above has a declarative twin:
every base-`Component` fusion method below takes a **comma-separated permission
list** (or is called bare) and decides rendering by itself. Declared as
`fui-*`/`fun-*`/`fur-*` in the Front, no Gate code needed at all
(verified against `vendor/sartajphp/sartajphp/res/Score/SphpDoc/Sphp/Tools/Component.php`):
| Fusion method | Attribute form | Effect when check fails |
|---------------|----------------|-------------------------|
| `fu_setAuth("ADMIN,MEMBER")` | `fur-setAuth="ADMIN"` | Component **not rendered** if role does not match |
| `fu_setUnAuth("GUEST")` | `fur-setUnAuth="GUEST"` | Component not rendered if role **does** match |
| `fu_setRender($permis)` | `fur-setRender="delete"` | Not rendered unless user has `{gate}-delete` |
| `fu_unsetRender($permis)` | `fur-unsetRender="delete"` | Not rendered if user has `{gate}-delete` |
| `fu_setRenderTag($permis)` | `fun-setRenderTag="view"` | Tag hidden but **children still render** |
| `fu_unsetRenderTag($permis)` | — | Tag hidden (children render) if permission matches |
| `fi_setDontFill($permis)` | `fui-setDontFill="delete"` | `viewData()` skips filling this component |
| `fi_setDontSubmit($permis)` | — | Component value ignored on submit |
| `fi_setDontInsert($permis)` | — | Column skipped by `insertData()` |
| `fi_setDontUpdate($permis)` | — | Column skipped by `updateData()` |
Two distinctions worth memorizing:
- **`setRender` vs `setRenderTag`** — `unsetRender` removes the component *and*
its children from output; `unsetRenderTag` removes only the wrapper tag, so a
permission-gated `<div>` can disappear while its inner content stays.
- **`setAuth` vs `setRender`** — `setAuth` checks **roles** (`getAuthenticate`
list: `GUEST,MEMBER,ADMIN`); `setRender` checks **permissions**
(`{gate}-{perm}` from the map in 14.5).
The `fi_setDont*` family is how you build one form that different roles submit
differently — e.g. a `status` column only ADMIN may write:
```html
<!-- everyone sees it, only ADMIN's submit can change it -->
<select id="sltstatus" runat="server" dtable="ex17_doc" dfield="status"
fun-setOptions="0=Pending,1=Published"
fui-setDontUpdate="delete"></select>
```
`fi_*` variants run at parse phase, so the flag is set **before** any Page
Event calls `insertData`/`updateData`/`viewData` — the Page helpers then honor
`blnDontFill` / `blnDontSubmit` / `blnDontUpdate` (Chapter 12's helper table).
Prefer these fusion attributes over hand-written `if (hasPermission())
fu_setRender()` blocks: they are declarative, survive Front refactors, and
cannot be forgotten on one branch of the Gate.
## **14.4 Event-Level Bans (Gate Open, Event Guarded)**
A Gate can be public while one event stays private — check inside the handler
(tested: `ex09permis-secret.html` as GUEST shows the denial):
```php
<?php
/** Event-level ban: Gate open for GUEST, this handler still needs ex09permis-secret. */
public function page_event_secret($evtp)
{
$this->page->getAuthenticatePerm();
if (!$this->page->hasPermission('secret')) {
$this->authInfo = $this->page->getAuthenticateType();
$this->permProbe = 'DENIED secret event';
setErr('ex09', 'Permission Denied — need ex09permis-secret');
$this->setFrontFile($this->frtMain);
return;
}
setMsg('ex09', 'Secret event OK for role ' . $this->page->getAuthenticateType());
$this->setFrontFile($this->frtMain);
}
```
## **14.5 How the Permission Map Is Built**
```mermaid
flowchart TD
A[registerGate permlist] -->|ADMIN: all perms| P[permission map]
B[session lstpermis<br/>from profile_permission] -->|MEMBER: listed perms| P
P --> H[page-hasPermission gate-perm]
H --> R[fu_setRender / fu_unsetRender<br/>addMenuLink roles / event checks]
```
- **ADMIN** (`profile_id = 0`) → every permission of every registered gate.
- **MEMBER** → only the comma list in session `lstpermis`
(stored in `profile_permission.permission_id`).
- **GUEST** → nothing.
**Do not** call `SphpBase::sphpPermissions()->setPermissions()` manually for
login profiles — `Page::getAuthenticatePerm()` loads the map from the session
via `getProfilePermission()`. Manual injection is the classic way to create
ghost permissions that vanish on the next request.
The demo Gate switches identities by writing sessions directly (test-only!):
```php
<?php
/** Demo MEMBER: setSession('MEMBER', uid>0) + lstpermis from profile_permission style list. */
public function page_event_asmember($evtp)
{
$req = SphpBase::sphpRequest();
$req->session('sid', '1');
$req->session('parentid', '1');
$req->session('usertype', 'MEMBER');
$req->session('profile_id', '1');
$req->session('lstpermis', 'ex09permis-view,ex09permis-secret');
setSession('MEMBER', 1);
$this->page->forward(getGateUrl('ex09permis'));
}
public function page_event_asguest($evtp)
{
destSession();
$this->page->forward(getGateUrl('ex09permis'));
}
```
Try the sequence: `ex09permis-asmember.html` → secret event OK, delete button
hidden; `ex09permis-asadmin.html` → everything visible;
`ex09permis-asguest.html` → denied.
## **14.6 Production Login: the `apps/permis/` Flow**
The real login is `apps/permis/Signin.gate.php` (registered as `signin`):
1. `page_submit()` reads `uname`/`pword` components
2. Super admin comes from `comp.php` (`$admUser`/`$admPass`) → sessions
`usertype=ADMIN`, `profile_id=0`, `lstpermis=""`
3. Members: `SELECT member.*, profile_permission.permission_id ... WHERE
username=... AND password=... AND member.status='1'` → sessions
`sid`, `parentid`, `usertype`, `profile_id`, `lstpermis`
4. `setSession('MEMBER', $row['id'])` marks the session authenticated
5. `getWelcome()` (function in `comp.php`) forwards by role:
```php
<?php
// comp.php — role-based landing (tested in this project)
function getWelcome(){
switch(SphpBase::page()->getAuthenticateType()){
case "ADMIN":{ $page->forward(getGateUrl("mebhome",'','',true)); break; }
case "MEMBER":{ $page->forward(getGateUrl("mebhome")); break; }
default:{ $page->forward(getGateUrl("index")); }
}
}
```
**Remember-me** uses two encrypted cookies (`algdec` marker + `algdec2`
encrypted session JSON via `encryptme`/`decryptme`); `page_new()` restores the
session from them when present. Logout expires both cookies and calls
`destSession()`.
Google OAuth is included in the same Gate (`page_event_gauth` →
`page_event_gauthr`): redirect to Google, exchange `code` for a token, fetch
userinfo, then match/create the `member` row and run the same `setAuthUser()`
+ `getWelcome()`. OAuth secrets live in `comp.php` globals — never in Gates or
docs.
## **14.7 Menus That Respect Permissions**
Menus are project-wide — define them in `masters/**/*.place.php` (Chapter 8).
From a Gate you may still add/ban (tested):
```php
<?php
$api = SphpBase::sphpApi();
$api->addMenu('Ex09Demo', '', 'fa fa-shield', 'root', false, 'GUEST,MEMBER,ADMIN');
$api->addMenuLink('Ex09 Home', getGateUrl('ex09permis'), 'fa fa-home', 'Ex09Demo', false, 'GUEST,MEMBER,ADMIN');
// role list can be a permission name — auto-hidden when the user lacks it
$api->addMenuLink('Ex09 Secret UI', getEventUrl('secret'), 'fa fa-key', 'Ex09Demo', false, 'ex09permis-secret');
$api->addMenuLink('Banned Link', '#banned', 'fa fa-ban', 'Ex09Demo');
$api->banMenuLink('Banned Link', 'Ex09Demo');
```
The last argument of `addMenuLink` is a **role or permission list**; a link
whose permission the user lacks is not rendered at all.
## **14.8 Permission-Aware Gates: Checklist**
1. Register the gate with its permlist in `reg.php`
2. `getAuthenticate('MEMBER,ADMIN')` in `onstart` (omit GUEST for member areas)
3. `getAuthenticatePerm()` — load only, or `getAuthenticatePerm('view')` to
require a permission
4. Guard UI with permission-aware fusion (`fur-setAuth`, `fur-setRender`,
`fun-setRenderTag`, `fui-setDontUpdate`) or with `hasPermission()` +
`fu_setRender/fu_unsetRender` in the Gate
5. Guard events inside handlers (defense in depth — hidden UI is not security)
6. Let menus hide themselves via the roles/permission argument
7. Keep secrets (admin password, OAuth keys) in `comp.php`, never in Gates
## **14.9 Verify It Yourself**
Against `http://localhost/SartajPhpDoc/`:
1. `ex09permis.html` as GUEST → probe shows `view=no; secret=no; delete=no`
2. `ex09permis-asadmin.html` → all `yes`, delete button visible
3. `ex09permis-asmember.html` → `view=yes; secret=yes; delete=no`
4. `ex09permis-secret.html` as MEMBER → "Secret event OK"; as GUEST →
"Permission Denied — need ex09permis-secret"
5. `signin.html` → log in with `comp.php` admin credentials → lands via
`getWelcome()` on `mebhome`
---
**Previous:** [Chapter 13 — AJAX and jsServer](chapter13.md) ·
**Next:** [Chapter 15 — Database Communication in the Gate](chapter15.md)