IT Issue Bootcamp

Day 5 / ชั่วโมงที่ 2

Login และป้องกันส่วนที่ต้องมีผู้ใช้

Login และ Logout ด้วย Server Action, บังคับ Login ก่อนใช้งาน และเมนูตามสถานะ Login

60 นาที
Login แล้วเปิดหน้าที่ต้องมีผู้ใช้ได้
สไลด์ในชั่วโมงนี้ (14)
  1. 1ต่อจาก Hour 1
  2. 2เตรียมบัญชีสำหรับทดลอง
  3. 3เพิ่ม Action สำหรับ Login
  4. 4สร้างหน้า /login
  5. 5เพิ่มฟอร์มและช่องอีเมล
  6. 6เพิ่มช่องรหัสผ่านและปุ่ม
  7. 7สร้าง Helper อ่านผู้ใช้
  8. 8บังคับ Login ก่อนเปิดหน้าแจ้งปัญหา
  9. 9บังคับ Login ก่อนบันทึกข้อมูล
  10. 10เพิ่ม Action สำหรับ Logout
  11. 11สร้างเมนูที่รู้สถานะ Login
  12. 12แสดงลิงก์ตามสถานะ Login
  13. 13ใช้เมนูใหม่ในทุกหน้า
  14. 14ทดสอบ Login และ Logout

เป้าหมายของชั่วโมงนี้

หลังจบชั่วโมงนี้ นักศึกษาจะสามารถ:

  1. สร้าง Login และ Logout ด้วย Server Action
  2. อ่านผู้ใช้ปัจจุบันจาก Session
  3. บังคับให้ Login ก่อนเปิดหน้าและก่อนบันทึกข้อมูล
  4. แสดงเมนูตามสถานะ Login

ไฟล์ที่ใช้

app/actions.ts             ← แก้ไข
app/login/page.tsx         ← สร้างใหม่
lib/auth.ts                ← สร้างใหม่
app/issues/new/page.tsx    ← แก้ไข
components/AppNav.tsx      ← สร้างใหม่
app/layout.tsx             ← แก้ไข

Slide 1: ต่อจาก Hour 1

ตอนนี้ Server Client และ Proxy อ่านและต่ออายุ Session ใน Cookie ได้แล้ว

ปัญหา: ยังไม่มีหน้า Login ผู้ใช้จึงเข้าสู่ระบบไม่ได้

ชั่วโมงนี้: สร้าง Login และ Logout ให้ครบตามลำดับนี้

Login → Supabase ตรวจบัญชี → เก็บ Session → ใช้งาน → Logout

รหัสผ่านถูกส่งไปตรวจที่ Server Action และไม่ถูกเก็บใน State หรือ Table ของ Project


Slide 2: เตรียมบัญชีสำหรับทดลอง

  • ตั้งรหัสผ่านที่จำได้สำหรับทดลอง
  • เปิด Auto Confirm User เพื่อให้ Login ได้ทันทีโดยไม่ต้องยืนยันอีเมล

ระบบแจ้งปัญหาเป็นระบบภายในองค์กร ผู้ดูแลจึงสร้างบัญชีให้ ไม่เปิดให้คนทั่วไปสมัครเอง

ตอนนี้ทั้งสองบัญชีใช้งานได้เหมือนกัน Hour 3 จะกำหนดให้ admin@example.com เป็น ADMIN


Slide 3: เพิ่ม Action สำหรับ Login

import { createClient } from "@/lib/supabase/server";
export async function signInAction(formData: FormData) {  const email = String(formData.get("email") ?? "").trim();  const password = String(formData.get("password") ?? "");  const supabase = await createClient();  const { error } = await supabase.auth.signInWithPassword({ email, password });  if (error) redirect("/login?error=1");  revalidatePath("/", "layout");  redirect("/issues");}

signInWithPassword ให้ Supabase ตรวจบัญชีแล้วเก็บ Session ใน Cookie ส่วน revalidatePath("/", "layout") ให้เมนูอ่านสถานะ Login ใหม่


Slide 4: สร้างหน้า /login

type LoginPageProps = {  searchParams: Promise<{ error?: string }>;}; export default async function LoginPage({ searchParams }: LoginPageProps) {  const { error } = await searchParams;  return (    <main className="mx-auto max-w-md px-6 py-12">      <h1 className="text-2xl font-bold text-slate-950">เข้าสู่ระบบ</h1>      {error && <p className="mt-4 text-sm font-medium text-red-700">อีเมลหรือรหัสผ่านไม่ถูกต้อง</p>}      {/* ฟอร์มเข้าสู่ระบบในขั้นถัดไป */}    </main>  );}

searchParams คือค่าหลังเครื่องหมาย ? ใน URL ถ้า Login ไม่ผ่าน Action จะพามาที่ /login?error=1 หน้าจึงแสดงข้อความแจ้ง


Slide 5: เพิ่มฟอร์มและช่องอีเมล

import { signInAction } from "@/app/actions";
<form action={signInAction} className="mt-6 grid gap-4">  <label className="grid gap-2 text-sm font-semibold text-slate-800">    อีเมล    <input      name="email" type="email" required      className="rounded-md border border-slate-300 px-3 py-2"    />  </label>  {/* ช่องรหัสผ่านและปุ่มในขั้นถัดไป */}</form>

<label> ที่ครอบช่องกรอกไว้ข้างใน เชื่อมกับช่องนั้นเองโดยไม่ต้องใช้ htmlFor


