User Management & Security

Complete guide to NkapBooks User Management & Security — User Accounts, Roles, Role Permissions, Document Sharing, Session Management, Authentication, and the Permission System architecture.

11. User Management & Security

NkapBooks includes a full-featured role-based access control (RBAC) system that lets you control who can view, create, edit, delete, submit, and share every document type in the application. The security model is built on schema-based entities — Users, Roles, Role Permissions, Sessions, and Document Shares — all managed through the standard document interface.

ComponentSchemaLocationDescription
User AccountsUserSetup → UsersIndividual login identities with profile, contact, and security settings
RolesRoleSetup → RolesNamed groupings of permissions (e.g., Sales User, Accounts Manager)
Role PermissionsRolePermissionRole → Permissions tabGranular per-doctype permission matrix for each role
Document SharingDocShareSetup → Document SharesShare specific documents with users who lack full doctype access
Session ManagementSessionSetup → SessionsTrack and control active login sessions across devices
AuthenticationAuthSettingsSettings → AuthenticationLogin requirements, password policy, 2FA, lockout, and API keys
Permission SystemPermissionManagerInternalThe engine that evaluates all permission checks at runtime
User management features are accessible from the sidebar under SetupUsers, Roles, Document Shares, and Sessions. Authentication settings are configured in Settings → Authentication tab. All user and role CRUD operations use the standard schema-based document interface (list view, form view, quick edit).

11.0 Security Model Overview

NkapBooks implements a layered permission model that evaluates access at multiple levels:

┌─────────────────────────────────────────────────┐
│  1. Administrator Bypass                         │
│     If user has Administrator role → ALLOW ALL   │
├─────────────────────────────────────────────────┤
│  2. System Doctype Bypass                        │
│     Core settings doctypes → ALLOW ALL           │
├─────────────────────────────────────────────────┤
│  3. Role-Based Permissions                       │
│     Check RolePermission records for user's roles│
├─────────────────────────────────────────────────┤
│  4. Owner-Based Permissions (ifOwner)            │
│     Permission applies only if user owns the doc │
├─────────────────────────────────────────────────┤
│  5. Document Sharing                             │
│     Check DocShare records for specific documents │
├─────────────────────────────────────────────────┤
│  6. Default: DENY                                │
└─────────────────────────────────────────────────┘

Permission Types

The system supports 13 distinct permission types that can be independently toggled per doctype per role:

PermissionFieldDescription
ReadreadPermView documents of this type
WritewritePermModify existing documents
CreatecreatePermCreate new documents
DeletedeletePermRemove documents
SubmitsubmitPermSubmit draft documents for finalization
CancelcancelPermCancel submitted documents
AmendamendPermCreate amended versions of cancelled documents
ReportreportPermAccess reports related to this doctype
ExportexportPermExport data (CSV, JSON)
ImportimportPermImport data from external sources
SharesharePermShare documents with other users
PrintprintPermPrint or generate PDFs
EmailemailPermSend documents via email

Standard Roles

NkapBooks ships with four system roles that cannot be deleted:

RoleTypeDescription
AdministratorSystemFull unrestricted access to everything — bypasses all permission checks
System ManagerSystemSystem configuration access — can manage settings and system-level operations
AllAutomaticAutomatically assigned to every user — used for universal baseline permissions
GuestAutomaticAssigned to unauthenticated or anonymous users
Important: Automatic roles (All and Guest) are assigned automatically and cannot be manually assigned or removed from users. System roles (Administrator and System Manager) cannot be deleted or renamed but can be assigned to users.

11.1 User Accounts

A User in NkapBooks represents an individual who can log in, perform actions, and own documents. Users are identified by their email address (which serves as the primary key) and have a rich profile including contact details, security settings, and role assignments.

User Schema

The User schema is organized into six sections:

Profile Section

FieldTypeRequiredDescription
name (Email)DataPrimary identifier — must be a valid email address (e.g., user@example.com)
passwordPasswordSet during creation only; not persisted in the database directly
firstNameDataUser's first name
lastNameDataUser's last name
fullNameData (read-only)Auto-computed from firstName + lastName
usernameDataOptional display username
enabledCheckWhether the user can log in (default: true)
imageAttachImageProfile picture
genderSelectMale, Female, Other, or Prefer not to say
birthDateDateDate of birth
locationDataGeographic location
bioTextShort biography

