>  기사  >  웹 프론트엔드  >  얼굴 인증으로 안전한 직원 대시보드 구축: 종합적인 Next.js 튜토리얼

얼굴 인증으로 안전한 직원 대시보드 구축: 종합적인 Next.js 튜토리얼

WBOY
WBOY원래의
2024-07-18 18:16:41620검색

직장 관리를 혁신할 준비가 되셨나요? 이 포괄적인 튜토리얼에서는 얼굴 인증을 활용하는 최첨단 직원 대시보드를 만드는 방법을 자세히 살펴보겠습니다. 우리는 웹 개발에서 가장 인기 있는 도구 중 일부인 Next.js, FACEIO 및 Shadcn UI를 사용할 것입니다. 이 가이드를 마치면 직원들이 미래에 살고 있는 듯한 느낌을 줄 수 있는 세련되고 안전한 대시보드를 갖게 될 것입니다!

시작하기 전에 필요한 것

자세히 살펴보기 전에 모든 오리를 연속해서 확보했는지 확인하세요.

  • 컴퓨터에 Node.js가 설치되어 있습니다
  • npm 또는 Yarn(배를 띄우는 것 중 하나)

다 알아냈나요? 엄청난! 이동 중에도 이 쇼를 감상해 보세요.

Faceio Authentication

프로젝트 설정: 첫 번째 단계

1단계: Next.js 프로젝트 시작하기

먼저 Next.js 프로젝트를 만들어 보겠습니다. 터미널을 열고 다음 마법의 단어를 입력하세요:

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

몇 가지 질문을 받게 됩니다. 답변하는 방법은 다음과 같습니다.

  • 타입스크립트? 그렇죠!
  • ESLint? 물론이죠!
  • 테일윈드 CSS? 물론이죠!
  • src/디렉토리? 아냐, 우린 괜찮아.
  • 앱 라우터? 네, 부탁드립니다!
  • 기본 가져오기 별칭을 맞춤설정하시겠습니까? 이건 패스하겠습니다.

2단계: 도구 수집

이제 필요한 물품을 모두 챙기세요. 종속 항목을 설치하려면 다음 명령을 실행하세요.

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

3단계: 비밀 소스 설정

프로젝트 루트에 .env.local이라는 파일을 만듭니다. 여기에 비밀 FACEIO 앱 ID를 보관할 것입니다:

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

'your-super-secret-faceio-app-id'를 실제 FACEIO 애플리케이션 ID로 바꾸는 것을 잊지 마세요. 안전하게 보관하세요!

4단계: 파일 구조

프로젝트 구조는 다음과 같아야 합니다.

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

5단계: Tailwind CSS 다듬기

Tailwind를 새롭게 단장할 시간입니다. 다음과 같은 멋진 구성으로 tailwind.config.js 파일을 업데이트하세요.

