Exemplo n.º 1
0
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="Пароли не совпадают")
        db_sess = db_session.create_session()
        if db_sess.query(User).filter(User.email == form.email.data).first():
            return render_template('register.html',
                                   title='Регистрация',
                                   form=form,
                                   message="Такой пользователь уже есть")
        user = User(surname=form.surname.data,
                    name=form.name.data,
                    age=form.age.data,
                    position=form.position.data,
                    speciality=form.speciality.data,
                    address=form.address.data,
                    email=form.email.data,
                    modified_date=dt.date.today())
        user.set_password(form.password.data)
        db_sess.add(user)
        db_sess.commit()
        return redirect('/login')
    return render_template('register.html', title='Регистрация', form=form)
Exemplo n.º 2
0
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="Пароли не совпадают",
                                   title='Регистрация')
        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="Такой пользователь уже есть",
                                   title='Регистрация')
        if db_sess.query(User).filter(
                User.hashed_password == form.password.data).first():
            return render_template('register.html',
                                   form=form,
                                   message="Такой пароль уже есть",
                                   title='Регистрация')
        user = User(name=form.name.data,
                    email=form.email.data,
                    surname=form.surname.data)
        user.set_password(form.password.data)
        db_sess.add(user)
        db_sess.commit()
        return redirect('/login')
    return render_template("register.html", form=form, title='Регистрация')
Exemplo n.º 3
0
def register():
    form = RegisterForm(request.form)
    if form.validate_on_submit():
        return redirect(url_for('home'))
    if request.method == 'POST':
        pass
    return render_template('user_related/register.html', form=form)
def register():
    if current_user.is_authenticated:
        return flask.redirect(flask.url_for("feedback.feedback"))

    form = RegisterForm()

    if form.validate_on_submit():
        hashed_password = UserModel.hash_password(form.password.data)
        user = UserModel(name=form.name.data,
                         email=form.email.data.lower(),
                         password=hashed_password)

        if UserModel.verify_email(form.email.data):
            flask.flash("An account with this email already exists", "danger")
        else:
            try:
                app.db.session.add(user)
                app.db.session.commit()
                flask.flash(
                    f"The account for {form.email.data} has been created",
                    "success")
                return flask.redirect(flask.url_for("user.login"))
            except Exception as e:  # pragma: no cover
                print(e)
    return flask.render_template("user/register.html", form=form)
Exemplo n.º 5
0
def reqister():
    db_sess = db_session.create_session()
    form = RegisterForm()
    if form.validate_on_submit():
        if form.password.data != form.password_again.data:
            return render_template('register_page.html',
                                   title='Регистрация',
                                   form=form,
                                   message="Пароли не совпадают")
        if db_sess.query(User).filter(User.email == form.email.data).first():
            return render_template('register_page.html',
                                   title='Регистрация',
                                   form=form,
                                   message="Такой пользователь уже есть")
        user = User(
            email=form.email.data,
            nickname=form.login.data,
            age=form.age.data,
        )
        user.set_password(form.password.data)
        db_sess.add(user)
        db_sess.commit()
        return redirect("/login")
    return render_template('register_page.html',
                           title='Регистрация',
                           form=form)
Exemplo n.º 6
0
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)
Exemplo n.º 7
0
def register():
    form = RegisterForm()
    user = User()
    if form.validate_on_submit():
        if form.password.data != form.password_again.data:
            return render_template('register.html', title='Регистрация',
                                   form=form,
                                   message="Пароли не совпадают")
        if not user.checkNumber(form.login.data):
            return render_template('register.html', title='Регистрация',
                                   form=form,
                                   message="Неверный номер телефона")
        db_sess = db_session.create_session()
        if db_sess.query(User).filter(User.login == form.login.data).first():
            return render_template('register.html', title='Регистрация',
                                   form=form,
                                   message="Такой пользователь уже есть")
        user.login = form.login.data
        user.setPassword(form.password.data)
        db_sess.add(user)
        db_sess.commit()
        return redirect('/login')
    params = {
        "title": "Регистрация",
    }
    return render_template('register.html', **params, form=form)
