2 # Copyright (C) 2018 rubenwardy
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.
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.
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/>.
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 *
23 import random, string, os, imghdr
25 def get_int_or_abort(v, default):
27 return int(v or default)
31 def getExtension(filename):
32 return filename.rsplit(".", 1)[1].lower() if "." in filename else None
34 def isFilenameAllowed(filename, exts):
35 return getExtension(filename) in exts
37 ALLOWED_IMAGES = set(["jpeg", "png"])
38 def isAllowedImage(data):
39 return imghdr.what(None, data) in ALLOWED_IMAGES
41 def shouldReturnJson():
42 return "application/json" in request.accept_mimetypes and \
43 not "text/html" in request.accept_mimetypes
46 return ''.join(random.choice(string.ascii_lowercase + \
47 string.ascii_uppercase + string.digits) for _ in range(n))
49 def doFileUpload(file, fileType, fileTypeDesc):
50 if not file or file is None or file.filename == "":
51 flash("No selected file", "error")
54 assert os.path.isdir(app.config["UPLOAD_DIR"]), "UPLOAD_DIR must exist"
56 allowedExtensions = []
58 if fileType == "image":
59 allowedExtensions = ["jpg", "jpeg", "png"]
61 elif fileType == "zip":
62 allowedExtensions = ["zip"]
64 raise Exception("Invalid fileType")
66 ext = getExtension(file.filename)
67 if ext is None or not ext in allowedExtensions:
68 flash("Please upload load " + fileTypeDesc, "danger")
71 if isImage and not isAllowedImage(file.stream.read()):
72 flash("Uploaded image isn't actually an image", "danger")
77 filename = randomString(10) + "." + ext
78 file.save(os.path.join(app.config["UPLOAD_DIR"], filename))
79 return "/uploads/" + filename
81 def make_flask_user_password(plaintext_str):
82 # http://passlib.readthedocs.io/en/stable/modular_crypt_format.html
83 # http://passlib.readthedocs.io/en/stable/lib/passlib.hash.bcrypt.html#format-algorithm
84 # Flask_User stores passwords in the Modular Crypt Format.
85 # https://github.com/lingthio/Flask-User/blob/master/flask_user/user_manager__settings.py#L166
86 # Note that Flask_User allows customizing password algorithms.
87 # USER_PASSLIB_CRYPTCONTEXT_SCHEMES defaults to bcrypt but if
88 # default changes or is customized, the code below needs adapting.
89 # Individual password values will look like:
90 # $2b$12$.az4S999Ztvy/wa3UdQvMOpcki1Qn6VYPXmEFMIdWQyYs7ULnH.JW
91 # $XX$RR$SSSSSSSSSSSSSSSSSSSSSSHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHH
92 # $XX : Selects algorithm (2b is bcrypt).
93 # $RR : Selects bcrypt key expansion rounds (12 is 2**12 rounds).
94 # $SSS... : 22 chars of (random, per-password) salt
95 # HHH... : 31 remaining chars of password hash (note no dollar sign)
97 plaintext = plaintext_str.encode("UTF-8")
98 password = bcrypt.hashpw(plaintext, bcrypt.gensalt())
99 if isinstance(password, str):
102 return password.decode("UTF-8")
104 def _do_login_user(user, remember_me=False):
111 # User must have been authenticated
115 if user.rank == UserRank.BANNED:
116 flash("You have been banned.", "error")
120 if not user.rank.atLeast(UserRank.NEW_MEMBER):
121 user.rank = UserRank.MEMBER
125 # Check if user account has been disabled
126 if not _call_or_get(user.is_active):
127 flash("Your account has not been enabled.", "error")
130 # Check if user has a confirmed email address
131 user_manager = current_app.user_manager
132 if user_manager.enable_email and user_manager.enable_confirm_email \
133 and not current_app.user_manager.enable_login_without_confirm_email \
134 and not user.has_confirmed_email():
135 url = url_for("user.resend_confirm_email")
136 flash("Your email address has not yet been confirmed", "error")
139 # Use Flask-Login to sign in user
140 login_user(user, remember=remember_me)
141 signals.user_logged_in.send(current_app._get_current_object(), user=user)
143 flash("You have signed in successfully.", "success")
149 if user_manager.enable_username:
150 user_mixin = user_manager.find_user_by_username(user.username)
152 return _do_login_user(user_mixin, True)
154 def rank_required(rank):
157 def decorated_function(*args, **kwargs):
158 if not current_user.is_authenticated:
159 return redirect(url_for("user.login"))
160 if not current_user.rank.atLeast(rank):
163 return f(*args, **kwargs)
165 return decorated_function
168 def getPackageByInfo(author, name):
169 user = User.query.filter_by(username=author).first()
173 package = Package.query.filter_by(name=name, author_id=user.id, soft_deleted=False).first()
179 def is_package_page(f):
181 def decorated_function(*args, **kwargs):
182 if not ("author" in kwargs and "name" in kwargs):
185 package = getPackageByInfo(kwargs["author"], kwargs["name"])
190 return f(package=package, *args, **kwargs)
192 return decorated_function
194 def triggerNotif(owner, causer, title, url):
195 if owner.rank.atLeast(UserRank.NEW_MEMBER) and owner != causer:
196 Notification.query.filter_by(user=owner, url=url).delete()
197 notif = Notification(owner, causer, title, url)
198 db.session.add(notif)
200 def clearNotifications(url):
201 if current_user.is_authenticated:
202 Notification.query.filter_by(user=current_user, url=url).delete()
206 YESES = ["yes", "true", "1", "on"]
209 return val and val.lower() in YESES
213 return val and not isYes(val)