summaryrefslogtreecommitdiffstats
path: root/lang/python/python-flask-httpauth/test.sh
blob: b9f15b7a653b80285589fb2ba3187ada1ef8f490 (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
#!/bin/sh

[ "$1" = python3-flask-httpauth ] || exit 0

python3 - << 'EOF'
from flask import Flask
from flask_httpauth import HTTPBasicAuth

app = Flask(__name__)
auth = HTTPBasicAuth()

users = {"alice": "secret"}

@auth.verify_password
def verify_password(username, password):
    return users.get(username) == password

@app.route("/protected")
@auth.login_required
def protected():
    return f"Hello, {auth.current_user()}!"

with app.test_client() as client:
    # No auth -> 401
    resp = client.get("/protected")
    assert resp.status_code == 401, f"Expected 401, got {resp.status_code}"

    # Wrong password -> 401
    import base64
    bad = base64.b64encode(b"alice:wrong").decode()
    resp = client.get("/protected", headers={"Authorization": f"Basic {bad}"})
    assert resp.status_code == 401, f"Expected 401, got {resp.status_code}"

    # Correct credentials -> 200
    good = base64.b64encode(b"alice:secret").decode()
    resp = client.get("/protected", headers={"Authorization": f"Basic {good}"})
    assert resp.status_code == 200, f"Expected 200, got {resp.status_code}"
    assert b"Hello, alice" in resp.data
EOF