예제 #1
0
def reqister_page():
    """"Register user with Register Form
    Fields: name, email, about, password"""
    form = RegisterForm()
    # register button
    if form.validate_on_submit():
        # check password match
        if form.password.data != form.password_again.data:
            # passwords isn't match
            return render_template('register.html', title='Регистрация',
                                   form=form,
                                   message="Пароли не совпадают")
        # new session
        db_sess = db_session.create_session()
        # check registered
        if db_sess.query(User).filter(User.email == form.email.data).first():
            # this email was registered
            return render_template('register.html', title='Регистрация',
                                   form=form,
                                   message="Такой пользователь уже есть")
        # user data
        user = User(
            name=form.name.data,
            email=form.email.data,
            about=form.about.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)
예제 #2
0
파일: main.py 프로젝트: shokkialexa/WEBapp
def register():
    """Функция обработки адреса /register - регистрация пользователя с помощью модели формы RegisterForm"""

    form = RegisterForm()
    if form.validate_on_submit():
        if form.password.data != form.password_again.data:
            return render_template('register.html',
                                   title='Register',
                                   form=form,
                                   message="Passwords don't match",
                                   img=get_background())
        db_sess = db_session.create_session()
        if db_sess.query(User).filter(User.email == form.email.data).first():
            return render_template('register.html',
                                   title='Register',
                                   form=form,
                                   message="We have such user",
                                   img=get_background())
        user = User(name=form.name.data, email=form.email.data)
        user.set_password(form.password.data)
        setting = Settings(theme='dark', user=user)
        db_sess.add(user)
        db_sess.add(setting)
        db_sess.commit()
        return redirect('/login')
    return render_template('register.html',
                           title='Register',
                           form=form,
                           img=get_background())
예제 #3
0
def register():
    register_form = RegisterForm(request.form)
    if request.method == 'POST':
        if register_form.validate():
            username = request.form['username']
            password = request.form['password']
            created = datetime.datetime.now()
            if register_validation(username):
                User.new_user(
                    username,
                    password,
                    created,
                )
                return redirect(
                    url_for('login_page.login',
                            register_redirect=REGISTER_SUCCESS))
            else:
                return render_template(
                    'register.html',
                    form=register_form,
                    message=REGISTER_FAILURE,
                )
        else:
            return render_template(
                'register.html',
                form=register_form,
                message=FORM_INVALID,
            )
    else:
        return render_template(
            'register.html',
            form=register_form,
        )
예제 #4
0
def reqister(redir=None):
    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(Guests).filter(
                Guests.email == form.email.data).first():
            return render_template('register.html',
                                   title='Регистрация',
                                   form=form,
                                   message="Такой пользователь уже есть")
        newguest = Guests(name=form.name.data,
                          surname=form.surname.data,
                          email=form.email.data,
                          phone=form.phone.data)
        newguest.set_password(form.password.data)
        db_sess.add(newguest)
        db_sess.commit()
        login_user(newguest, remember=True)
        if redir:
            return redirect(url_for(redir))
        else:
            return redirect("/booking")
    return render_template('register.html', title='Регистрация', form=form)
예제 #5
0
def register():
    # Загрузка формы регистрации
    form = RegisterForm()
    store_settings = get_store_settings()
    store_settings['title'] = 'Регистрация'
    # Проверка правильности введённых данных
    if form.validate_on_submit():
        if form.password.data != form.password_again.data:
            return render_template('register.html',
                                   form=form,
                                   message="Пароли не совпадают",
                                   **store_settings)
        if check_password(form.password.data):
            return render_template('register.html',
                                   form=form,
                                   message=check_password(form.password.data),
                                   **store_settings)
        if not form.age.data.isnumeric():
            return render_template('register.html',
                                   form=form,
                                   message="Неверный возраст",
                                   **store_settings)
        db_sess = db_session.create_session()
        if db_sess.query(User).filter(User.email == form.email.data).first():
            return render_template('register.html',
                                   form=form,
                                   message="Такой пользователь уже есть",
                                   **store_settings)
        # Создание нового пользователя и занесение в базу данных
        user = User(name=form.name.data,
                    email=form.email.data,
                    surname=form.surname.data,
                    age=int(form.age.data),
                    address=form.address.data,
                    got_bonus=0)
        user.set_password(form.password.data)
        db_sess.add(user)
        db_sess.commit()
        # Создание json-файла с данными нового пользователя: счёт, корзина и заказы
        with open(f'accounts/user_{user.id}.json', 'w',
                  encoding='utf-8') as jsonfile:
            data = {
                'shopping_cart': {
                    'items': [],
                    'summary': {}
                },
                'orders': {},
                'currencies': dict()
            }
            for i in db_sess.query(Currency).all():
                data['currencies'][i.id] = 0
            json.dump(data, jsonfile)
        return redirect("/")
    return render_template('register.html', form=form, **store_settings)
