Skip to main content
  1. Artikel-artikel/
  2. Framework Javascript/

Svelte Basic Auth Auth 4

·927 words·5 mins· loading · loading · ·
Development Js Framework Svelte Nodejs
Humaedi
Author
Humaedi
Halo, nama saya Humaedi 👋. Saya seorang CEO of Akaktekno.id & { full-stack developer } Bekerjalah seakan hidup abadi, beribadah seakan mau mati, jangan lupa☕️ untuk mendapat inspirasi.
svelte-basic-auth - This article is part of a series.
Part : This Article

Halo para seniman yang budiman! Selamat datang kembali! Pada bagian ini, kita akan membangun halaman frontend untuk fitur login, register, dan dashboard menggunakan TailwindCSS. Selain itu, kita akan menambahkan logika untuk memastikan halaman dashboard hanya dapat diakses setelah login, serta mencegah akses ke halaman login dan register jika pengguna sudah masuk.

1. Halaman Register
#

a. Membuat File +page.server.ts untuk Register
#

Buat file src/routes/register/+page.server.ts untuk menangani pengiriman form dari halaman register.

// src/routes/register/+page.server.ts
import { redirect } from '@sveltejs/kit';
import type { Actions } from './$types';

export const actions: Actions = {
  default: async ({ request, fetch }) => {
    const formData = await request.formData();
    const email = formData.get('email') as string;
    const password = formData.get('password') as string;
    const firstName = formData.get('firstName') as string;
    const lastName = formData.get('lastName') as string;

    // Kirim permintaan POST ke API register
    const response = await fetch('/api/register', {
      method: 'POST',
      body: JSON.stringify({ email, password, firstName, lastName }),
      headers: { 'Content-Type': 'application/json' }
    });

    if (response.ok) {
      // Jika berhasil register, redirect ke halaman login
      return redirect(302, '/login');
    } else {
      return {
        status: 400,
        errors: { message: 'Registration failed. Try again.' }
      };
    }
  }
};
b. Membuat Halaman +page.svelte untuk Register
#

Buat file src/routes/register/+page.svelte untuk halaman register dengan TailwindCSS.

<script>
  export let errors = {};
</script>

