Pular para o conteúdo

Auth JS Helper

The auth helper at site/public/static/js/auth.js provides a simple promise-based API for interacting with the auth worker.

API Reference

auth.register(credentials)

Create a new account.

await auth.register({ email: 'user@example.com', password: 'secret123', name: 'João' });

auth.login(credentials)

Authenticate and set the session cookie.

await auth.login({ email: 'user@example.com', password: 'secret123' });

auth.getMe()

Get the current authenticated user.

const { user } = await auth.getMe();
console.log(user.name, user.email);

auth.logout()

Destroy the session.

await auth.logout();

Usage Example

<script src="/static/js/auth.js"></script>
<script>
document.getElementById('login-form').addEventListener('submit', async (e) => {
e.preventDefault();
const email = document.getElementById('email').value;
const password = document.getElementById('password').value;
try {
await auth.login({ email, password });
window.location.href = '/conta/';
} catch (err) {
alert('Login failed: ' + err.message);
}
});
</script>

How It Works

The helper is a thin wrapper around fetch() that:

  • Sets credentials: 'include' so cookies are sent
  • Handles JSON request/response bodies
  • Throws on non-2xx status codes
  • Provides convenient methods for each auth endpoint