예제 #6
0
def reqister():
    form = RegisterForm()
    # register button
    if form.validate_on_submit():
        # check password match
        if form.password.data != form.password_again.data:
            # passwords isn't match
            return render_template('register.html', title='Регистрация',
                                   form=form,
                                   message="Пароли не совпадают")
        # new session
        db_sess = db_session.create_session()
        # check registered
        if db_sess.query(User).filter(User.email == form.email.data).first():
            # this email was registered
            return render_template('register.html', title='Регистрация',
                                   form=form,
                                   message="Такой пользователь уже есть")
        # если статус пользователя потребитель, потребление случайно 200-500
        if form.status.data == 'Потребитель':
            consumption = random.randint(200, 500)
        # сотрудник, потребелние нет
        else:
            consumption = -1
        # user data
        # генерация, накопление и кошелек потребителя в лк по дефолту -1
        user = User(
            name=form.name.data,
            email=form.email.data,
            status=form.status.data,
            consumption=consumption,
            generation=-1,
            storage=-1,
            wallet=-1
        )
        # объявляем глобальные переменные для использования в функции send_message()
        global cod_authentication, email_for_authentication
        # почта зарег пользователя
        email_for_authentication = form.email.data
        # генерация рандомного 5 значного кода
        cod_authentication = random.randint(10000, 99999)
        # функция отправки письма на почту
        send_message(form.email.data, cod_authentication)
        # установить пароль, коммит бд
        user.set_password(form.password.data)
        db_sess.add(user)
        db_sess.commit()
        # переход на страницу подтвержения почты
        return redirect('/authentication')

    return render_template('register.html',
                           title='Регистрация',
                           form=form
                           )
예제 #7
0
def register():
    form = RegisterForm()
    if form.validate_on_submit():
        user = User(None)
        user.username = form.username.data
        user.password = hashlib.sha1(form.password.data).hexdigest()
        db.session.add(user)
        try:
            db.session.commit()
            login_user(user)
            return redirect('/panel')
        except Exception as e:
            raise BadRequest()

    return render_template('register.html', form=form)
예제 #8
0
def signup():
    form = RegisterForm()
    if request.method == 'GET':
        return render_template("signup.html", title='Регистрация', form=form)
    else:
        # TODO: POST
        pass
예제 #9
0
class RegisterController(Controller):
    __view__ = "register"
    __title__ = "Регистрация"

    form = None

    def __init__(self):
        super(RegisterController, self).__init__()
        self.form = RegisterForm()
        self.css("register.css")

    def view(self, session: Session, **kwargs):
        if self.form.validate_on_submit():
            user = User(
                login=self.form.login.data,
                email=self.form.email.data,
                nickname=self.form.nickname.data,
                sex=self.form.sex.data,
            )
            user.set_password(self.form.password.data)
            status = DataBaseWorker.add_user(session, user)
            if status == "ok":
                return redirect("/login")
            else:
                return super(RegisterController, self).view(form=self.form, error=status)

        else:
            return super(RegisterController, self).view(form=self.form)
예제 #10
0
def render_register_page():
    register_form = RegisterForm()
    user_service = UserService(current_app)
    user = User()
    if request.method == 'POST' and register_form.validate_on_submit():
        user.login = register_form.email.data
        user.title = register_form.title.data
        user.password = register_form.password.data

        user_service.create(user)
        return redirect('/')

    # return render_template("user/register.html", form=register_form)
    return (WebSiteHtmlView("main_blocks/main_template.html").set_title(
        'Регистрация на сайте').set_content('user/register.html').render(
            form=register_form))
예제 #11
0
    def post(self, request):
        register_form = RegisterForm(request.POST)
        if not register_form.is_valid():
            return render(request, self.template_name, {"form":register_form})

        password = register_form.cleaned_data['password']
        if password != register_form.cleaned_data['password_again']:
            return render(request, self.template_name, {"form":register_form})

        login = register_form.cleaned_data['username']

        conn = cx_Oracle.connect(dbset.URL)
        cursor = conn.cursor()
        cursor.execute("BEGIN api.register('{}','{}'); END;"
                        .format(login, password))
        cursor.close()
        conn.commit()
        conn.close()
        return redirect(self.success_url)
