def login(): global recent recent = '/login' form = LoginForm() # Переход к регистрации if form.reg.data: return redirect("/registration") elif form.validate_on_submit(): user_name = form.username.data password = form.password.data user_model = UsersModel(db.get_connection()) # Проверка, существует ли аккаунт exists = user_model.exists(user_name, password) if exists[0]: session['username'] = exists[2] session['user_id'] = exists[1] else: return render_template( 'login.html', title='Авторизация', form=form, err='Проверьте правильность введенных данных', session=session) # Переход к новостям return redirect("/index") return render_template('login.html', title='Авторизация', form=form, about_page='', session=session)
def add_news(): if 'username' not in session: return redirect('/login') form = AddNewsForm() if form.back.data: return redirect('/index') elif form.validate_on_submit(): title = form.title.data content = form.content.data nm = NewsModel(db.get_connection()) nm.insert(title, content, session['user_id'], data_return()) return redirect("/index") user = UsersModel(db.get_connection()) position = user.return_position(session['user_id']) # Если пользователь случайно вбил, проверяется, имеет ли он права if not position: return render_template('indifferent/not_for_admin.html', title='У вас недостаточно прав!') else: return render_template('add_news.html', title='Добавление новости', form=form, username=session['username'], about_page='', session=session)
def show_performance(performance_id): if 'username' not in session: return redirect('/login') performances_model = PerformancesModel(db.get_connection()) exists = performances_model.exists(performance_id) if not exists[0]: return redirect('/performances') performance = performances_model.get(performance_id) actors_model = ActorsModel(db.get_connection()) res_actors = [] actors = performance[4].split(',') for actor in actors: actor = actor.strip() exists = actors_model.exists(actor) if exists[0]: res_actors.append(exists[1:]) if session['username'] == ADMIN_NAME: admin = True else: admin = False users_model = UsersModel(db.get_connection()) if str(performance_id) in users_model.get_favourites( session['user_id']).split(','): in_favourites = True else: in_favourites = False return render_template('performance.html', title=performance[1], performance=performance, actors=res_actors, admin=admin, in_favourites=in_favourites)
def registration(): global recent recent = 'registration' form = RegistrationForm() user_model = UsersModel(db.get_connection()) if form.back.data: return redirect('/login') elif form.validate_on_submit(): user_name = form.username.data password = form.password.data email = form.email.data about = form.about.data user_model.insert(user_name, password, email, about) # Проверка, точно ли все в базе exists = user_model.exists(user_name, password) if exists[0]: session['username'] = user_name session['user_id'] = exists[1] # Переход к новостям return redirect('/index') return render_template('registration.html', title='Регистрация', form=form, err='', about_page='Расскажите нам немного о себе!', session=session)
def sign_up(): form = RegistrationForm() if form.validate_on_submit(): username = form.username.data password1 = form.password1.data password2 = form.password2.data users_model = UsersModel(db.get_connection()) for user in users_model.get_all(): if user[1] == username: return render_template('registration.html', title='Регистрация', form=form, error_text='Этот логин уже занят') if len(password1) < 5: return render_template('registration.html', title='Регистрация', form=form, error_text='Пароль слишком короткий') elif password1 != password2: return render_template('registration.html', title='Регистрация', form=form, error_text='Пароли различаются') else: users_model.insert(username, generate_password_hash(password1)) return redirect('/login') return render_template('registration.html', title='Регистрация', form=form)
def user_page(username): if "userid" not in session: return redirect('/login') posts = PostsModel(db.get_connection()) users = UsersModel(db.get_connection()) subs = SubsModel(db.get_connection()) userid = users.get_by_name(username)[0] all_posts = [] for i in posts.get_all(userid): all_posts.append({ 'pub_date': datetime.fromtimestamp(i[5]).strftime('%d.%m.%Y %H:%M'), 'title': i[1], 'thumb': i[3], 'userid': i[4], 'pid': i[0] }) user_data = users.get(userid) user_info = { 'username': user_data[1], 'main_photo': user_data[4], 'subscribed': subs.check_subscribed(session['userid'], userid), 'userid': user_data[0] } user_data = users.get(session['userid']) sess_info = {'username': user_data[1], 'main_photo': user_data[4]} return render_template('project_index.html', title='Instagram', posts=all_posts, user_info=user_info, sess_info=sess_info)
def index(): if "userid" not in session: return redirect('/login') posts = PostsModel(db.get_connection()) all_posts = [] for i in posts.get_all(session['userid']): all_posts.append({ 'pub_date': datetime.fromtimestamp(i[5]).strftime('%d.%m.%Y %H:%M'), 'title': i[1], 'thumb': i[3], 'userid': i[4], 'pid': i[0] }) users = UsersModel(db.get_connection()) subs = SubsModel(db.get_connection()) user_data = users.get(session['userid']) user_info = { 'username': user_data[1], 'main_photo': user_data[4], 'followers_count': subs.get_followers(session['userid']), 'subscriptions_count': subs.get_subscriptions(session['userid']), 'posts_count': posts.get_count(session['userid']), 'userid': session['userid'] } return render_template('project_index.html', title='Instagram', posts=all_posts, user_info=user_info, sess_info=user_info)
def add_topic(): if 'username' not in session: return redirect('/login') form = AddTopicForm() if form.back.data: return redirect('/topics') elif form.validate_on_submit(): title = form.title.data content = form.content.data nm = TopicModel(db.get_connection()) nm.insert(title, content, session['user_id'], data_return()) return redirect("/topics") user = UsersModel(db.get_connection()) position = user.return_position(session['user_id']) # Проверка, имеет ли пользователь права if not position: return render_template('indifferent/not_for_admin.html', title='У вас недостаточно прав!', session=session) else: return render_template('add_topic.html', title='Добавление темы', form=form, username=session['username'], about_page='', session=session)
def register(): form = RegisterForm() if form.validate_on_submit(): users = UsersModel(db.get_connection()) users.insert(form.username.data, form.password.data) speak('registration successful!') flash('You have successfully registered', 'success') return redirect('/login') return render_template('register.html', title='Registration', form=form)
def search_user(self): username = self.search_line.text() users = UsersModel(self.db.get_connection()) user = users.get_by_name(username) if not user: self.warning.setText('Пользователя с таким именем не существует.') else: self.warning.setText('') self.current_page = user self.show_page()
def delete_from_favourites(perf_id): if 'username' not in session: return redirect('/login') user_id = session['user_id'] users_model = UsersModel(db.get_connection()) favourites = users_model.get_favourites(user_id).split(',') if str(perf_id) not in favourites: return redirect('/performances') del favourites[favourites.index(str(perf_id))] users_model.edit_favourites(user_id, ','.join(favourites)) return redirect('/performances')
def change_info(): if "userid" not in session: return redirect('/login') form = ChangeInfoForm() if form.password_hash.data: password_hash = generate_password_hash(form.password_hash.data) else: password_hash = '' keys = {'user_name': form.user_name.data, 'password_hash': password_hash} users = UsersModel(db.get_connection()) if form.validate_on_submit(): if not users.get_by_name(form.user_name.data): if form.main_photo.data != '': f = request.files['main_photo'] save_filename, thmb_filename = save_file(f) users.update_user_info(session['userid'], 'main_photo', thmb_filename) for key in keys: if keys[key] != '': users.update_user_info(session['userid'], key, keys[key]) return redirect('/') else: form.username.errors.append( 'Пользователь с таким именем уже существует') user_data = users.get(session['userid']) user_info = {'username': user_data[1], 'main_photo': user_data[4]} return render_template('project_change_info.html', form=form, user_info=user_info, sess_info=user_info)
def show_favourites(): if 'username' not in session: return redirect('/login') performances_model = PerformancesModel(db.get_connection()) users_model = UsersModel(db.get_connection()) res = [] favourites = users_model.get_favourites(session['user_id']) for item in favourites.split(','): exists = performances_model.exists(item) if exists[0]: res.append(exists[1:5]) return render_template('favourites.html', title='Избранное', username=session['username'], favourites=res)
def login(): form = LoginForm() if form.validate_on_submit(): username = form.username.data password = form.password.data users_model = UsersModel(db.get_connection()) exists = users_model.exists(username) if exists[0] and check_password_hash(exists[2], password): session['username'] = username session['user_id'] = exists[1] return redirect('/performances') return render_template('login.html', title='Авторизация', form=form, error_text='Неверный логин или пароль') return render_template('login.html', title='Авторизация', form=form)
def register(): form = RegisterForm() if form.validate_on_submit(): users = UsersModel(db.get_connection()) if not users.get_by_name(form.username.data): hashed_password = generate_password_hash(form.password.data) users.insert(form.username.data, hashed_password) flash('Спасибо за регистрацию', 'success') return redirect('/login') else: form.username.errors.append( 'Пользователь с таким именем уже существует') return render_template('project_register.html', title='Instagram', form=form, user_info={'userid': 0})
def topics(): global recent recent = '/topics' if 'username' not in session: return redirect('/login') if request.method == 'POST': if 'perenap' in request.form: return redirect('/add_topic') user = UsersModel(db.get_connection()) position = user.return_position(session['user_id']) topics = TopicModel(db.get_connection()) topics = topics.get_all() return render_template('topics.html', title='Наиболее актуальные и волнующие темы', topics=topics, position=position, session=session)
def upload_photo(): if "userid" not in session: return redirect('/login') form = UploadPhotoForm() if form.validate_on_submit(): f = request.files['file'] save_filename, thmb_filename = save_file(f) posts = PostsModel(db.get_connection()) posts.insert(form.descrypt.data, save_filename, thmb_filename, session['userid']) return redirect('/') users = UsersModel(db.get_connection()) user_data = users.get(session['userid']) user_info = {'username': user_data[1], 'main_photo': user_data[4]} return render_template('project_add_photos.html', form=form, user_info=user_info, sess_info=user_info)
def login(): try: session.pop('username', 0) session.pop('user_id', 0) except Exception: pass form = LoginForm() if form.validate_on_submit(): user_name = form.username.data password = form.password.data user_model = UsersModel(db.get_connection()) exists = user_model.exists(user_name, password) if (exists[0]): session['username'] = user_name session['user_id'] = exists[1] return redirect("/crimes") return render_template('login.html', title='TattleCrime.com', form=form)
def for_adm(): if 'username' not in session: return redirect('/login') um = UsersModel(db.get_connection()) user = um.return_position(session['user_id']) # Проверка, есть ли права if user: nm = NewsModel(db.get_connection()) news = nm.get_all_likes() print(news) return render_template('for_admin.html', mas=news, title='Информация о лайках', session=session) else: return render_template('indifferent/not_for_admin.html', title='У вас недостаточно прав!', session=session)
def login(): form = LoginForm() login_error = '' if form.validate_on_submit(): users = UsersModel(db.get_connection()) # проверяем существует ли пользователь с таким логином и паролем user = users.exists(form.username.data, form.password.data) if user[0]: # выставляем id пользователя в сессию session['userid'] = users.get(user[1])[0] return redirect('/') else: login_error = 'Неправильный логин или пароль' return render_template('project_login.html', title='Instagram', form=form, login_error=login_error, user_info={'userid': 0})
def index(): global recent recent = '/index' if 'username' not in session: return redirect('/login') if request.method == 'POST': # Добавление новости. Только для админа if 'perenap' in request.form: return redirect('/add_news') user = UsersModel(db.get_connection()) # Проверка. User или adm (пользователь или админ) position = user.return_position(session['user_id']) news = NewsModel(db.get_connection()) news = news.get_all(session['user_id']) return render_template('all_news.html', title='Новости', news=news, position=position, session=session)
def new_user(self): if self.login_line.text() != '' and self.password_line.text( ) != '' and self.password_line_2.text() != '': user = UsersModel(self.db.get_connection()).get_by_name( self.login_line.text()) if not user: if self.password_line.text() == self.password_line_2.text(): UsersModel(self.db.get_connection()).insert( self.login_line.text(), self.password_line.text()) self.reg = RegDialog() self.reg.show() self.reg.ok.clicked.connect(self.login) else: self.warning.move(330, 390) self.warning.setText('Пароли не совпадают.') else: self.warning.move(290, 390) self.warning.setText('Это имя пользователя уже занято.') else: self.warning.move(330, 390) self.warning.setText('Заполните все поля.')
def show_performances(): if 'username' not in session: return redirect('/login') performances_model = PerformancesModel(db.get_connection()) performances = performances_model.get_all() if session['username'] == ADMIN_NAME: admin = True else: admin = False res = {} users_model = UsersModel(db.get_connection()) for item in performances: if str(item[0]) in users_model.get(session['user_id'])[3].split(','): res[item[0]] = True else: res[item[0]] = False return render_template('performances.html', username=session['username'], title='Спектакли', performances=performances, admin=admin, in_favourites=res)
def admin(): if "username" not in session or session['admin'] != 1: flash('Access is denied', 'danger') return redirect('/') event, users = EventModel(db.get_connection()), UsersModel( db.get_connection()) names, amount = {}, {} for n in event.get_all(): if n[3] in amount: amount[n[3]] += 1 else: names[n[3]] = users.get(n[3])[1] amount[n[3]] = 1 return render_template('admin.html', title='User statistics', amount=amount, names=names)
def registration(): try: session.pop('username', 0) session.pop('user_id', 0) except Exception: pass form = RegistrationForm() if form.validate_on_submit(): user_name = form.username.data password = form.password.data age = form.age.data user_model = UsersModel(db.get_connection()) exists = user_model.exists(user_name, password) if not (exists[0]): um = UsersModel(db.get_connection()) um.insert(user_name, password, age) return redirect("/login") return render_template('registration.html', title='Tattle Crime', form=form)
def get(self, user_id): abort_if_not_authorized() if user_id == 0: # поиск пользователя parser = reqparse.RequestParser() parser.add_argument('user_name') args = parser.parse_args() # получаем данные пользователя по имени user = UsersModel(db.get_connection()).get_by_name( args['user_name']) return jsonify({'user': user}) else: # вывод статистики posts = PostsModel(db.get_connection()) subs = SubsModel(db.get_connection()) return jsonify({ 'followers_count': subs.get_followers(user_id), 'subscriptions_count': subs.get_subscriptions(user_id), 'posts_count': posts.get_count(user_id) })
def check_password(self): if self.login_line.text() != '' and self.password_line.text() != '': user = UsersModel(self.db.get_connection()).get_by_name( self.login_line.text()) if user: if user[2] == self.password_line.text(): self.warning.setText('') self.current_user = user self.current_page = user self.show_page() elif user[2] != self.password_line.text(): self.warning.move(210, 390) self.warning.setText( 'Неверное имя пользователя или пароль. Попробуйте еще раз.' ) else: self.warning.move(210, 390) self.warning.setText( 'Неверное имя пользователя или пароль. Попробуйте еще раз.' ) else: self.warning.move(330, 390) self.warning.setText('Заполните все поля.')
def add_to_favourites(perf_id): if 'username' not in session: return redirect('/login') user_id = session['user_id'] performances_model = PerformancesModel(db.get_connection()) exists = performances_model.exists(perf_id)[0] if not exists: return redirect('/performances') users_model = UsersModel(db.get_connection()) if str(perf_id) in users_model.get_favourites( session['user_id']).split(','): return redirect('/performances') favourites = users_model.get_favourites(user_id) if len(favourites) > 0: favourites += ',{}'.format(perf_id) else: favourites += str(perf_id) users_model.edit_favourites(user_id, favourites) return redirect('/favourites')
def login(): form = LoginForm() login_error = '' if form.validate_on_submit(): users = UsersModel(db.get_connection()) user = users.exists(form.username.data, form.password.data) if user[0]: session['userid'] = users.get(user[1])[0] session['username'] = users.get(user[1])[1] session['admin'] = users.get(user[1])[3] session['sort'] = 0 speak('Login approved!') return redirect('/') else: login_error = 'Invalid Login Cradentials.' speak('Invalid Login Cradentials.') return render_template('login.html', title='My Diary', brand="Personal Diary", form=form, login_error=login_error)
title='Избранное', username=session['username'], favourites=res) @app.route('/favourites/<int:perf_id>/delete') def delete_from_favourites(perf_id): if 'username' not in session: return redirect('/login') user_id = session['user_id'] users_model = UsersModel(db.get_connection()) favourites = users_model.get_favourites(user_id).split(',') if str(perf_id) not in favourites: return redirect('/performances') del favourites[favourites.index(str(perf_id))] users_model.edit_favourites(user_id, ','.join(favourites)) return redirect('/performances') if __name__ == '__main__': db = DataBase() ActorsModel(db.get_connection()).init_table() PerformancesModel(db.get_connection()).init_table() um = UsersModel(db.get_connection()) um.init_table() if not um.exists(ADMIN_NAME)[0]: um.insert(ADMIN_NAME, ADMIN_PASSWORD_HASH) app.run(port=8080, host='127.0.0.1')