Uma guarda que redireciona
Tradução automática
Esta página foi traduzida automaticamente do inglês e ainda não foi revisada por um falante nativo; correções são bem-vindas no GitHub. Se algo não bater, vale o original em inglês. O código e os resultados são os mesmos do original, importados dos arquivos testados.
Tarefa: mandar quem não entrou para a página de login com uma mensagem, e garantir que também não consiga enviar para as ações da 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
Um q:if no topo da página cujo ramo tem um q:redirect é uma guarda. Ela roda antes da página e antes de cada uma das suas ações, então um envio mandado direto para add também é barrado:
<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
O segundo teste envia para a ação sem sessão e confere que nenhuma linha foi gravada:
<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
Uma guarda pode verificar qualquer coisa que a sessão guarda. Para pedir só um usuário que entrou ou um papel, require_auth e require_role dizem isso num atributo (Uma página só para um papel).