]> git.lizzy.rs Git - cheatdb.git/blob - app/utils.py
a47f6d0472e2689f334a4bbbeb26bd4246219cc6
[cheatdb.git] / app / utils.py
1 # ContentDB
2 # Copyright (C) 2018  rubenwardy
3 #
4 # This program is free software: you can redistribute it and/or modify
5 # it under the terms of the GNU General Public License as published by
6 # the Free Software Foundation, either version 3 of the License, or
7 # (at your option) any later version.
8 #
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12 # GNU General Public License for more details.
13 #
14 # You should have received a copy of the GNU General Public License
15 # along with this program.  If not, see <https://www.gnu.org/licenses/>.
16
17
18 from flask import request, flash, abort, redirect
19 from flask_user import *
20 from flask_login import login_user, logout_user
21 from .models import *
22 from . import app
23 import random, string, os, imghdr, user_agents
24 from urllib.parse import urljoin
25 from werkzeug.datastructures import MultiDict
26
27 # These are given to Jinja in template_filters.py
28
29 def abs_url_for(path, **kwargs):
30         scheme = "https" if app.config["BASE_URL"][:5] == "https" else "http"
31         return url_for(path, _external=True, _scheme=scheme, **kwargs)
32
33 def abs_url(path):
34         return urljoin(app.config["BASE_URL"], path)
35
36 def url_set_query(**kwargs):
37         args = MultiDict(request.args)
38
39         for key, value in kwargs.items():
40                 if key == "_add":
41                         for key2, value_to_add in value.items():
42                                 values = set(args.getlist(key2))
43                                 values.add(value_to_add)
44                                 args.setlist(key2, list(values))
45                 elif key == "_remove":
46                         for key2, value_to_remove in value.items():
47                                 values = set(args.getlist(key2))
48                                 values.discard(value_to_remove)
49                                 args.setlist(key2, list(values))
50                 else:
51                         args.setlist(key, [ value ])
52
53
54         dargs = dict(args.lists())
55
56         return url_for(request.endpoint, **dargs)
57
58 def get_int_or_abort(v, default=None):
59         if v is None:
60                 return default
61
62         try:
63                 return int(v or default)
64         except ValueError:
65                 abort(400)
66
67 def is_user_bot():
68         user_agent = user_agents.parse(request.headers.get('User-Agent'))
69         return user_agent.is_bot
70
71 def getExtension(filename):
72         return filename.rsplit(".", 1)[1].lower() if "." in filename else None
73
74 def isFilenameAllowed(filename, exts):
75         return getExtension(filename) in exts
76
77 ALLOWED_IMAGES = set(["jpeg", "png"])
78 def isAllowedImage(data):
79         return imghdr.what(None, data) in ALLOWED_IMAGES
80
81 def shouldReturnJson():
82         return "application/json" in request.accept_mimetypes and \
83                         not "text/html" in request.accept_mimetypes
84
85 def randomString(n):
86         return ''.join(random.choice(string.ascii_lowercase + \
87                         string.ascii_uppercase + string.digits) for _ in range(n))
88
89 def doFileUpload(file, fileType, fileTypeDesc):
90         if not file or file is None or file.filename == "":
91                 flash("No selected file", "danger")
92                 return None, None
93
94         assert os.path.isdir(app.config["UPLOAD_DIR"]), "UPLOAD_DIR must exist"
95
96         allowedExtensions = []
97         isImage = False
98         if fileType == "image":
99                 allowedExtensions = ["jpg", "jpeg", "png"]
100                 isImage = True
101         elif fileType == "zip":
102                 allowedExtensions = ["zip"]
103         else:
104                 raise Exception("Invalid fileType")
105
106         ext = getExtension(file.filename)
107         if ext is None or not ext in allowedExtensions:
108                 flash("Please upload " + fileTypeDesc, "danger")
109                 return None, None
110
111         if isImage and not isAllowedImage(file.stream.read()):
112                 flash("Uploaded image isn't actually an image", "danger")
113                 return None, None
114
115         file.stream.seek(0)
116
117         filename = randomString(10) + "." + ext
118         filepath = os.path.join(app.config["UPLOAD_DIR"], filename)
119         file.save(filepath)
120         return "/uploads/" + filename, filepath
121
122 def make_flask_user_password(plaintext_str):
123         # http://passlib.readthedocs.io/en/stable/modular_crypt_format.html
124         # http://passlib.readthedocs.io/en/stable/lib/passlib.hash.bcrypt.html#format-algorithm
125         # Flask_User stores passwords in the Modular Crypt Format.
126         # https://github.com/lingthio/Flask-User/blob/master/flask_user/user_manager__settings.py#L166
127         #   Note that Flask_User allows customizing password algorithms.
128         #   USER_PASSLIB_CRYPTCONTEXT_SCHEMES defaults to bcrypt but if
129         #   default changes or is customized, the code below needs adapting.
130         # Individual password values will look like:
131         #   $2b$12$.az4S999Ztvy/wa3UdQvMOpcki1Qn6VYPXmEFMIdWQyYs7ULnH.JW
132         #   $XX$RR$SSSSSSSSSSSSSSSSSSSSSSHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHH
133         # $XX : Selects algorithm (2b is bcrypt).
134         # $RR : Selects bcrypt key expansion rounds (12 is 2**12 rounds).
135         # $SSS... : 22 chars of (random, per-password) salt
136         #  HHH... : 31 remaining chars of password hash (note no dollar sign)
137         import bcrypt
138         plaintext = plaintext_str.encode("UTF-8")
139         password = bcrypt.hashpw(plaintext, bcrypt.gensalt())
140         if isinstance(password, str):
141                 return password
142         else:
143                 return password.decode("UTF-8")
144
145 def loginUser(user):
146         def _call_or_get(v):
147                 if callable(v):
148                         return v()
149                 else:
150                         return v
151
152         # User must have been authenticated
153         if not user:
154                 return False
155
156         if user.rank == UserRank.BANNED:
157                 flash("You have been banned.", "danger")
158                 return False
159
160         user.active = True
161         if not user.rank.atLeast(UserRank.NEW_MEMBER):
162                 user.rank = UserRank.MEMBER
163
164         db.session.commit()
165
166         # Check if user account has been disabled
167         if not _call_or_get(user.is_active):
168                 flash("Your account has not been enabled.", "danger")
169                 return False
170
171         # Use Flask-Login to sign in user
172         login_user(user, remember=True)
173         signals.user_logged_in.send(current_app._get_current_object(), user=user)
174
175         flash("You have signed in successfully.", "success")
176
177         return True
178
179
180 def rank_required(rank):
181         def decorator(f):
182                 @wraps(f)
183                 def decorated_function(*args, **kwargs):
184                         if not current_user.is_authenticated:
185                                 return redirect(url_for("user.login"))
186                         if not current_user.rank.atLeast(rank):
187                                 abort(403)
188
189                         return f(*args, **kwargs)
190
191                 return decorated_function
192         return decorator
193
194 def getPackageByInfo(author, name):
195         user = User.query.filter_by(username=author).first()
196         if user is None:
197                 return None
198
199         package = Package.query.filter_by(name=name, author_id=user.id, soft_deleted=False).first()
200         if package is None:
201                 return None
202
203         return package
204
205 def is_package_page(f):
206         @wraps(f)
207         def decorated_function(*args, **kwargs):
208                 if not ("author" in kwargs and "name" in kwargs):
209                         abort(400)
210
211                 author = kwargs["author"]
212                 name = kwargs["name"]
213
214                 package = getPackageByInfo(author, name)
215                 if package is None:
216                         package = getPackageByInfo(author, name + "_game")
217                         if package is None or package.type != PackageType.GAME:
218                                 abort(404)
219
220                         args = dict(kwargs)
221                         args["name"] = name + "_game"
222                         return redirect(url_for(request.endpoint, **args))
223
224                 del kwargs["author"]
225                 del kwargs["name"]
226
227                 return f(package=package, *args, **kwargs)
228
229         return decorated_function
230
231
232 def addNotification(target, causer, title, url, package=None):
233         try:
234                 iter(target)
235                 for x in target:
236                         addNotification(x, causer, title, url, package)
237                 return
238         except TypeError:
239                 pass
240
241         if target.rank.atLeast(UserRank.NEW_MEMBER) and target != causer:
242                 Notification.query.filter_by(user=target, causer=causer, title=title, url=url, package=package).delete()
243                 notif = Notification(target, causer, title, url, package)
244                 db.session.add(notif)
245
246
247 def addAuditLog(severity, causer, title, url, package=None, description=None):
248         entry = AuditLogEntry(causer, severity, title, url, package, description)
249         db.session.add(entry)
250
251
252 def clearNotifications(url):
253         if current_user.is_authenticated:
254                 Notification.query.filter_by(user=current_user, url=url).delete()
255                 db.session.commit()
256
257
258 YESES = ["yes", "true", "1", "on"]
259
260 def isYes(val):
261         return val and val.lower() in YESES
262
263
264 def isNo(val):
265         return val and not isYes(val)
266
267 def nonEmptyOrNone(str):
268         if str is None or str == "":
269                 return None
270
271         return str