def register(): form = RegisterForm() if form.validate_on_submit(): if form.password.data != form.password_again.data: return render_template('register.html', title='Регистрация', form=form, message="Пароли не совпадают") db_sess = db_session.create_session() if db_sess.query(Users).filter(Users.email == form.email.data).first(): return render_template( 'register.html', title='Регистрация', form=form, message="Пользователь с такой почтой уже есть") if db_sess.query(Users).filter(Users.login == form.login.data).first(): return render_template( 'register.html', title='Регистрация', form=form, message="Пользователь с таким логином уже есть") user = Users(name=form.name.data, login=form.login.data, email=form.email.data) user.set_password(form.password.data) db_sess.add(user) db_sess.commit() return redirect('/login') return render_template('register.html', title='Регистрация', form=form)
def post(self, name=None): if name is not None: abort(405, message="Can't POST to this endpoint. Try /user") received_json = request.get_json() errors = validate_values_in_dictionary( received_json, Users, required_keys={'name', 'email', 'password'}, sensitive_keys={'name'}, unique_keys={'name', 'email'}) if errors: abort(400, errors=errors) hashed_password = hash_string_with_salt(received_json['password']) try: new_user = Users(active=True, is_admin=False, name=received_json['name'], email=received_json['email'], password=hashed_password, registered_datetime=datetime.utcnow(), posts=[], comments=[]).save() except Exception as e: abort(400, errors=str(e)) return { 'message': "User '{}' registered successfully".format(new_user.name), 'user': new_user.to_json() }, 201
def reqister(): form = RegisterForm() if form.validate_on_submit(): if form.password.data != form.password_again.data: return render_template('register.html', title='Регистрация', form=form, message="Пароли не совпадают") session = db_session.create_session() if session.query(Users).filter(Users.email == form.email.data).first(): return render_template('register.html', title='Регистрация', form=form, message="Такой пользователь уже есть") if session.query(Users).filter(Users.name == form.name.data).first(): return render_template('register.html', title='Регистрация', form=form, message="Это имя уже занято") user = Users(name=form.name.data, email=form.email.data, about=form.about.data) user.set_password(form.password.data) session.add(user) session.commit() return redirect('/login') return render_template('register.html', title='Регистрация', form=form)
def register(): form = RegisterForm() if form.validate_on_submit(): if form.password.data != form.password_again.data: return render_template("register.html", form=form, message="Пароли не совпадают") session = db_session.create_session() if session.query(Users).filter(Users.email == form.email.data).first(): return render_template("register.html", title="Регистрация", form=form, message="Такой пользователь уже есть") user = Users(surname=form.surname.data, name=form.name.data, email=form.email.data, phone=form.phone.data) user.set_password(form.password.data) session.add(user) session.commit() id = session.query(Users).filter( Users.name == user.name, Users.email == user.email, Users.surname == user.surname).first().id os.chdir('static/users_data') new_dir_name = 'profile_' + str(id) if not os.path.isdir(new_dir_name): os.mkdir(new_dir_name) os.chdir('../..') return redirect('/login') return render_template('register.html', title='Регистрация', form=form)
def addUser(uid): user = Users() user.uid = uid user.state = 'firstMeet' user.last_entrace = datetime.today() session.add(user) session.commit()
def test_check_auth_non_admin(self): with allure.step("Verify check_auth flag using non admin user"): self.assertTrue( AuthenticationHelper.check_auth( username=self.non_admin_user["name"], password=self.non_admin_user["password"], user_list=Users().get_users()))
def register(): form = RegisterForm() if form.validate_on_submit(): if form.password.data != form.repeated_password.data: return render_template('register.html', form=form, error_message="Passwords don't match", title='Register') sess = db_session.create_session() if sess.query(Users).filter(Users.email == form.email.data).first(): return render_template( 'register.html', form=form, error_message='User with same email already exists', title='Register') if sess.query(Users).filter(Users.login == form.login.data).first(): return render_template('register.html', form=form, error_message='User with same login exists', title='Register') user = Users() user.email = form.email.data user.login = form.login.data user.generate_password(form.password.data) user.creation_date = datetime.datetime.now() sess.add(user) sess.commit() login_user(user) return redirect('/') return render_template('register.html', form=form, title='Register')
def reqister(): """Обработчик регистрации пользователя""" form = RegisterForm() if form.validate_on_submit(): if form.password.data != form.password_again.data: return render_template('register.html', title='Registration', form=form, message="Пароли не совпадают") session = db_session.create_session() if session.query(Users).filter(Users.email == form.email.data).first(): return render_template('register.html', title='Registration', form=form, message="Такой пользователь уже есть") user = Users(email=form.email.data) user.set_password(form.password.data) session.add(user) session.commit() return redirect('/login') return render_template('register.html', title='Registration', form=form)
def registration(): # Форма регистрации form = RegistrationForm() # POST if form.validate_on_submit(): # Проверка паролей на совпадение if form.password.data != form.password_again.data: return render_template('registration.html', form=form, message='Пароли не совпадают!') # Создаём сессию подключения к БД session = db_session.create_session() # Проверка почты на уникальность if session.query(Users).filter(Users.email == form.email.data).first(): return render_template( 'registration.html', form=form, message='Пользователь с такой почтой уже существует!') # Проверка логина на уникальность if session.query(Users).filter(Users.login == form.login.data).first(): return render_template( 'registration.html', form=form, message='Пользователь с таким логином уже существует!') # Добавление пользователя в БД user = Users(login=form.login.data, email=form.email.data) # Генерация хешированного пароля user.generate_hashed_password(form.password.data) session.add(user) # Сохранение пользователя session.commit() # Перенаправление на страницу входа return redirect('/login') return render_template('registration.html', form=form)
def post(self, token): abort_if_token_not_match(token) args = parser.parse_args() if errors_if_wrong_data(args) != "": return jsonify({"errors": errors_if_wrong_data(args)}) session = db_session.create_session() users = Users(nickname=args['nickname'], email=args['email'], hashed_password=args['hashed_password'], access_level=args['access_level']) session.add(users) session.commit() return jsonify({'success': 'OK'})
def index(): form = RegisterForm() if form.validate_on_submit(): if form.password.data != form.password_again.data: return render_template("registration.html", form=form, message="Пароли не совпадают") session = db_session.create_session() if session.query(Users).filter(Users.login == form.login.data).first(): return render_template("registration.html", title="Регистрация", form=form, message="Такой пользователь уже есть") user = Users( surname=form.surname.data, name=form.name.data, login=form.login.data, ) user.set_password(form.password.data) session.add(user) session.commit() return redirect('/login') return render_template('registration.html', form=form, title='Регистрация')
def add_data(form): session = create_session() user = Users() user.email = form.email.data user.name = form.name.data user.surname = form.surname.data user.password = hash_password(form.password.data) session.add(user) session.commit()
def delete(current_user, self, name=None): if name is None: abort( 405, message="Can't DELETE at this endpoint. Try /user/<username>") if current_user.name != name and not current_user.is_admin: abort(401, message="Missing rights.") existing_user = Users.objects(name=name).first() if existing_user is None: abort(404, message="User '{}' doesn't exist".format(name)) existing_user.delete() return {}, 204
def get(current_user, self, name=None): if name is None and not current_user.is_admin: abort( 401, message="Missing rights. Try /user/<username> for user info.") kwarg = {} if name is None else {'name': name} user_data = Users.objects(**kwarg) user_data = [user.to_json() for user in user_data] if name is None: return {'users': user_data}, 200 else: if len(user_data) < 1: abort(404, message="User '{}' doesn't exist".format(name)) return {'user': user_data[0]}, 200
def get(self): auth = request.authorization user = Users.objects(name=auth.username).first() if not auth or not auth.username or not auth.password or user is None or not verify_password(user.password, auth.password): return {'message': 'Could not verify'}, 401, {'WWW-Authenticate': 'Basic realm="Login required"'} if not user.active: abort(401, message='Your account has been banned. Please contact the moderators if you feel that was a mistake.') token = encode({ 'exp': datetime.utcnow() + timedelta(minutes=60), 'iat': datetime.utcnow(), 'sub': str(user.id) }, app_secret_key) return {'token': token.decode('UTF-8')}, 200
def decorated(*args, **kwargs): try: token = request.headers['authorization'][7:] payload = decode(token, app_secret_key) assert payload['exp'] > timegm(datetime.utcnow().utctimetuple()) assert payload['iat'] > timegm( (datetime.utcnow() - token_expiration_time).utctimetuple()) current_user = Users.objects(id=payload['sub']).first() assert current_user is not None assert current_user.active is True assert payload['iat'] >= current_user.last_logout_time except Exception as e: abort(401, message='Token is missing, invalid or expired') return f(current_user, *args, **kwargs)
def start(bot, update, user_data): userid = update.message.from_user.id username = update.message.from_user.first_name session = db_session.create_session() if not isAuthorized(userid): user = Users(userid=userid, username=username) session.add(user) session.commit() update.message.reply_text( 'Добро пожаловать в бот, который поможет вам вести учет. Учет чего? Решать вам. Бега в километрах, книги в метрах (например, Анатолий Вассерман прочитал около 100 метров "в толщину" книг и примерно столько же журналов к 2012 году)', reply_markup=default_keyboard()) if len( session.query(Categories).filter( Categories.userid == userid).all()) == 0: update.message.reply_text( 'Напишите через пробел все категории, по которым вы собираетесь вести учет. Например, "Бег(км) Фантастика(стр)"', reply_markup=ReplyKeyboardRemove()) user_data['cats'] = True return PROGRESS
def get(self, name, post_id=None): if post_id is not None and (not isinstance(post_id, str) or len(post_id) != 24): abort(404, message="{} is not a valid post id".format(post_id)) user_data = Users.objects(name=name).first() if user_data is None: abort(404, message="User '{}' doesn't exist".format(name)) if post_id is None: post_data = [post.to_json() for post in user_data.posts] return {"user's '{}' posts".format(name): post_data}, 200 else: post_data = [ post.to_json() for post in user_data.posts if str(post.id) == post_id ] if len(post_data) < 1: abort( 404, message="Post with id '{}' doesn't exist".format(post_id)) return {"user's '{}' post".format(name): post_data[0]}, 200
def put(current_user, self, name=None): if name is None: abort(405, message="Can't PUT to this endpoint. Try /user/<username>") if current_user.name != name and not current_user.is_admin: abort(401, message="Missing rights.") existing_user = Users.objects(name=name).first() if existing_user is None: abort(404, message="User '{}' doesn't exist".format(name)) received_json = request.get_json() errors = validate_values_in_dictionary( received_json, Users, sensitive_keys={'name'}, unique_keys={'name', 'email'}, admin=current_user.is_admin, admin_keys={'active', 'is_admin', 'name'}) if errors: abort(400, errors=errors) if received_json.get('active') is not None: existing_user.active = bool(received_json.get('active')) if received_json.get('is_admin') is not None: existing_user.is_admin = bool(received_json.get('is_admin')) if received_json.get('name') is not None: existing_user.name = received_json.get('name') if received_json.get('email') is not None: existing_user.email = received_json.get('email') if received_json.get('password') is not None: existing_user.password = hash_string_with_salt( received_json.get('password')) existing_user.save() return {}, 204
# post.save() # print(post.to_json()) post = Posts.objects().first_or_404() print(post.to_json()) ########################## User ########################## user_list = [] for i in range(0, 10): name = "test" + str(i) email = "primary.email_" + str(i) + "@gmail.com" user_list.append( Users(active=True, is_admin=False, name=name, email=email, password=urandom(16), registered_datetime=datetime.utcnow(), posts=[], comments=[]).save()) # print(Users.list_indexes()) # Users( # active=True, # is_admin=False, # name="test1", # email="*****@*****.**", # password=urandom(16), # registered_datetime=datetime.utcnow(), # posts=[], # comments=[]
def registration(): form = RegistrationForm() if form.validate_on_submit(): db_sess = db_session.create_session() if db_sess.query(Users).filter(Users.email == form.email.data).first(): return render_template('registration.html', title='Registration', form=form, message='Такой пользователь уже зарегистрирован.') user = Users() user.email = form.email.data user.surname = form.surname.data user.name = form.name.data user.age = form.age.data user.position = form.position.data user.speciality = form.speciality.data user.address = form.address.data user.set_password(form.password_1.data) db_sess.add(user) db_sess.commit() login_user(user, remember=True) db_sess.close() return redirect('/') return render_template('registration.html', title='Registration', form=form)
def add_user(db_sess): """ для теста создаем юзеров :param db_sess: :return: """ user1 = Users(name="Редактор", login="******", email="*****@*****.**", user_type_id=1, hashed_password='******') user2 = Users(name="Обычный пользователь", login="******", email="*****@*****.**", user_type_id=2, hashed_password='******') user3 = Users(name="Прохожий", login="******", email="*****@*****.**", user_type_id=2, hashed_password='******') user1.set_password(user1.hashed_password) user2.set_password(user2.hashed_password) user3.set_password(user3.hashed_password) db_sess.add(user1) db_sess.add(user2) db_sess.add(user3) db_sess.commit()
from api.authentication_helper import AuthenticationHelper from data.cars import Cars from data.users import Users app = Flask(__name__) # write logs for app filehandler of logging module # is not creating log directory if dir does not exist if not os.path.exists('log'): os.makedirs('log') file_handler = logging.FileHandler('log/app.log') app.logger.addHandler(file_handler) app.logger.setLevel(logging.INFO) CARS_LIST = Cars().get_cars() USER_LIST = Users().get_users() REGISTERED_CARS = [] def requires_auth(f): """ verify given user authentication details :param f: :return: """ @wraps(f) def decorated(*args, **kwargs): auth = request.authorization auth_flag = True