」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > 使用臉部身份驗證建立安全的員工儀表板:綜合 Next.js 教程

使用臉部身份驗證建立安全的員工儀表板:綜合 Next.js 教程

發佈於2024-07-31
瀏覽:113

Are you ready to revolutionize your workplace management? In this comprehensive tutorial, we're diving deep into creating a state-of-the-art employee dashboard that leverages facial authentication. We'll be using some of the hottest tools in web development: Next.js, FACEIO, and Shadcn UI. By the end of this guide, you'll have a sleek, secure dashboard that'll make your employees feel like they're living in the future!

What You'll Need Before We Start

Before we dive in, let's make sure you've got all your ducks in a row:

  • Node.js installed on your machine
  • npm or yarn (whichever floats your boat)

Got all that? Great! Let's get this show on the road.

Faceio Authentication

Setting Up Your Project: The First Steps

Step 1: Kickstarting Your Next.js Project

First things first, let's create our Next.js project. Open up your terminal and type in these magic words:

npx create-next-app@latest faceio-app
cd faceio-app

You'll be asked a few questions. Here's how to answer them:

  • TypeScript? Heck yes!
  • ESLint? Absolutely!
  • Tailwind CSS? You bet!
  • src/ directory? Nah, we're good.
  • App Router? Yes, please!
  • Customize default import alias? We'll pass on this one.

Step 2: Gathering Your Tools

Now, let's grab all the goodies we need. Run this command to install our dependencies:

npm install @faceio/fiojs @shadcn/ui class-variance-authority clsx tailwind-merge

Step 3: Setting Up Your Secret Sauce

Create a file called .env.local in your project's root. This is where we'll keep our secret FACEIO app ID:

NEXT_PUBLIC_FACEIO_APP_ID=your-super-secret-faceio-app-id

Remember to replace 'your-super-secret-faceio-app-id' with your actual FACEIO application ID. Keep it safe!

Step 4: File Structure

Your project structure should look like this:

faceio-app/
├── app/
│   ├── layout.tsx
│   ├── page.tsx
│   └── components/
│       ├── FaceAuth.tsx
│       └── EmployeeDashboard.tsx
├── public/
├── .env.local
├── next.config.js
├── package.json
├── tsconfig.json
└── tailwind.config.js

Step 5: Sprucing Up Tailwind CSS

Time to give Tailwind a makeover. Update your tailwind.config.js file with this fancy configuration:

/** @type {import('tailwindcss').Config} */
module.exports = {
  darkMode: ["class"],
  content: [
    './app/**/*.{ts,tsx}',
  ],
  theme: {
    container: {
      center: true,
      padding: "2rem",
      screens: {
        "2xl": "1400px",
      },
    },
    extend: {
      colors: {
        border: "hsl(var(--border))",
        input: "hsl(var(--input))",
        ring: "hsl(var(--ring))",
        background: "hsl(var(--background))",
        foreground: "hsl(var(--foreground))",
        primary: {
          DEFAULT: "hsl(var(--primary))",
          foreground: "hsl(var(--primary-foreground))",
        },
        secondary: {
          DEFAULT: "hsl(var(--secondary))",
          foreground: "hsl(var(--secondary-foreground))",
        },
        destructive: {
          DEFAULT: "hsl(var(--destructive))",
          foreground: "hsl(var(--destructive-foreground))",
        },
        muted: {
          DEFAULT: "hsl(var(--muted))",
          foreground: "hsl(var(--muted-foreground))",
        },
        accent: {
          DEFAULT: "hsl(var(--accent))",
          foreground: "hsl(var(--accent-foreground))",
        },
        popover: {
          DEFAULT: "hsl(var(--popover))",
          foreground: "hsl(var(--popover-foreground))",
        },
        card: {
          DEFAULT: "hsl(var(--card))",
          foreground: "hsl(var(--card-foreground))",
        },
      },
      borderRadius: {
        lg: "var(--radius)",
        md: "calc(var(--radius) - 2px)",
        sm: "calc(var(--radius) - 4px)",
      },
      keyframes: {
        "accordion-down": {
          from: { height: 0 },
          to: { height: "var(--radix-accordion-content-height)" },
        },
        "accordion-up": {
          from: { height: "var(--radix-accordion-content-height)" },
          to: { height: 0 },
        },
      },
      animation: {
        "accordion-down": "accordion-down 0.2s ease-out",
        "accordion-up": "accordion-up 0.2s ease-out",
      },
    },
  },
  plugins: [require("tailwindcss-animate")],
}

