def trip_route(id): """ Route function for trip.html """ trip = db.query(Trip).get(id) days = db.query(Day).filter_by(trip_id=id).order_by(Day.day_seq).all() regions = get_regions() # Calculate the milage per day form the trip segments milage_per_day = {} for day in days: total_milage = 0 for segment in day.segments: total_milage += segment.milage milage_per_day[day.day_seq] = total_milage # Format the trip name for multiline names trip_name = trip.name.split("-") # Get the photos photos = db.query(Photo).filter_by(trip_id=id).order_by(Photo.photo_seq).all() return render_template('trip.html', trip_name=trip_name, milage_per_day=milage_per_day, trip=trip, days=days, regions=regions, photos=photos)
def success(): active = "active" name = request.form["name"] email = request.form["email"] password = request.form["pwd"] password_hash = generate_password_hash(password) name_exists = db.query(User).filter_by(name=name).first() email_exists = db.query(User).filter_by(email=email).first() if name_exists or email_exists: successMessage = "The username or email address already exists!" successClass = "alert alert-danger" return render_template("form.html", active1=active, successMessage = successMessage, successClass = successClass) else: user_registration = User(name=name, email=email, password_hash=password_hash) successMessage = "You have successfully registered!" successClass = "alert alert-success" db.add(user_registration) db.commit() response = make_response(render_template("index.html", successMessage=successMessage, successClass=successClass, emailAddress=email, active0=active, user=name)) response.set_cookie("email", email) return response
def login(): if request.method == "POST": username = request.form.get("username") password = request.form.get("password") # query, check if there is a user with this username in the DB # user = db.query(User).filter(User.username == username).one() # -> needs to find one, otherwise raises Error # user = db.query(User).filter(User.username == username).first() # -> find first entry, if no entry, return None # users = db.query(User).filter(User.username == username).all() # -> find all, always returns list. if not entry found, empty list password_hash = hashlib.sha256(password.encode()).hexdigest() # right way to find user with correct password user = db.query(User) \ .filter(User.username == username, User.password_hash == password_hash) \ .first() session_cookie = str(uuid.uuid4()) expiry_time = datetime.datetime.now() + datetime.timedelta( seconds=COOKIE_DURATION) if user is None: flash("Username or password is wrong", "warning") app.logger.info( f"User {username} failed to login with wrong password.") redirect_url = request.args.get('redirectTo', url_for('index')) return redirect(url_for('login', redirectTo=redirect_url)) else: user.session_cookie = session_cookie user.session_expiry_datetime = expiry_time db.add(user) db.commit() app.logger.info(f"User {username} is logged in") redirect_url = request.args.get('redirectTo', url_for('index')) response = make_response(redirect(redirect_url)) response.set_cookie(WEBSITE_LOGIN_COOKIE_NAME, session_cookie, httponly=True, samesite='Strict') return response elif request.method == "GET": cookie = request.cookies.get(WEBSITE_LOGIN_COOKIE_NAME) user = None if cookie is not None: user = db.query(User) \ .filter_by(session_cookie=cookie) \ .filter(User.session_expiry_datetime >= datetime.datetime.now()) \ .first() if user is None: logged_in = False else: logged_in = True return render_template("login.html", logged_in=logged_in, user=request.user)
def delete(self, id=None): if not id: # response = jsonify({"error": "id should be provided"}) # response.status_code = 400 return make_response(jsonify({"error": "id should be provided"}), 400) # or response else: db.query(DELETE_BY_ID, id)
def index(): session_token = request.cookies.get("session_token") user = db.query(User).filter_by(session_token=session_token).first() if session_token and user.delete == "no": user = db.query(User).filter_by(session_token=session_token).first() else: user = None return render_template("index.html", user=user)
def get_search_results(): """ Ajax call to return the results for a trip """ region = request.args.get("region") max_days = request.args.get("max_days") min_days = request.args.get("min_days") max_elev = request.args.get("max_elev") min_elev = request.args.get("min_elev") avg_miles = request.args.get("avg_miles") x_c = request.args.get("x_country") # Translate checkbox result to boolean value if x_c == 'checked': x_c = True else: x_c = False # Calculate mile range based on average miles per day and min and max days if max_days and avg_miles: max_miles = int(avg_miles) * int(max_days) else: max_miles = 1000 # arbitraty big number if min_days and avg_miles: min_miles = int(avg_miles) * int(min_days) else: min_miles = 0 # arbitraty small number if max_days: max_days = int(max_days) else: max_days = 1000 # arbitraty big number if min_days: min_days = int(min_days) else: min_days = 0 # arbitraty small number if max_elev: max_elev = int(max_elev) else: max_elev = 30000 # arbitraty big number if min_elev: min_elev = int(min_elev) else: min_elev = 0 # arbitrary small number if region == "All": # Do the search with region obmitted results = db.query(Trip).filter_by(has_xc=x_c).filter(Trip.milage >= min_miles, Trip.milage <= max_miles).filter(Trip.num_days <= max_days, Trip.num_days >= min_days).filter(Trip.elev_max <= max_elev, Trip.elev_min >= min_elev).all() else: results = db.query(Trip).filter_by(has_xc=x_c).filter_by(region=region).filter(Trip.milage >= min_miles, Trip.milage <= max_miles).filter(Trip.num_days <= max_days, Trip.num_days >= min_days).filter(Trip.elev_max <= max_elev, Trip.elev_min >= min_elev).all() return render_template("partials/search_results.html", results=results)
def profile(): session_token = request.cookies.get("session_token") user = db.query(User).filter_by(session_token=session_token).first() if not user: # if no user is logged in return render_template("login.html") else: sent_no = len(db.query(Message).filter_by(sender=user.name).all()) rec_no = len(db.query(Message).filter_by(receiver=user.name).all()) return render_template("profile.html", user=user, brpo=sent_no, brpr=rec_no)
def admin(): active = "active" all_users = db.query(User).all() email_address = request.cookies.get("email") if email_address: user = db.query(User).filter_by(email=email_address).first() userEmail = user.email else: userEmail = "Not logged in" return render_template("admin.html", users=all_users, active3=active, emailAddress=userEmail)
async def update_time_step2(message: types.Message, state: FSMContext): birthday = db.query(Notification).filter(Notification.chat_id == message.chat.id).first() if birthday is None: notification = Notification(chat_id=message.chat.id, time=message.text) db.add(notification) db.commit() else: db.query(Notification).filter(Notification.chat_id == message.chat.id).update({'time': message.text}) db.commit() await state.finish()
def result(): guess = int(request.form.get("guess")) session_token = request.cookies.get("session_token") # get user from the database based on her/his email address user = db.query(User).filter_by(session_token=session_token).first() if guess == user.secret_number: message = "Correct! The secret number is {0}".format(str(guess)) # create a new random secret number new_secret = random.randint(1, 30) # update the user's secret number user.secret_number = new_secret # update the user object in a database db.add(user) db.commit() elif guess > user.secret_number: message = "Your guess is not correct... try something smaller." elif guess < user.secret_number: message = "Your guess is not correct... try something bigger." return render_template("result.html", message=message)
def put(self, id=None): if not id: return make_response(jsonify({"error": "id should be provided"}), 400) else: # db.query(FIND_BY_ID, id) self.reqparse = reqparse.RequestParser() self.reqparse.add_argument('success', type=str, required=True, help='No success is provided', location='json') self.reqparse.add_argument('low_point', type=str, required=True, help='No low_point is provided', location='json') self.reqparse.add_argument('take_away', type=str, required=True, help='No title is provided', location='json') values = self.reqparse.parse_args() # logger(values) response = db.query(UPDATE_BY_ID, values) # it works finally return json.loads(json.dumps(response["data"])), response["status"]
def login(): name = request.form.get("user-name") # like in bind.param in PHP email = request.form.get("user-email") # like in bind.param in PHP password = request.form.get("user-password") # like in bind.param in PHP hashed_pw = hashlib.sha256(password.encode()).hexdigest() #new Object from tpe User (model) user = db.query(User).filter_by(email=email).first() if not user: user = User(name=name, email=email, password=hashed_pw) db.add(user) db.commit() if hashed_pw != user.password: return "Wrong Password!!!" elif hashed_pw == user.password: session_token = str(uuid.uuid4()) # SESSION user.session_token = session_token db.add(user) db.commit() #Cookie response = make_response(redirect(url_for('index'))) response.set_cookie('session_token', session_token, httponly=True, samesite='Strict') return response
def login(): name = request.form.get("user-name") email = request.form.get("user-email") password = request.form.get("user-password") hashed_password = hashlib.sha256(password.encode()).hexdigest() content = "Welcome" date = datetime.datetime.now() user = db.query(ToDo).filter_by(email=email).first() if not user: user = ToDo(name=name, email=email, password=hashed_password, content=content, date=date) db.add(user) db.commit() if hashed_password != user.password: return "Wrong Password" else: session_token = str(uuid.uuid4()) user.session_token = session_token db.add(user) db.commit() response = make_response(redirect("/task")) response.set_cookie("session_token", session_token, httponly=True, samesite='Strict') return response
def index(): session_token = request.cookies.get("session_token") if session_token: user = db.query(User).filter_by(session_token=session_token).first() else: user = None return render_template('index.html', user=user)
def ajax_trip(id): """ Ajax call to return the information for a specific trips """ trip = db.query(Trip).get(id) trip_dict = compile_trip(trip) return json.dumps(trip_dict)
def login(): name = request.form.get("user-name") email = request.form.get("user-email") password = request.form.get("user-password") hashed_pw = hashlib.sha256(password.encode()).hexdigest() #neues Objekt User(Model user = db.query(User).filter_by(email=email).first() if not user: user = User(name=name, email=email, password=hashed_pw) db.add(user) db.commit() if hashed_pw != user.password: return "Wrong Password! Tra again!" elif hashed_pw == user.password: session_token = str(uuid.uuid4()) user.session_token = session_token db.add(user) db.commit() #cookie response = make_response(redirect(url_for('index'))) response.set_cookie("session_token", session_token, httponly=True, samesite="Strict") return response
def result(): num_user = int(request.form.get("num_user")) token_session = request.cookies.get("token_session") user = db.query(User).filter_by(token_session=token_session, delete=False).first() if user and num_user == user.secret_number: mensaje = "Enhorabuena!! El numero correcto es: " + str(num_user) new_secret = random.randint(1, 30) user.secret_number = new_secret db.add(user) db.commit() return render_template("result.html", mensaje=mensaje) elif num_user > user.secret_number: mensaje = "Tu numero no es correcto! Intentalo con uno mas pequeƱo!" return render_template("result.html", mensaje=mensaje) elif num_user < user.secret_number: mensaje = "Tu numero no es correcto! Intentalo con uno mas grande!" return render_template("result.html", mensaje=mensaje)
def password_check(): session_token = request.cookies.get("session_token") user = db.query(User).filter_by(session_token=session_token).first() new_password = request.form.get("new-password") new_password2 = request.form.get("new-password2") if new_password != new_password2: return "The Passwords Do Not Match" else: user.password = hashlib.sha256(new_password.encode()).hexdigest() session_token = str(uuid.uuid4()) user.session_token = session_token db.add(user) db.commit() response = make_response(redirect(url_for('profile'))) response.set_cookie("session_token", session_token, httponly=True, samesite='Strict') return response
def profile_edit(): token_session = request.cookies.get("token_session") user = db.query(User).filter_by(token_session=token_session, delete=False).first() if request.method == "GET": if user: return render_template("profile_edit.html", user=user) else: return redirect(url_for("index")) elif request.method == "POST": name = request.form.get("profile-name") email = request.form.get("profile-email") old_password = request.form.get("old-password") new_password = request.form.get("new-password") if old_password and new_password: h_old_password = hashlib.sha256(old_password.encode()).hexdigest() h_new_password = hashlib.sha256(new_password.encode()).hexdigest() if h_old_password == user.password: user.password = h_new_password else: return "Operacion incorrecta! Su antigua contraseƱa no es correcta" user.name = name user.email = email db.add(user) db.commit() return redirect(url_for("profile"))
def login(): active = "active" email = request.form["email"] password = request.form["pwd"] check_em = db.query(User).filter_by(email=email).first() if check_em is None: successMessage = "The email address or password is wrong!" successClass = "alert alert-danger" user = None return render_template("index.html", active0=active, successMessage = successMessage, successClass = successClass, user=user) elif check_em.check_password(password): successMessage = "You have successfully logged on!" successClass = "alert alert-success" name=check_em.name response = make_response( render_template("index.html", successMessage=successMessage, successClass=successClass, emailAddress=email, active0=active, user=name)) response.set_cookie("email", email) return response else: successMessage = "The email address or password is wrong!" successClass = "alert alert-danger" user = None return render_template("index.html", active0=active, successMessage = successMessage, successClass = successClass, user=user)
def blog(): current_user = request.user if request.method == "POST": title = request.form.get("posttitle") text = request.form.get("posttext") post = Post(title=title, text=text, user=current_user) db.add(post) db.commit() # send notification email msg = Message(subject="WebDev Blog - Registration Successful", sender=SENDER, recipients=[current_user.email]) msg.body = f"Hi {current_user.username}!\nWelcome to our WebDev Flask site!\nEnjoy!" msg.html = render_template("new_post.html", username=current_user.username, link=f"{HOST_ADDR}/posts/{post.id}", post=post) mail.send(msg) return redirect(url_for('blog')) if request.method == "GET": posts = db.query(Post).all() return render_template("blog.html", posts=posts, user=request.user)
def delete(id): task_to_delete = db.query(Todo).get(id) db.delete(task_to_delete) db.commit() return redirect("/")
def index(): email_adress = request.cookies.get("email") if email_adress: user = db.query(User).filter_by(email=email_adress).first() else: user = None # print(user.name) return render_template("index.html", user=user)
def posts(post_id): current_user = request.user post = db.query(Post).filter(Post.id == post_id).first() if request.method == "POST": text = request.form.get("text") comment = Comment(text=text, post=post, user=current_user) db.add(comment) db.commit() return redirect('/posts/{}'.format(post_id)) elif request.method == "GET": comments = db.query(Comment).filter(Comment.post_id == post_id).all() return render_template('posts.html', post=post, comments=comments, user=request.user)
def get_regions(): """ Return the distinct trip regions as a list to pass to the search form """ trips = db.query(Trip.region).distinct() regions= [] for trip in trips: regions.append(trip.region) return regions
def ajax_trips(): """ Ajax call to return the information for all the trips """ trips = db.query(Trip).all() all_trips = [] for trip in trips: all_trips.append(compile_trip(trip)) return json.dumps(all_trips)
def index(): # email_address = request.cookies.get("email") session_token = request.cookies.get("session_token") if session_token: user = db.query(User).filter_by(session_token=session_token).first() else: user = None return render_template("index.html", user=user)
def index(): email = request.cookies.get("email") if email: user = db.query(User).filter_by(email=email).first() else: user = None return render_template("index.html", user=user)
def task(): session = request.cookies.get("session_token") user = db.query(ToDo).filter_by(session_token=session).first() name = user.name if request.method == "POST": task_content = request.form.get("content") new_content = ToDo(name=name, content=task_content, session_token=session) db.add(new_content) db.commit() return redirect("/task") else: tasks = db.query(ToDo).filter_by(name=name).all() return render_template("task.html", tasks=tasks)
def update(id): task = db.query(Todo).get(id) if request.method == "POST": task.content = request.form["content"] db.commit() return redirect("/") else: return render_template("/update.html", task=task)
def profile(): session_token = request.cookies.get("session_token") #get user from db based on his email address / session token user = db.query(User).filter_by(session_token=session_token).first() if user: return render_template("profile.html", user=user) else: return redirect(url_for("index"))
def index(): token_session = request.cookies.get("token_session") if token_session: user = db.query(User).filter_by(token_session=token_session).first() else: user = None return render_template("index.html", user=user)
async def job(): curr_day = str(datetime.today().day) curr_month = str(datetime.today().month) curr_year = str(datetime.today().year) birthdays = db.query(Birthday).filter(Birthday.month == int(curr_month), Birthday.day == int(curr_day)).all() for b in birthdays: aioschedule.every(1).day.at('00:55').do(lambda: send_notification(b, curr_year))
def profile(): token_session = request.cookies.get("token_session") user = db.query(User).filter_by(token_session=token_session, delete=False).first() if user: return render_template("profile.html", user=user) else: return redirect(url_for("index"))
async def delete_step2(message: types.Message, state: FSMContext): birthday = db.query(Birthday).filter(Birthday.name == message.text).first() if birthday is None: await message.reply('No such name in the list') else: db.delete(birthday) db.commit() await state.finish()