Contact Section

FieldTypeDescription
phoneDataOffice/home phone number
mobileNoDataMobile phone number

Roles Section

FieldTypeDescription
rolesTable → UserRoleChild table linking the user to one or more roles

Each row in the roles table is a UserRole record:

FieldTypeDescription
roleLink → RoleReference to a Role record

Security Section

FieldTypeDefaultDescription
simultaneousSessionsInt3Max concurrent sessions (1–100)
restrictIpDataComma-separated allowed IP addresses
loginAfterDataEarliest allowed login time (HH:MM format, e.g., 09:00)
loginBeforeDataLatest allowed login time (HH:MM format, e.g., 18:00)
twoFactorEnabledCheckfalseWhether 2FA is enabled for this user

Activity Section (read-only)

FieldTypeDescription
lastLoginDatetimeTimestamp of last successful login
lastIpDataIP address of last login
lastActiveDatetimeTimestamp of last activity
Activity fields are hidden in the form view and updated automatically by the system. They are read-only and cannot be edited manually.

Settings Section

FieldTypeDefaultDescription
languageSelectEnglishPreferred language (English or French)
timeZoneDataUser's time zone
muteSoundsCheckfalseMute UI notification sounds
allowedInMentionsChecktrueWhether this user appears in mention lists

Email Section

FieldTypeDefaultDescription
emailSignatureTextCustom signature for outgoing emails
sendWelcomeEmailChecktrueSend welcome email on account creation
threadNotifyChecktrueReceive thread notification emails
sendMeCopyCheckfalseCC the user on outgoing emails

Creating a User

  1. Navigate to Setup → Users from the sidebar
  2. Click + New User (or press Ctrl+N)
  3. Enter the email address in the Name field — this is the user's login identifier
  4. Fill in First Name and Last Name (Full Name is auto-computed)
  5. Set a Password (only visible during creation; hidden after save)
  6. Assign Roles in the Roles table — click Add Row and select a role
  7. Click Save (Ctrl+S)

User Lifecycle

EventBehavior
Before SyncEmail is set to name if not provided; full name is computed; password is extracted for separate secure storage
After SyncPassword is set via Tauri secure command (set_password); permission cache is cleared for this user
DeactivationSet enabled to false — the user can no longer log in but their data and history are preserved

List View

The Users list view displays three columns by default:

ColumnDescription
nameEmail address (primary key)
fullNameComputed display name
enabledActive/inactive status

Keyword search works across name, email, fullName, and username.

Quick Edit Fields

When viewing a user in quick edit mode, these fields are shown:

  • Email, First Name, Last Name, Enabled, Phone

11.2 Roles

A Role defines a named set of permissions. Roles are assigned to users and determine what actions each user can perform across the application.

Role Schema

FieldTypeRequiredDefaultDescription
nameDataUnique role name (2–140 characters, no commas or semicolons)
descriptionTextHuman-readable description of what this role grants
disabledCheckfalseDisable the role without deleting it
deskAccessChecktrueWhether users with this role can access the application desk/modules
twoFactorAuthCheckfalseRequire two-factor authentication for users with this role
isCustomChecktrueSystem flag — true for user-created roles, false for built-in roles
restrictToDomainDataOptional domain restriction
permissionsTable → RolePermissionChild table defining per-doctype permissions

Built-in Roles

NkapBooks comes with several pre-configured roles:

RoleTypeCan DeleteCan AssignDescription
AdministratorSystemFull access to all features and data
System ManagerSystemAccess to system configuration and settings
AllAutomatic❌ (auto-assigned)Baseline permissions for all authenticated users
GuestAutomatic❌ (auto-assigned)Permissions for unauthenticated users
Accounts ManagerCustom (built-in)Full access to accounting features
Sales UserCustom (built-in)Access to sales documents and customers
Purchase UserCustom (built-in)Access to purchase documents and suppliers
Inventory UserCustom (built-in)Access to inventory and stock management