Building the Heart of Your Dashboard

Step 1: Crafting the FaceAuth Component

Let's create the star of our show - the FaceAuth component. Create a new file app/components/FaceAuth.tsx and paste in this code:

import { useEffect } from 'react';
import faceIO from '@faceio/fiojs';
import { Button, Card, CardHeader, CardTitle, CardContent } from '@shadcn/ui';
import { useToast } from '@shadcn/ui';

interface FaceAuthProps {
  onSuccessfulAuth: (data: any) => void;
}

const FaceAuth: React.FC = ({ onSuccessfulAuth }) => {
  const { toast } = useToast();

  useEffect(() => {
    const faceio = new faceIO(process.env.NEXT_PUBLIC_FACEIO_APP_ID);

    const enrollNewUser = async () => {
      try {
        const userInfo = await faceio.enroll({
          locale: 'auto',
          payload: {
            email: '[email protected]',
            pin: '12345',
          },
        });
        toast({
          title: "Success!",
          description: "You're now enrolled in the facial recognition system!",
        });
        console.log('User Enrolled!', userInfo);
      } catch (errCode) {
        toast({
          title: "Oops!",
          description: "Enrollment failed. Please try again.",
          variant: "destructive",
        });
        console.error('Enrollment Failed', errCode);
      }
    };

    const authenticateUser = async () => {
      try {
        const userData = await faceio.authenticate();
        toast({
          title: "Welcome back!",
          description: "Authentication successful.",
        });
        console.log('User Authenticated!', userData);
        onSuccessfulAuth({
          name: 'John Doe',
          position: 'Software Developer',
          department: 'Engineering',
          photoUrl: 'https://example.com/john-doe.jpg',
        });
      } catch (errCode) {
        toast({
          title: "Authentication failed",
          description: "Please try again or enroll.",
          variant: "destructive",
        });
        console.error('Authentication Failed', errCode);
      }
    };

    const enrollBtn = document.getElementById('enroll-btn');
    const authBtn = document.getElementById('auth-btn');

    if (enrollBtn) enrollBtn.onclick = enrollNewUser;
    if (authBtn) authBtn.onclick = authenticateUser;

    return () => {
      if (enrollBtn) enrollBtn.onclick = null;
      if (authBtn) authBtn.onclick = null;
    };
  }, [toast, onSuccessfulAuth]);

  return (
    Facial Authentication
        
      
  );
};

export default FaceAuth;

Step 2: Building the EmployeeDashboard Component

Now, let's create the dashboard that our employees will see. Create app/components/EmployeeDashboard.tsx:

import { useState } from 'react';
import { Card, CardHeader, CardTitle, CardContent } from '@shadcn/ui';
import { Button, Avatar, Badge, Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@shadcn/ui';
import FaceAuth from './FaceAuth';

interface EmployeeData {
  name: string;
  position: string;
  department: string;
  photoUrl: string;
}

const EmployeeDashboard: React.FC = () => {
  const [isAuthenticated, setIsAuthenticated] = useState(false);
  const [employeeData, setEmployeeData] = useState(null);

  const handleSuccessfulAuth = (data: EmployeeData) => {
    setIsAuthenticated(true);
    setEmployeeData(data);
  };

  const mockAttendanceData = [
    { date: '2024-07-14', timeIn: '09:00 AM', timeOut: '05:30 PM' },
    { date: '2024-07-13', timeIn: '08:55 AM', timeOut: '05:25 PM' },
    { date: '2024-07-12', timeIn: '09:05 AM', timeOut: '05:35 PM' },
  ];

  return (
    
{!isAuthenticated ? ( ) : ( Employee Profile

{employeeData?.name}

{employeeData?.position}

{employeeData?.department}
Quick Actions Attendance RecordsDateTime InTime Out {mockAttendanceData.map((record, index) => ( {record.date}{record.timeIn}{record.timeOut} ))}
> )}
); }; export default EmployeeDashboard;

Step 3: Bringing It All Together

Finally, let's update our main page to show off our hard work. Update app/page.tsx:

import EmployeeDashboard from './components/EmployeeDashboard';

export default function Home() {
  return (
    
); }

Now, let's set up the layout that'll wrap our entire app. Add this code: app/layout.tsx

import './globals.css'
import type { Metadata } from 'next'
import { Inter } from 'next/font/google'

const inter = Inter({ subsets: ['latin'] })

export const metadata: Metadata = {
  title: 'Employee Dashboard with Facial Authentication',
  description: 'A cutting-edge employee dashboard featuring facial recognition for secure authentication and efficient workplace management.',
}

export default function RootLayout({
  children,
}: {
  children: React.ReactNode
}) {
  return (
    
      
        

Faceio Solutions

{children}

© 2024 Faceio . All rights reserved.

) }

This layout is like the frame of a house - it provides structure for your entire app. It includes a header with your company name, a main content area where your dashboard will appear, and a footer. Plus, it sets up some SEO magic with metadata!

Key Privacy and Security Practices for FACEIO Integration

Privacy by Design

  • Use access controls, user consent, and opt-out options to protect privacy.

Meaningful Consent

  • Ensure users are aware of data collection.
  • Offer freedom of choice and control over their data.
  • Allow revocation of consent and data deletion anytime.

Best Practices

  • Obtain clear and appropriate consent, especially for minors.
  • Make consent requests easy to find and understand.
  • Avoid auto-enrollment and unauthorized enrollments.
  • Notify users before collecting biometric data.
  • Follow legal data privacy requirements.

Data Security

  • Delete user data upon account deletion.
  • Maintain strong data retention and disposal practices.
  • Implement and review security safeguards regularly.

For more details, refer to FACEIO Best Practices.

Key Security Considerations for FACEIO Integration

Security by Design

  • Application security is essential to preserve user trust.
  • Follow FACEIO's security best practices to mitigate risks.

Core Security Features

  1. Reject Weak PINs

    • Prevent weak PINs like 0000 or 1234.
    • Default: No.
  2. Prevent Duplicate Enrollments

    • Stops users from enrolling multiple times.
    • Default: No.
  3. Protect Against Deep-Fakes

    • Detects and blocks spoofing attempts.
    • Default: No.
  4. Forbid Minor Enrollments

    • Blocks users under 18 from enrolling.
    • Default: No.
  5. Require PIN for Authentication

    • Requires PIN code for each authentication.
    • Default: Yes.
  6. Enforce Unique PINs

    • Ensures each user's PIN is unique.
    • Default: No.
  7. Ignore Obscured Faces

    • Discards faces under poor lighting or partially masked.
    • Default: Yes.
  8. Reject Missing Headers

    • Blocks instantiation without proper HTTP headers.
    • Default: Yes.
  9. Restrict Instantiation

    • Limits to specific domains and countries.
    • Default: No.
  10. Enable Webhooks

    • Notifies your backend of FACEIO events.
    • Default: No.

For more details, refer to FACEIO Security Best Practices.

Real-World Applications: Where Can You Use This?

Now that we've built this awesome dashboard, you might be wondering, "Where can I use this in the real world?" Well, let me tell you, the possibilities are endless! Here are just a few ideas:

  1. Office Management: Say goodbye to old-school punch cards! This system can revolutionize how you track attendance, control access to different areas of your office, and manage employee information.

  2. Security Systems: Imagine a world where your office is Fort Knox, but without the hassle. This facial recognition system can be the cornerstone of a robust security protocol.

  3. Customer Service Kiosks: Picture this - a customer walks up to a kiosk, it recognizes them instantly, and provides personalized service. It's not science fiction anymore!

What's Next? The Sky's the Limit!

Congratulations, tech wizard! You've just built a cutting-edge employee dashboard with facial authentication. But why stop here? The beauty of this system is its flexibility. Here are some ideas to take it to the next level:

  • Implement real-time notifications for important updates
  • Add detailed reporting features for HR
  • Integrate with other systems like payroll or project management tools

Remember, in the world of tech, the only limit is your imagination (and maybe your caffeine intake).

So, what do you think? Are you ready to bring your workplace into the future? Give this project a try and let me know how it goes. I'd love to hear about your experiences, any cool features you add, or any challenges you face along the way.

Happy coding, and may your facial recognition never mistake you for your office plant!

版本聲明 本文轉載於:https://dev.to/vyan/building-a-secure-employee-dashboard-with-facial-authentication-a-comprehensive-nextjs-tutorial-2c4g?1如有侵犯,請聯絡study_golang@163 .com刪除
最新教學 更多>
  • 何時將成功回呼函數與 jQuery Ajax 呼叫分離?
    何時將成功回呼函數與 jQuery Ajax 呼叫分離?
    從jQuery Ajax 呼叫解耦成功回調函數使用jQuery ajax 從伺服器檢索資料時,通常的做法是定義成功.ajax () 區塊中的回呼函數。這將回調處理與 AJAX 呼叫緊密結合在一起,限制了靈活性和可重複使用性。 要在 .ajax() 區塊之外定義成功回調,通常需要宣告一個用於儲存返回資...
    程式設計 發佈於2024-11-03
  • 極簡設計初學者指南
    極簡設計初學者指南
    我一直是乾淨和簡單的倡導者——這是我的思維最清晰的方式。然而,就像生活中的大多數任務一樣,不同的工作有不同的工具,設計也是如此。在這篇文章中,我將分享我發現的極簡設計實踐,這些實踐有助於創建乾淨簡單的網站、模板和圖形——在有限的空間內傳達必要的內容。 簡單可能比複雜更難:你必須努力讓你的思維清晰,...
    程式設計 發佈於2024-11-03
  • 了解 React 應用程式中的渲染和重新渲染:它們如何運作以及如何優化它們
    了解 React 應用程式中的渲染和重新渲染:它們如何運作以及如何優化它們
    当我们在 React 中创建应用程序时,我们经常会遇到术语渲染和重新渲染组件。虽然乍一看这似乎很简单,但当涉及不同的状态管理系统(如 useState、Redux)或当我们插入生命周期钩子(如 useEffect)时,事情会变得有趣。如果您希望您的应用程序快速高效,那么了解这些流程是关键。 ...
    程式設計 發佈於2024-11-03
  • 如何在 Node.js 中將 JSON 檔案讀入伺服器記憶體?
    如何在 Node.js 中將 JSON 檔案讀入伺服器記憶體?
    在Node.js 中將JSON 檔案讀入伺服器記憶體為了增強伺服器端程式碼效能,您可能需要讀取JSON 對象從文件到記憶體以便快速存取。以下是在Node.js 中實現此目的的方法:同步方法:對於同步檔案讀取,請利用fs(檔案系統)中的readFileSync () 方法模組。此方法將檔案內容作為字串...
    程式設計 發佈於2024-11-03
  • 人工智慧可以提供幫助
    人工智慧可以提供幫助
    我剛剛意識到人工智慧對開發人員有很大幫助。它不會很快接管我們的工作,因為它仍然很愚蠢,但是,如果你像我一樣正在學習編程,可以用作一個很好的工具。 我要求 ChatGpt 為我準備 50 個項目來幫助我掌握 JavaScript,它帶來了令人驚嘆的項目,我相信當我完成這些項目時,這些項目將使我成為 ...
    程式設計 發佈於2024-11-03
  • Shadcn UI 套件 - 管理儀表板和網站模板
    Shadcn UI 套件 - 管理儀表板和網站模板
    Shadcn UI 套件是預先設計的多功能儀表板、網站範本和元件的綜合集合。它超越了 Shadcn 的標準產品,為那些不僅僅需要基礎知識的人提供更先進的設計和功能。 獨特的儀表板模板 Shadcn UI Kit 提供了各種精心製作的儀表板模板。目前,有 7 個儀表板模板可用,隨著時...
    程式設計 發佈於2024-11-03
  • 如何使用正規表示式捕獲多行文字區塊?
    如何使用正規表示式捕獲多行文字區塊?
    符合多行文字區塊的正規表示式符合跨多行的文字可能會為正規表示式建構帶來挑戰。考慮以下範例文本:some Varying TEXT DSJFKDAFJKDAFJDSAKFJADSFLKDLAFKDSAF [more of the above, ending with a newline] [yep, ...
    程式設計 發佈於2024-11-03
  • 軟體開發中結構良好的日誌的力量
    軟體開發中結構良好的日誌的力量
    日誌是了解應用程式底層發生的情況的關鍵。 簡單地使用 console.log 列印所有值並不是最有效的日誌記錄方法。日誌的用途不僅僅是顯示數據,它們還可以幫助您診斷問題、追蹤系統行為以及了解與外部 API 或服務的交互作用。在您的應用程式在沒有使用者介面的情況下運行的情況下,例如在系統之間處理和傳...
    程式設計 發佈於2024-11-03
  • 如何在單一命令列命令中執行多行Python語句?
    如何在單一命令列命令中執行多行Python語句?
    在單一命令列指令中執行多行Python語句Python -c 選項允許單行循環執行,但在指令中匯入模組可能會導致語法錯誤。要解決此問題,請考慮以下解決方案:使用Echo 和管道:echo -e "import sys\nfor r in range(10): print 'rob'&quo...
    程式設計 發佈於2024-11-03
  • 尋找數組/列表中的重複元素
    尋找數組/列表中的重複元素
    給定一個整數數組,找到所有重複的元素。 例子: 輸入:[1,2,3,4,3,2,5] 輸出:[2, 3] 暗示: 您可以使用 HashSet 來追蹤您已經看到的元素。如果某個元素已在集合中,則它是重複的。為了保留順序,請使用 LinkedHashSet 來儲存重複項。 使用 HashSet 的 ...
    程式設計 發佈於2024-11-03
  • JavaScript 回呼何時異步?
    JavaScript 回呼何時異步?
    JavaScript 回呼:是否非同步? JavaScript 回呼並非普遍非同步。在某些場景下,例如您提供的 addOne 和 simpleMap 函數的範例,程式碼會同步執行。 瀏覽器中的非同步 JavaScript基於回呼的 AJAX 函數jQuery 中通常是異步的,因為它們涉及 XHR (...
    程式設計 發佈於2024-11-03
  • 以下是根據您提供的文章內容產生的英文問答類標題:

Why does `char` behave differently from integer types in template instantiation when comparing `char`, `signed char`, and `unsigned char`?
    以下是根據您提供的文章內容產生的英文問答類標題: Why does `char` behave differently from integer types in template instantiation when comparing `char`, `signed char`, and `unsigned char`?
    char、signed char 和unsigned char 之間的行為差異下面的程式碼可以成功編譯,但char 的行為與整數類型不同。 cout << getIsTrue< isX<int8>::ikIsX >() << endl; cout ...
    程式設計 發佈於2024-11-03
  • 如何在動態產生的下拉方塊中設定預設選擇?
    如何在動態產生的下拉方塊中設定預設選擇?
    確定下拉框中選定的項目使用 標籤建立下拉清單時,您可以可能會遇到需要將特定選項設定為預設選擇的情況。這在預先填寫表單或允許使用者編輯其設定時特別有用。 在您呈現的場景中, 標籤是使用 PHP 動態產生的,並且您希望根據值儲存在資料庫中。實現此目的的方法如下:設定選定的屬性要在下拉方塊中設定選定的項目...
    程式設計 發佈於2024-11-03
  • Tailwind CSS:自訂配置
    Tailwind CSS:自訂配置
    介紹 Tailwind CSS 是一種流行的開源 CSS 框架,近年來在 Web 開發人員中廣受歡迎。它提供了一種獨特的可自訂方法來創建美觀且現代的用戶介面。 Tailwind CSS 有別於其他 CSS 框架的關鍵功能之一是它的可定製配置。在這篇文章中,我們將討論 Tailwin...
    程式設計 發佈於2024-11-03
  • 使用 jQuery
    使用 jQuery
    什麼是 jQuery? jQuery 是一個快速的 Javascript 函式庫,其功能齊全,旨在簡化 HTML 文件遍歷、操作、事件處理和動畫等任務。 「少寫多做」 MDN 狀態: jQuery使得編寫多行程式碼和tsk變得更加簡潔,甚至一行程式碼.. 使用 jQuery 處理事件 jQuery...
    程式設計 發佈於2024-11-03

免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。

Copyright© 2022 湘ICP备2022001581号-3