Skip to content

Commit 00f812c

Browse files
committed
Add @auth.admin_required and .mod_required decorators
These make sure there is a user and that the user has room-admin or room-moderator permissions.
1 parent e41bba0 commit 00f812c

File tree

2 files changed

+39
-4
lines changed

2 files changed

+39
-4
lines changed

sogs/routes/auth.py

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -123,6 +123,44 @@ def required_user_wrapper(*args, **kwargs):
123123
return required_user_wrapper
124124

125125

126+
def require_mod(room, *, admin=False):
127+
"""Checks a room for moderator or admin permission; aborts with 401 Unauthorized if there is no
128+
user in the request, and 403 Forbidden if g.user does not have moderator (or admin, if
129+
specified) permission."""
130+
require_user()
131+
if not (room.check_admin(g.user) if admin else room.check_moderator(g.user)):
132+
abort_with_reason(
133+
http.FORBIDDEN,
134+
f"This endpoint requires {'admin' if admin else 'moderator'} room permissions",
135+
)
136+
137+
138+
def mod_required(f):
139+
"""Decorator for an endpoint that requires a user that has moderator permission in the given
140+
room. The function must take a `room` argument by name, as is typically used with flask
141+
endpoints with a <Room:room> argument."""
142+
143+
@wraps(f)
144+
def required_mod_wrapper(*args, room, **kwargs):
145+
require_mod(room)
146+
return f(*args, room=room, **kwargs)
147+
148+
return required_mod_wrapper
149+
150+
151+
def admin_required(f):
152+
"""Decorator for an endpoint that requires a user that has admin permission in the given room.
153+
The function must take a `room` argument by name, as is typically used with flask endpoints with
154+
a <Room:room> argument."""
155+
156+
@wraps(f)
157+
def required_admin_wrapper(*args, room, **kwargs):
158+
require_mod(room, admin=True)
159+
return f(*args, room=room, **kwargs)
160+
161+
return required_admin_wrapper
162+
163+
126164
@app.before_request
127165
def handle_http_auth():
128166
"""

sogs/routes/rooms.py

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -71,12 +71,9 @@ def get_rooms():
7171

7272

7373
@rooms.put("/room/<Room:room>")
74-
@auth.user_required
74+
@auth.admin_required
7575
def update_room(room):
7676

77-
if not room.check_admin(g.user):
78-
abort(http.FORBIDDEN)
79-
8077
req = request.json
8178

8279
with db.transaction():

0 commit comments

Comments
 (0)