Exemplo n.º 8
0
def reqister():
    global text_msg, email
    form = RegisterForm()
    delete()
    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(User).filter(User.email == form.email.data).first():
            return render_template('register.html',
                                   title='Регистрация',
                                   form=form,
                                   message="Такой пользователь уже есть")
        text_msg = random.randint(10000, 99999)
        email = form.email.data
        send_email(email, 'Потверждение почты', str(text_msg))
        user = User(name=form.name.data, email=form.email.data, checking=False)
        user.set_password(form.password.data)
        db_sess.add(user)
        db_sess.commit()
        return redirect('/register_email')
    return render_template('register.html', title='Регистрация', form=form)
Exemplo n.º 9
0
def register():
    logger.info("Entered register method")
    form = RegisterForm(request.form)
    if request.method == 'POST' and form.validate():
        email = form.email.data
        username = form.username.data
        password = sha256_crypt.encrypt(str(form.password.data))
        data = {
            "email": form.email.data,
            "username": form.username.data,
            "password": sha256_crypt.encrypt(str(form.password.data))
        }
        data = json.dumps(data)
        logger.info("Received form data")
        logger.info("Generating token")
        token = jwt.encode({}, app.config['SECRET_KEY'])
        token = token.decode('UTF-8')
        headers = {'access-token': token, 'content-type': 'application/json'}
        url = 'http://edureka-1630729118.us-east-1.elb.amazonaws.com:5002/register'
        response = requests.post(url, data=data, headers=headers)
        logger.info("Response from Register: {}".format(response.status_code))
        if response.status_code is 200:
            flash('You are now registered and can login', 'success')
            return redirect(url_for('index'))
    return render_template('register.html', form=form)
Exemplo n.º 10
0
def add_user():
    password = False
    email = False
    form = RegisterForm()
    if form.hashed_password.data != form.confirm_password.data:
        password = True
    db_sess = db_session.create_session()
    emails = []
    for user in db_sess.query(User).all():
        emails.append(user.email)
    if form.email.data in emails:
        email = True
    if form.validate_on_submit() and not password and not email:
        user = User()
        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.email = form.email.data
        user.set_password(form.hashed_password.data)
        db_sess.add(user)

        db_sess.commit()
        login_user(user)
        return redirect('/')
    return render_template('register.html',
                           title='Регистрация',
                           password=password,
                           email=email,
                           form=form)
Exemplo n.º 11
0
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="Пароли не совпадают")
        session = db_session.create_session()
        if session.query(User).filter(User.email == form.login.data).first():
            return render_template("register.html",
                                   title="Регистрация",
                                   form=form,
                                   message="Такой пользователь уже есть")
        user = User(
            surname=form.surname.data,
            name=form.name.data,
            age=form.age.data,
            position=form.position.data,
            speciality=form.speciality.data,
            address=form.address.data,
            email=form.login.data,
        )
        user.set_password(form.password.data)
        session.add(user)
        session.commit()
        return redirect("/")
    return render_template("register.html", title="Регистрация", form=form)
Exemplo n.º 12
0
def register():
    form = RegisterForm()
    if current_user.is_authenticated:
        return abort(404)
    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(User).filter(User.email == form.email.data).first()) or \
                (db_sess.query(User).filter(User.username == form.username.data).first()):
            return render_template('register.html',
                                   title='Регистрация',
                                   form=form,
                                   message='Такой пользователь уже есть')
        user = User()
        user.username = form.username.data
        user.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)
Exemplo n.º 13
0
def register():
    title = 'Регистрация | ' + TITLE
    form = RegisterForm()
    if form.validate_on_submit():
        if not check_password(form.password.data):
            return render_template('register.html', form=form, title=title,
                                   message='Пароль не соответствует требованиям')
        if form.password.data != form.password_again.data:
            return render_template('register.html', form=form, title=title, message='Пароли не совпадают!')
        sess = db_session.create_session()
        if sess.query(User).filter(User.nickname == form.nickname.data).first():
            return render_template('register.html', form=form, title=title,
                                   message='Пользователь с таким именем уже существует')
        if sess.query(User).filter(User.email == form.email.data).first():
            return render_template('register.html', form=form, title=title, message='Почта уже используется')

        user = User(
            nickname=form.nickname.data,
            email=form.email.data
        )
        user.set_password(form.password.data)
        sess.add(user)
        sess.commit()
        return redirect('/login')
    return render_template('register.html', title=title, form=form)
