add admin login page at /login

This commit is contained in:
Yisroel Baum 2026-05-17 10:40:03 +03:00
parent f0da523ae4
commit e8e7cf9ea9
Signed by: yisroelbaum
GPG key ID: 0FA60884F75520A9
7 changed files with 289 additions and 7 deletions

View file

@ -0,0 +1,40 @@
<?php
namespace App\Middleware;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Slim\Psr7\Response;
class CorsMiddleware implements MiddlewareInterface
{
private const ALLOWED_ORIGIN = 'http://localhost:5173';
public function process(
ServerRequestInterface $request,
RequestHandlerInterface $handler,
): ResponseInterface {
if ($request->getMethod() === 'OPTIONS') {
return $this->withCorsHeaders(new Response(204));
}
return $this->withCorsHeaders($handler->handle($request));
}
private function withCorsHeaders(ResponseInterface $response): ResponseInterface
{
return $response
->withHeader('Access-Control-Allow-Origin', self::ALLOWED_ORIGIN)
->withHeader('Access-Control-Allow-Credentials', 'true')
->withHeader(
'Access-Control-Allow-Headers',
'Content-Type, Authorization',
)
->withHeader(
'Access-Control-Allow-Methods',
'GET, POST, OPTIONS',
);
}
}

View file

@ -2,11 +2,14 @@
use App\Controllers\AuthController;
use App\Middleware\AuthMiddleware;
use App\Middleware\CorsMiddleware;
use Slim\App;
use Slim\Routing\RouteCollectorProxy;
return function (App $app): void {
$app->add(CorsMiddleware::class);
$app->get('/me', [AuthController::class, 'me'])
->add(AuthMiddleware::class);

View file

@ -0,0 +1 @@
VITE_API_BASE_URL=http://127.0.0.1:8000

View file

@ -27,13 +27,11 @@ describe('admin login page', () => {
cy.get('[data-cy="login-error"]').should('be.visible')
})
it('redirects to home on successful login', () => {
cy.visit('/login')
it('is not linked from any navigation element on the home page', () => {
cy.visit('/')
cy.get('[data-cy="login-email"]').type('admin@example.com')
cy.get('[data-cy="login-password"]').type('password123')
cy.get('[data-cy="login-submit"]').click()
cy.url().should('eq', Cypress.config().baseUrl + '/')
cy.get('header a').each(($link) => {
cy.wrap($link).should('not.have.attr', 'href', '/login')
})
})
})

View file

@ -1,5 +1,6 @@
import { createRouter, createWebHistory } from 'vue-router'
import HomePage from '@/views/HomePage.vue'
import LoginPage from '@/views/LoginPage.vue'
const router = createRouter({
history: createWebHistory(import.meta.env.BASE_URL),
@ -9,6 +10,11 @@ const router = createRouter({
name: 'home',
component: HomePage,
},
{
path: '/login',
name: 'login',
component: LoginPage,
},
],
})

View file

@ -0,0 +1,77 @@
import { ref, computed } from 'vue'
import { defineStore } from 'pinia'
interface User {
id: number
email: string
}
const API_BASE_URL = import.meta.env.VITE_API_BASE_URL as string
export const useAuthStore = defineStore('auth', () => {
const user = ref<User | null>(null)
const loginError = ref<string | null>(null)
const isSubmitting = ref(false)
const isAuthenticated = computed(() => user.value !== null)
async function login(email: string, password: string): Promise<boolean> {
loginError.value = null
isSubmitting.value = true
try {
const response = await fetch(`${API_BASE_URL}/login`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
credentials: 'include',
body: JSON.stringify({ email, password }),
})
if (!response.ok) {
const data: { error?: string } = await response.json()
loginError.value = data.error ?? 'Login failed'
return false
}
const data: { user: User } = await response.json()
user.value = data.user
return true
} catch {
loginError.value = 'Network error - could not reach server'
return false
} finally {
isSubmitting.value = false
}
}
async function fetchUser(): Promise<void> {
try {
const response = await fetch(`${API_BASE_URL}/me`, {
credentials: 'include',
})
if (!response.ok) {
user.value = null
return
}
const data: { user: User } = await response.json()
user.value = data.user
} catch {
user.value = null
}
}
async function logout(): Promise<void> {
try {
await fetch(`${API_BASE_URL}/logout`, {
method: 'POST',
credentials: 'include',
})
} finally {
user.value = null
}
}
return { user, loginError, isSubmitting, isAuthenticated, login, fetchUser, logout }
})

View file

@ -0,0 +1,157 @@
<script setup lang="ts">
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { useAuthStore } from '@/stores/auth'
const router = useRouter()
const authStore = useAuthStore()
const email = ref('')
const password = ref('')
async function handleSubmit(): Promise<void> {
const success = await authStore.login(email.value, password.value)
if (success) {
router.push('/')
}
}
</script>
<template>
<div class="login-page">
<div class="login-card">
<h1 class="login-card__title">Admin Login</h1>
<form class="login-card__form" @submit.prevent="handleSubmit">
<label class="login-card__field">
<span class="login-card__label">Email</span>
<input
v-model="email"
data-cy="login-email"
type="email"
class="login-card__input"
autocomplete="email"
/>
</label>
<label class="login-card__field">
<span class="login-card__label">Password</span>
<input
v-model="password"
data-cy="login-password"
type="password"
class="login-card__input"
autocomplete="current-password"
/>
</label>
<p v-if="authStore.loginError" data-cy="login-error" class="login-card__error">
{{ authStore.loginError }}
</p>
<button
data-cy="login-submit"
type="submit"
class="login-card__submit"
:disabled="authStore.isSubmitting"
>
{{ authStore.isSubmitting ? 'Signing in...' : 'Sign In' }}
</button>
</form>
</div>
</div>
</template>
<style scoped>
.login-page {
display: flex;
align-items: center;
justify-content: center;
min-height: 100vh;
background: var(--color-cream);
padding: 1rem;
}
.login-card {
background: var(--color-white);
border: 1px solid var(--color-border);
border-radius: 8px;
padding: 2.5rem;
width: 100%;
max-width: 400px;
}
.login-card__title {
font-family: var(--font-serif);
font-size: 1.5rem;
color: var(--color-slate);
text-align: center;
margin: 0 0 1.5rem;
}
.login-card__form {
display: flex;
flex-direction: column;
gap: 1rem;
}
.login-card__field {
display: flex;
flex-direction: column;
gap: 0.25rem;
}
.login-card__label {
font-size: 0.875rem;
color: var(--color-text-muted);
}
.login-card__input {
padding: 0.625rem 0.75rem;
border: 1px solid var(--color-border);
border-radius: 4px;
font-family: var(--font-sans);
font-size: 0.9375rem;
color: var(--color-text);
background: var(--color-white);
outline: none;
transition: border-color 0.15s ease;
}
.login-card__input:focus {
border-color: var(--color-olive);
}
.login-card__error {
font-size: 0.875rem;
color: #b33;
margin: 0;
padding: 0.5rem 0.75rem;
background: #fef2f2;
border: 1px solid #fecaca;
border-radius: 4px;
}
.login-card__submit {
padding: 0.75rem 1rem;
background: var(--color-olive);
color: var(--color-white);
font-family: var(--font-sans);
font-size: 0.9375rem;
font-weight: 500;
border: none;
border-radius: 4px;
cursor: pointer;
transition: background 0.15s ease;
margin-top: 0.5rem;
}
.login-card__submit:hover:not(:disabled) {
background: var(--color-slate);
}
.login-card__submit:disabled {
opacity: 0.6;
cursor: not-allowed;
}
</style>