/** @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")],
}

대시보드의 핵심 구축

1단계: FaceAuth 구성요소 제작

우리 쇼의 스타인 FaceAuth 구성 요소를 만들어 보겠습니다. 새 파일 app/comComponents/FaceAuth.tsx를 만들고 다음 코드를 붙여넣습니다.

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<FaceAuthProps> = ({ 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: 'employee@example.com',
            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 (
    <Card className="w-full max-w-md mx-auto">
      <CardHeader>
        <CardTitle>Facial Authentication</CardTitle>
      </CardHeader>
      <CardContent className="space-y-4">
        <Button id="enroll-btn" variant="outline" className="w-full">
          Enroll New Employee
        </Button>
        <Button id="auth-btn" variant="default" className="w-full">
          Authenticate
        </Button>
      </CardContent>
    </Card>
  );
};

export default FaceAuth;

2단계: EmployeeDashboard 구성 요소 구축

이제 직원들이 보게 될 대시보드를 만들어 보겠습니다. 앱/구성 요소/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<EmployeeData | null>(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 (
    <div className="space-y-6">
      {!isAuthenticated ? (
        <FaceAuth onSuccessfulAuth={handleSuccessfulAuth} />
      ) : (
        <>
          <Card>
            <CardHeader>
              <CardTitle>Employee Profile</CardTitle>
            </CardHeader>
            <CardContent className="flex items-center space-x-4">
              <Avatar className="h-20 w-20" src={employeeData?.photoUrl} alt={employeeData?.name} />
              <div>
                <h2 className="text-2xl font-bold">{employeeData?.name}</h2>
                <p className="text-gray-500">{employeeData?.position}</p>
                <Badge variant="outline">{employeeData?.department}</Badge>
              </div>
            </CardContent>
          </Card>

          <Card>
            <CardHeader>
              <CardTitle>Quick Actions</CardTitle>
            </CardHeader>
            <CardContent className="space-y-4">
              <Button className="w-full">Check-in</Button>
              <Button className="w-full" variant="secondary">Request Leave</Button>
            </CardContent>
          </Card>

          <Card>
            <CardHeader>
              <CardTitle>Attendance Records</CardTitle>
            </CardHeader>
            <CardContent>
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>Date</TableHead>
                    <TableHead>Time In</TableHead>
                    <TableHead>Time Out</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {mockAttendanceData.map((record, index) => (
                    <TableRow key={index}>
                      <TableCell>{record.date}</TableCell>
                      <TableCell>{record.timeIn}</TableCell>
                      <TableCell>{record.timeOut}</TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            </CardContent>
          </Card>
        </>
      )}
    </div>
  );
};

export default EmployeeDashboard;

3단계: 모든 것을 하나로 모으기

마지막으로 메인 페이지를 업데이트하여 우리의 노력을 보여드리겠습니다. app/page.tsx 업데이트:

import EmployeeDashboard from './components/EmployeeDashboard';

export default function Home() {
  return (
    <main className="flex min-h-screen flex-col items-center justify-center p-4">
      <EmployeeDashboard />
    </main>
  );
}

이제 전체 앱을 감싸는 레이아웃을 설정해 보겠습니다. 다음 코드를 추가하세요: 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 (
    <html lang="en">
      <body className={inter.className}>
        <header className="bg-primary text-white p-4">
          <h1 className="text-2xl font-bold">Faceio Solutions</h1>
        </header>
        <main className="container mx-auto p-4">
          {children}
        </main>
        <footer className="bg-gray-100 text-center p-4 mt-8">
          <p>&copy; 2024 Faceio . All rights reserved.</p>
        </footer>
      </body>
    </html>
  )
}

이 레이아웃은 집의 틀과 같아서 전체 앱에 구조를 제공합니다. 여기에는 회사 이름이 포함된 헤더, 대시보드가 ​​표시될 기본 콘텐츠 영역 및 바닥글이 포함됩니다. 게다가 메타데이터로 SEO 마법을 설정합니다!

FACEIO 통합을 위한 주요 개인 정보 보호 및 보안 관행

개인정보 보호 설계

  • 액세스 제어, 사용자 동의, 거부 옵션을 사용하여 개인정보를 보호하세요.

의미있는 동의

  • 사용자에게 데이터 수집에 대해 알리십시오.
  • 데이터에 대한 선택과 통제의 자유를 제공합니다.
  • 언제든지 동의 철회 및 데이터 삭제를 허용하세요.

모범 사례

  • 특히 미성년자의 경우 명확하고 적절한 동의를 얻으세요.
  • 동의 요청을 쉽게 찾고 이해할 수 있도록 하세요.
  • 자동 등록 및 승인되지 않은 등록을 피하세요.
  • 생체인식 데이터를 수집하기 전에 사용자에게 알립니다.
  • 법적 데이터 개인정보 보호 요구사항을 따르세요.

데이터 보안

  • 계정 삭제 시 사용자 데이터를 삭제하세요.
  • 강력한 데이터 보관 및 폐기 관행을 유지하세요.
  • 보안 조치를 정기적으로 구현하고 검토하세요.

자세한 내용은 FACEIO 모범 사례를 참조하세요.

FACEIO 통합을 위한 주요 보안 고려 사항

보안 설계

  • 사용자 신뢰를 유지하려면 애플리케이션 보안이 필수적입니다.
  • FACEIO의 보안 모범 사례를 따라 위험을 완화하세요.

핵심 보안 기능

  1. 취약한 PIN 거부

    • 0000이나 1234와 같은 취약한 PIN을 방지하세요.
    • 기본값: 아니요
  2. 중복등록 방지

    • 사용자가 여러 번 등록하는 것을 방지합니다.
    • 기본값: 아니요
  3. 딥 페이크로부터 보호

    • 스푸핑 시도를 탐지하고 차단합니다.
    • 기본값: 아니요
  4. 미성년자 등록 금지

    • 18세 미만 사용자의 등록을 차단합니다.
    • 기본값: 아니요
  5. 인증을 위해 PIN 필요

    • 인증할 때마다 PIN 코드가 필요합니다.
    • 기본값: 예.
  6. 고유 PIN 시행

    • 각 사용자의 PIN이 고유한지 확인합니다.
    • 기본값: 아니요
  7. 가려진 얼굴 무시

    • 어두운 조명이나 부분적으로 마스크를 쓴 얼굴은 폐기됩니다.
    • 기본값: 예.
  8. 누락된 헤더 거부

    • 적절한 HTTP 헤더 없이 인스턴스화를 차단합니다.
    • 기본값: 예.
  9. 인스턴스화 제한

    • 특정 도메인 및 국가로 제한됩니다.
    • 기본값: 아니요
  10. 웹훅 활성화

    • FACEIO 이벤트를 백엔드에 알립니다.
    • 기본값: 아니요

자세한 내용은 FACEIO 보안 모범 사례를 참조하세요.

실제 응용 프로그램: 이것을 어디에 사용할 수 있습니까?

이제 멋진 대시보드를 만들었으니 "이걸 실제로 어디에 사용할 수 있지?"라고 궁금해하실 것입니다. 글쎄요, 가능성은 무한합니다! 다음은 몇 가지 아이디어입니다.

  1. 사무실 관리: 기존의 펀치 카드와 작별하세요! 이 시스템은 출석을 추적하고, 사무실의 다양한 영역에 대한 접근을 제어하고, 직원 정보를 관리하는 방법을 혁신적으로 바꿀 수 있습니다.

  2. 보안 시스템: Fort Knox에 사무실이 있으면서도 번거로움이 없는 세상을 상상해 보세요. 이 얼굴 인식 시스템은 강력한 보안 프로토콜의 초석이 될 수 있습니다.

  3. 고객 서비스 키오스크: 고객이 키오스크에 다가가면 즉시 인식하고 맞춤형 서비스를 제공합니다. 더 이상 공상과학 소설이 아닙니다!

다음은 무엇입니까? 하늘이 한계다!

축하합니다, 기술 마법사님! 얼굴 인증 기능을 갖춘 최첨단 직원 대시보드를 구축하셨습니다. 그런데 왜 여기서 멈춰야 할까요? 이 시스템의 장점은 유연성입니다. 다음 단계로 나아가기 위한 몇 가지 아이디어는 다음과 같습니다.

  • 중요 업데이트에 대한 실시간 알림 구현
  • HR에 대한 세부 보고 기능 추가
  • 급여 또는 프로젝트 관리 도구와 같은 다른 시스템과 통합

기술 세계에서 유일한 한계는 상상력(그리고 카페인 섭취량)뿐이라는 점을 기억하세요.

그럼 어떻게 생각하시나요? 귀하의 업무 공간을 미래로 바꿀 준비가 되셨나요? 이 프로젝트를 시도해보고 어떻게 진행되는지 알려주세요. 귀하의 경험, 추가한 멋진 기능 또는 그 과정에서 직면한 어려움에 대해 듣고 싶습니다.

즐거운 코딩 되시기 바랍니다. 얼굴 인식 기능을 사무실 식물로 오해하지 않으시길 바랍니다!

위 내용은 얼굴 인증으로 안전한 직원 대시보드 구축: 종합적인 Next.js 튜토리얼의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.