隨著現代聊天應用程式的發展,即時通訊需要越來越精細的存取控制。即時管理各種聊天室和參與者的動態權限,尤其是在複雜或多用戶環境中,很快就會變得具有挑戰性。如果您可以輕鬆地為您的聊天應用程式實現細粒度授權而不影響效能,結果會如何?
Permit.io 讓將強大的即時存取控制整合到您的聊天應用程式中變得簡單。透過將 Permit.io 的高級授權模型與 WebSocket 配對,您可以確保正確的使用者在正確的時間進行訪問,同時保持聊天應用程式所需的回應能力。
在本教程中,您將學習如何使用 Permit.io 在基於 WebSocket 的聊天應用程式中實現即時授權。最後,您將了解如何動態實施基於角色和基於屬性的存取控制,保護不同的聊天室、訊息可見性和即時互動。
我們都以某種形式使用聊天應用程式來與朋友和家人保持聯繫,與同事討論重要事務,甚至開展業務。隨著對無縫、即時通訊的需求不斷增長,人們很容易認為保護這些互動的複雜安全措施是理所當然的。然而,隨著聊天應用程式變得越來越複雜,保護用戶資料和對話的挑戰也越來越大。細粒度的存取控制有助於確保只有授權使用者才能存取敏感資訊和操作。
細粒度的存取控制對於即時聊天應用程式至關重要,以確保安全性、用戶自訂和法規遵循。
透過設定強大的身份驗證方法和基於角色的權限,聊天應用程式可以防止未經授權的使用者存取敏感對話,並允許管理員有效地管理使用者互動。這種方法還可以根據個人角色或偏好參與各種聊天類型(公共、私人或群組),從而增強用戶體驗,從而創建更具吸引力的互動。
此外,細粒度的存取控制可以幫助組織滿足嚴格的資料隱私法規(例如 GDPR),保護機密資料並最大程度地降低法律風險。
這些要點涵蓋了段落中的所有主要思想。這是包含所有細節的精緻版本:
Permit.io 的授權解決方案可以顯著簡化聊天應用程式中即時授權的實現,特別是與 WebSocket 整合時。以下概述了這種組合如何增強動態存取控制:
對於我們基於 Web 套接字的應用程序,我們將使用 Next.js 和 Ably,該服務使我們能夠輕鬆整合和管理由 Web 套接字支援的應用程式中的即時功能。
除了 Ably 和 Next Auth 之外,我們還可以使用 Firebase 之類的東西來處理身份驗證和即時功能。 Permit.io 部落格上有關於此內容的完整教學。
話不多說,我們繼續吧!
執行以下指令並依照指示操作:
npx create-next-app@latest live-chat Need to install the following packages: create-next-app@15.1.0 Ok to proceed? (y) y ✔ Would you like to use TypeScript? … No / Yes ✔ Would you like to use ESLint? … No / Yes ✔ Would you like to use Tailwind CSS? … No / Yes ✔ Would you like your code inside a `src/` directory? … No / Yes ✔ Would you like to use App Router? (recommended) … No / Yes ✔ Would you like to use Turbopack for `next dev`? … No / Yes ✔ Would you like to customize the import alias (`@/*` by default)? … No / Yes Creating a new Next.js app in /Users/miracleio/Documents/writing/permit/real-time-authorization-in-a-chat-application-with-permitio-and-websockets/live-chat. Using npm. Initializing project with template: app-tw Installing dependencies: - react - react-dom - next Installing devDependencies: - typescript - @types/node - @types/react - @types/react-dom - postcss - tailwindcss - eslint - eslint-config-next - @eslint/eslintrc added 371 packages, and audited 372 packages in 1m 141 packages are looking for funding run `npm fund` for details found 0 vulnerabilities Initialized a git repository. Success! Created live-chat at /Users/miracleio/Documents/writing/permit/real-time-authorization-in-a-chat-application-with-permitio-and-websockets/live-chat
導航到新建立的專案資料夾並安裝一些我們將用於建立應用程式的軟體包:
npx create-next-app@latest live-chat Need to install the following packages: create-next-app@15.1.0 Ok to proceed? (y) y ✔ Would you like to use TypeScript? … No / Yes ✔ Would you like to use ESLint? … No / Yes ✔ Would you like to use Tailwind CSS? … No / Yes ✔ Would you like your code inside a `src/` directory? … No / Yes ✔ Would you like to use App Router? (recommended) … No / Yes ✔ Would you like to use Turbopack for `next dev`? … No / Yes ✔ Would you like to customize the import alias (`@/*` by default)? … No / Yes Creating a new Next.js app in /Users/miracleio/Documents/writing/permit/real-time-authorization-in-a-chat-application-with-permitio-and-websockets/live-chat. Using npm. Initializing project with template: app-tw Installing dependencies: - react - react-dom - next Installing devDependencies: - typescript - @types/node - @types/react - @types/react-dom - postcss - tailwindcss - eslint - eslint-config-next - @eslint/eslintrc added 371 packages, and audited 372 packages in 1m 141 packages are looking for funding run `npm fund` for details found 0 vulnerabilities Initialized a git repository. Success! Created live-chat at /Users/miracleio/Documents/writing/permit/real-time-authorization-in-a-chat-application-with-permitio-and-websockets/live-chat
此外,從 Radix UI 安裝一些 UI 元件:
cd live-chat npm install -D prettier prettier-plugin-tailwindcss @tailwindcss/forms
在專案根目錄下建立一個新檔案 - .prettierrc 並輸入以下內容:
npm install @radix-ui/react-scroll-area
在 tailwind.config.ts 檔案中,輸入以下內容:
{ "plugins": ["prettier-plugin-tailwindcss"] }
// ./tailwind.config.ts import type { Config } from "tailwindcss"; import tailwindForms from "@tailwindcss/forms"; export default { content: [ "./pages/**/*.{js,ts,jsx,tsx,mdx}", "./components/**/*.{js,ts,jsx,tsx,mdx}", "./app/**/*.{js,ts,jsx,tsx,mdx}", ], theme: { extend: { colors: { background: "var(--background)", foreground: "var(--foreground)", }, }, }, plugins: [tailwindForms], } satisfies Config;
在 ./app/globals.css 檔案中,輸入以下內容:
In the `./next.config.ts`, enter the following: // ./next.config.ts import type { NextConfig } from "next"; const nextConfig: NextConfig = { /* config options here */ images: { remotePatterns: [ { protocol: "https", hostname: "lh3.googleusercontent.com", }, { protocol: "https", hostname: "www.tapback.co", }, ], }, }; export default nextConfig;
我們將使用 Auth.js,一個最初為 Next.js 建置的身份驗證函式庫。
執行以下命令來安裝軟體包:
/* ./app/globals.css */ @tailwind base; @tailwind components; @tailwind utilities; @layer base { body { @apply bg-white text-gray-800 dark:bg-gray-900 dark:text-gray-300; } } @layer components { .btn { @apply inline-flex items-center justify-center gap-2 rounded-full bg-gray-100 px-4 py-2 text-sm font-semibold text-gray-500 hover:brightness-95 focus:outline-none focus:ring-2 focus:ring-gray-200 focus:ring-offset-2 dark:bg-gray-800 dark:text-gray-300 dark:brightness-105 dark:hover:bg-gray-700 dark:focus:ring-gray-800 dark:focus:ring-offset-gray-900; } .btn:has(> .icon:first-child) { @apply pl-2; } .btn:has(> .icon:last-child) { @apply pr-2; } .icon { @apply h-5 w-5 text-current; } .form-input { @apply flex grow rounded-full border border-none bg-gray-100 px-4 py-2 text-sm font-semibold text-gray-500 outline-none hover:brightness-95 focus:border-none focus:outline-none focus:ring-2 focus:ring-gray-200 focus:ring-offset-2 dark:bg-gray-800 dark:text-gray-300 dark:brightness-105 dark:hover:bg-gray-700 dark:focus:ring-gray-800 dark:focus:ring-offset-gray-900; } .site-section { @apply py-16 md:py-24; } .site-section > .wrapper { @apply mx-auto max-w-5xl px-4 sm:px-6 lg:px-8; } .noscroll { @apply overflow-auto; scrollbar-width: none; } }
我們必須建立一個 AUTH_SECRET 環境變數。該庫使用此隨機值來加密令牌和電子郵件驗證雜湊。 (請參閱部署以了解更多資訊)。您可以透過執行官方 Auth.js CLI 來產生一個:
npm install next-auth@beta
接下來,建立 Auth.js 設定檔和物件 - ./auth.js:
npx auth secret ? Created /Users/miracleio/Documents/writing/permit/real-time-authorization-in-a-chat-application-with-permitio-and-websockets/live-chat/.env.local with `AUTH_SECRET`.
在 ./app/api/auth/[...nextauth]/route.ts 下新增路由處理程序:
// ./auth.ts import NextAuth from "next-auth"; export const { handlers, signIn, signOut, auth } = NextAuth({ providers: [], });
新增可選的中間件以保持會話處於活動狀態;這將在每次呼叫時更新會話過期時間 - ./middleware.ts:
// ./app/api/auth/[...nextauth]/route.ts import { handlers } from "@/auth"; // Referring to the auth.ts we just created export const { GET, POST } = handlers;
NextAuth 支援多個 OAuth 提供者進行身份驗證。在本教程中,我們將使用 Google。
要取得我們的 Google 用戶端 ID 和金鑰,我們必須在 Google Cloud Console 中設定一個新專案 - https://console.cloud.google.com/projectcreate
接下來,在新建立的專案中,我們將設定一個新的同意畫面:
建立同意畫面後,我們就可以設定憑證。從側邊欄導覽至憑證。
按一下 建立憑證 按鈕,然後從下拉清單中選擇 OAuth 用戶端 ID。
在以下畫面中,選擇Web 應用程序, 輸入授權的JavaScript 來源,並重定向URI:http://localhost:3000 和http://localhost:3000/api/auth/callback /分別谷歌。
這樣我們就應該擁有我們的客戶端 ID 和秘密:
複製值並將其輸入到 .env 檔案中:
npx create-next-app@latest live-chat Need to install the following packages: create-next-app@15.1.0 Ok to proceed? (y) y ✔ Would you like to use TypeScript? … No / Yes ✔ Would you like to use ESLint? … No / Yes ✔ Would you like to use Tailwind CSS? … No / Yes ✔ Would you like your code inside a `src/` directory? … No / Yes ✔ Would you like to use App Router? (recommended) … No / Yes ✔ Would you like to use Turbopack for `next dev`? … No / Yes ✔ Would you like to customize the import alias (`@/*` by default)? … No / Yes Creating a new Next.js app in /Users/miracleio/Documents/writing/permit/real-time-authorization-in-a-chat-application-with-permitio-and-websockets/live-chat. Using npm. Initializing project with template: app-tw Installing dependencies: - react - react-dom - next Installing devDependencies: - typescript - @types/node - @types/react - @types/react-dom - postcss - tailwindcss - eslint - eslint-config-next - @eslint/eslintrc added 371 packages, and audited 372 packages in 1m 141 packages are looking for funding run `npm fund` for details found 0 vulnerabilities Initialized a git repository. Success! Created live-chat at /Users/miracleio/Documents/writing/permit/real-time-authorization-in-a-chat-application-with-permitio-and-websockets/live-chat
接下來,在我們的 Auth.js 配置中啟用 Google 作為登入選項。我們必須從套件中匯入 Google 提供程序,並將其傳遞給我們先前在 Auth.js 設定檔中設定的提供者數組:
cd live-chat npm install -D prettier prettier-plugin-tailwindcss @tailwindcss/forms
讓我們為我們的應用程式建立一個包含登入和登出按鈕的標頭。建立一個新檔案 - ./components/Site/Header.tsx:
npm install @radix-ui/react-scroll-area
這裡,SiteHeader 元件充當主導覽列。
如果存在使用者會話(會話?.使用者),則顯示使用者的頭像、姓名和「退出」按鈕。
否則,顯示「登入」按鈕,並且由於我們使用 Next.js 伺服器操作,因此我們將其放入表單中。
登入和登出函數包裝在伺服器操作標記(「使用伺服器」)中,以便在 Next.js 中在伺服器端執行。
在我們的 ./app/layout.tsx 檔案中匯入 SiteHeader 元件:
{ "plugins": ["prettier-plugin-tailwindcss"] }
在首頁 ./app/page.tsx 中,輸入以下內容:
// ./tailwind.config.ts import type { Config } from "tailwindcss"; import tailwindForms from "@tailwindcss/forms"; export default { content: [ "./pages/**/*.{js,ts,jsx,tsx,mdx}", "./components/**/*.{js,ts,jsx,tsx,mdx}", "./app/**/*.{js,ts,jsx,tsx,mdx}", ], theme: { extend: { colors: { background: "var(--background)", foreground: "var(--foreground)", }, }, }, plugins: [tailwindForms], } satisfies Config;
有了這個,我們應該有這樣的東西:
現在我們已經設定了身份驗證,讓我們繼續使用 Ably 將 websockets 功能添加到我們的應用程式中。
要開始使用,請註冊 Ably,然後使用以下選項建立一個新應用程式:
在下一個畫面中,複製您的 API 金鑰:
將其保存在 .env 檔案中:
In the `./next.config.ts`, enter the following: // ./next.config.ts import type { NextConfig } from "next"; const nextConfig: NextConfig = { /* config options here */ images: { remotePatterns: [ { protocol: "https", hostname: "lh3.googleusercontent.com", }, { protocol: "https", hostname: "www.tapback.co", }, ], }, }; export default nextConfig;
在我們的應用程式中,安裝 Ably React SDK 和 JWT 的 jose 庫:
/* ./app/globals.css */ @tailwind base; @tailwind components; @tailwind utilities; @layer base { body { @apply bg-white text-gray-800 dark:bg-gray-900 dark:text-gray-300; } } @layer components { .btn { @apply inline-flex items-center justify-center gap-2 rounded-full bg-gray-100 px-4 py-2 text-sm font-semibold text-gray-500 hover:brightness-95 focus:outline-none focus:ring-2 focus:ring-gray-200 focus:ring-offset-2 dark:bg-gray-800 dark:text-gray-300 dark:brightness-105 dark:hover:bg-gray-700 dark:focus:ring-gray-800 dark:focus:ring-offset-gray-900; } .btn:has(> .icon:first-child) { @apply pl-2; } .btn:has(> .icon:last-child) { @apply pr-2; } .icon { @apply h-5 w-5 text-current; } .form-input { @apply flex grow rounded-full border border-none bg-gray-100 px-4 py-2 text-sm font-semibold text-gray-500 outline-none hover:brightness-95 focus:border-none focus:outline-none focus:ring-2 focus:ring-gray-200 focus:ring-offset-2 dark:bg-gray-800 dark:text-gray-300 dark:brightness-105 dark:hover:bg-gray-700 dark:focus:ring-gray-800 dark:focus:ring-offset-gray-900; } .site-section { @apply py-16 md:py-24; } .site-section > .wrapper { @apply mx-auto max-w-5xl px-4 sm:px-6 lg:px-8; } .noscroll { @apply overflow-auto; scrollbar-width: none; } }
安裝 jose 和 ively 後,建立 ./app/api/ically/route.ts:
npm install next-auth@beta
讓我們來分解這裡發生的事情:
接下來,我們將建立該聊天頁面所需的所有元件。我們將從顯示用戶發送的單一訊息的訊息項目元件開始。
建立一個新檔案 - ./components/Message/Item.tsx:
npx create-next-app@latest live-chat Need to install the following packages: create-next-app@15.1.0 Ok to proceed? (y) y ✔ Would you like to use TypeScript? … No / Yes ✔ Would you like to use ESLint? … No / Yes ✔ Would you like to use Tailwind CSS? … No / Yes ✔ Would you like your code inside a `src/` directory? … No / Yes ✔ Would you like to use App Router? (recommended) … No / Yes ✔ Would you like to use Turbopack for `next dev`? … No / Yes ✔ Would you like to customize the import alias (`@/*` by default)? … No / Yes Creating a new Next.js app in /Users/miracleio/Documents/writing/permit/real-time-authorization-in-a-chat-application-with-permitio-and-websockets/live-chat. Using npm. Initializing project with template: app-tw Installing dependencies: - react - react-dom - next Installing devDependencies: - typescript - @types/node - @types/react - @types/react-dom - postcss - tailwindcss - eslint - eslint-config-next - @eslint/eslintrc added 371 packages, and audited 372 packages in 1m 141 packages are looking for funding run `npm fund` for details found 0 vulnerabilities Initialized a git repository. Success! Created live-chat at /Users/miracleio/Documents/writing/permit/real-time-authorization-in-a-chat-application-with-permitio-and-websockets/live-chat
此 MessageItem 元件會根據 fromUser 屬性動態調整其佈局,並使用 flex-row-reverse 進行對齊。
它顯示來自 message.data.avatarUrl 的寄件者頭像。顯示訊息文字 (message.data.text) 及其時間戳記 (message.timestamp),格式為本地化時間字串。
對於目前使用者發送的訊息,有條件地顯示一個以 SVG 圖示呈現的刪除按鈕,並透過 message.id 觸發 onDelete 回呼。
建立一個新檔案 - ./components/Message/List.tsx:
cd live-chat npm install -D prettier prettier-plugin-tailwindcss @tailwindcss/forms
MessageList 元件使用 messages.map() 循環呈現可捲動的訊息列表,其中每個訊息都透過 MessageItem 元件顯示。
它透過將會話電子郵件 (session.data.user.email) 與訊息的 clientId 進行比較,確定訊息是否是由登入使用者發送的,並使用 self-end 設計使用者訊息以實現右對齊。
每個 MessageItem 都會接收其訊息和 onDelete 回呼。
建立新檔案 - ./components/Message/Input.tsx:
npm install @radix-ui/react-scroll-area
MessageInput 元件透過 useState 管理使用者輸入,並透過 onSubmit 提交訊息,提交後重設欄位。輸入欄位 () 顯示上下文佔位符,並在停用屬性為 true 時停用。
建立一個新檔案 - ./components/Chat/ChannelList.tsx:
npx create-next-app@latest live-chat Need to install the following packages: create-next-app@15.1.0 Ok to proceed? (y) y ✔ Would you like to use TypeScript? … No / Yes ✔ Would you like to use ESLint? … No / Yes ✔ Would you like to use Tailwind CSS? … No / Yes ✔ Would you like your code inside a `src/` directory? … No / Yes ✔ Would you like to use App Router? (recommended) … No / Yes ✔ Would you like to use Turbopack for `next dev`? … No / Yes ✔ Would you like to customize the import alias (`@/*` by default)? … No / Yes Creating a new Next.js app in /Users/miracleio/Documents/writing/permit/real-time-authorization-in-a-chat-application-with-permitio-and-websockets/live-chat. Using npm. Initializing project with template: app-tw Installing dependencies: - react - react-dom - next Installing devDependencies: - typescript - @types/node - @types/react - @types/react-dom - postcss - tailwindcss - eslint - eslint-config-next - @eslint/eslintrc added 371 packages, and audited 372 packages in 1m 141 packages are looking for funding run `npm fund` for details found 0 vulnerabilities Initialized a git repository. Success! Created live-chat at /Users/miracleio/Documents/writing/permit/real-time-authorization-in-a-chat-application-with-permitio-and-websockets/live-chat
ChatChannelList 元件將頻道清單呈現為連結。使用基於目前路徑名的 font-bold 類別來突出顯示活動通道。
建立一個新檔案 - ./components/Chat/index.tsx:
cd live-chat npm install -D prettier prettier-plugin-tailwindcss @tailwindcss/forms
在這個組件中,我們做了一些事情:
接下來,我們會將所有內容放在聊天頁面中。
建立一個新檔案 - ./app/chat/[[...channel]]/page.tsx:
npm install @radix-ui/react-scroll-area
頁面元件將聊天應用程式包裝在提供者中以進行狀態和上下文管理。 SessionProvider 確保對使用者會話的全域訪問,而 AblyProvider 和 ChannelProvider 透過共用即時客戶端(authUrl:「/api/ically」)和當前頻道名稱(例如 chat:general)來實現與 Ably 的無縫整合。
佈局使用包含三個部分的網格:左側邊欄(
有了這個,當我們導航到 http://localhost:3000/chat/general:
時,我們應該有這樣的東西現在我們的茶
在 https://www.permit.io/ 建立一個新帳號:
輸入您的專案名稱,在此範例中我將使用即時聊天:
要為我們的聊天應用程式建立頻道,Permit 允許我們建立資源,這些資源是代表使用者可以存取的內容的實體,讓我們將頻道設定為資源以繼續:
現在我們可以編輯資源並在頻道資源上新增角色:
這是我們創造的角色。您可以前往政策頁面上的角色標籤查看。
現在我們可以更新我們的策略來決定誰有權存取每個資源的哪些內容:
為聊天中我們想要的每個頻道建立資源實例,這裡我們為常規頻道建立一個實例,我們可以為隨機和mod.
查看實例
現在我們已經設定了 Permit Dashboard,我們可以將 Permit 添加到我們的 Next.js 應用程式中。
將 Permit.io 添加到您的 Next.js 應用程式
首先,我們必須安裝permitio套件:
npx create-next-app@latest live-chat Need to install the following packages: create-next-app@15.1.0 Ok to proceed? (y) y ✔ Would you like to use TypeScript? … No / Yes ✔ Would you like to use ESLint? … No / Yes ✔ Would you like to use Tailwind CSS? … No / Yes ✔ Would you like your code inside a `src/` directory? … No / Yes ✔ Would you like to use App Router? (recommended) … No / Yes ✔ Would you like to use Turbopack for `next dev`? … No / Yes ✔ Would you like to customize the import alias (`@/*` by default)? … No / Yes Creating a new Next.js app in /Users/miracleio/Documents/writing/permit/real-time-authorization-in-a-chat-application-with-permitio-and-websockets/live-chat. Using npm. Initializing project with template: app-tw Installing dependencies: - react - react-dom - next Installing devDependencies: - typescript - @types/node - @types/react - @types/react-dom - postcss - tailwindcss - eslint - eslint-config-next - @eslint/eslintrc added 371 packages, and audited 372 packages in 1m 141 packages are looking for funding run `npm fund` for details found 0 vulnerabilities Initialized a git repository. Success! Created live-chat at /Users/miracleio/Documents/writing/permit/real-time-authorization-in-a-chat-application-with-permitio-and-websockets/live-chat
將複製的金鑰加入 .env 檔案:
cd live-chat npm install -D prettier prettier-plugin-tailwindcss @tailwindcss/forms
從 Docker Hub 拉取 PDP 容器(點擊此處安裝 Docker):
npm install @radix-ui/react-scroll-area
{ "plugins": ["prettier-plugin-tailwindcss"] }
對於這個例子,我們需要設定一些可重複使用的函數和路由,讓我們從在 ./lib/permit.ts 中建立一個 Permit 函式庫函數開始:
npx create-next-app@latest live-chat Need to install the following packages: create-next-app@15.1.0 Ok to proceed? (y) y ✔ Would you like to use TypeScript? … No / Yes ✔ Would you like to use ESLint? … No / Yes ✔ Would you like to use Tailwind CSS? … No / Yes ✔ Would you like your code inside a `src/` directory? … No / Yes ✔ Would you like to use App Router? (recommended) … No / Yes ✔ Would you like to use Turbopack for `next dev`? … No / Yes ✔ Would you like to customize the import alias (`@/*` by default)? … No / Yes Creating a new Next.js app in /Users/miracleio/Documents/writing/permit/real-time-authorization-in-a-chat-application-with-permitio-and-websockets/live-chat. Using npm. Initializing project with template: app-tw Installing dependencies: - react - react-dom - next Installing devDependencies: - typescript - @types/node - @types/react - @types/react-dom - postcss - tailwindcss - eslint - eslint-config-next - @eslint/eslintrc added 371 packages, and audited 372 packages in 1m 141 packages are looking for funding run `npm fund` for details found 0 vulnerabilities Initialized a git repository. Success! Created live-chat at /Users/miracleio/Documents/writing/permit/real-time-authorization-in-a-chat-application-with-permitio-and-websockets/live-chat
我們也會為所有與授權相關的實用函數建立 ./utils/permit.ts 檔案:
cd live-chat npm install -D prettier prettier-plugin-tailwindcss @tailwindcss/forms
我們必須建立一個 useUser 鉤子,這將使我們能夠輕鬆地在前端檢索許可使用者。建立一個新檔案./hooks/useUser.ts:
npm install @radix-ui/react-scroll-area
要在登入期間自動將使用者新增至 Permit,請使用 NextAuth 的 signIn 回呼。回調期間:
用更新後的程式碼取代 ./auth.ts 檔案:
{ "plugins": ["prettier-plugin-tailwindcss"] }
這可確保使用者經過身份驗證並無縫整合到 Permit 中以進行存取控制。
如下所示,當使用者登入時,他們的帳戶將被添加到我們的許可儀表板中:
在繼續之前,我們還需要設定一些東西,讓我們從類型開始,以便在開發應用程式時安撫 TypeScript。建立一個新的 ./types/user.ts 檔案並輸入以下內容:
// ./tailwind.config.ts import type { Config } from "tailwindcss"; import tailwindForms from "@tailwindcss/forms"; export default { content: [ "./pages/**/*.{js,ts,jsx,tsx,mdx}", "./components/**/*.{js,ts,jsx,tsx,mdx}", "./app/**/*.{js,ts,jsx,tsx,mdx}", ], theme: { extend: { colors: { background: "var(--background)", foreground: "var(--foreground)", }, }, }, plugins: [tailwindForms], } satisfies Config;
接下來,我們將建立一些 API 路由來取得使用者資料和權限以及對使用者進行升級和降級。
建立一個新檔案 - ./app/api/permit/getUsers/route.ts:
In the `./next.config.ts`, enter the following: // ./next.config.ts import type { NextConfig } from "next"; const nextConfig: NextConfig = { /* config options here */ images: { remotePatterns: [ { protocol: "https", hostname: "lh3.googleusercontent.com", }, { protocol: "https", hostname: "www.tapback.co", }, ], }, }; export default nextConfig;
建立一個新檔案 *./app/api/permit/getUser/route.ts*:
/* ./app/globals.css */ @tailwind base; @tailwind components; @tailwind utilities; @layer base { body { @apply bg-white text-gray-800 dark:bg-gray-900 dark:text-gray-300; } } @layer components { .btn { @apply inline-flex items-center justify-center gap-2 rounded-full bg-gray-100 px-4 py-2 text-sm font-semibold text-gray-500 hover:brightness-95 focus:outline-none focus:ring-2 focus:ring-gray-200 focus:ring-offset-2 dark:bg-gray-800 dark:text-gray-300 dark:brightness-105 dark:hover:bg-gray-700 dark:focus:ring-gray-800 dark:focus:ring-offset-gray-900; } .btn:has(> .icon:first-child) { @apply pl-2; } .btn:has(> .icon:last-child) { @apply pr-2; } .icon { @apply h-5 w-5 text-current; } .form-input { @apply flex grow rounded-full border border-none bg-gray-100 px-4 py-2 text-sm font-semibold text-gray-500 outline-none hover:brightness-95 focus:border-none focus:outline-none focus:ring-2 focus:ring-gray-200 focus:ring-offset-2 dark:bg-gray-800 dark:text-gray-300 dark:brightness-105 dark:hover:bg-gray-700 dark:focus:ring-gray-800 dark:focus:ring-offset-gray-900; } .site-section { @apply py-16 md:py-24; } .site-section > .wrapper { @apply mx-auto max-w-5xl px-4 sm:px-6 lg:px-8; } .noscroll { @apply overflow-auto; scrollbar-width: none; } }
建立一個新檔案 - ./app/api/permit/promoteUser/route.ts 並輸入以下內容:
npm install next-auth@beta
這裡有一個 Next.js API 路由,它透過使用 Permit.io 在不同資源實例上為使用者分配特定角色來提升使用者。
PromotionUser 函數檢查目前使用者是否有權限推廣其他用戶,並為指定頻道上的目標使用者指派「參與者」、「主持人」和「管理員」等角色。
GET 函數處理傳入請求、提取查詢參數、驗證它們、取得資源實例並執行升級過程。如果出現任何問題,它會以 JSON 回應的形式傳回結果或錯誤訊息。
建立一個新檔案 - ./app/api/permit/demoteUser/route.ts 並輸入以下內容:
npx create-next-app@latest live-chat Need to install the following packages: create-next-app@15.1.0 Ok to proceed? (y) y ✔ Would you like to use TypeScript? … No / Yes ✔ Would you like to use ESLint? … No / Yes ✔ Would you like to use Tailwind CSS? … No / Yes ✔ Would you like your code inside a `src/` directory? … No / Yes ✔ Would you like to use App Router? (recommended) … No / Yes ✔ Would you like to use Turbopack for `next dev`? … No / Yes ✔ Would you like to customize the import alias (`@/*` by default)? … No / Yes Creating a new Next.js app in /Users/miracleio/Documents/writing/permit/real-time-authorization-in-a-chat-application-with-permitio-and-websockets/live-chat. Using npm. Initializing project with template: app-tw Installing dependencies: - react - react-dom - next Installing devDependencies: - typescript - @types/node - @types/react - @types/react-dom - postcss - tailwindcss - eslint - eslint-config-next - @eslint/eslintrc added 371 packages, and audited 372 packages in 1m 141 packages are looking for funding run `npm fund` for details found 0 vulnerabilities Initialized a git repository. Success! Created live-chat at /Users/miracleio/Documents/writing/permit/real-time-authorization-in-a-chat-application-with-permitio-and-websockets/live-chat
類似地,我們有一個 Next.js API 路由,它透過使用 Permit.io 取消分配使用者在特定資源實例上的角色來降級使用者。 demoteUser 函數刪除指定頻道上使用者的「參與者」、「主持人」和「管理員」等角色。 GET 函數處理傳入請求、提取查詢參數、驗證它們、取得資源實例、檢索使用者指派的角色並執行降級程序。
建立一個新檔案 - ./app/api/permit/listResourceInstances/route.ts 並輸入以下內容:
cd live-chat npm install -D prettier prettier-plugin-tailwindcss @tailwindcss/forms
在我們的檔案 ./app/api/ously/route.ts 中,將其替換為以下更新的程式碼:
npm install @radix-ui/react-scroll-area
這裡我們合併了Permit.io來管理角色和權限,用基於角色的動態權限取代靜態設定。
generatePermissions 函數使用來自 Permit.io 的資料將角色對應到特定通道功能,確保權限與使用者角色即時保持一致。這種方法提高了靈活性,並確保系統適應角色或權限的變化,與 Ably 基於 JWT 的身份驗證無縫整合。
現在我們已經將資源(通道)添加到了許可儀表板中,我們可以從那裡獲取它們,而不是對它們進行硬編碼。
在 ./components/Chat/ChannelList.tsx 檔案中,進行以下變更:
{ "plugins": ["prettier-plugin-tailwindcss"] }
讓我們建立一個使用者清單元件,用於取得所有授權使用者並在使用者名稱旁邊顯示 升級 或 降級 按鈕。
建立一個新檔案 - ./components/Chat/UserList.tsx 並輸入以下內容:
// ./tailwind.config.ts import type { Config } from "tailwindcss"; import tailwindForms from "@tailwindcss/forms"; export default { content: [ "./pages/**/*.{js,ts,jsx,tsx,mdx}", "./components/**/*.{js,ts,jsx,tsx,mdx}", "./app/**/*.{js,ts,jsx,tsx,mdx}", ], theme: { extend: { colors: { background: "var(--background)", foreground: "var(--foreground)", }, }, }, plugins: [tailwindForms], } satisfies Config;
這裡,我們使用自訂鉤子 useUser 來獲取當前用戶的信息,並使用 Ably 的 useChannel 鉤子進行即時通道通訊。 getUserList 函數使用 Permit.io API 從伺服器取得使用者清單。此元件訂閱 Ably 通道進行即時更新,並在發生升級/降級事件時取得更新的使用者清單。使用者清單儲存在元件的狀態中,不包括目前使用者。
最後,我們可以將其新增到我們的頁面,在 ./app/chat/[[...channel]]/page.tsx 中:
In the `./next.config.ts`, enter the following: // ./next.config.ts import type { NextConfig } from "next"; const nextConfig: NextConfig = { /* config options here */ images: { remotePatterns: [ { protocol: "https", hostname: "lh3.googleusercontent.com", }, { protocol: "https", hostname: "www.tapback.co", }, ], }, }; export default nextConfig;
這樣我們應該能夠即時提升和降級用戶:
這是實際降級:
建立具有即時授權的聊天應用程式是一個充滿挑戰但有益的過程。透過整合 Permit.io 和 WebSockets 等強大的工具,您可以創建無縫體驗,確保安全且細粒度的存取控制。在本文中,我們探討了動態授權在聊天應用程式中的重要性,使用 Ably 建立了基於 WebSocket 的架構,並整合 Permit.io 進行授權管理。
此工作流程展示了現代工具如何簡化曾經複雜的實現,使開發人員能夠更多地關注用戶體驗和可擴展性,而不是底層基礎設施。透過正確的方法,您可以確保您的聊天應用程式既動態又安全。
基礎設定完成後,您可以探索簡單且進階的功能,例如:
以上是使用 Permit.io 和 WebSockets 在聊天應用程式中進行即時授權的詳細內容。更多資訊請關注PHP中文網其他相關文章!