summaryrefslogtreecommitdiff
path: root/sw/auth.py
blob: 1f9e5d8bce2c086e5d5ff7a4873e951f48b734a1 (plain) (blame)
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
import functools

import logging

from flask import (
    abort,
    redirect,
    Blueprint,
    flash,
    g,
    redirect,
    render_template,
    request,
    session,
    url_for,
    Response,
)

from werkzeug.security import generate_password_hash, check_password_hash

from sw.db import get_db
from sw.util import prepared_output

bp = Blueprint("auth", __name__, url_prefix="/auth")


@bp.before_app_request
def load_logged_in_user():
    user_id = session.get("user_id")

    if user_id is None:
        g.user = None

    else:
        g.user = (
            get_db().execute("select * from users where id=?", (user_id,)).fetchone()
        )


def json_input(view):
    @functools.wraps(view)
    def wrapped_view(**kwargs):
        if not request.is_json:
            return "Request body is not JSON", 422

        return view(**kwargs)

    return wrapped_view


def from_trusted_server(view):
    # TODO
    return view


@bp.route("/register", methods=["POST"])
@json_input
def register():

    data = request.json

    username = data.get("username")
    password = data.get("password")

    if username is None:
        return "Username required", 400

    if password is None:
        return "Password required", 400

    if username == "":
        return "Username must not be empty", 400

    if password == "":
        return "Password must not be empty", 400

    db = get_db()
    existing_user = db.execute(
        "select id from users where username=?", (username,)
    ).fetchone()

    if existing_user is not None:
        return f"Username {username} is taken", 409

    db.execute(
        "insert into users (username, password) values (?, ?)",
        (username, generate_password_hash(password)),
    )
    db.commit()

    response = Response(status=201)
    # response.location = url_for("ap.get_user", user=username)

    return response


def login(username, password):
    db = get_db()
    user = db.execute("select * from users where username=?", (username,)).fetchone()

    if (user is None) or (password is None):
        abort(403)

    if not check_password_hash(user["password"], password):
        return False

    session.clear()
    session["user_id"] = user["id"]

    return True


@bp.route("/login", methods=["GET"])
def get_login():
    if request.args:
        username = request.args.get("username")
        password = request.args.get("password")

        if login(username, password):
            url = url_for("users.get_user_info", username=username)
            return redirect(url, 200)

    # I saw it suggested online that this response should have a 401
    # status code, but lynx acts funny when this is the case. Since
    # other (maybe more popular) browsers might also behave this way,
    # this is being left as 200 for now.
    return prepared_output("login", status=200)


@bp.route("/login", methods=["POST"])
@json_input
def post_login():
    username = request.json.get("username")
    password = request.json.get("password")

    if login(username, password):
        return Response(status=200)

    else:
        abort(403)


@bp.route("/logout")
def logout():
    session.clear()
    return "Logout Successful", 200


def login_required(view):
    @functools.wraps(view)
    def wrapped_view(**kwargs):
        if g.user is None:
            abort(403, "Login required")

        return view(**kwargs)

    return wrapped_view


def specific_user_required(view):
    @functools.wraps(view)
    def wrapped_view(**kwargs):
        username = kwargs.get("username") or kwargs.get("user")
        if (g.user is None) or (g.user["username"] != username):
            abort(403, "Unauthorised")

        return view(**kwargs)

    return wrapped_view