Creating a Custom Role

  1. Navigate to Setup → Roles from the sidebar
  2. Click + New Role
  3. Enter a Role Name (e.g., "Cashier", "Branch Manager")
  4. Add a Description explaining the role's purpose
  5. Configure Desk Access and Two-Factor Auth settings
  6. Add Permissions in the permissions table (see Role Permissions)
  7. Click Save

Role Properties

PropertyMethodDescription
isSystemRoleGetterReturns true for Administrator, System Manager, All, Guest
isAutomaticRoleGetterReturns true for All, Guest (auto-assigned)
canBeAssignedGettertrue if the role is not automatic and not disabled
canDeleteGettertrue if the role is not a system role

Role Lifecycle

EventBehavior
Before SyncSets isCustom flag for new roles (true if not a system role)
Before DeletePrevents deletion of system roles; checks for assigned users and throws error if any
After SyncClears the global permission cache so changes take effect immediately

Role Deletion Protection

When you try to delete a role:

  1. System roles — Cannot be deleted. An error is shown: "Cannot delete system role: Administrator"
  2. Assigned roles — Cannot be deleted while assigned to users. Error: "Cannot delete role 'Cashier' as it is assigned to 3 user(s). Please remove the role from all users first."
  3. Custom unassigned roles — Can be deleted safely. Associated RolePermission child entries are deleted automatically.

List View

ColumnDescription
nameRole name
descriptionRole description
deskAccessWhether the role grants desk access
disabledDisabled status

Clicking a role in the list opens the role form at /edit/Role/{name}.


11.3 Role Permissions

Role Permissions (RolePermission) define the granular access rights for each role on each document type. They are stored as a child table within the Role document.

RolePermission Schema

FieldTypeDefaultDescription
docTypeAutoCompleteThe document type this permission applies to (e.g., SalesInvoice)
permLevelInt0Permission level — 0 for document-level, 1–9 for field-level
readPermChecktrueCan view documents
writePermCheckfalseCan edit existing documents
createPermCheckfalseCan create new documents
deletePermCheckfalseCan delete documents
submitPermCheckfalseCan submit draft documents
cancelPermCheckfalseCan cancel submitted documents
amendPermCheckfalseCan amend cancelled documents
reportPermCheckfalseCan view related reports
exportPermCheckfalseCan export data
importPermCheckfalseCan import data
sharePermCheckfalseCan share documents with others
printPermCheckfalseCan print or generate PDFs
emailPermCheckfalseCan send documents via email
selectPermChecktrueCan select/reference this doctype in Link fields
setUserPermissionsCheckfalseCan set user-level permissions
ifOwnerCheckfalsePermission applies only if the user is the document owner

Table View Columns

When viewing permissions in the Role form, the table shows:

ColumnDescription
docTypeDocument type name
readPermRead checkbox
writePermWrite checkbox
createPermCreate checkbox
deletePermDelete checkbox

Additional permissions are accessible via the row quick edit (click a row to expand).

The ifOwner Flag

The ifOwner flag is a powerful feature that restricts a permission to only apply when the current user is the owner (creator) of the document:

ScenarioifOwner = falseifOwner = true
User created the invoice✅ Can edit✅ Can edit
Another user created the invoice✅ Can edit❌ Cannot edit

This is useful for creating roles where users can manage their own documents but not others'. For example, a "Sales User" role might have:

  • SalesInvoice → Read (ifOwner: false), Write (ifOwner: true), Create, Submit (ifOwner: true)
  • This means: can view all invoices, but can only edit/submit their own

Setting Up Permissions

Via Role Form

  1. Open a Role (e.g., Setup → Roles → Sales User)
  2. Scroll to the Permissions section
  3. Click Add Row
  4. Select a Document Type from the dropdown
  5. Toggle the permission checkboxes as needed
  6. Enable If Owner if the permission should be owner-restricted
  7. Save the role

Via Code (Programmatic)

The setRolePermission() function in src/utils/auth.ts provides programmatic permission management:

ParameterTypeDescription
rolestringRole name
docTypestringDocument type name
permissionsobjectPermission flags to set

Permission Resolution

