]> git.lizzy.rs Git - cheatdb.git/blob - app/utils.py
5960fa66ca18a575de463f2c2138242ab7e8bb87
[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
24 from urllib.parse import urljoin
25
26 def abs_url_for(path, **kwargs):
27         scheme = "https" if app.config["BASE_URL"][:5] == "https" else "http"
28         return url_for(path, _external=True, _scheme=scheme, **kwargs)
29
30 def abs_url(path):
31         return urljoin(app.config["BASE_URL"], path)
32
33 def get_int_or_abort(v, default=None):
34         if v is None:
35                 return default
36
37         try:
38                 return int(v or default)
39         except ValueError:
40                 abort(400)
41
42 def getExtension(filename):
43         return filename.rsplit(".", 1)[1].lower() if "." in filename else None
44
45 def isFilenameAllowed(filename, exts):
46         return getExtension(filename) in exts
47
48 ALLOWED_IMAGES = set(["jpeg", "png"])
49 def isAllowedImage(data):
50         return imghdr.what(None, data) in ALLOWED_IMAGES
51
52 def shouldReturnJson():
53         return "application/json" in request.accept_mimetypes and \
54                         not "text/html" in request.accept_mimetypes
55
56 def randomString(n):
57         return ''.join(random.choice(string.ascii_lowercase + \
58                         string.ascii_uppercase + string.digits) for _ in range(n))
59
60 def doFileUpload(file, fileType, fileTypeDesc):
61         if not file or file is None or file.filename == "":
62                 flash("No selected file", "danger")
63                 return None, None
64
65         assert os.path.isdir(app.config["UPLOAD_DIR"]), "UPLOAD_DIR must exist"
66
67         allowedExtensions = []
68         isImage = False
69         if fileType == "image":
70                 allowedExtensions = ["jpg", "jpeg", "png"]
71                 isImage = True
72         elif fileType == "zip":
73                 allowedExtensions = ["zip"]
74         else:
75                 raise Exception("Invalid fileType")
76
77         ext = getExtension(file.filename)
78         if ext is None or not ext in allowedExtensions:
79                 flash("Please upload " + fileTypeDesc, "danger")
80                 return None, None
81
82         if isImage and not isAllowedImage(file.stream.read()):
83                 flash("Uploaded image isn't actually an image", "danger")
84                 return None, None
85
86         file.stream.seek(0)
87
88         filename = randomString(10) + "." + ext
89         filepath = os.path.join(app.config["UPLOAD_DIR"], filename)
90         file.save(filepath)
91         return "/uploads/" + filename, filepath
92
93 def make_flask_user_password(plaintext_str):
94         # http://passlib.readthedocs.io/en/stable/modular_crypt_format.html
95         # http://passlib.readthedocs.io/en/stable/lib/passlib.hash.bcrypt.html#format-algorithm
96         # Flask_User stores passwords in the Modular Crypt Format.
97         # https://github.com/lingthio/Flask-User/blob/master/flask_user/user_manager__settings.py#L166
98         #   Note that Flask_User allows customizing password algorithms.
99         #   USER_PASSLIB_CRYPTCONTEXT_SCHEMES defaults to bcrypt but if
100         #   default changes or is customized, the code below needs adapting.
101         # Individual password values will look like:
102         #   $2b$12$.az4S999Ztvy/wa3UdQvMOpcki1Qn6VYPXmEFMIdWQyYs7ULnH.JW
103         #   $XX$RR$SSSSSSSSSSSSSSSSSSSSSSHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHH
104         # $XX : Selects algorithm (2b is bcrypt).
105         # $RR : Selects bcrypt key expansion rounds (12 is 2**12 rounds).
106         # $SSS... : 22 chars of (random, per-password) salt
107         #  HHH... : 31 remaining chars of password hash (note no dollar sign)
108         import bcrypt
109         plaintext = plaintext_str.encode("UTF-8")
110         password = bcrypt.hashpw(plaintext, bcrypt.gensalt())
111         if isinstance(password, str):
112                 return password
113         else:
114                 return password.decode("UTF-8")
115
116 def loginUser(user):
117         def _call_or_get(v):
118                 if callable(v):
119                         return v()
120                 else:
121                         return v
122
123         # User must have been authenticated
124         if not user:
125                 return False
126
127         if user.rank == UserRank.BANNED:
128                 flash("You have been banned.", "danger")
129                 return False
130
131         user.active = True
132         if not user.rank.atLeast(UserRank.NEW_MEMBER):
133                 user.rank = UserRank.MEMBER
134
135         db.session.commit()
136
137         # Check if user account has been disabled
138         if not _call_or_get(user.is_active):
139                 flash("Your account has not been enabled.", "danger")
140                 return False
141
142         # Use Flask-Login to sign in user
143         login_user(user, remember=True)
144         signals.user_logged_in.send(current_app._get_current_object(), user=user)
145
146         flash("You have signed in successfully.", "success")
147
148         return True
149
150
151 def rank_required(rank):
152         def decorator(f):
153                 @wraps(f)
154                 def decorated_function(*args, **kwargs):
155                         if not current_user.is_authenticated:
156                                 return redirect(url_for("user.login"))
157                         if not current_user.rank.atLeast(rank):
158                                 abort(403)
159
160                         return f(*args, **kwargs)
161
162                 return decorated_function
163         return decorator
164
165 def getPackageByInfo(author, name):
166         user = User.query.filter_by(username=author).first()
167         if user is None:
168                 abort(404)
169
170         package = Package.query.filter_by(name=name, author_id=user.id, soft_deleted=False).first()
171         if package is None:
172                 abort(404)
173
174         return package
175
176 def is_package_page(f):
177         @wraps(f)
178         def decorated_function(*args, **kwargs):
179                 if not ("author" in kwargs and "name" in kwargs):
180                         abort(400)
181
182                 package = getPackageByInfo(kwargs["author"], kwargs["name"])
183
184                 del kwargs["author"]
185                 del kwargs["name"]
186
187                 return f(package=package, *args, **kwargs)
188
189         return decorated_function
190
191
192 def addNotification(target, causer, title, url, package=None):
193         try:
194                 iter(target)
195                 for x in target:
196                         addNotification(x, causer, title, url, package)
197                 return
198         except TypeError:
199                 pass
200
201         if target.rank.atLeast(UserRank.NEW_MEMBER) and target != causer:
202                 Notification.query.filter_by(user=target, causer=causer, title=title, url=url, package=package).delete()
203                 notif = Notification(target, causer, title, url, package)
204                 db.session.add(notif)
205
206
207 def addAuditLog(severity, causer, title, url, package=None, description=None):
208         entry = AuditLogEntry(causer, severity, title, url, package, description)
209         db.session.add(entry)
210
211
212 def clearNotifications(url):
213         if current_user.is_authenticated:
214                 Notification.query.filter_by(user=current_user, url=url).delete()
215                 db.session.commit()
216
217
218 YESES = ["yes", "true", "1", "on"]
219
220 def isYes(val):
221         return val and val.lower() in YESES
222
223
224 def isNo(val):
225         return val and not isYes(val)
226
227 def nonEmptyOrNone(str):
228         if str is None or str == "":
229                 return None
230
231         return str