-
Notifications
You must be signed in to change notification settings - Fork 2
/
auth.py
53 lines (45 loc) · 1.74 KB
/
auth.py
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
from typing import Callable
from template_engine.parser import render
from db import db_api as db
from back_end.common import get_username
USER_COOKIE = "current_user"
ALL_USER = {} # username : USER (object)
def authenticate_cookie(request):
"""Returns True if cookies can be authenicated"""
user_cookie = request.get_secure_cookie(USER_COOKIE)
if user_cookie:
user_cookie = user_cookie.decode("utf-8")
print(user_cookie)
user = db.User.find_by_username(user_cookie) # type: User
if user is not None:
print('user_cookie in alluser')
return True
return False
def render_no_login(request):
request.write(render('notsignedin.html', {'signed_in':authenticate_cookie(request), 'username': get_username(request)}))
def requires_login(func: Callable):
"""
Function decorator for requiring login
"""
def ret(request, *args, **kwargs):
if authenticate_cookie(request):
# noinspection PyCallingNonCallable
return func(request, *args, **kwargs)
else:
return render_no_login(request)
return ret
def require_specific_user(func):
"""Decorator that requires the user to = to the cookie set in request"""
def ret(request, username, *args, **kwargs):
if authenticate_correct_username(request, username):
return func(request,username, *args, **kwargs)
else:
request.write("you cannot edit someone else's profile you hacker!")
return ret
def authenticate_correct_username(request, username):
user_cookie = request.get_secure_cookie(USER_COOKIE)
if user_cookie:
user_cookie = user_cookie.decode("UTF-8")
return user_cookie == username
else:
return False