When checking if a user can perform an action, the system:

  1. Gets all roles assigned to the user (including automatic roles like All)
  2. For each role, checks the RolePermission entries for the target doctype
  3. If any role grants the permission → ALLOW (union of all role permissions)
  4. If the granting permission has ifOwner set → checks document ownership
  5. If no role grants the permission → falls through to document sharing check
Tip: Permissions are additive across roles. If a user has both "Sales User" and "Accounts Manager" roles, they get the union of all permissions from both roles. You cannot use one role to remove permissions granted by another.

11.4 Document Sharing

Document Sharing (DocShare) lets you grant access to specific documents to users who may not have full doctype-level permissions. This is useful for collaboration scenarios where you want to share a particular invoice or report with a colleague without giving them access to all documents of that type.

DocShare Schema

FieldTypeRequiredDefaultDescription
userLink → UserThe user to share the document with
shareNameDataThe name/ID of the document being shared
shareDocTypeDataThe document type (e.g., SalesInvoice)
everyoneCheckfalseIf true, the document is shared with all users
readAccessChecktrueCan view the shared document
writeAccessCheckfalseCan edit the shared document
shareAccessCheckfalseCan re-share the document with others
submitAccessCheckfalseCan submit the shared document
notifyByEmailChecktrueSend an email notification to the shared user
notifyByEmailSentCheck (read-only)falseWhether the notification email was sent
sharedByLink → User (read-only)The user who created the share

Sharing a Document

Via the UI

  1. Navigate to Setup → Document Shares from the sidebar
  2. Click + New Document Share
  3. Select the User to share with
  4. Enter the Document Type (e.g., SalesInvoice)
  5. Enter the Document Name (e.g., SINV-00042)
  6. Configure access levels (Read, Write, Share, Submit)
  7. Save

Via the Permission Manager (Programmatic)

The shareDocument() method is available on both the AuthService and PermissionManager:

ParameterDescription
docTypeDocument type to share
docNameSpecific document name/ID
userIdUser to share with
options.readGrant read access (default: true)
options.writeGrant write access (default: false)
options.shareGrant re-share access (default: false)
options.submitGrant submit access (default: false)

Share with Everyone

Setting the everyone flag to true makes the document accessible to all authenticated users without specifying individual users. This is checked during permission evaluation — if any DocShare record exists with everyone: true and the matching doctype/name, the permission is granted.

Share Permission Checking

When the role-based permission check denies access, the system performs a secondary check:

  1. Look for DocShare records matching { shareDocType, shareName, user } (direct share)
  2. Look for DocShare records matching { shareDocType, shareName, everyone: true } (everyone share)
  3. Check the access field (readAccess, writeAccess, shareAccess, submitAccess) corresponding to the requested permission
  4. If either check finds a match → ALLOW

Managing Shares

FunctionDescription
shareDocument()Create or update a share for a specific document
unshareDocument()Remove a specific user's share on a document
getDocumentShares()List all shares for a specific document
getUserDocumentShares()List all documents shared with a specific user
clearDocumentShares()Remove all shares for a specific document
To share a document, the sharing user must themselves have the Share permission (sharePerm) on the relevant doctype. This prevents unprivileged users from granting access they don't have.

11.5 Session Management

NkapBooks tracks user sessions to provide security monitoring, multi-device support, and automatic session cleanup.

Session Schema

FieldTypeRequiredDefaultDescription
userLink → UserThe user this session belongs to
sessionIdData (read-only)Unique session identifier (randomly generated)
deviceDataDevice name or type (auto-detected)
ipAddressData (read-only)IP address of the session
userAgentData (read-only)Browser/app user agent string
lastActiveDatetime (read-only)Timestamp of the most recent activity
expiresAtDatetimeWhen the session will automatically expire
isValidChecktrueWhether the session is still valid
isLockedCheckfalseWhether the session is currently locked (screen lock)
lockedAtDatetime (read-only)When the session was locked

Session Lifecycle

Login Request
    │
    ▼
