def login(): if my_app.config['IP_TRACKABLE']: if 'X-Forwarded-For' in request.headers: remote_addr = request.headers.getlist( "X-Forwarded-For")[0].rpartition(' ')[-1] else: remote_addr = request.remote_addr or 'untrackable' if current_user.is_authenticated: current_user.set_location(remote_addr) db.session.commit() return redirect(url_for('index')) form = LoginForm() if form.validate_on_submit(): user = User.query.filter_by(username=form.username.data).first() if user is None: flash( u'Введенное вами имя пользователя не корректно. Проверьте свое имя пользователя и повторите попытку.' ) return redirect(url_for('login')) elif not user.check_password(form.password.data): flash( u'Неверный пароль. Проверьте свое имя пользователя или пароль и повторите попытку.' ) return redirect(url_for('login')) login_user(user, remember=form.remember_me.data) user.set_location(remote_addr) db.session.commit() next_page = request.args.get('next') if not next_page or url_parse(next_page).netloc != '': next_page = url_for('index') return redirect(next_page) return render_template('login.html', title='Вход', form=form)
def settings(): """Return CRUD view for User data""" (lat, lon) = (current_user.latitude, current_user.longitude) userStocks = current_user.stocks.all() stockList = [stock.symbol for stock in userStocks] userTodos = current_user.todos.all() todoList = [(todo.id, todo.todo) for todo in userTodos] userEmbeds = current_user.embeds.all() embedList = [(embed.embed, embed.name) for embed in userEmbeds] # TODO move all forms to top locationForm = LocationForm() # TODO move `if` blocks to a func if locationForm.submitLoc.data and locationForm.validate_on_submit(): current_user.set_location(locationForm.lat.data, locationForm.lon.data) db.session.commit() flash('Updated location.') return redirect('/settings') stockForm = StockForm() if stockForm.submitStock.data and stockForm.validate_on_submit(): stock = Stock(symbol=stockForm.symbol.data, author=current_user) db.session.add(stock) db.session.commit() flash('Added stock!') return redirect('/settings') todoForm = TodoForm() if todoForm.submitTodo.data and todoForm.validate_on_submit(): todo = Todo(todo=todoForm.todo.data, author=current_user) db.session.add(todo) db.session.commit() flash('Added todo!') return redirect('/settings') embedForm = EmbedForm() if embedForm.submitEmbed.data and embedForm.validate_on_submit(): embed = Embed(embed=embedForm.embed.data, name=embedForm.name.data, author=current_user) db.session.add(embed) db.session.commit() flash('Added embed!') return redirect('/settings') return render_template('settings.html', stocks=stockList, stockForm=stockForm, todoForm=todoForm, todos=todoList, embedForm=embedForm, embeds=embedList, locationForm=locationForm, lat=lat, lon=lon)
def before_request(): if current_user.is_authenticated: if my_app.config['IP_TRACKABLE']: if 'X-Forwarded-For' in request.headers: remote_addr = request.headers.getlist( "X-Forwarded-For")[0].rpartition(' ')[-1] else: remote_addr = request.remote_addr or 'untrackable' current_user.last_seen = datetime.utcnow() current_user.set_location(remote_addr) db.session.commit()
def register(): if my_app.config['IP_TRACKABLE']: if 'X-Forwarded-For' in request.headers: remote_addr = request.headers.getlist( "X-Forwarded-For")[0].rpartition(' ')[-1] else: remote_addr = request.remote_addr or 'untrackable' if current_user.is_authenticated: current_user.set_location(remote_addr) db.session.commit() return redirect(url_for('index')) form = RegistrationForm() if form.validate_on_submit(): user = User(username=form.username.data, email=form.email.data) user.set_password(form.password.data) user.set_location(remote_addr) db.session.add(user) db.session.commit() flash('Поздравляем, Вы зарегистрированы!') return redirect(url_for('login')) return render_template('register.html', title='Регистрация', form=form)
def edit_profile(): if request.method == 'POST': name = request.form.get("name") bio = request.form.get("bio") location = request.form.get("location") month = request.form.get("month") day = request.form.get("day") year = request.form.get("year") gender = request.form.get("gender") skills = eval(request.form.get("skills")) file = request.files.get("image") if not name: print("All fields required") return json.dumps({'status': 'Name must be filled in', 'box_id': 'name'}) if not location: print("All fields required") return json.dumps({'status': 'Location must be filled in', 'box_id': 'location'}) if not month or not day or not year: print("All fields required") return json.dumps({'status': 'Birthday must be filled in', 'box_id': 'birthdate'}) birthdate = date(month=int(month), day=int(day), year=int(year)) if not get_age(birthdate) >= 13: return json.dumps({'status': 'You must be over the age of 13', 'box_id': 'birthdate'}) location = geocode(location) if not location: print("Non-valid location") return json.dumps({'status': 'Non-valid location', 'box_id': 'location'}) if file: image = Image.open(file) new_image = image.resize((256, 256), Image.ANTIALIAS) new_image.format = image.format current_user.profile_pic.save(image=new_image) current_user.name = name.strip() current_user.bio = bio.strip() current_user.set_location(location=location, prelocated=True) current_user.set_birthdate(birthdate) current_user.gender = gender # Add skills that are not already there for skill in skills: if not current_user.skills.filter_by(title=skill).first(): skill = Skill(owner=current_user, title=skill) db.session.add(skill) # Delete skills that are meant to be deleted for skill in current_user.skills: if not skill.title in skills: db.session.delete(skill) db.session.commit() return json.dumps({'status': 'Successfully saved'}) return render_template('profile.html', edit_profile=True, profile=current_user, available_skills=available_skills, selected_month=current_user.birthdate.month, selected_day=current_user.birthdate.day, selected_year=current_user.birthdate.year)
def edit_user(): if flask_request.method == 'POST': name = flask_request.form.get("name") bio = flask_request.form.get("bio") show_location = int(flask_request.form.get("show-location")) is_visible = flask_request.form.get("visible") if is_visible: is_visible = int(is_visible) lat = flask_request.form.get("lat") lng = flask_request.form.get("lng") month = flask_request.form.get("month") day = flask_request.form.get("day") year = flask_request.form.get("year") gender = flask_request.form.get("gender") skills = eval(flask_request.form.get("skills")) file = flask_request.files.get("photo") print(file) if not name: return json.dumps({ 'status': 'Name must be filled in', 'box_id': 'name' }) if show_location: if not lat or not lng: return json.dumps({ 'status': 'Coordinates must be filled in, if you want to show your location and or be visible on the map', 'box_id': 'location' }) if [current_user.latitude, current_user.longitude ] != [float(lat), float(lng)]: location = funcs.reverse_geocode([lat, lng]) if not location: return json.dumps({ 'status': 'Invalid coordinates', 'box_id': 'location' }) current_user.set_location(location=location) current_user.show_location = True if is_visible: current_user.is_visible = True else: current_user.latitude = None current_user.longitude = None current_user.sin_rad_lat = None current_user.cos_rad_lat = None current_user.rad_lng = None current_user.address = None current_user.is_visible = False current_user.show_location = False if not month or not day or not year: return json.dumps({ 'status': 'Birthday must be filled in', 'box_id': 'birthdate' }) try: birthdate = date(month=int(month), day=int(day), year=int(year)) except ValueError: return json.dumps({ 'status': 'Invalid date', 'box_id': 'birthdate' }) if not funcs.get_age(birthdate) >= 13: return json.dumps({ 'status': 'You must be over the age of 13', 'box_id': 'birthdate' }) if len(bio) > 160: return json.dumps({ 'status': 'Your bio can\'t exceed a length of 160 characters', 'box_id': 'bio' }) current_user.bio = bio.strip() if file: current_user.profile_photo.save(file=file) current_user.name = name.strip() current_user.set_birthdate(birthdate) current_user.gender = gender # Add skills that are not already there for skill in skills: if not current_user.skills.filter_by(title=skill).first(): skill = models.Skill(owner=current_user, title=skill) db.session.add(skill) # Delete skills that are meant to be deleted for skill in current_user.skills: if not skill.title in skills: db.session.delete(skill) db.session.commit() return json.dumps({ 'status': 'success', 'username': current_user.username }) skillrows = [ current_user.skills.all()[i:i + 3] for i in range(0, len(current_user.skills.all()), 3) ] return render_template( "profiles/user/profile.html", user=current_user, skillrows=skillrows, skill_aspects=current_app.config["SKILL_ASPECTS"], available_skills=current_app.config["AVAILABLE_SKILLS"], background=True, navbar=True, size="medium", noscroll=True)