-
Notifications
You must be signed in to change notification settings - Fork 0
/
admin.py
109 lines (76 loc) · 2.42 KB
/
admin.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
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
import psycopg2
from psycopg2.extras import RealDictCursor
from flask import redirect, render_template, session
from functools import wraps
def apology(message, code=400):
"""Render message as an apology to user."""
def escape(s):
"""
Escape special characters.
https://github.com/jacebrowning/memegen#special-characters
"""
for old, new in [("-", "--"), (" ", "-"), ("_", "__"), ("?", "~q"),
("%", "~p"), ("#", "~h"), ("/", "~s"), ("\"", "''")]:
s = s.replace(old, new)
return s
return render_template("apology.html", top=code, bottom=escape(message)), code
def login_required(f):
"""
Decorate routes to require login.
http://flask.pocoo.org/docs/0.12/patterns/viewdecorators/
"""
@wraps(f)
def decorated_function(*args, **kwargs):
if session.get("user_id") is None:
return redirect("/login")
if session.get("status") != 'admin':
return redirect("/login")
return f(*args, **kwargs)
return decorated_function
def get_registered(db, new_username, new_password):
# Create connection and cursor
conn = psycopg2.connect(db)
cursor = conn.cursor()
# Create query
query = "INSERT INTO users (username, hash) "
query = query + "VALUES (%s, %s); "
# Execute query
cursor.execute(query, (new_username, new_password))
# Commit insert
conn.commit()
# Close cursor and connection
cursor.close()
conn.close()
return 1
def get_admin_user_add(db, new_username, new_password):
# Create connection and cursor
conn = psycopg2.connect(db)
cursor = conn.cursor()
# Create query
query = "INSERT INTO users (username, hash) "
query = query + "VALUES (%s, %s); "
# Execute query
cursor.execute(query, (new_username, new_password))
# Commit insert
conn.commit()
# Close cursor and connection
cursor.close()
conn.close()
return 1
def get_admin_login_user_info(db, user_id):
conn = psycopg2.connect(db)
cursor = conn.cursor(cursor_factory=RealDictCursor)
# Set query
query = """
SELECT *
FROM users
WHERE username = %s
AND status = 'admin';
"""
# Run query
cursor.execute(query, (user_id,))
# Get results
user_info = cursor.fetchone()
cursor.close()
conn.close()
return(user_info)