Exemplo n.º 14
0
def login_register():
    form_login = LoginForm()
    form_register = RegisterForm()
    if form_login.validate_on_submit():
        db_sess = db_session.create_session()
        user = db_sess.query(User).filter(
            User.email == form_login.login_email.data).first()
        if user and user.check_password(form_login.login_password.data):
            login_user(user, remember=form_login.login_remember_me.data)
            return redirect("/tasks")
        return render_template('login_register.html',
                               login_message="Неправильный логин или пароль",
                               form_login=form_login,
                               form_register=form_register,
                               login=True,
                               date=datetime.datetime.now())
    elif form_register.validate_on_submit():
        if form_register.register_password.data != form_register.register_password_again.data:
            return render_template('login_register.html',
                                   title='Регистрация',
                                   form_login=form_login,
                                   form_register=form_register,
                                   register_message="Пароли не совпадают",
                                   login=False,
                                   date=datetime.datetime.now())
        db_sess = db_session.create_session()
        if db_sess.query(User).filter(
                User.email == form_register.register_email.data).first():
            return render_template(
                'login_register.html',
                title='Регистрация',
                form_login=form_login,
                form_register=form_register,
                register_message="Такой пользователь уже есть",
                login=False,
                date=datetime.datetime.now())
        user = User(
            name=form_register.register_name.data,
            surname=form_register.register_surname.data,
            email=form_register.register_email.data,
        )
        user.set_password(form_register.register_password.data)
        db_sess.add(user)
        db_sess.commit()
        session = db_session.create_session(
        )  # каждая задача относится к какой-то категории,поэтому по умолчанию создаем категорию "Без категории"
        category = Category(color='110,110,110',
                            name='Без категории',
                            user_id=user.id)
        session.add(category)
        session.commit()

        return redirect('/login_register')
    return render_template('login_register.html',
                           title='Авторизация',
                           form_login=form_login,
                           form_register=form_register,
                           login=True,
                           date=datetime.datetime.now())
Exemplo n.º 15
0
def cek_register():
    form = RegisterForm(request.form)
    voters = None
    if request.method == 'GET':
        voters = evote.search_voters_by_name('%')
    elif request.method == 'POST' and form.validate():
        voters = evote.search_voters_by_name(request.form.get('name'))
    return render_template('cek_register.html', form=form, voters=voters)
def register():
    try:
        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(User).filter(
                    User.email == form.email.data).first():
                return render_template('register.html',
                                       title='Регистрация',
                                       form=form,
                                       message="Такой пользователь уже есть")

            verification_code = generate_code()

            email_text = "Кто-то пытается зарегистрироваться в игре Petersburg Explorer, исользуя данный email-адрес." \
                         "Если это вы, введите данный код в соответствующее поле: {}".format(verification_code)

            session['Verification Code'] = verification_code
            session['User Email'] = form.email.data
            session['User Nickname'] = form.name.data
            session['User Password'] = form.password.data

            if send_email(session['User Email'],
                          'Регистрация в Petersburg Explorer', email_text):
                logging.info(
                    'Email letter was sent. Redirected to email verification handler'
                )
                return redirect('/email_verification')

            else:
                if send_email(session['User Email'],
                              'Регистрация в Petersburg Explorer',
                              email_text,
                              from_yandex=True):
                    logging.info(
                        'Email letter was sent. Redirected to email verification handler'
                    )
                    return redirect('/email_verification')

                return render_template(
                    'register.html',
                    title='Регистрация',
                    form=form,
                    message=
                    "К сожалению, письмо не было отправлено. Попробуйте еще раз"
                )

        return render_template('register.html', title='Регистрация', form=form)

    except Exception:
        return render_template('error.html')
Exemplo n.º 17
0
def registration():
    if current_user.is_authenticated:
        return redirect("/user")
    form = RegisterForm()
    if form.validate_on_submit():
        db_sess = db_session.create_session()
        count = len(
            list(db_sess.query(User).filter(User.email == form.email.data)))
        db_sess.close()
        reg(form)
        login(form.email.data, form.password.data)
        return redirect('/')
    return render_template('registration.html', form=form)
Exemplo n.º 18
0
def register():
    form = RegisterForm()
    if form.validate_on_submit() and form.password.data == \
            form.password_again.data:
        user = User()
        user.surname = form.surname.data
        user.name = form.name.data
        user.age = form.age.data
        user.email = form.email.data
        user.set_password(form.password.data)
        db_sess = db_session.create_session()
        db_sess.add(user)
        db_sess.commit()
        return redirect('/')
    return render_template('register.html', form=form)