예제 #12
0
def register():
    if current_user.is_authenticated:
        return redirect("/")
    form = RegisterForm()
    if form.validate_on_submit():
        login = form.login.data.strip()
        password = form.password.data.strip()
        user = session.query(User).filter(User.login == login).first()
        if user:
            return render_template(
                'register.html',
                message="Пользователь с таким логином уже зарегистрирован",
                form=form)
        new_user = User(login=login)
        new_user.set_password(password)
        session.add(new_user)
        session.commit()
        login_user(new_user, remember=REMEMBER_USER)
        return redirect('/')
    return render_template('register.html', form=form)
예제 #13
0
def register():
    ava = stay_ava()
    form = RegisterForm()
    param = return_files(ava=ava, form=form)
    if form.validate_on_submit():
        if form.password.data != form.password_again.data:
            return render_template('register.html', message="Пароли не совпадают", **param)
        check_pass = check_password(form.password.data)
        if check_pass:
            return render_template('register.html', **param,
                                   message=check_pass)
        db_sess = db_session.create_session()
        if db_sess.query(User).filter(User.email == form.email.data).first():
            return render_template('register.html', **param,
                                   message="Такой пользователь уже есть")
        if check_email(form.email.data):
            return render_template('register.html', **param,
                                   message=check_email(form.email.data))
        try:
            id_for_avatar = max([user.id for user in db_sess.query(User).all()]) + 1
        except ValueError:
            id_for_avatar = 0
        photo = form.avatar_photo.data
        if photo:
            with open(f'static/img/avatars/{id_for_avatar}_avatar.png', 'wb') as file:
                file.write(photo.read())
            photo = f'{id_for_avatar}_avatar.png'
        else:
            photo = 'defold_avatarka.png'
        user = User(
            surname=form.surname.data,
            name=form.name.data,
            email=form.email.data,
            photo=photo
        )
        user.set_password(form.password.data)
        db_sess.add(user)
        db_sess.commit()
        login_user(user, remember=form.remember_me.data)
        return redirect('/')
    return render_template('register.html', **param)
예제 #14
0
def register():
    form = RegisterForm()
    if form.validate_on_submit():
        '''
        if 数据库中没有该用户:存入数据库,注册成功跳转
        else: 用户已存在,跳转到登录界面
        '''
        if db.session.query(Users).filter_by(email=form.email.data).first():
            flash("该用户已存在!")
            return redirect(url_for('register'))
        else:
            user_id = db.session.query(Users).count() + 1
            #加盐hash:method='pbkdf2:sha1', salt_length=8
            #session_protection可以设为None, ‘basic‘ 或‘strong‘, 以提供不同的安全等级防止用户会话遭篡改
            user = Users(id=user_id,
                         email=form.email.data,
                         password=generate_password_hash(form.password.data))
            db.session.add(user)
            db.session.commit()
            return redirect(url_for('signin'))
    return render_template('register.html', form=form)
예제 #15
0
def register():
    form = RegisterForm()
    if form.validate_on_submit():
        db_sess = db_session.create_session()

        if form.password.data != form.repeat_password.data:
            redirect("/register")

        new_user = User()

        new_user.surname = form.surname.data
        new_user.name = form.name.data
        new_user.age = form.age.data
        new_user.position = form.position.data
        new_user.speciality = form.speciality.data
        new_user.address = form.address.data
        new_user.email = form.email.data
        new_user.hashed_password = hashlib.md5(
            form.password.data.encode()).hexdigest()

        db_sess.add(new_user)
        db_sess.commit()
    return render_template("register.html", title="Регистрация", form=form)
예제 #16
0
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='Регистрация')
예제 #17
0
def edit_account():
    store_settings = get_store_settings()
    store_settings['title'] = 'Изменить данные'
    edit_form = RegisterForm()
    db_sess = db_session.create_session()
    user = db_sess.query(User).filter(User.id == current_user.id).first()
    if not user:
        return abort(404)
    # Заполенение формы уже имеющимися данными
    if request.method == "GET":
        edit_form.email.data = user.email
        edit_form.name.data = user.name
        edit_form.surname.data = user.surname
        edit_form.age.data = user.age
        edit_form.address.data = user.address
    # Проверка правильностьи введённых данных в случае подтверждения формы
    if edit_form.validate_on_submit():
        if edit_form.password.data != edit_form.password_again.data:
            return render_template('register.html',
                                   form=edit_form,
                                   message="Пароли не совпадают",
                                   **store_settings)
        if not edit_form.age.data.isnumeric():
            return render_template('register.html',
                                   form=edit_form,
                                   message="Неверный возраст",
                                   **store_settings)
        # Перезапись данных пользователя
        user.email = edit_form.email.data
        user.name = edit_form.name.data
        user.surname = edit_form.surname.data
        user.age = int(edit_form.age.data)
        user.address = edit_form.address.data
        user.set_password(edit_form.password.data)
        db_sess.commit()
        return redirect('/user_page')
    return render_template('register.html', form=edit_form, **store_settings)
