Una guarda que redirige
Traducción automática
Esta página se tradujo automáticamente del inglés y todavía no la revisó un hablante nativo; las correcciones son bienvenidas en GitHub. Si algo no coincide, vale el original en inglés.
Tarea: enviar a los visitantes sin sesión a la página de inicio de sesión con un mensaje, y asegurarse de que tampoco puedan enviar datos a las acciones de la página.
# Recipe: a guard -- a top-level q:if with q:redirect -- protects the page and
# its actions.
paths:
components: ./components
migrations: ./migrations
datasources:
db:
driver: sqlite
database: ./data/notes.db2
3
4
5
6
7
8
9
10
CREATE TABLE notes (
id INTEGER PRIMARY KEY AUTOINCREMENT,
author TEXT NOT NULL,
body TEXT NOT NULL
);2
3
4
5
Un q:if al principio de la página cuya rama tiene un q:redirect es una guarda. Se ejecuta antes de la página y antes de cada una de sus acciones, así que un envío mandado directamente a add también se detiene:
<q:component name="Notes">
<!-- The guard: it runs before the page AND before each of its actions. -->
<q:if condition="not session.authenticated">
<q:redirect url="/login" flash="Sign in to write notes." />
</q:if>
<q:action name="add" method="POST">
<q:param name="body" required="true" minlength="2" />
<q:query name="added" datasource="db">
INSERT INTO notes (author, body) VALUES (:author, :body)
<q:param name="author" value="{session.userName}" type="string" />
<q:param name="body" value="{body}" type="string" />
</q:query>
<q:redirect url="/" flash="Saved." />
</q:action>
<q:query name="notes" datasource="db">
SELECT author, body FROM notes ORDER BY id DESC
</q:query>
<h1>Notes</h1>
<q:if condition="flash"><p>{flash}</p></q:if>
<form method="POST"><input name="body" /><button>Add</button></form>
<q:loop query="notes"><p>{notes.author}: {notes.body}</p></q:loop>
</q:component>2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<q:component name="Login">
<q:if condition="flash"><p>{flash}</p></q:if>
<h1>Sign in</h1>
</q:component>2
3
4
La segunda prueba envía datos a la acción sin sesión y verifica que no se escribió ninguna fila:
<q:test name="the guard sends a visitor to sign in" page="/">
<test:visit />
<test:expect status="302" redirect="/login" />
<test:expect text="Sign in to write notes." />
</q:test>
<q:test name="the guard also stops the action: nothing is written" page="/">
<test:submit action="add" body="Sneaky note" />
<test:expect status="302" redirect="/login" />
<test:expect table="notes" count="0" />
</q:test>
<q:test name="a signed-in user writes a note" page="/">
<test:as user="ana" role="member" />
<test:submit action="add" body="Buy coffee" />
<test:expect redirect="/" flash="Saved." />
<test:expect table="notes" count="1" where="author = 'ana' AND body = 'Buy coffee'" />
<test:expect text="ana: Buy coffee" />
</q:test>2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
tests/guard.test.q
PASS the guard sends a visitor to sign in
PASS the guard also stops the action: nothing is written
PASS a signed-in user writes a note
3 passed, 0 failed2
3
4
5
Una guarda puede verificar cualquier cosa que tenga la sesión. Para pedir solo un usuario con sesión iniciada o un rol, require_auth y require_role lo dicen en un atributo (Una página solo para un rol).