Exemplo n.º 19
0
def register():
    # form = request.form.to_dict()
    # # 用类函数来判断
    # u = User.register(form)
    # flash("注册" + ("成功" if u else "失败"))
    # return redirect(url_for('.login'))
    form = RegisterForm()
    if form.validate_on_submit():
        user = User.register(form.data)
        if user:
            flash('注册成功')
        else:
            flash('注册失败')
        return redirect(url_for('.login'))
    return render_template("register.html", form=form)
Exemplo n.º 20
0
def register():
    form = RegisterForm()
    if form.validate_on_submit():
        user = User()
        user.email = form.email.data
        user.set_password(form.password.data)
        user.name = form.name.data
        user.surname = form.surname.data
        user.employment = form.employment.data
        user.info = form.info.data
        session = db_session.create_session()
        session.add(user)

        session.commit()
        return redirect('/')
    return render_template('register.html', title='Register', form=form)
Exemplo n.º 21
0
def register():

    session = db_session.create_session()

    param = {}

    param['title'] = 'Регистрация'

    param['styles'] = os.listdir('static/css/styleForRegister/')
    param['path_for_style'] = '/static/css/styleForRegister/'

    form = RegisterForm()
    if form.validate_on_submit():
        user = session.query(User).filter(
            User.login == form.login.data).first()
        if user:
            return render_template(
                'register.html',
                message="Пользователь с такой почтой уже есть",
                form=form,
                **param)
        else:
            user = session.query(User).filter(
                User.name == form.name.data).first()
            if user:
                return render_template(
                    'register.html',
                    message="Пользователь с таким ником уже есть",
                    form=form,
                    **param)
            else:
                user = User()
                user.name = request.form['name']
                user.login = request.form['login']
                user.set_password(request.form['password'])
                session.add(user)
                session.commit()
                session.commit()
                login_user(user)

                return redirect('/user_info')

    return render_template('register.html', form=form, **param)


#application.run()
Exemplo n.º 22
0
def register(template):
    if current_user.is_authenticated:
        redirect('/homework')

    form = RegisterForm()

    if form.validate_on_submit():
        if form.password.data != form.password_again.data:
            return render_template(template,
                                   title='Регистрация',
                                   form=form,
                                   message="Пароли не совпадают",
                                   btn_label='Войти')

        db_sess = db_session.create_session()
        if db_sess.query(User).filter(User.email == form.email.data).first():
            return render_template(template,
                                   title='Регистрация',
                                   form=form,
                                   message="Такой пользователь уже есть",
                                   btn_label='Войти')

        # noinspection PyArgumentList
        user = User(surname=form.surname.data,
                    name=form.name.data,
                    patronymic=form.last_name.data,
                    date_of_birth=form.date_of_birth.data,
                    email=form.email.data,
                    epos_login=form.epos_login.data,
                    epos_password=form.epos_password.data,
                    school_id=int(
                        db_sess.query(School.id).filter(
                            School.title == form.school.data).first()[0]),
                    about=form.about.data)
        user.set_password(form.password.data)
        db_sess.add(user)
        db_sess.commit()
        login_user(user)
        return redirect('/profile')

    return render_template(template,
                           title='Регистрация',
                           form=form,
                           btn_label='Войти')
Exemplo n.º 23
0
def register(request):
    if request.method == 'POST':
        form = RegisterForm(request.POST)
        if form.is_valid():
            password = hashlib.md5()
            password.update(form.cleaned_data['password'].encode('utf-8'))
            password = str(password.hexdigest())
            login = form.cleaned_data['login']
            email = form.cleaned_data['email']
            if not User.objects.filter(login=login).count():
                user = User.objects.create(login=login,password=password,email=email)
                user.save()
                if not os.path.exists('/home/jurek/PycharmProjects/gpghosting/files/'+login):
                    os.mkdir('/home/jurek/PycharmProjects/gpghosting/files/'+login)
                return render(request,'gratz.html',{'login':login,'gratulowac':True})
            else:
                return render(request,'gratz.html',{'gratulowac':False})
    else:
        return render(request,'register.html',{'form':RegisterForm})
