def decorated_function(*args, **kwargs): try: # if True: if "email" not in session: return redirect(url_for('login', next=request.url)) elif not database.user_authed(session["email"]) and database.user_exists(session["email"]): return redirect(url_for("unauthorized")) elif not database.user_exists(session["email"]): return redirect(url_for("signup")) return f(*args, **kwargs) except Exception as e: return render_template("error.html", error=str(e.__repr__()))
def user_render(access): if not database.valid_access(access): return render_template("error.html", error="Page not found.") elif not database.is_admin(session["access"]): return redirect(url_for("unauthorized")) else: users = database.get_users() if request.method == "POST": email = request.form["email"] password = request.form["password"] password2 = request.form["password-two"] new_access = request.form["access"] name = request.form["name"] location = request.form["location"] # Change this to create a user if authentic email if password != password2: return render_template("users.html", users=users, access=access, error="Passwords for " + email + " do not match.") if database.user_exists(email): return render_template("users.html", users=users, access=access, error="User: "******" already exists.") database.create_user(email, password, name, new_access, location) token = security.generate_confirmation_token(email) confirm_url = url_for("confirm", token=token, _external=True) html = render_template("account.html", confirm_url=confirm_url, access = new_access, password=password) subject = "Please confirm your email" send_email(email, subject, html) print("CONFIRM: ", confirm_url) print("EMAIL: ", email) return render_template("users.html", users=users, access=access, error="An authentication email has been send to: " + email) else: return render_template("users.html", users=users, access=access)
def signup(): if request.method == "POST": email = request.form["email"] session["email"] = email password = request.form["password"] password2 = request.form["password-two"] access = request.form["access"] name = request.form["name"] location = request.form["location"] # Change this to create a user if authentic email if password != password2: return render_template("home.html", correct={"signup":True}, bad_signup=True, error="Passwords must match.") if database.user_exists(email): return render_template("home.html", correct={"signup":True}, bad_signup=True, error="User already exists.") if security.check_email(email): database.create_user(email, password, name, access, location) token = security.generate_confirmation_token(email) confirm_url = url_for("confirm", token=token, _external=True) html = render_template("activate.html", confirm_url=confirm_url) subject = "Please confirm your email" send_email(email, subject, html) flash("A confirmation email has been sent via email.", "success") return render_template("home.html", correct={"login":True}, bad_login=True, error="An authentication link has been sent to your email.", resend_auth=True) else: return render_template("home.html", correct={"signup":True}, bad_signup=True, error="Invalid email.") else: return render_template("home.html", correct={"signup":True}, bad_signup=False)
async def on_message(self, message): if message.author.id in cmds.BOT_IDS: return split = message.content.split(' ', 1) # separate mom?[cmd] from args cmd = split[0] args = split[1].split(' ') if len(split) > 1 else None # Retrieve user from database and create if non-existing user = db.user_exists(message.author.id) if not user: db.adduser(message.author.id) prefix = db.get_prefix(message.author.id) # Check if a bot command if not cmd.startswith(f"mom{prefix}"): return # Debugging stuff name = author_name(message.author) print(f"{name} issued {cmd} command. <{args}>") cur_cmd = None try: suffix = cmd[4:] # Get command suffix cur_cmd = COMMANDS[suffix]['cmd'] await cur_cmd(self, message, args) except Exception as error: if not cur_cmd: return await cmds.error_message(message, title=f"Unknown command '{suffix}'") cmds.ERRORS += [time.ctime() + ': ' + str(error)] cmd = cmds.format_cmd(prefix, "report") await cmds.error_message(message, title=f"The command {suffix} failed...", desc=f"Please use ``{cmd}`` if you think it's an unexpected behaviour")
def login_user(identifier, password): if not db.user_exists(identifier): return jsonify({"response": ["User doesn't exist"]}) elif not db.correct_password(identifier, password): return jsonify({"response": ["Incorrect Password"]}) else: return jsonify({"response": ["Success"]})
def login_user(identifier, password): if not db.user_exists(identifier): return {"response": "User doesn't exist"} elif not db.correct_password(identifier, password): return {"response": "Incorrect Password"} else: return {"response": "Success"}
def post_sign_up(): next_url = request.args['next'] email = request.form['email'] password = request.form['password'] confirmation = request.form['confirmation'] # Check if the fields were filled. email_valid = email is not None and email != '' email_feedback = 'Please enter your email address' password_valid = password is not None and password != '' password_feedback = 'Please enter your password' confirmation_valid = confirmation is not None and confirmation != '' confirmation_feedback = 'Please enter your password again' # Check if the fields match our simple regex. if email_valid: email_valid = re.match(r'[^@]+@[^@]+\.[^@]+', email) email_feedback = 'The value you’ve entered is not a valid email address' if password_valid: password_valid = len(password) >= 6 password_feedback = 'The password you’ve entered is too short to be valid' if confirmation_valid: confirmation_valid = password == confirmation confirmation_feedback = 'The passwords you’ve entered don’t match' # Check if the user does not already exist in the DB. if email_valid: email_valid = not database.user_exists(email) email_feedback = 'The email you’ve entered is already in use by another account' if email_valid and password_valid and confirmation_valid: # Hash the password. salt = os.urandom(SALT_LENGTH) password_hash = scrypt.hash(password, salt) # Create the user and their password in the database. user_id = database.create_user(email) database.create_password(user_id, salt, password_hash) # Set the login cookie. session['user_id'] = user_id session['email'] = email return redirect(next_url) else: return render_template('sign_up.html', next=next_url, email=email, email_valid=email_valid, email_feedback=email_feedback, password=password, password_valid=password_valid, password_feedback=password_feedback, confirmation=confirmation, confirmation_valid=confirmation_valid, confirmation_feedback=confirmation_feedback)
def login(): if request.method == "POST": email = request.form["email"] session["email"] = email try: session["access"] = database.get_access(email) except AssertionError: return render_template("home.html", correct={"login":True}, bad_login=True, error="User does not exist.", resend_auth=False) password = request.form["password"] if database.user_exists(email) and not database.user_authed(email): return render_template("home.html", correct={"login":True}, bad_login=True, error="You have not authorized your account.", resend_auth=True) if database.correct_user(email, password): session["access"] = database.get_access(email) session["gitlink"] = database.get_git_link(email) session["location"] = database.get_location(email) return redirect(url_for("login_home", access=session["access"])) else: return render_template("home.html", correct={"login":True}, bad_login=True, error="Incorrect username or password.", resend_auth=False) else: if "email" in session: if "access" in session: session["gitlink"] = database.get_git_link(session["email"]) session["location"] = database.get_location(session["email"]) return redirect(url_for("login_home", access=session["access"])) return render_template("home.html", correct={"login":True}, bad_login=False)
def show_user(username=None): key = request.args.get('uuid', None) if username is not None and key is not None and db.user_exists( username, key): url = request.url_root[:-1] + url_for( 'get_data_heatmap') + '?user='******'&uuid=' + str(key) return render_template('/overview.html', image_url=url) else: return get_error('Specify username and uuid.')
def resend(): if "email" not in session: return redirect(url_for("login")) elif not database.user_exists(session["email"]): return redirect(url_for("signup")) else: email = session["email"] token = security.generate_confirmation_token(email) confirm_url = url_for("confirm", token=token, _external=True) html = render_template("activate.html", confirm_url=confirm_url) subject = "Please confirm your email" send_email(email, subject, html) return render_template("home.html", correct={"login":True}, bad_login=True, error="An authentication link has been sent to " + session["email"], resend_auth=False)
def transfer_money(source, destination, amount): if not database.user_exists(source) or not database.user_exists(destination): message_queue.add(source, "who that") return False if ask_money(source) < amount * (1 + TRANSFER_FEE_RATE): message_queue.add(source, "you're poor lol") return False real_amount = amount * 1000 base = real_amount # Round to nearest multiple of 2 cents fee = math.ceil(real_amount * TRANSFER_FEE_RATE / 2) * 2 database.take_money(source, base + fee) database.give_money(destination, base) database.give_money(config.nickname, fee) message_queue.add(source, f"sent {amount:.2f} newbux to {destination} ({fee / 1000:.2f} fee)") message_queue.add(destination, f"received {amount:.2f} newbux from {source} (sender paid a {fee / 1000:.2f} fee)") bank_logger.info(f"Transfer {source} -> {destination}: {amount:.2f} bux ({fee / 1000:.2f} fee)") return True
def register(): if request.method == 'POST': username = request.form['username'] password = request.form['password'] if db.user_exists(username): flash('The Username {} is Already Taken'.format(username)) return redirect(url_for('register')) else: db.insert_user(username, password) return redirect(url_for('login')) else: args = {'active': 'register'} return render_template('register.html', args=args)
def islamic_gommunism(source, target, amount, channel, users): if channel not in users.keys() or target == source: message_queue.add(source, "smoke weed and protest against bankers") return False other_users = [user for user in users[channel] if user not in (target, config.nickname)] if not database.user_exists(source) or not database.user_exists(destination): message_queue.add(source, "who that") return False if not transfer_money(target, config.nickname, amount): message_queue.add(source, f"{target} isn't ready for the intifada yet") return False if not transfer_money(source, config.nickname, amount): # Do nothing and fail return False for user in other_users: transfer_money(config.nickname, user, amount / len(other_users)) message_queue.add(channel, "alhamdulillah")
def transfer_money(source, destination, amount): if not database.user_exists(source) or not database.user_exists(destination): message_queue.add(source, "who that") return False if ask_money(source) < amount * (1 + TRANSFER_FEE_RATE): message_queue.add(source, "you're poor lol") return False real_amount = amount * 1000 base = real_amount # Round to nearest multiple of 2 cents fee = math.ceil(real_amount * TRANSFER_FEE_RATE / 2) * 2 database.take_money(source, base + fee) database.give_money(destination, base) database.give_money(config.nickname, fee) message_queue.add(source, f"sent {amount:.2f} newbux to {destination} ({fee / 1000:.2f} fee)") message_queue.add(destination, f"received {amount:.2f} newbux from {source} (sender paid a {fee / 1000:.2f} fee)") timestamp = datetime.datetime.utcnow().strftime("%Y-%m-%d %H:%M") print(f"{timestamp} Transfer {source} -> {destination}: {amount:.2f} bux ({fee / 1000:.2f} fee)") return True
def islamic_gommunism(source, target, amount, channel, users): if channel not in users.keys() or target == source: message_queue.add(source, "smoke weed and protest against bankers") return False other_users = [user for user in users[channel] if user not in (target, config.nickname)] if not database.user_exists(source) or not database.user_exists(target): message_queue.add(source, "who that") return False if not transfer_money(source, config.nickname, amount): # Do nothing and fail return False if not transfer_money(target, config.nickname, amount): message_queue.add(source, f"{target} isn't ready for the intifada yet") return False for user in other_users: transfer_money(config.nickname, user, amount / len(other_users)) message_queue.add(channel, "alhamdulillah")
def user_remove(access): if not database.valid_access(access): return render_template("error.html", error="Page not found.") elif not database.is_admin(session["access"]): return redirect(url_for("unauthorized")) else: email = request.form["email"] users = database.get_users() if not database.user_exists(email): return render_template("users.html", users=users, access=access, error="User: "******" does not exist.") database.remove_user(email=email) users = database.get_users() return render_template("users.html", users=users, access=access, error=email + " has been removed permanantly.")
def create_user(): """Creates a new user.""" if 'username' in session: return jsonify(ok=0, msg='First logout before creating a new user') user = request.form['user'] passw = request.form['pass'] if database.user_exists(user): return jsonify(ok=0, msg='User already exists') if database.create_user(user, passw): session['username'] = user session['userid'] = database.get_userid(user) session['password'] = passw return jsonify(ok=1, msg='User created!') return jsonify(ok=0, msg='User could not be created')
def post_sign_in(): next_url = request.args['next'] email = request.form['email'] password = request.form['password'] # Check if the fields were filled. email_valid = email is not None and email != '' email_feedback = 'Please enter your email address' password_valid = password is not None and password != '' password_feedback = 'Please enter your password' # Check if the fields match our simple regex. #if email_valid: #email_valid = re.match(r'[^@]+@[^@]+\.[^@]+', email) #email_feedback = 'The value you’ve entered is not a valid email address' if password_valid: password_valid = len(password) >= 6 password_feedback = 'The password you’ve entered is too short to be valid' # Check if the user exists in the DB. if email_valid: email_valid = database.user_exists(email) email_feedback = 'The email you’ve entered doesn’t match any account' # Check if the password is correct. Do not run this check if the email is incorrect, since we can't tell if the user # inputted a correct password or not until they input a correct email. if email_valid and password_valid: salt, password_hash = database.get_password(email) password_valid = password_hash == scrypt.hash(password, salt) password_feedback = 'The password you’ve entered is incorrect' if email_valid and password_valid: # Set the login cookie. session['user_id'] = database.get_user_id(email) session['email'] = email return redirect(next_url) else: return render_template('sign_in.html', next=next_url, email=email, email_valid=email_valid, email_feedback=email_feedback, password=password, password_valid=password_valid, password_feedback=password_feedback)
def get_data_heatmap(): username = request.args.get('user', None) key = request.args.get('uuid', None) if db.user_exists(username, key): user = User.get(User.username == username, User.key == key) days = DayAction.select().where(DayAction.user == user) result = dict() for day in days: result[str(day.date)] = day.actions response = make_response(heatmap.generate_image(result).getvalue()) response.headers['Content-Type'] = 'image/png' return response # return jsonify(result) else: return get_error('No username or wrong key.')
def do_register(): if request.form['password'] != request.form['passwordconfirm']: return render_template('/register.html', msg="Passwords do not match.") if database.user_exists(request.form['username']): return render_template('/register.html', msg="A user already exists with that username.") if request.form['accesscode'] != str(access_code): return render_template('/register.html', msg="Incorrect access code. " "Find it in the application console.") current_user = user.User(request.form['username'], request.form['password'], 0, 0) current_user.add_to_db() return render_template('/login.html', msg="Registration successful. You may now log in.")
def reset(): if request.method == "POST": email = request.form["email"] # Change this to create a user if authentic email if not database.user_exists(email): return render_template("home.html", correct={"reset":True}, bad_reset=True, error="User does not exist.") token = security.generate_confirmation_token(email) reset_url = url_for("reset_password", token=token, _external=True) html = render_template("reset.html", reset_url=reset_url) subject = "Reset MEET Password" send_email(email, subject, html) return render_template("home.html", correct={"reset": True}, bad_reset=True, error="A password reset link has been sent to " + email) else: return render_template("home.html", correct={"reset":True}, bad_signup=False)
def register(): username = bleach.clean(request.form['username']) key = uuid.uuid4().hex if not db.user_exists(username, key) and studip.is_valid(username): points = studip.get_points(username) rank = studip.get_rank(username) try: db.create_user(username, key, points, rank) except db.IntegrityError: return get_error('Could not create user.') # return jsonify({'username': username, 'key': key, 'points': points, 'rank': rank}) return redirect( url_for('show_user', username=username) + '?uuid=' + str(key)) else: return get_error( 'Username not available in Stud.IP or already registered in this service.' )
def facebook_authorized(resp): if resp is None: return 'Access denied: reason=%s error=%s' % ( request.args['error_reason'], request.args['error_description']) session['oauth_token'] = (resp['access_token'], '') session['token'] = resp['access_token'] me = facebook.get('/me') session['name'] = me.data['name'] fburl = "https://graph.facebook.com/v2.2/me?access_token=" + urllib.quote_plus( str((session["token"]))) req = urllib2.urlopen(fburl) result = req.read() d = json.loads(result) # a = open('sample.json').read() # d = json.loads(a) session['id'] = d['id'] if not database.user_exists(session['id']): database.add_user(session['name'], session['id']) flash("Since you are a new user, please update your food preferences.") return redirect(url_for('account')) return redirect(url_for('index'))
def login(): if request.method == 'POST': username = request.form['username'] password = request.form['password'] if not db.user_exists(username): flash("Username Doesn't Exist, Make Sure To Register") return redirect(url_for('register')) user_password = db.get_user_password(username) if password == user_password: db.mark_loggedin(username) user = db.get_user_by_username(username) login_user(user) return redirect(url_for('index')) else: flash('Username and Password Combination is Incorrect') return redirect(url_for('login')) else: args = {'active': 'login'} return render_template('login.html', args=args)