def login(): if current_user.is_authenticated: return redirect(url_for('index')) if request.method == "POST": data = request.form if data["type"] == "reg": try: code = User.add_user(session, data["name"], data["surname"], data["gosb"], data["vsp"], data["job"]) except ValueError: return render_template("error.html") return render_template("success.html", code=code) elif data["type"] == "auth": check = User.check_code(session, data["code"]) if check: response = redirect(url_for("index")) token = Cookie.create_cookie(session, data["code"]) user = session.query(User).filter( data["code"] == User.code).first() if "checkbox" in data.keys(): response.set_cookie('token', token, max_age=60 * 60 * 24 * 365) flask_session["remember_me"] = True login_user(user, remember=True) else: flask_session["remember_me"] = False response.set_cookie('token', token, max_age=60) login_user(user, remember=False) return response return render_template('auth.html')
async def wrapper(message): user_id = get_user_id(message) exists = User.check_user_exists(user_id) is_active = User.check_user_is_active(user_id) if not exists: await Registration.not_registration.set() from handlers.autorization import registration_not_registration_handler await registration_not_registration_handler(message) elif is_active: await func(message) else: await message.answer("Пользователь не активен!")
def create_user(username, password, admin=False): username = username.lower() if get_user_with_username(username): return False user = User(username=username, password=password) user.set_admin(admin) db.session.add(user) db.session.commit() return user.id
def prepare(self): 'Provide a db object' self.db = self.application.db_session() current_user = self.get_current_user() if current_user is not None: self.user = User.from_jupyterhub_user(current_user, self.db) else: self.user = None
def find_or_create_user(self, user_id): 'Return a User object from id; create if not found' user = self.db.query(User).filter(User.id == user_id).one_or_none() if user is None: user = User(user_id) self.db.add(user) self.db.commit() return user
async def admin_change_user_is_active_handler(call: types.CallbackQuery, *args, **kwargs): user_id = int(call.data.split(":")[1]) is_active = call.data.split(":")[2] is_active = True if is_active == "False" else False change = User.update_user({"is_active": is_active, "user_id": user_id}) if change: await call.message.edit_reply_markup( reply_markup=get_admin_change_user_handler(user_id, status=is_active)) await call.answer("Изменения приняты!")
async def registration_phone_number_handler(message: types.Message, state: FSMContext, *args, **kwargs): ''' Create new user :param state: current state of user ''' data = await state.get_data() user_dict = data.get("user_dict") user_dict['phone_number'] = message.text is_active = User.check_user_is_active(user_dict["user_id"]) if not is_active: User.create_user(user_dict) await message.answer("Регистрация прошла успешно!") else: User.update_user(user_dict) await message.answer("Изменения приняты!") await state.finish() from handlers import admin_handlers await admin_handlers.admin_main_menu_handler(message)
async def admin_change_user_handler(call: types.CallbackQuery, *args, **kwargs): await call.message.answer( "Пожалуйста подождите, идёт загрузка пользователей!") users = User.get_users() await call.message.answer(text=hbold("СПИСОК ПОЛЛЬЗОВАТЕЛЕЙ:")) for num, user in enumerate(users, start=1): await call.message.answer( text=f"{num}.Пользователь: {hbold(user.fio)}\n" f"Телефон: {user.phone_number}\n" f"ID: {user.user_id}", reply_markup=get_admin_change_user_handler(user.user_id)) await get_back(call, callback_data="to_admin_main_menu")
def insert_user(self, username, prename, name): with SafeSession() as safe_session: try: if safe_session.get_session().query(User).filter_by(username=username).first() is None: user = User(username=username, prename=prename, name=name) safe_session.add(user) safe_session.commit() return True else: return False except (SQLAlchemyError, DBAPIError) as e: safe_session.rollback() raise DBException(str)
def register(): """ :return: {"Status": 'Status', "Method": "Register", "User": {"ID": id}} """ s = sessionmaker(bind=engine) s = s() data = request.get_json() try: print(data) u = User(username=data["username"], password=data["password"], email=data["email"], phone_number=data["number"], instrument=data["instrument"], genre=data["genre"]) create_user.create(s, u) print(u) return {"Status": "OK", "Method": "Register", "User": {"ID": u.id}} except Exception as e: delete_user.delete(s, get_user.by_username(s, data["username"])) print(e) return {"Status": "NOT OK", "Method": "Register", "Detail": str(e)}
def get_admin_change_user_handler(user_id, status=None): """ :param user_id: id user's for make his active or inactive :param status: current user status :return: Keyboard for user edit """ if not isinstance(status, bool): status = User.check_user_is_active(user_id) status_name = "неактивным" if status else "активным" keyboard = InlineKeyboardMarkup( inline_keyboard=[ [InlineKeyboardButton(text="Редактировать", callback_data=f"admin_change_user_edit:{user_id}")], [InlineKeyboardButton( text=f"Сделать {status_name}", callback_data=f"admin_change_user_is_active:{user_id}:{status}" )], ] ) return keyboard
async def registration_not_registration_handler(message: types.Message, *args, **kwargs): ''' Enter personal data :param message: first name, last name and middle name ''' user_dict = {} user_id = int(kwargs.get("user_id")) if kwargs.get( "user_id") else message['chat']['id'] if user_id: user_db = User.get_user(user_id) user_dict = {"fio": user_db.fio, "phone_number": user_db.phone_number} user_dict['user_id'] = user_id if user_dict.get('fio'): await message.answer( "Введите новые Фамилию Имя и Отчество (в одну строчку)") await message.answer(f"Текущие: {user_dict.get('fio')}") else: await message.answer("Введите Фамилию Имя и Отчество (в одну строчку)") await Registration.fio.set() state = dp.current_state() await state.update_data(user_dict=user_dict)