예제 #18
0
def register():
    if current_user.is_authenticated:
        return redirect('/')

    form = RegisterForm()
    context = {'form': form, 'title': 'Регистрация'}
    if form.validate_on_submit():
        db_sess = create_session()
        password = form.hashed_password.data
        if form.repeat_password.data != password:
            return render_template('register.html',
                                   message='Пароли не совпадают',
                                   **context)
        if form.email.data in [
                user.email for user in db_sess.query(User).all()
        ]:
            return render_template('register.html',
                                   message='Email уже занят',
                                   **context)
        if len(password) < 8:
            return render_template(
                'register.html',
                message='Длина пароля должна быть не менее 8 символов',
                **context)
        if not any(map(str.isdigit, password)) or not any(
                map(str.isalpha, password)):
            return render_template(
                'register.html',
                message='Пароль должен состоять из букв и цифр',
                **context)
        user = User(name=form.name.data, email=form.email.data)
        user.set_password(form.hashed_password.data)
        db_sess.add(user)
        db_sess.commit()
        return redirect('/login')
    return render_template('register.html', **context)
예제 #19
0
def register():
    loggedInUser = getLoggedUser(getUserSessionId(request))
    if loggedInUser != None:
        return redirect('/')

    form = RegisterForm()

    if request.method == 'POST':
        if not form.validate():
            return render_template('register_form.html',
                                   isUserLoggedIn=False,
                                   form=form,
                                   form_name="Register",
                                   action="register",
                                   method='POST')
        else:
            user = Users(password_hash=getPasswordHash(form.password.data),
                         username=form.username.data,
                         email=form.email.data)

            db = PostgresDb()
            db.sqlalchemy_session.add(user)
            try:
                db.sqlalchemy_session.commit()
            except DatabaseError as e:
                db.sqlalchemy_session.rollback()
                print(e)

            return redirect('/')

    return render_template('register_form.html',
                           isUserLoggedIn=False,
                           form=form,
                           form_name="Register",
                           action="register",
                           method='POST')
예제 #20
0
 def __init__(self):
     super(RegisterController, self).__init__()
     self.form = RegisterForm()
     self.css("register.css")
예제 #21
0
def register_page():
    """"Register user with Register Form
    Fields: name, email, about, password"""
    form = RegisterForm()
    # register button

    # random background image 1 of 5
    bg_index = randint(0, 4)

    if form.validate_on_submit():
        # check password match
        if form.password.data != form.password_again.data:
            # passwords isn't match
            return render_template('register.html', title='Регистрация',
                                   form=form,
                                   message="Пароли не совпадают",
                                   bg_index=bg_index)
        # new session
        db_sess = db_session.create_session()

        # check registered
        if db_sess.query(UserLogin).filter(UserLogin.email == form.email.data).first():
            return render_template('register.html', title='Регистрация',
                                   form=form,
                                   message="Такой пользователь уже есть",
                                   bg_index=bg_index)
        # user login info
        user_login = UserLogin(
            name=form.name.data,
            email=form.email.data,
            about=form.about.data
        )

        user_login.set_password(form.password.data)
        db_sess.add(user_login)

        user_inputs = UserInputs(
            weight=70,
            height=175,
            age=25,
            gender="Мужской",
            activity=2,
            wrists=18,
            waist=70,
            neck=40,
            hip=80
        )

        user_results = UserResults(
            BMI=22,
            body_type='Мезоморф'
        )

        user_login.user_inputs.append(user_inputs)
        db_sess.merge(user_login)
        db_sess.commit()

        user_login.user_results.append(user_results)
        db_sess.merge(user_login)
        db_sess.commit()

        return redirect('/login')

    return render_template('register.html', title='Регистрация', form=form, bg_index=bg_index)
예제 #22
0
    def get(self, request):

        register_form = RegisterForm()

        return render(request, self.template_name, {"form":register_form})