<form method="post" class="max-w-lg mx-auto mt-10 space-y-6">
  <div>
    <label for="firstName" class="block text-sm font-medium text-gray-700">First Name</label>
    <input type="text" name="firstName" id="firstName" required class="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm">
  </div>

  <div>
    <label for="lastName" class="block text-sm font-medium text-gray-700">Last Name</label>
    <input type="text" name="lastName" id="lastName" required class="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm">
  </div>

  <div>
    <label for="email" class="block text-sm font-medium text-gray-700">Email</label>
    <input type="email" name="email" id="email" required class="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm">
  </div>

  <div>
    <label for="password" class="block text-sm font-medium text-gray-700">Password</label>
    <input type="password" name="password" id="password" required class="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm">
  </div>

  {#if errors.message}
    <p class="text-red-500">{errors.message}</p>
  {/if}

  <button type="submit" class="w-full flex justify-center py-2 px-4 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500">
    Register
  </button>
</form>

2. Halaman Login
#

a. Membuat File +page.server.ts untuk Login
#

Buat file src/routes/login/+page.server.ts untuk menangani pengiriman form dari halaman login.

// src/routes/login/+page.server.ts
import { redirect } from '@sveltejs/kit';
import type { Actions } from './$types';

export const actions: Actions = {
  default: async ({ request, cookies, fetch }) => {
    const formData = await request.formData();
    const email = formData.get('email') as string;
    const password = formData.get('password') as string;

    // Kirim permintaan POST ke API login
    const response = await fetch('/api/login', {
      method: 'POST',
      body: JSON.stringify({ email, password }),
      headers: { 'Content-Type': 'application/json' }
    });

    if (response.ok) {
      // Jika berhasil login, set cookie sesi
      return redirect(302, '/dashboard');
    } else {
      return {
        status: 401,
        errors: { message: 'Login failed. Check your credentials.' }
      };
    }
  }
};
b. Membuat Halaman +page.svelte untuk Login
#

Buat file src/routes/login/+page.svelte untuk halaman login dengan menggunakan TailwindCSS untuk membuat tampilan yang menarik.

<script>
  export let errors = {};
</script>

<form method="post" class="max-w-lg mx-auto mt-10 space-y-6">
  <div>
    <label for="email" class="block text-sm font-medium text-gray-700">Email</label>
    <input type="email" name="email" id="email" required class="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm">
  </div>
  
  <div>
    <label for="password" class="block text-sm font-medium text-gray-700">Password</label>
    <input type="password" name="password" id="password" required class="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm">
  </div>

  {#if errors.message}
    <p class="text-red-500">{errors.message}</p>
  {/if}

  <button type="submit" class="w-full flex justify-center py-2 px-4 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500">
    Login
  </button>
</form>

3. Halaman Dashboard
#

a. Membuat File +page.server.ts untuk Dashboard
#

Buat file src/routes/dashboard/+page.server.ts untuk memeriksa apakah pengguna sudah login sebelum mengakses dashboard.

// src/routes/dashboard/+page.server.ts
import { redirect } from '@sveltejs/kit';
import type { PageServerLoad } from './$types';

export const load: PageServerLoad = async ({ cookies }) => {
  const session = cookies.get('session');

  if (!session) {
    // Redirect ke login jika tidak ada sesi
    throw redirect(302, '/login');
  }

  // Kembalikan data jika pengguna sudah login
  return { session };
};
b. Membuat Halaman +page.svelte untuk Dashboard
#

Buat file src/routes/dashboard/+page.svelte untuk halaman dashboard.

<script>
  export let session;
</script>

<div class="max-w-lg mx-auto mt-10 space-y-6">
  <h1 class="text-2xl font-semibold">Welcome to your Dashboard</h1>
  <p>You are logged in with session: {session}</p>

  <form method="post" action="/api/logout">
    <button type="submit" class="w-full flex justify-center py-2 px-4 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-red-600 hover:bg-red-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-red-500">
      Logout
    </button>
  </form>
</div>

4. Redirect Logika untuk Login dan Register
#

Untuk memastikan pengguna tidak dapat mengakses halaman login dan register jika sudah login, kita akan menambahkan logika redirect di file +page.server.ts di halaman login dan register.

a. Update File src/routes/login/+page.server.ts
#
// src/routes/login/+page.server.ts
import { redirect } from '@sveltejs/kit';
import type { PageServerLoad } from './$types';

export const load: PageServerLoad = async ({ cookies }) => {
  const session = cookies.get('session');

  if (session) {
    // Redirect ke dashboard jika pengguna sudah login
    throw redirect(302, '/dashboard');
  }
};
b. Update File src/routes/register/+page.server.ts
#
// src/routes/register/+page.server.ts
import { redirect

 } from '@sveltejs/kit';
import type { PageServerLoad } from './$types';

export const load: PageServerLoad = async ({ cookies }) => {
  const session = cookies.get('session');

  if (session) {
    // Redirect ke dashboard jika pengguna sudah login
    throw redirect(302, '/dashboard');
  }
};

Kesimpulan
#

  • Login & Register Pages: Dibuat menggunakan TailwindCSS untuk tampilan, dan setiap halaman mengirim data ke API untuk diproses.
  • Dashboard Page: Hanya bisa diakses ketika pengguna sudah login, dan menampilkan sesi pengguna yang aktif.
  • Redirection Logic: Jika pengguna sudah login, mereka otomatis diarahkan ke dashboard dan tidak bisa mengakses halaman login atau register.
svelte-basic-auth - This article is part of a series.
Part : This Article

Related

Svelte Basic Auth Auth 2
·858 words·5 mins· loading · loading
Development Js Framework Svelte Nodejs
Halo para seniman yang budiman!
Svelte Basic Auth Auth 1
·870 words·5 mins· loading · loading
Development Js Framework Svelte Nodejs
Halo para seniman yang budiman!
Svelte Basic Auth Auth 3
·951 words·5 mins· loading · loading
Development Js Framework Svelte Nodejs
Halo para seniman yang budiman!