aboutsummaryrefslogtreecommitdiff
path: root/frontend/src/routes/login/+page.server.js
blob: a0e9f7f9af288d0e1c521878adcc6b379de69167 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
import { redirect } from '@sveltejs/kit';
import { building } from '$app/environment';

const API_BASE = building ? 'http://localhost:8080/api' : '/api';

export async function load({ cookies }) {
	const token = cookies.get('auth_token');
	if (token) {
		const res = await fetch(`${API_BASE}/auth/verify`, {
			headers: { Authorization: `Bearer ${token}` }
		});
		if (res.ok) {
			throw redirect(302, '/admin');
		}
	}
	return {};
}

export const actions = {
	default: async ({ request, cookies }) => {
		const data = await request.formData();
		const username = data.get('username');
		const password = data.get('password');

		if (!username || !password) {
			return { error: 'Preencha todos os campos' };
		}

		const res = await fetch(`${API_BASE}/auth/login`, {
			method: 'POST',
			headers: { 'Content-Type': 'application/json' },
			body: JSON.stringify({ username, password })
		});

		if (!res.ok) {
			const err = await res.json().catch(() => ({}));
			return { error: err.error || 'Credenciais inválidas' };
		}

		const { token } = await res.json();

		cookies.set('auth_token', token, {
			httpOnly: true,
			secure: process.env.NODE_ENV === 'production',
			sameSite: 'lax',
			path: '/',
			maxAge: 7 * 24 * 60 * 60
		});

		throw redirect(302, '/admin');
	}
};