┌──────────────┐     ┌──────────────┐
│ Authenticate │────►│ Create       │
│ Credentials  │     │ Session      │
└──────────────┘     └──────┬───────┘
                            │
                            ▼
                    ┌──────────────┐
                    │ Active       │◄──── Refresh / Activity
                    │ Session      │
                    └──────┬───────┘
                            │
              ┌─────────────┼─────────────┐
              │             │             │
              ▼             ▼             ▼
      ┌──────────┐  ┌──────────┐  ┌──────────┐
      │ Logout   │  │ Timeout  │  │ Lock     │
      │ (Manual) │  │ (Auto)   │  │ (Idle)   │
      └──────────┘  └──────────┘  └──────┬───┘
                                          │
                                          ▼
                                  ┌──────────────┐
                                  │ Unlock       │
                                  │ (Password)   │
                                  └──────────────┘

Session Operations

OperationMethodDescription
LoginauthService.login()Creates a new session, returns session token
ValidateauthService.validateSession()Checks if a session token is still valid
RefreshauthService.refreshSession()Extends session expiry, returns new token
LogoutauthService.logout()Invalidates the current session
Logout AllauthService.logoutAllDevices()Invalidates all sessions for the current user
Get SessionsgetUserSessions()Lists all active sessions for a user

Viewing Sessions

Navigate to Setup → Sessions to see all active sessions. The list view shows:

ColumnDescription
UserThe session owner
DeviceDevice name/type
Is ValidWhether the session is active

Session Security Features

FeatureDescription
Session TimeoutConfigurable in Auth Settings — sessions expire after the specified duration
Idle TimeoutSeparate idle timeout — locks the session after inactivity
Session LockingLocked sessions require password re-entry to unlock
Max SessionsConfigurable per user (simultaneousSessions field) and globally (maxSessionsPerUser in AuthSettings)
Token StorageSession tokens are stored securely using the Tauri Stronghold plugin

11.6 Authentication

Authentication in NkapBooks is controlled by the AuthSettings schema (accessible via Settings → Authentication tab) and the AuthService class.

AuthSettings Schema

The AuthSettings is a singleton document organized into six sections:

General Section

FieldTypeDefaultDescription
requireAuthChecktrueIf enabled, users must log in to access the application
allowSkipAuthCheckfalseAllow users to skip authentication (for development/testing)

Password Section

FieldTypeDefaultDescription
allowPasswordResetChecktrueAllow users to reset their password
passwordMinLengthInt8Minimum number of characters required
passwordRequireUppercaseChecktrueRequire at least one uppercase letter
passwordRequireNumberChecktrueRequire at least one number
passwordRequireSpecialCheckfalseRequire at least one special character

Session Section

FieldTypeDefaultDescription
sessionTimeoutInt (minutes)60Session timeout duration (0 = no timeout)
maxSessionsPerUserInt3Maximum simultaneous sessions per user
sessionIdleTimeoutInt (minutes)30Idle timeout before auto-lock (0 = disabled)

Two-Factor Section

FieldTypeDefaultDescription
enableTwoFactorCheckfalseAllow users to enable 2FA
requireTwoFactorCheckfalseRequire all users to enable 2FA
twoFactorMethodSelectTOTPMethod: TOTP (Time-based One-Time Password) or Email

Security Section

FieldTypeDefaultDescription
maxLoginAttemptsInt5Maximum failed attempts before lockout (0 = unlimited)
lockoutDurationInt (minutes)15Duration of account lockout after max failed attempts

API Section

FieldTypeDefaultDescription
allowApiKeysChecktrueAllow users to generate API keys for programmatic access

Registration Section

FieldTypeDefaultDescription
allowPublicRegistrationCheckfalseAllow public user registration
defaultRoleLink → RoleDefault role assigned to newly registered users
requireEmailVerificationChecktrueRequire email verification for new accounts

Login Flow

User enters email/username + password
    │
    ▼
