Authentication System Setup Guide
This guide provides comprehensive instructions for setting up and managing the University Inventory Management System’s authentication system, including creating the first admin account and managing user roles.
Authentication Overview
The system supports two authentication methods:
- University Single Sign-On (SSO)
SAML 2.0 integration with university identity providers
Automatic role assignment based on university affiliations
Seamless integration with existing university accounts
- Local Email/Password Accounts
Secure bcrypt password hashing
Strong password requirements
Perfect for external users or when SSO isn’t available
- Development Admin Override
Bypass authentication for development and testing
Automatic admin access without login requirements
Only available in development environment
Code Architecture
Authentication System Structure
The authentication system is built with a modular architecture:
Authentication Layer
├── server/localAuth.ts # Local email/password authentication
├── server/universitySso.ts # SAML SSO integration
├── server/storage.ts # User data management
└── shared/schema.ts # User database schema
Key Components:
- Local Authentication (server/localAuth.ts)
Password validation and hashing
User account creation and management
Session management with PostgreSQL
Role-based access control middleware
- SSO Integration (server/universitySso.ts)
SAML 2.0 strategy implementation
Attribute mapping from university directories
Automatic role assignment based on affiliations
- Database Schema (shared/schema.ts)
User table with both local and SSO support
Role-based permission system
Session storage for secure authentication
User Database Schema
The users table supports both authentication methods:
export const users = pgTable("users", {
id: varchar("id").primaryKey().notNull(),
email: varchar("email").unique().notNull(),
passwordHash: varchar("password_hash"), // null for SSO users
firstName: varchar("first_name"),
lastName: varchar("last_name"),
role: varchar("role").notNull().default("user"), // user, superuser, admin
isActive: boolean("is_active").notNull().default(true),
mustChangePassword: boolean("must_change_password").notNull().default(false),
lastLogin: timestamp("last_login"),
profileImageUrl: varchar("profile_image_url"),
createdAt: timestamp("created_at").defaultNow(),
updatedAt: timestamp("updated_at").defaultNow(),
});
Role System
Three-Tier Permission Model
- User Role (Basic Access)
View inventory items and stock levels
Search and filter inventory data
Generate basic reports
Submit requisition requests
- Superuser Role (Operational Management)
All User permissions, plus:
Add, edit, and manage inventory items
Update stock levels and track movements
Create and modify categories
Generate detailed operational reports
Approve requisitions
- Admin Role (System Administration)
All Superuser permissions, plus:
Manage user accounts and roles
Create new user accounts
Reset user passwords
Access backup and system functions
View audit logs and security features
Configure system-wide settings
Initial Setup: Creating Your First Admin Account
Method 1: Database Direct Setup (Recommended)
Since you need an admin account to create other accounts, the first admin must be created directly in the database:
Step 1: Access Your Database
# Using psql
psql $DATABASE_URL
# Or using Docker
docker exec -it inventory-db psql -U postgres -d university_inventory
Step 2: Create the First Admin Account
-- Insert the first admin user
INSERT INTO users (
id,
email,
password_hash,
first_name,
last_name,
role,
is_active,
must_change_password
) VALUES (
'admin_' || extract(epoch from now())::text,
'admin@your-university.edu',
'$2b$12$LQv3c1yqBwEHxv5hSyHKdOCOFUTp9.7bAD0EzHkzUl9r7XZ8Kcqoe', -- password: AdminPass123!
'System',
'Administrator',
'admin',
true,
true -- User must change password on first login
);
Step 3: Verify the Account
SELECT id, email, role, is_active FROM users WHERE role = 'admin';
Step 4: First Login
Navigate to your application URL
Click “Sign in with email”
Use credentials: - Email:
admin@your-university.edu- Password:AdminPass123!You’ll be prompted to change the password immediately
Method 2: Environment Variable Setup
For automated deployments, you can set up the admin account via environment variables:
# Add to your .env file or environment
INITIAL_ADMIN_EMAIL=admin@your-university.edu
INITIAL_ADMIN_PASSWORD=SecureAdminPassword123!
INITIAL_ADMIN_FIRST_NAME=System
INITIAL_ADMIN_LAST_NAME=Administrator
The system will automatically create this admin account on first startup if no admin users exist.
Password Security Requirements
Strong Password Policy
All passwords must meet these requirements:
Minimum 8 characters long
At least one uppercase letter (A-Z)
At least one lowercase letter (a-z)
At least one number (0-9)
At least one special character (!@#$%^&*()_+-=[]{}|;:,.<>?)
Password Hashing: - Uses bcrypt with 12 salt rounds - Automatically handles salt generation - Resistant to rainbow table attacks
Password Management: - Admins can reset user passwords to temporary passwords - Users must change temporary passwords on next login - Last login tracking for security monitoring
Managing User Accounts
Creating New Users (Admin Only)
Via API (for integrations):
// POST /api/users
{
"email": "john.doe@university.edu",
"password": "SecurePassword123!",
"firstName": "John",
"lastName": "Doe",
"role": "user" // user, superuser, or admin
}
Via Admin Interface:
Log in as an admin user
Navigate to “Users” in the admin menu
Click “Add User” button
Fill in user details: - Email address (must be unique) - Strong password - First and last name - Initial role assignment
Click “Create User”
The new user will receive their credentials and can log in immediately.
Changing User Roles
Role Change Process:
Navigate to Users management page
Find the target user in the list
Click “Edit” or the role dropdown
Select new role: - user → superuser (promote to manager) - superuser → admin (promote to admin) - admin → superuser (demote from admin)
Confirm the role change
User’s permissions update immediately
Role Change API:
// PUT /api/users/:id/role
{
"role": "superuser"
}
Important Security Notes: - Only admins can change user roles - Role changes are logged for audit purposes - Users are notified of role changes via email (if configured) - At least one admin account must remain active
Password Reset and Management
Admin Password Reset
For Other Users:
Go to Users management page
Find the user who needs a password reset
Click “Reset Password” button
System generates a secure temporary password
Share the temporary password with the user securely
User must change password on next login
Reset Password API:
// POST /api/users/:id/reset-password
// Returns: { "temporaryPassword": "TempPass123!" }
User Self-Service Password Change
Users can change their own passwords:
Click profile menu in top-right corner
Select “Change Password”
Enter current password
Enter new password (must meet requirements)
Confirm new password
Click “Update Password”
Password Change API:
// POST /api/auth/change-password
{
"currentPassword": "OldPassword123!",
"newPassword": "NewSecurePassword456!"
}
Security Configuration
Session Management
# Session configuration
SESSION_SECRET=your-super-secure-session-secret-here
# Session duration (default: 1 week)
SESSION_TTL=604800000
Session Security Features: - HTTP-only cookies (prevent XSS) - Secure flag for HTTPS - SameSite protection against CSRF - Automatic session cleanup - PostgreSQL session storage for scalability
Account Security
# Password security
MIN_PASSWORD_LENGTH=8
SALT_ROUNDS=12
# Account lockout (optional)
MAX_LOGIN_ATTEMPTS=5
LOCKOUT_DURATION=900000 # 15 minutes
Authentication Flow
Login Process
Local Authentication Flow:
User submits email and password
System looks up user by email
Validates password against stored hash
Checks account status (active, not locked)
Creates secure session
Updates last login timestamp
Redirects to intended destination
SSO Authentication Flow:
User clicks “Sign in with University Account”
Redirects to university SSO provider
User authenticates with university credentials
SSO provider returns SAML assertion
System validates assertion and extracts attributes
Creates or updates user account
Assigns role based on university affiliation
Creates secure session
Code Examples
Custom Authentication Middleware
// Require authentication for routes
app.get('/api/protected', requireAuth, (req, res) => {
const user = req.user;
res.json({ message: `Hello ${user.firstName}!` });
});
// Require specific roles
app.post('/api/admin-only', requireRole(['admin']), (req, res) => {
// Only admins can access this endpoint
});
// Multiple role access
app.get('/api/managers', requireRole(['admin', 'superuser']), (req, res) => {
// Admins and superusers can access
});
Creating Users Programmatically
import { createUser } from './server/localAuth';
// Create a new user account
const newUser = await createUser({
email: 'jane.smith@university.edu',
password: 'SecurePassword123!',
firstName: 'Jane',
lastName: 'Smith',
role: 'superuser'
});
Troubleshooting Authentication Issues
Common Problems and Solutions
Login Fails with “Invalid Credentials”
Verify email address is correct
Check if account exists:
SELECT * FROM users WHERE email = 'user@email.com'Verify account is active:
is_active = trueFor SSO users, ensure they use SSO login (no local password)
“Account is Disabled” Error
-- Reactivate user account
UPDATE users SET is_active = true WHERE email = 'user@email.com';
Password Reset Issues
Verify admin has reset permissions
Check if temporary password was generated correctly
Ensure user tries to log in (not password change)
Check
must_change_passwordflag is set
SSO Integration Problems
Verify SAML configuration environment variables
Check university SSO metadata is accessible
Validate callback URLs are registered with university
Review SAML assertion attributes in logs
Session/Cookie Issues
Check
SESSION_SECRETis setVerify database connectivity for session storage
Clear browser cookies and try again
Check HTTPS configuration for secure cookies
Database Maintenance
Regular User Cleanup:
-- Find inactive users (no login in 90 days)
SELECT id, email, last_login
FROM users
WHERE last_login < NOW() - INTERVAL '90 days'
OR last_login IS NULL;
-- Cleanup old sessions (done automatically)
DELETE FROM sessions WHERE expire < NOW();
User Audit Queries:
-- Count users by role
SELECT role, COUNT(*) FROM users GROUP BY role;
-- Recent login activity
SELECT email, last_login, role
FROM users
WHERE last_login > NOW() - INTERVAL '7 days'
ORDER BY last_login DESC;
Best Practices
Security Recommendations
Regular Password Updates: Encourage users to change passwords every 90 days
Role Reviews: Audit user roles quarterly
Session Monitoring: Monitor unusual login patterns
Backup Admin: Always maintain at least 2 admin accounts
Secure Communications: Use encrypted channels for sharing temporary passwords
Operational Guidelines
User Onboarding: Create accounts with temporary passwords
Role Assignment: Start with minimal permissions, escalate as needed
Account Deactivation: Disable rather than delete departed users
Documentation: Keep records of role changes and reasons
Training: Ensure admins understand the permission model
This authentication system provides enterprise-grade security suitable for university environments while maintaining ease of use and administrative control.