{"id":31886838,"url":"https://github.com/onurlulardan/nextjstemplate","last_synced_at":"2025-10-13T05:50:41.466Z","repository":{"id":278582460,"uuid":"936102886","full_name":"Onurlulardan/nextjstemplate","owner":"Onurlulardan","description":"demo login info: Mail: superadmin@superadmin.com Password: 0ZzfqAxK!","archived":false,"fork":false,"pushed_at":"2025-05-29T10:20:05.000Z","size":1915,"stargazers_count":12,"open_issues_count":2,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-05-29T11:57:15.933Z","etag":null,"topics":["crm","erp","nextjs","permission-manager","permissions","react","role-based-access-control","role-based-authorization","role-based-permissions","saas","starter-kit","starter-project","starter-template","user-based-aut"],"latest_commit_sha":null,"homepage":"https://nextjstarter.altuntasonur.com","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/Onurlulardan.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2025-02-20T14:33:39.000Z","updated_at":"2025-05-29T10:20:08.000Z","dependencies_parsed_at":"2025-05-29T12:06:14.878Z","dependency_job_id":null,"html_url":"https://github.com/Onurlulardan/nextjstemplate","commit_stats":null,"previous_names":["onurlulardan/nextjstemplate"],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/Onurlulardan/nextjstemplate","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Onurlulardan%2Fnextjstemplate","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Onurlulardan%2Fnextjstemplate/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Onurlulardan%2Fnextjstemplate/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Onurlulardan%2Fnextjstemplate/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/Onurlulardan","download_url":"https://codeload.github.com/Onurlulardan/nextjstemplate/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Onurlulardan%2Fnextjstemplate/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":279013711,"owners_count":26085394,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","status":"online","status_checked_at":"2025-10-13T02:00:06.723Z","response_time":61,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["crm","erp","nextjs","permission-manager","permissions","react","role-based-access-control","role-based-authorization","role-based-permissions","saas","starter-kit","starter-project","starter-template","user-based-aut"],"created_at":"2025-10-13T05:50:35.731Z","updated_at":"2025-10-13T05:50:41.461Z","avatar_url":"https://github.com/Onurlulardan.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# NextJS Starter\n\n![NextJS Starter Template](/public/readme-img/2.png)\n\n[All Images](#all-images)\n\nA modern and scalable system. Developed with Next.js 15, TypeScript, Knex.js, and Ant Design.\n\n## Features\n\n- Modern and responsive user interface (Ant Design v5)\n- Advanced authentication and authorization system\n- Multi-organization support\n- Detailed permission and role management\n- Dark/Light theme support\n- Real-time data synchronization\n- Mobile-responsive design\n\n### Security Logs\n\nThe system keeps track of all authentication attempts, including:\n\n- Login attempts (successful/failed)\n- IP addresses\n- Browser information\n- Login timestamps\n\n## Technology Stack\n\n- **Framework**: [Next.js 15](https://nextjs.org/) (App Router)\n- **Language**: [TypeScript](https://www.typescriptlang.org/)\n- **Database**: [PostgreSQL](https://www.postgresql.org/)\n- **Query Builder**: [Knex.js](https://knexjs.org/)\n- **UI**: [Ant Design](https://ant.design/)\n- **Authentication**: [NextAuth.js](https://next-auth.js.org/)\n\n## Project Structure\n\n```\nnextstarter/\n├── app/                         # Next.js App Router structure\n│   ├── (protected)/             # Protected routes\n│   │   ├── dashboard/           # Dashboard and statistics\n│   │   │   ├── page.tsx         # Main dashboard page\n│   │   │   └── components/      # Dashboard components\n│   │   └── administrations/     # Administration panel\n│   │       ├── users/           # User management\n│   │       │   ├── page.tsx     # User list\n│   │       │   └── profile/     # Profile management\n│   │       ├── organizations/   # Organization management\n│   │       ├── roles/           # Role management\n│   │       └── permissions/     # Permission management\n│   ├── api/                     # API endpoints\n│   │   ├── auth/                # Authentication APIs\n│   │   ├── dashboard/           # Dashboard APIs\n│   │   │   ├── stats/           # Statistics APIs\n│   │   │   └── activity/        # Activity APIs\n│   │   └── administrations/     # Administration APIs\n│   │       ├── users/           # User APIs\n│   │       ├── organizations/   # Organization APIs\n│   │       ├── roles/           # Role APIs\n│   │       ├── permissions/     # Permission APIs\n│   │       ├── resources/       # Resource APIs\n│   │       └── actions/         # Action APIs\n│   └── auth/                    # Authentication pages\n├── contexts/                    # React Contexts\n│   └── NotificationContext.tsx  # Notification management\n├── lib/                         # Helper functions and services\n│   ├── apiClient/               # API client\n│   │   └── index.ts             # Central API operations\n│   ├── auth/                    # Authentication and authorization\n│   │   ├── auth-options.ts      # NextAuth configuration\n│   │   ├── permissions.ts       # Permission control hooks\n│   │   └── session.ts           # Session management\n│   └── utils/                   # Utility functions\n├── hooks/                       # Custom React hooks\n│   └── useNotificationSetup.ts  # Notification hook\n└── knex/                        # Database configuration\n    ├── knexfile.ts              # Knex configuration\n    ├── index.ts                 # Knex database client\n    ├── setdb.ts                 # Database schema creation\n    ├── seed.ts                  # Database seeding\n    ├── adapters/                # Database adapters\n    │   └── nextauth-knex-adapter.ts  # NextAuth Knex adapter\n    ├── types/                   # TypeScript type definitions\n    │   ├── user.ts              # User types\n    │   ├── organization.ts      # Organization types\n    │   ├── role.ts              # Role types\n    │   └── permission.ts        # Permission types\n    └── migrations/              # Database migrations\n```\n\n## Detailed Permission System Explanation\n\n### 1. Basic Concepts\n\n#### Resource\n\nRepresents protected entities in the system.\n\n```typescript\n// Example resource definitions\nconst resources = [\n  { name: 'Product', slug: 'product' },\n  { name: 'Customer', slug: 'customer' },\n  { name: 'Order', slug: 'order' },\n];\n```\n\n#### Action\n\nDefines operations that can be performed on resources.\n\n```typescript\n// Example action definitions\nconst actions = [\n  { name: 'View', slug: 'view' },\n  { name: 'Create', slug: 'create' },\n  { name: 'Edit', slug: 'edit' },\n  { name: 'Delete', slug: 'delete' },\n];\n```\n\n### 2. Permission Management Examples\n\n#### a) User-Based Permission\n\nAssigning permission directly to a user:\n\n```typescript\n// Example: Give John permission to view and edit products\nconst permission = {\n  target: 'USER',\n  userId: 'john_123',\n  resourceId: 'product',\n  actions: ['view', 'edit'],\n};\n```\n\n#### b) Role-Based Permission\n\nAssigning permission to a role:\n\n```typescript\n// Example: Give Sales Manager role customer and order management permissions\nconst permission = {\n  target: 'ROLE',\n  roleId: 'sales_manager',\n  resourceId: 'customer',\n  actions: ['view', 'create', 'edit', 'delete'],\n};\n```\n\n#### c) Organization-Based Permission\n\nAssigning permission to an entire organization:\n\n```typescript\n// Example: Give Branch X permission to view orders\nconst permission = {\n  target: 'ORGANIZATION',\n  organizationId: 'branch_x',\n  resourceId: 'order',\n  actions: ['view'],\n};\n```\n\n### 3. Permission Check Examples\n\n#### Permission Check in Frontend\n\n```typescript\n// Permission check within component\nconst CanEditProduct = () =\u003e {\n  const hasPermission = usePermission(\"product\", \"edit\");\n\n  if (!hasPermission) {\n    return \u003cdiv\u003eYou don't have permission for this operation\u003c/div\u003e;\n  }\n\n  return \u003cEditProductForm /\u003e;\n};\n```\n\n#### Permission Check in Backend\n\n```typescript\n// Permission check in API route\nexport async function PUT(request: NextRequest) {\n  try {\n    await requirePermission('product', 'edit');\n    // Continue if permission exists\n  } catch (error) {\n    return new NextResponse('Unauthorized', { status: 401 });\n  }\n}\n```\n\n### 4. API Endpoints\n\n#### Permission Management\n\n- `GET /api/administrations/permissions`: List all permissions\n- `POST /api/administrations/permissions`: Create new permission\n- `PUT /api/administrations/permissions/[id]`: Update permission\n- `DELETE /api/administrations/permissions/[id]`: Delete permission\n\n#### Resource Management\n\n- `GET /api/administrations/resources`: List all resources\n- `POST /api/administrations/resources`: Create new resource\n- `PUT /api/administrations/resources/[id]`: Update resource\n- `DELETE /api/administrations/resources/[id]`: Delete resource\n\n#### Action Management\n\n- `GET /api/administrations/actions`: List all actions\n- `POST /api/administrations/actions`: Create new action\n- `PUT /api/administrations/actions/[id]`: Update action\n- `DELETE /api/administrations/actions/[id]`: Delete action\n\n### 5. Example Usage Scenarios\n\n#### Scenario 1: Sales Team Permissions\n\n```typescript\n// 1. Create Sales Role\nconst salesRole = await knex('roles')\n  .insert({\n    name: 'Sales Team',\n    description: 'Sales team members',\n  })\n  .returning('*')\n  .first();\n\n// 2. Assign Permissions to Sales Role\nconst permissions = [\n  {\n    target: 'ROLE',\n    roleId: salesRole.id,\n    resourceId: 'customer',\n    actions: ['view', 'create', 'edit'],\n  },\n  {\n    target: 'ROLE',\n    roleId: salesRole.id,\n    resourceId: 'order',\n    actions: ['view', 'create'],\n  },\n];\n\n// 3. Apply Permissions\nawait Promise.all(permissions.map((perm) =\u003e knex('permissions').insert(perm)));\n```\n\n#### Scenario 2: Regional Manager Permissions\n\n```typescript\n// 1. Create Regional Manager Role\nconst managerRole = await knex('roles')\n  .insert({\n    name: 'Regional Manager',\n    description: 'Regional management team',\n  })\n  .returning('*')\n  .first();\n\n// 2. Create Region Organization\nconst regionOrg = await knex('organizations')\n  .insert({\n    name: 'East Region',\n    code: 'EAST_001',\n  })\n  .returning('*')\n  .first();\n\n// 3. Assign Organization-wide Permissions\nconst permissions = [\n  {\n    target: 'ORGANIZATION',\n    organizationId: regionOrg.id,\n    resourceId: 'sales_report',\n    actions: ['view'],\n  },\n  {\n    target: 'ORGANIZATION',\n    organizationId: regionOrg.id,\n    resourceId: 'performance_metrics',\n    actions: ['view', 'edit'],\n  },\n];\n\nawait Promise.all(permissions.map((perm) =\u003e knex('permissions').insert(perm)));\n```\n\n## Notification System\n\nThe notification system uses Ant Design's notification component with a custom context setup:\n\n```typescript\n// types.ts\nexport type NotificationType = 'success' | 'error' | 'info' | 'warning';\n\nexport interface ShowNotificationFunction {\n  (type: NotificationType, message: string, description?: string): void;\n}\n\n// NotificationContext.tsx\nconst NotificationContext = createContext\u003cNotificationContextType | null\u003e(null);\n\nexport const NotificationProvider = ({ children }: { children: React.ReactNode }) =\u003e {\n  const [notificationApi, contextHolder] = notification.useNotification();\n\n  const showNotification: ShowNotificationFunction = (type, message, description) =\u003e {\n    notificationApi[type]({\n      message,\n      description,\n      placement: 'topRight'\n    });\n  };\n\n  return (\n    \u003cNotificationContext.Provider value={{ showNotification, notificationApi }}\u003e\n      {contextHolder}\n      {children}\n    \u003c/NotificationContext.Provider\u003e\n  );\n};\n\nexport const useNotification = () =\u003e {\n  const context = useContext(NotificationContext);\n  if (!context) {\n    throw new Error('useNotification must be used within a NotificationProvider');\n  }\n  return context;\n};\n```\n\nUsage in API Client:\n\n```typescript\n// Success case (POST/PUT/DELETE)\nif (['POST', 'PUT', 'DELETE'].includes(response.config.method?.toUpperCase() || '')) {\n  const message =\n    response.config.method?.toUpperCase() === 'DELETE'\n      ? 'Deletion successful!'\n      : 'Process completed successfully';\n\n  const showNotification = window.__showNotification as ShowNotificationFunction;\n  showNotification?.('success', message);\n}\n\n// Error case\nconst errorMessage = (error.response?.data as string) || error.message;\nconst showNotification = window.__showNotification as ShowNotificationFunction;\nconst truncatedMessage =\n  errorMessage.length \u003e 500 ? errorMessage.slice(0, 497) + '...' : errorMessage;\nshowNotification?.('error', 'Hata', truncatedMessage);\n```\n\n### Best Practices\n\n1. **Consistent Usage**\n\n   - Use the same notification system across the entire application\n   - Maintain consistent message formats and durations\n\n2. **Error Handling**\n\n   - Always provide clear error messages\n   - Include relevant error details in the description\n   - Add action buttons for error recovery when applicable\n\n3. **User Experience**\n\n   - Keep notifications concise and informative\n   - Use appropriate notification types\n   - Don't overwhelm users with too many notifications\n   - Consider notification stacking and positioning\n\n4. **Integration with API Calls**\n\n```typescript\nconst apiCall = async () =\u003e {\n  try {\n    const response = await fetch('/api/data');\n    const data = await response.json();\n\n    showNotification({\n      type: 'success',\n      message: 'Data Retrieved',\n      description: 'Successfully fetched the requested data.',\n    });\n\n    return data;\n  } catch (error) {\n    showNotification({\n      type: 'error',\n      message: 'API Error',\n      description: error.message,\n    });\n\n    throw error;\n  }\n};\n```\n\n### Notification Types\n\n1. **Success Notifications**\n\n```typescript\nshowNotification('success', 'Order Created', 'Order #12345 has been successfully created');\n```\n\n2. **Error Notifications**\n\n```typescript\nshowNotification('error', 'API Error', 'Failed to process your request');\n```\n\n3. **Warning Notifications**\n\n```typescript\nshowNotification('warning', 'Low Stock Alert', 'Product stock is below the minimum threshold');\n```\n\n4. **Info Notifications**\n\n```typescript\nshowNotification('info', 'System Update', 'A system update is scheduled for tonight at 00:00');\n```\n\n### API Error Handling\n\n```typescript\n// API error interceptor\naxiosInstance.interceptors.response.use(\n  (response: AxiosResponse) =\u003e {\n    // Success notification for POST, PUT, DELETE requests\n    if (\n      typeof window !== 'undefined' \u0026\u0026\n      ['POST', 'PUT', 'DELETE'].includes(response.config.method?.toUpperCase() || '')\n    ) {\n      const message =\n        response.config.method?.toUpperCase() === 'DELETE'\n          ? 'Deletion successful!'\n          : 'Process completed successfully';\n\n      const showNotification = window.__showNotification as ShowNotificationFunction;\n      showNotification?.('success', message);\n    }\n    return response.data;\n  },\n  async (error: AxiosError) =\u003e {\n    if (error.response?.status === 401) {\n      if (typeof window !== 'undefined') {\n        await signOut({ callbackUrl: '/auth/login' });\n      }\n    }\n\n    const errorMessage = (error.response?.data as string) || error.message;\n\n    if (typeof window !== 'undefined') {\n      const showNotification = window.__showNotification as ShowNotificationFunction;\n      const truncatedMessage =\n        errorMessage.length \u003e 500 ? errorMessage.slice(0, 497) + '...' : errorMessage;\n      showNotification?.('error', 'Hata', truncatedMessage);\n    }\n\n    throw new Error(errorMessage);\n  }\n);\n```\n\n### Form Validation Notifications\n\n```typescript\nconst handleFormSubmit = async (values: FormValues) =\u003e {\n  try {\n    await validateForm(values);\n    await submitForm(values);\n\n    showNotification('success', 'Form Submitted', 'Your form has been successfully submitted');\n  } catch (error) {\n    if (error instanceof ValidationError) {\n      showNotification('warning', 'Validation Error', error.message);\n    } else {\n      showNotification('error', 'Submission Error', 'Failed to submit form. Please try again');\n    }\n  }\n};\n```\n\n### 3. Permission System Working Logic\n\nThe `lib/auth/permissions.ts` file forms the core of the permission system:\n\n#### a) Permission Check Functions\n\n```typescript\n// 1. Basic permission check\nasync function checkPermission(\n  resourceSlug: string,\n  actionSlug: string,\n  organizationId?: string\n): Promise\u003cboolean\u003e;\n\n// 2. Permission requirement\nasync function requirePermission(\n  resourceSlug: string,\n  actionSlug: string,\n  organizationId?: string\n): Promise\u003cvoid\u003e;\n\n// 3. React hook\nfunction usePermission(resourceSlug: string, actionSlug: string, organizationId?: string): boolean;\n\n// 4. Higher-order component\nfunction withPermission(\n  Component: React.ComponentType\u003cP\u003e,\n  resourceSlug: string,\n  actionSlug: string\n): React.FC\u003cP\u003e;\n```\n\n#### b) Permission Check Hierarchy\n\n1. **System Admin Check**\n\n   ```typescript\n   if (session.user.role === 'ADMIN') return true;\n   ```\n\n2. **Direct Permission Check**\n\n   ```typescript\n   const hasDirectPermission = checkResourcePermission(\n     session.user.permissions,\n     resourceSlug,\n     actionSlug\n   );\n   ```\n\n3. **Role-Based Permission Check**\n\n   ```typescript\n   const rolePermissions = membership.role?.permissions || [];\n   const hasRolePermission = checkResourcePermission(rolePermissions, resourceSlug, actionSlug);\n   ```\n\n4. **Organization Permission Check**\n   ```typescript\n   const organizationPermissions = membership.organization.permissions;\n   return checkResourcePermission(organizationPermissions, resourceSlug, actionSlug);\n   ```\n\n### 4. Next.js 15 Route Handler Rules\n\n#### a) Params Promise Structure\n\n```typescript\n// ✅ CORRECT USAGE\nexport async function GET(request: NextRequest, { params }: { params: Promise\u003c{ id: string }\u003e }) {\n  const { id } = await params;\n  // ... operations\n}\n\n// ❌ INCORRECT USAGE\nexport async function GET(request: NextRequest, { params }: { params: { id: string } }) {\n  const { id } = params; // missing await!\n  // ... operations\n}\n```\n\n#### b) Route Handler Examples\n\n```typescript\n// 1. Single parameter\nexport async function GET(request: NextRequest, { params }: { params: Promise\u003c{ id: string }\u003e }) {\n  const { id } = await params;\n  // ... operations\n}\n\n// 2. Multiple parameters\nexport async function GET(\n  request: NextRequest,\n  {\n    params,\n  }: {\n    params: Promise\u003c{\n      organizationId: string;\n      userId: string;\n    }\u003e;\n  }\n) {\n  const { organizationId, userId } = await params;\n  // ... operations\n}\n\n// 3. Query parameters\nexport async function GET(request: NextRequest) {\n  const searchParams = request.nextUrl.searchParams;\n  const query = searchParams.get('q');\n  // ... operations\n}\n```\n\n#### c) Important Notes\n\n- `params` in route handlers is a Promise\n- Use `Promise\u003c{ id: string }\u003e` in TypeScript definition\n- Always resolve `params` with `await`\n- This rule applies to all dynamic routes\n- Pay attention to this rule to prevent build errors\n\n## API Client Usage\n\nThe API client provides a type-safe way to make HTTP requests with built-in error handling and automatic notifications.\n\n#### Basic Usage\n\n```typescript\nimport { getRequest, postRequest, putRequest, deleteRequest } from '@/lib/apiClient';\n\n// GET request\nconst users = await getRequest\u003cUser[]\u003e('/users');\n\n// POST request\nconst newUser = await postRequest\u003cUser\u003e('/users', {\n  name: 'John',\n  email: 'john@example.com',\n});\n\n// PUT request\nconst updated = await putRequest\u003cUser\u003e(`/users/${id}`, {\n  name: 'Updated Name',\n});\n\n// DELETE request\nconst deleted = await deleteRequest\u003cboolean\u003e(`/users/${id}`);\n```\n\n#### Features\n\n1. **Automatic API Prefix**\n\n   - All requests are automatically prefixed with `/api`\n   - Example: `/users` becomes `/api/users`\n\n2. **Automatic Notifications**\n\n   ```typescript\n   // Success notifications (for POST, PUT, DELETE)\n   if (['POST', 'PUT', 'DELETE'].includes(response.config.method?.toUpperCase() || '')) {\n     const message =\n       response.config.method?.toUpperCase() === 'DELETE'\n         ? 'Deletion successful!'\n         : 'Process completed successfully';\n     showNotification?.('success', message);\n   }\n\n   // Error notifications\n   showNotification({\n     type: 'error',\n     message: 'API Error',\n     description: errorMessage,\n   });\n   ```\n\n   - Success cases:\n     - Shows for POST/PUT/DELETE operations\n     - DELETE: \"Deletion successful!\"\n     - POST/PUT: \"Process completed successfully\"\n   - Error cases:\n     - Shows \"API Error\" as title\n     - Shows error message in description\n\n3. **Retry Configuration**\n\n   - 3 retry attempts for failed requests\n   - Uses exponential backoff\n   - Only retries on:\n     - Network errors\n     - 500+ server errors\n   - Does not retry if response contains error data\n\n4. **Type Safety**\n\n   ```typescript\n   interface User {\n     id: number;\n     name: string;\n     email: string;\n   }\n\n   // TypeScript will ensure type safety\n   const user = await getRequest\u003cUser\u003e('/users/1');\n   console.log(user.name); // TypeScript knows this exists\n   ```\n\n#### Error Handling Example\n\n```typescript\ntry {\n  const users = await getRequest\u003cUser[]\u003e('/users');\n  // Success case - for POST/PUT/DELETE, automatically shows success notification\n} catch (error) {\n  // Error notification is automatically shown:\n  // - Shows \"Hata\" with truncated error message\n  // - For 401, redirects to login page\n  console.error('API Error:', error);\n}\n```\n\n#### Request Options\n\n```typescript\ninterface RequestOptions {\n  headers?: Record\u003cstring, string\u003e;\n  [key: string]: any; // Additional axios request config\n}\n\n// With custom headers\nconst response = await getRequest\u003cUser[]\u003e('/users', {\n  headers: {\n    Authorization: 'Bearer token',\n    'Custom-Header': 'value',\n  },\n});\n\n// With query parameters\nconst filtered = await getRequest\u003cUser[]\u003e('/users', {\n  role: 'admin',\n  active: true,\n});\n```\n\n## Installation and Development\n\n1. Clone the repository\n\n```bash\ngit clone https://github.com/yourusername/nextstarter.git\n```\n\n2. Install dependencies\n\n```bash\nnpm install\n```\n\n3. Prepare the database\n\n```bash\nnpm run reset-db    # Create database schema\nnpm run seed        # Load initial data\n```\n\n4. Start the development server\n\n```bash\nnpm run dev\n```\n\n## Contributing\n\n1. Fork the project\n2. Create a feature branch (`git checkout -b feature/amazing-feature`)\n3. Commit your changes (`git commit -m 'feat: add amazing feature'`)\n4. Push to the branch (`git push origin feature/amazing-feature`)\n5. Create a Pull Request\n\n## Environment Variables and Configuration\n\nCreate a `.env` file in the project root directory and define the following variables:\n\n```env\n# Database Connection\nDB_HOST=\"localhost\"\nDB_PORT=\"5432\"\nDB_USER=\"postgres\"\nDB_PASSWORD=\"password\"\nDB_NAME=\"nextstarter\"\n\n# NextAuth.js Configuration\nNEXTAUTH_SECRET=\"your-secret-key\"\nNEXTAUTH_URL=\"http://localhost:3000\"\nNEXTAUTH_SESSION_MAX_AGE=604800   # 7 days (7 * 24 * 60 * 60)\nNEXTAUTH_SESSION_UPDATE_AGE=3600  # 1 hour (60 * 60)\n\n# Super Admin Account Details\nSUPER_ADMIN_MAIL=\"superadmin@superadmin.com\"\nSUPER_ADMIN_FIRSTNAME=\"Super\"\nSUPER_ADMIN_LASTNAME=\"Admin\"\nSUPER_ADMIN_PASSWORD=\"your-secure-password\"\n```\n\n### Important Notes\n\n1. **Database Connection**: The database configuration uses separate environment variables for host, port, user, password, and database name for Knex.js connection.\n\n2. **NextAuth.js Configuration**:\n\n   - `NEXTAUTH_SECRET`: Secret key used for session security\n   - `NEXTAUTH_URL`: URL where the application runs (usually `http://localhost:3000` in development)\n   - `NEXTAUTH_SESSION_MAX_AGE`: Maximum session duration for session security (in seconds)\n   - `NEXTAUTH_SESSION_UPDATE_AGE`: Session update duration for session security (in seconds)\n\n3. **Super Admin Account**:\n   - System automatically creates a super admin account during initial setup\n   - Account details are taken from the `.env` file\n   - This account has all system permissions\n\n## Developer Guide\n\n### 1. Commands and Scripts\n\n```bash\n# Development\nnpm run dev         # Start development server\nnpm run build       # Build project for production\nnpm run start       # Start production server\n\n# Database\nnpm run migrate     # Create and apply Knex migration\nnpm run reset-db    # Reset database\nnpm run seed        # Load seed data\n\n# Code Quality\nnpm run lint        # Code check with ESLint\nnpm run format      # Format code with Prettier\n```\n\n### 2. Database Seed Process\n\nThe `knex/seed.ts` file creates initial data:\n\n1. **Default Resources**\n\n   ```typescript\n   // Example resources\n   const defaultResources = [\n     { name: 'ALL', slug: '*' },\n     { name: 'ORGANIZATION', slug: 'organization' },\n     { name: 'USER', slug: 'user' },\n     // ...\n   ];\n   ```\n\n2. **Default Actions**\n\n   ```typescript\n   const defaultActions = [\n     { name: 'VIEW', slug: 'view' },\n     { name: 'CREATE', slug: 'create' },\n     { name: 'EDIT', slug: 'edit' },\n     { name: 'DELETE', slug: 'delete' },\n     { name: 'MANAGE', slug: 'manage' },\n   ];\n   ```\n\n3. **Super Admin and Roles**\n   - Creates super admin user\n   - Defines default roles\n   - Assigns basic permissions\n\n## All Images\n\n![Image 1](/public/readme-img/1.png)\n\n![Image 2](/public/readme-img/2.png)\n\n![Image 3](/public/readme-img/3.png)\n\n![Image 4](/public/readme-img/4.png)\n\n![Image 5](/public/readme-img/5.png)\n\n![Image 6](/public/readme-img/6.png)\n\n![Image 7](/public/readme-img/7.png)\n\n![Image 8](/public/readme-img/8.png)\n\n![Image 9](/public/readme-img/9.png)\n\n![Image 10](/public/readme-img/10.png)\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fonurlulardan%2Fnextjstemplate","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fonurlulardan%2Fnextjstemplate","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fonurlulardan%2Fnextjstemplate/lists"}