Secure the Admin Page

The admin page needs to be secured from unauthorized access. Let's work on securing it.

Securing the admin page

Click Run to open the services/web/src/routes/admin/index.svelte page and add the following <script>:

<script>
  import { goto } from '@sapper/app';
  import { onMount } from "svelte";
  import { currentUser } from "../../stores/user";

  onMount(() => {
    // Checking if user not already logged in using the value from the store.
    if (!$currentUser) {
      goto("/auth/login")
    }
  });
</script>

Below, we can now wrap all content in an if-statement to make sure it is only available to authenticated users.

{#if $currentUser}
  <h1>Admin dashboard</h1>
  <p>Only authenticated users have access to this.</p>
{/if}

Click Run again to save the file.

Now, if you try to access /admin when you are signed out, you will get redirected to the login page.

Get hands-on with 1400+ tech skills courses.