Exemplo n.º 24
0
def register():
    registerForm = RegisterForm()
    auth = firebase.auth()

    if registerForm.validate_on_submit():
        error = None
        if not registerForm.email.data:
            error = "Please enter an email address"
            flash(error)
        elif not registerForm.password.data:
            error = "please enter a password"
        # Get a reference to the auth service
        if error is None:

            try:
                user = auth.create_user_with_email_and_password(
                    registerForm.email.data, registerForm.password.data)

                data = {
                    u'user_id': user['localId'],
                    u'email': user['email'],
                    u'phone_number': '',
                    u'full_names': '',
                    u'address': '',
                    u'login': False
                }
                userRef = firestore.createUserProfile(data,
                                                      user_id=user['localId'])
                session.clear()
                session['user_id'] = user['localId']
                flash(userRef)
                return redirect('/')
            except Exception as err:
                """Return JSON instead of HTML for HTTP errors."""
                # start with the correct headers and status code from the error
                print(err)
                error = "An error occured while creating the password"

        flash(error)

    return render_template('auth/register.html', form=registerForm)
Exemplo n.º 25
0
def register():
    form = RegisterForm()
    if form.validate_on_submit():
        session = db_session.create_session()
        if form.password.data != form.password_again.data:
            return render_template('register.html', title='Регистрация', form=form, message="Пароли не совпадают")
        is_valid_password, message = valid_password(form.password.data)
        if not is_valid_password:
            return render_template('register.html', title='Регистрация', form=form, message=message)
        if session.query(User).filter(User.email == form.email.data).first():
            return render_template('register.html', title='Регистрация', form=form, message="Такой пользователь уже есть")
        user = User(
            email=form.email.data,
            name=form.name.data,
            surname=form.surname.data,
            photo_url=user_defoult_image)
        user.set_password(form.password.data)
        session.add(user)
        session.commit()
        return redirect('/login')
    return render_template('register.html', title='Регистрация', form=form)
Exemplo n.º 26
0
def register():
    if current_user.is_authenticated:
        return redirect(url_for('index'))
    form = RegisterForm()
    error = None
    if form.validate_on_submit():
        username = form.username.data
        email = form.email.data
        password = form.password.data
        # Comprobamos que no hay ya un usuario con ese email
        user = Usuario.get_by_email(email)
        if user is not None:
            flash('El email {} ya está siendo utilizado por otro usuario'.format(email))
        else:
            # Creamos el usuario y lo guardamos
            user = Usuario(name=username, email=email)
            user.set_password(password)
            user.save()
            # Dejamos al usuario logueado
            login_user(user, remember=True)
            return redirect(url_for('index'))
    return render_template("register.html", form=form)
def register():
    logger.info("Entered register method")
    form = RegisterForm(request.form)
    if request.method == 'POST' and form.validate():
        email = form.email.data
        username = form.username.data
        password = sha256_crypt.encrypt(str(form.password.data))
        data = {
            "email": form.email.data,
            "username": form.username.data,
            "password": sha256_crypt.encrypt(str(form.password.data))
        }
        data = json.dumps(data)
        logger.info("Received form data")
        headers = {'content-type': 'application/json'}
        url = 'http://user:5002/register'
        response = requests.post(url, data=data, headers=headers)
        logger.info("Response from Register: {}".format(response.status_code))
        if response.status_code is 200:
            flash('You are now registered and can login', 'success')
            return redirect(url_for('index'))
    return render_template('register.html', form=form)
Exemplo n.º 28
0
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="Пароли не совпадают")
        user = get_user_by_email(form.email.data)
        if user:
            return render_template('register.html',
                                   title='Регистрация',
                                   form=form,
                                   message="Такой пользователь уже есть")
        user = User(name=form.name.data,
                    email=form.email.data,
                    surname=form.surname.data,
                    birth_date=form.birth_date.data,
                    address=form.address.data)
        user.set_password(form.password.data)
        new_user(user)
        return redirect('/login')
    return render_template('register.html', title='Регистрация', form=form)
Exemplo n.º 29
0
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="Пароли не совпадают")
        db_sess = db_session.create_session()

        # email = session.get('email', None)
        # ok = session.get('ok', False)

        # if email is None or not ok:
        #     session.pop('email', None)
        #     session.pop('password', None)
        #     session.pop('ok', None)
        #     return redirect('/')

        user = User(
            name=form.name.data,
            email=form.email.data,
            # au_attitude=form.au_attitude.data,
            # frog_attitude=form.frog_attitude.data,
            # cvc_code=form.cvc_code.data,
            # modified_date=dt.date.today()
        )
        user.set_password(form.password.data)
        db_sess.add(user)
        db_sess.commit()
        login_user(user, remember=True)

        # session.pop('email', None)
        # session.pop('password', None)
        # session.pop('ok', None)

        return redirect('/')
    return render_template('register.html', form=form)
