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