Slide 6: เพิ่มช่องรหัสผ่านและปุ่ม

<label className="grid gap-2 text-sm font-semibold text-slate-800">  รหัสผ่าน  <input    name="password" type="password" required    className="rounded-md border border-slate-300 px-3 py-2"  /></label><button  className="rounded-md bg-teal-700 px-4 py-3 font-bold text-white hover:bg-teal-800">  เข้าสู่ระบบ</button>

type="password" ซ่อนตัวอักษรที่พิมพ์ เปิด /login แล้วควรเห็นช่องอีเมล รหัสผ่าน และปุ่มเข้าสู่ระบบ


Slide 7: สร้าง Helper อ่านผู้ใช้

import { redirect } from "next/navigation";import { createClient } from "@/lib/supabase/server"; export async function getCurrentUser() {  const supabase = await createClient();  const { data } = await supabase.auth.getUser();  return data.user;} export async function requireUser() {  const user = await getCurrentUser();  if (!user) redirect("/login");  return user;}

getCurrentUser คืนผู้ใช้หรือ null ส่วน requireUser พาไป /login ถ้ายังไม่ Login


Slide 8: บังคับ Login ก่อนเปิดหน้าแจ้งปัญหา

import { IssueForm } from "@/components/IssueForm";import { requireUser } from "@/lib/auth"; export default function NewIssuePage() {export default async function NewIssuePage() {  await requireUser();   // return เดิม}

เปิด /issues/new ตอนยังไม่ Login จะถูกพาไป /login


Slide 9: บังคับ Login ก่อนบันทึกข้อมูล

import { requireUser } from "@/lib/auth";// Import และ Function อื่นเดิม export async function createIssueAction(formData: FormData) {  await requireUser();  const input = parseIssueInput(formData);  // ...โค้ดเดิม}

ป้องกันหน้าอย่างเดียวไม่พอ เพราะคนอื่นส่งคำขอตรงไปที่ Server Action ได้โดยไม่เปิดหน้า

ป้องกันหน้า   → กันการเปิดฟอร์มผ่าน URL
ป้องกัน Action → กันการส่งข้อมูลตรงมาที่ Server

Slide 10: เพิ่ม Action สำหรับ Logout

export async function signOutAction() {  const supabase = await createClient();  await supabase.auth.signOut();  revalidatePath("/", "layout");  redirect("/login");}

signOut ลบ Session ปัจจุบัน แล้วพากลับหน้า Login


Slide 11: สร้างเมนูที่รู้สถานะ Login

import Link from "next/link";import { signOutAction } from "@/app/actions";import { getCurrentUser } from "@/lib/auth"; export async function AppNav() {  const user = await getCurrentUser();  return (    <nav className="border-b border-slate-200 bg-white" aria-label="เมนูหลัก">      <div className="mx-auto flex max-w-5xl flex-wrap items-center gap-2 px-6 py-3">        {/* ลิงก์ตามสถานะ Login ในขั้นถัดไป */}      </div>    </nav>  );}

กรอบเมนูใช้ Class เดียวกับเมนูที่ทำใน Day 3 ส่วน getCurrentUser บอกว่าตอนนี้มีใคร Login อยู่หรือไม่


Slide 12: แสดงลิงก์ตามสถานะ Login

const linkClass = "rounded-md px-3 py-2 font-semibold text-slate-700 hover:bg-slate-100";
<Link className={linkClass} href="/issues">รายการปัญหา</Link>{user ? (  <>    <Link className={linkClass} href="/issues/new">แจ้งปัญหาใหม่</Link>    <span className="ml-auto text-sm text-slate-600">{user.email}</span>    <form action={signOutAction}>      <button className="rounded-md px-3 py-2 font-semibold text-teal-700">ออกจากระบบ</button>    </form>  </>) : (  <Link className={linkClass} href="/login">เข้าสู่ระบบ</Link>)}

Slide 13: ใช้เมนูใหม่ในทุกหน้า

import Link from "next/link";import { AppNav } from "@/components/AppNav"; <nav className="border-b border-slate-200 bg-white" aria-label="เมนูหลัก">  {/* เมนูเดิมทั้งชุด */}</nav><AppNav />{children}

ลบ Import Link เพราะ Layout ไม่ได้สร้างลิงก์เองแล้ว ส่วน <html>, <body> และ {children} ให้เก็บไว้

ห้ามเรียก requireUser ใน Layout เพราะหน้า /login ก็ใช้ Layout นี้ จะทำให้เปิดหน้า Login ไม่ได้


Slide 14: ทดสอบ Login และ Logout

  1. เปิด /issues/new ตอนยังไม่ Login: ถูกพาไป /login
  2. ใส่รหัสผ่านผิด: เห็นข้อความ "อีเมลหรือรหัสผ่านไม่ถูกต้อง"
  3. Login ด้วย user@example.com: ไป /issues และเมนูแสดงอีเมล
  4. แจ้งปัญหาใหม่: บันทึกได้
  5. กด ออกจากระบบ: กลับ /login และเปิด /issues/new ไม่ได้อีก

ถ้า Login แล้วเมนูไม่เปลี่ยน ให้ตรวจ revalidatePath("/", "layout") ใน signInAction

Hour 3 จะแบ่งสิทธิ์ USER และ ADMIN ให้ Database ตรวจจริง


อ้างอิง