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