Exemplo n.º 30
0
def register():
    form = RegisterForm()
    if request.method == 'POST':
        if not form.validate_on_submit():
            return render_template('register.html', form=form)

        user = User.query.filter(
            User.accountNumber == form.accountNumber.data).first()

        if user:
            flash("The account is exist!")
            return render_template('register.html', form=form)

        user = User()
        user.accountNumber = form.accountNumber.data
        user.password = md5(form.password.data)
        user.name = form.name.data

        db.session.add(user)
        db.session.commit()

        return render_template('login.html', form=form)

    return render_template('register.html', form=form)
Exemplo n.º 31
0
def register():
    # Только для новых пользователей, иначе - ошибка 404
    if not current_user.is_authenticated:
        # Используется форма регистрации
        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="Passwords don't match")
            # Создаётся сессия в базе данных, обрабатывается возможность того, что пользователь уже существует
            db_sess = db_session.create_session()
            if db_sess.query(User).filter(User.email == form.email.data).first():
                return render_template('register.html', title='Registration',
                                       form=form,
                                       message="This user is already exists")
            # Вызывается функция генерации случайного аватара, если он не был загружен
            if not form.avatar.data:
                avatar_name = avatar_function('')
            else:
                # Если аватар был указан, он загружается в папку и указвается пользователю в базу данных
                avatar = form.avatar.data
                # Обрабатывается возможность того, что загруженный файл не является картинкой
                if avatar.filename.split('.')[-1] not in ['png', 'jpeg', 'jpg', 'ico', 'gif', 'bmp']:
                    return render_template('register.html', title='Registration',
                                           form=form,
                                           message="This file is not an image")
                # Имя аватара имеет вид Avatar {email пользователя} {текущая дата}
                avatar_name = 'Avatar ' + form.email.data + ' ' + str(datetime.datetime.now()).replace(":", "-") + \
                              '.' + avatar.filename.split('.')[-1]
                # Аватар сохраняется в папку static/img/Avatars/{Имя аватара}
                avatar.save("static/img/Avatars/" + avatar_name)
            # Проверка на фамилию, имя и возраст
            # Длина фамилии - не больше 20, имени - не более 15
            if len(form.surname.data) >= 20:
                return render_template('register.html', title='Registration',
                                       form=form,
                                       message="Your surname is so big, please, enter up to 20 characters")
            if len(form.name.data) >= 15:
                return render_template('register.html', title='Registration',
                                       form=form,
                                       message="Your name is so big, please, enter up to 15 characters")
            # Возраст - не менее 12 и не более 200
            if not form.age.data.isnumeric() or int(form.age.data) > 200:
                return render_template('register.html', title='Registration',
                                       form=form,
                                       message="Please, enter your correct age")
            if int(form.age.data) < 12:
                return render_template('register.html', title='Registration',
                                       form=form,
                                       message="We are sorry, this website is only for 12+ users")
            # Если пользователь успешно зарегестрировался, добавляем его в базу, имя и фамилию пишем с большой буквы,
            # имя аватара пользователя также добавляется в базу.
            user = User(
                surname=form.surname.data.strip()[0].upper() + form.surname.data.strip()[1:],
                name=form.name.data.strip()[0].upper() + form.name.data.strip()[1:],
                age=form.age.data.strip(),
                role=form.role.data.strip(),
                email=form.email.data.strip(),
                avatar=avatar_name,
            )
            # Пароль перед сохранением проверяется на надёжность и длину
            if check_user_password(form.password.data) != True:
                return render_template('register.html', title='Registration',
                                       form=form,
                                       message=check_user_password(form.password.data))
            user.set_password(form.password.data.strip())
            db_sess.add(user)
            # Сохраняем данные в базе и выводим пользователя из системы для дальнейшего входа
            db_sess.commit()
            logout_user()
            return redirect('/login')
        return render_template('register.html', title='Registration', form=form)
    else:
        abort(404)