بتل کد Battle Codeدارد باز می‌شود…

جواب «Not Yours: 403» چالش 5 از جلسه‌ی 23

سؤال

(سخت‌تر) یادداشت ۱ مال سارا و یادداشت ۲ مال علی است. دو مسیر بنویس:
- GET /notes/<int:note_id>: یادداشت نبود: 404 با {"error": "no such note"}؛ صاحبش request.user نبود: 403 با {"error": "this note is not yours"}؛ وگرنه کل ردیف، مثل {"id": 1, "owner": "Sara", "text": "Buy a gift for Mina"}.
- DELETE /notes/<int:note_id>: همان دو بررسی، به همان ترتیب؛ بعد ردیف را با ? پاک کن و "", 204 بده.
درخواست‌ها آماده‌اند. کدها به ترتیب: 200، 403، 404، 403، 204، 404، 401.

راهنما

note = db.one("SELECT * FROM notes WHERE id = ?", (note_id,))؛ if note is None: abort(404, ...)؛ if note["owner"] != request.user: abort(403, ...). در DELETE همین دو بررسی، بعد db.run("DELETE FROM notes WHERE id = ?", (note_id,)).

یک جواب درست

from server import app, ask, request, abort, db, new_token

db.script("""
CREATE TABLE notes (id INTEGER PRIMARY KEY, owner TEXT, text TEXT);
INSERT INTO notes (owner, text) VALUES ('Sara', 'Buy a gift for Mina');
INSERT INTO notes (owner, text) VALUES ('Ali', 'Football at 5');
""")
tokens = {}

def log_in(name):
    token = new_token()
    tokens[token] = name
    return {"Authorization": "Bearer " + token}

@app.before
def guard():
    request.user = tokens.get(request.token)
    if request.path.startswith("/notes") and request.user is None:
        abort(401, "log in first")

@app.get("/notes/<int:note_id>")
def one_note(note_id):
    note = db.one("SELECT * FROM notes WHERE id = ?", (note_id,))
    if note is None:
        abort(404, "no such note")
    if note["owner"] != request.user:
        abort(403, "this note is not yours")
    return note

@app.delete("/notes/<int:note_id>")
def delete_note(note_id):
    note = db.one("SELECT * FROM notes WHERE id = ?", (note_id,))
    if note is None:
        abort(404, "no such note")
    if note["owner"] != request.user:
        abort(403, "this note is not yours")
    db.run("DELETE FROM notes WHERE id = ?", (note_id,))
    return "", 204

sara = log_in("Sara")
ali = log_in("Ali")
ask("GET /notes/1", headers=sara)
ask("GET /notes/2", headers=sara)
ask("GET /notes/9", headers=sara)
ask("DELETE /notes/2", headers=sara)
ask("DELETE /notes/2", headers=ali)
ask("GET /notes/2", headers=ali)
ask("GET /notes/1")

اول خودت امتحان کن؛ جواب‌های دیگر هم قبول است. برگرد و خودت حلش کن