┌──────────────────────┐
│ AuthDemux.login()    │──── Tauri backend command
└──────────┬───────────┘
           │
           ▼
   ┌───────────────┐     ┌──────────────────┐
   │ Credentials   │─NO─►│ Return error     │
   │ Valid?        │     │ (increment fails) │
   └───────┬───────┘     └──────────────────┘
           │ YES
           ▼
   ┌───────────────┐     ┌──────────────────┐
   │ Account       │─YES►│ Return lockout   │
   │ Locked?       │     │ error            │
   └───────┬───────┘     └──────────────────┘
           │ NO
           ▼
   ┌───────────────┐     ┌──────────────────┐
   │ 2FA           │─YES►│ Return 2FA       │
   │ Required?     │     │ challenge        │
   └───────┬───────┘     └──────────────────┘
           │ NO
           ▼
   ┌───────────────┐
   │ Create Session│──── Session token stored
   │ Return Success│     via Tauri Stronghold
   └───────────────┘

Password Management

NkapBooks provides several password management operations:

OperationFunctionDescription
Set PasswordsetPassword(userId, password)Admin sets a user's password directly
Change PasswordchangePassword(current, new)User changes their own password
Request ResetrequestPasswordReset(email)Initiate a password reset flow
Reset PasswordresetPassword(token, new)Complete a password reset with a reset token
Security Note: Passwords are never stored in the database directly. They are hashed and managed through Tauri backend commands (set_password, change_password). The password field on the User schema is only used during creation and is cleared before the document is saved.

API Key Management

When allowApiKeys is enabled in AuthSettings, users can generate API keys for programmatic access:

OperationFunctionDescription
generateApiKeys(userId)Generate new API key pair for a user
revokeApiKeys(userId)Revoke all API keys for a user

User Registration

When allowPublicRegistration is enabled, new users can register through the application:

  1. The system creates a new User document with the provided details
  2. Assigns the default role configured in AuthSettings
  3. If requireEmailVerification is enabled, sends a verification email
  4. Sets the user's password through the secure Tauri backend

11.7 Permission System Architecture

The PermissionManager (fyo/core/permissionManager.ts) is the central engine that evaluates all permission checks in NkapBooks. It is accessed through fyo.perm and provides both simple boolean checks and detailed permission results.

Permission Check Flow

Every permission check follows this decision tree:

StepCheckResult
1Permission checking disabled?→ Allow
2Setup not complete?→ Allow (for setup phase)
3User is Administrator?→ Allow (bypasses everything)
4Doctype is bypass-exempt?→ Allow (core system doctypes)
5Check role-based permissions→ Allow if any role grants it
6Check ifOwner permissions→ Allow if user owns document
7Check document sharing→ Allow if document is shared
8None of the aboveDeny

Bypass Doctypes

The following core system doctypes always bypass permission checks — they are essential for the application to function:

CategoryDoctypes
CorePatchRun, SingleValue, NumberSeries, Misc
SetupSetupWizard, GetStarted
SettingsSystemSettings, Defaults, PrintSettings, AccountingSettings, InventorySettings, AuthSettings

Additionally, auth-related doctypes (User, Role, UserRole, RolePermission, Session, DocShare) bypass permission checks during initial setup before permissions are configured.

Permission Caching

The PermissionManager uses a two-level cache for performance:

CacheTTLDescription
Permission Cache5 minutesCaches the result of individual permission checks
Role Cache5 minutesCaches the role assignments for each user

The cache is automatically cleared when:

  • A User document is modified → clears that user's cached roles and permissions
  • A Role document is modified → clears the entire permission cache
  • clearCache() is called explicitly

Key API Methods

Simple Permission Checks

MethodReturnsDescription
hasPermission(docType, permType, options)booleanSimple yes/no permission check
canRead(docType, userId)booleanCan the user read this doctype?
canWrite(docType, userId)booleanCan the user write this doctype?
canCreate(docType, userId)booleanCan the user create this doctype?
canDelete(docType, userId)booleanCan the user delete this doctype?
canSubmit(docType, userId)booleanCan the user submit this doctype?
canCancel(docType, userId)booleanCan the user cancel this doctype?

Detailed Permission Checks

MethodReturnsDescription
hasPermissionDetailed(docType, permType, options)PermissionCheckResultDetailed result with granting roles and denial reason
getDocPermissions(docType, options)DocPermissionsAll 13 permission flags for a doctype

The PermissionCheckResult object contains:

FieldTypeDescription
allowedbooleanWhether the permission is granted
grantedByRolesstringWhich roles granted the permission (if allowed)
denialReasonstringHuman-readable reason for denial (if denied)
viaSharingbooleanWhether access was granted via document sharing
isOwnerBasedbooleanWhether the permission is owner-restricted

Document-Level Checks

MethodReturnsDescription
canReadDoc(docType, docName, owner)booleanCan read a specific document?
canWriteDoc(docType, docName, owner)booleanCan write a specific document?
canDeleteDoc(docType, docName, owner)booleanCan delete a specific document?
canSubmitDoc(docType, docName, owner)booleanCan submit a specific document?
canCancelDoc(docType, docName, owner)booleanCan cancel a specific document?

Discovery Methods

MethodReturnsDescription
getReadableDoctypes(userId)string[]All doctypes the user can read
getCreatableDoctypes(userId)string[]All doctypes the user can create
getAccessibleDocuments(docType, userId){ hasFullAccess, accessibleNames }Documents accessible to a user for a doctype

Validation Methods

MethodBehavior
validatePermission(docType, permType, options)Throws ForbiddenError if permission is denied
validateDocPermission(docType, permType, docName, owner)Throws ForbiddenError for specific document

Vue Composables

NkapBooks provides Vue composables for permission-aware UI development:

useAuth()

Returns reactive references for the current authentication state:

PropertyTypeDescription
isAuthenticatedRef<boolean>Whether the user is logged in
userRef<string>Current user email
isLoadingRef<boolean>Whether an auth operation is in progress
errorRef<string>Last auth error message
isAdministratorComputedRef<boolean>Whether current user is Administrator
isSystemManagerComputedRef<boolean>Whether current user is System Manager
rolesRef<string[]>Current user's role names
hasRole(role)FunctionCheck if user has a specific role
hasAnyRole(roles)FunctionCheck if user has any of the specified roles
hasAllRoles(roles)FunctionCheck if user has all of the specified roles

usePermissions()

Returns permission-checking helpers:

PropertyTypeDescription
isAdminRef<boolean>Whether user is Administrator
isSystemManagerRef<boolean>Whether user is System Manager

useRolePermissions()

Returns comprehensive role permission utilities for UI components.

Route-Level Protection

NkapBooks uses Vue Router meta fields to enforce permissions at the route level:

Meta FieldTypeDescription
requiresAuthbooleanRoute requires authentication
bypassPermissionCheckbooleanSkip permission check for this route
requiredPermission{ docType, permissionType }Specific permission required to access

Example route definitions:

RouteAuth RequiredPermission
/usersUser.read
/rolesRole.read
/doc-sharesDocShare.read
/sessionsSession.read
/user-settingsBypass (own settings)
/permission-deniedNone (error page)
Tip: When a user navigates to a route they don't have permission for, they are redirected to the /permission-denied page with a clear explanation of what permission is required.

11.8 Best Practices

Role Design

RecommendationDescription
Start with built-in rolesUse Administrator, Accounts Manager, Sales User, etc. as a starting point
Create task-specific rolesE.g., "Cashier" with only POS and payment permissions
Use ifOwner judiciouslyGreat for allowing users to manage their own documents without seeing others
Avoid excessive roles per userPermissions are additive — too many roles can be hard to audit
Test permissionsUse the hasPermissionDetailed() function to debug permission issues

Security Configuration

RecommendationDescription
Enable authenticationSet requireAuth: true in production environments
Set strong password policiesMinimum 8 characters, require uppercase and numbers
Configure session timeouts60 minutes session, 30 minutes idle timeout for office environments
Enable 2FA for sensitive rolesRequire two-factor authentication for Administrator and Accounts Manager roles
Limit concurrent sessionsSet simultaneousSessions to 3 or fewer per user
Review active sessionsPeriodically check Setup → Sessions for unexpected activity

Document Sharing

RecommendationDescription
Prefer role-based accessUse document sharing for exceptions, not as the primary access model
Audit shares regularlyReview Setup → Document Shares for stale or unnecessary shares
Use "everyone" sparinglyOnly for documents that genuinely need universal access
Require share permissionEnsure only authorized users have sharePerm on sensitive doctypes