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