Beispiel #1
0
 def addUser(self, info):
     ses = self.takeSes()
     new_user = User()
     new_user.insert_before(info)
     # new_user = User(name=info['name'] + '_abc', password=info['password'])
     # ses.add(new_user)
     try:
         ses.add(new_user)
         ses.commit()
         # result = ses.query(User).filter(User.id == 1).all()
         #
         # if len(result) == 0:
         #     raise BaseException
         # else:
         #     ret = new_user.to_dict()
         #
         #     ses.commit()
         #     ses.close()
         #     return ret
         # 此处需将关闭连接放到finally里面去做  否则获取不到id
         # ses.close()
         return new_user.id
     except:
         return False
     finally:
         ses.close()
Beispiel #2
0
 def regisration():
     title = "Регистрация в Apotheka"
     login_form = RegistrationForm(request.form)
     if request.method == 'POST' and login_form.validate():
         user = User(username=login_form.user_name.data,
                     email=login_form.email.data,
                     userTelegrammChat=request.form.get("telegram"))
         try:
             user.set_password(login_form.password.data)
             db.session.add(user)
             db.session.commit()
             profile = Profile(
                 user_id=user.id,
                 name=login_form.Name.data,
                 sername=login_form.Sername.data,
                 age=int(login_form.age.data),
                 isWoman=(
                     # Не уверен на счет верности переноса
                     str_to_bool(request.form.get("gender"))))
             db.session.add(profile)
             db.session.commit()
             flash('Спасибо за регистрацию')
             return redirect(url_for('login'))
         except IntegrityError:
             flash('Пользователи с такими данными уже существуют')
             return redirect(url_for('regisration'))
     return render_template('/user/registration.html',
                            title=title,
                            form=login_form,
                            User="",
                            Profile="")
Beispiel #3
0
def registration():
    if current_user.is_authenticated:
        return redirect(url_for('index'))
    form = RegistrationForm()
    if form.validate_on_submit():
        user = User(username=form.username.data, email=form.email.data)
        user.set_password(form.password.data)
        db.session.add(user)
        db.session.commit()
        flash('You are now registered user!')
        return redirect(url_for('login'))
    return render_template('registration.html', title='Register', form=form)
Beispiel #4
0
def new_user():
    json_data = request.json
    name = json_data['name']
    email = json_data['email']
    password = json_data['password']
    delivers = json_data['delivers']

    if User.query.filter_by(email=email).first() is None:
        user = User(name=name, email=email, delivers=delivers)
        user.set_password(password)
        db.session.add(user)
        db.session.commit()
        return jsonify({'id': user.id, 'name': user.name}), 201

    return jsonify({'msg': "Something got wrong"}), 400
Beispiel #5
0
    def process_reg():
        form = RegistrationForm()
        if form.validate_on_submit():
            new_user = User(username=form.username.data,
                            email=form.email.data,
                            role='user')
            if form.first_name.data:
                new_user.first_name = form.first_name.data
            if form.last_name.data:
                new_user.last_name = form.last_name.data
            if form.city.data:
                new_user.city = form.city.data
            new_user.set_password(form.password.data)
            db.session.add(new_user)
            db.session.commit()
            flash('Вы успешно зарегистрировались')
            return redirect(url_for('login'))

        else:
            for field, errors in form.errors.items():
                for error in errors:
                    flash('Ошибка в поле {}: {}'.format(
                        getattr(form, field).label.text, error))

        return redirect(url_for('register'))
Beispiel #6
0
def test_db ():
    user_test=User(name='Vasya', surname='Ivanov', email='*****@*****.**', login='******', password='******')
    print (user_test)
    db.session.add(user_test)
    try:
        db.session.commit()
    except:
        return 'Пользователь с такими логином или почтой уже есть'
    return ('Проверьте, прошла ли запись в БД')
 def process_registration():
     if current_user.is_authenticated:
         return redirect('/')
     form = RegistrationsForm()
     if form.validate_on_submit():
         username = request.form['username']
         password = request.form['password']
         user = User(username=username)
         user.set_password(password)
         db.session.add(user)
         db.session.commit()
         flash('Вы успешно зарегистрировались!')
         return redirect('/login')
     else:
         for field, errors in form.errors.items():
             for error in errors:
                 flash('Ошибка в поле "{}":  {}'.format(
                     getattr(form, field).label.text, error))
     return redirect(url_for('registration'))
Beispiel #8
0
 def process_reg():
     form = RegistrationForm()
     if form.validate_on_submit():
         new_user = User(username=form.username.data,
                         email=form.email.data,
                         role='user')
         new_user.set_password(form.password.data)
         db.session.add(new_user)
         db.session.commit()
         flash('Вы успешно зарегистрировались!')
         return redirect(url_for('login'))
     else:
         for field, errors in form.errors.items():
             for error in errors:
                 flash('Ошибка в поле "{}": - {}'.format(
                     getattr(form, field).label.text, error))
         return redirect(url_for('register'))
     flash('Пожалуйста, исправьте ошибки в форме')
     return redirect(url_for('register'))
 def Import(self, file_path):
     with open(file_path, 'r') as f:
         u = eval(f.read())
         # print(u)
         for user in u['db']:
             # print(user)
             obj = User(firstname=user['firstname'],
                        lastname=user['lastname'],
                        email=user['email'],
                        phone=user['phone'],
                        address=user['address'],
                        roll=user['roll'],
                        password=user['password'],
                        dob=user['dob'])
             db.session.add(obj)
             db.session.commit()
Beispiel #10
0
def users():
    title = 'Пользователи'
    positions = [(p.id, p.position_name) for p in Position_type.query.all()]
    user_form = UserForm(request.form)
    user_form.position_type.choices = positions
    users_list = User.query.all()

    if user_form.validate_on_submit():
        print(1)
        first_name = user_form.first_name.data
        last_name = user_form.last_name.data
        slack_id = user_form.slack_id.data
        position_type = user_form.position_type.data
        start_date = user_form.start_date.data
        new_user = User(first_name=first_name,
                        last_name=last_name,
                        slack_id=slack_id,
                        start_date=start_date,
                        position_type=position_type)
        schedule_to_insert = [new_user]
        events = Event.query.filter(
            Event.positions.any(id=user_form.position_type.data)).all()

        for event in events:
            day_now = datetime.now().date()
            interval = timedelta(days=event.interval)
            delivery_date = start_date + interval

            if delivery_date < day_now:
                continue

            schedule_to_insert.append(
                Schedule(user=new_user,
                         event_id=event.id,
                         delivery_date=delivery_date))
        print(schedule_to_insert)
        db.session.add_all(schedule_to_insert)
        db.session.commit()
        flash('Пользователь успешно добавлен.')
        return redirect(url_for('user.users'))

    return render_template('user/users.html',
                           title=title,
                           form=user_form,
                           users_list=users_list)
Beispiel #11
0
def signup():
    form = SignUp()
    if form.validate_on_submit():
        test_user = User.query.filter_by(username=form.username.data).first()
        print(test_user)
        if test_user:
            flash("Username registered...!")
            return redirect(url_for('users.signup'))
        if int(form.age.data) < 18:
            flash("You are under aged to create an account...!")
            return redirect(url_for('users.signup'))

        user = User(form.username.data,
                    form.password.data, form.email.data, form.city.data,
                    int(form.age.data), form.occupation.data, form.state.data)
        db.session.add(user)
        db.session.commit()
        flash('Thanks for Registrating..!')
        return redirect(url_for('users.login', username=form.username.data))
    return render_template('signup.html', form=form)
Beispiel #12
0
def mySign():
    form = RegisterationForm()
    if request.method == 'POST' and form.validate_on_submit():
        firstname = request.form['firstname']
        lastname = request.form['lastname']
        phone = request.form['phone']
        address = request.form['address']
        dob = request.form['dob']
        email = request.form['email']
        password = request.form['password']
        cpassword = request.form['confirmpassword']

        try:
            user = User.query.filter_by(phone=phone).first()
        except:
            user = None
        if not user:
            if password != cpassword:
                flash('confirm password should be same', 'danger')
                return render_template('signin.html')
            else:
                roll = 'U'
                new = User(firstname=firstname, lastname=lastname,
                           email=email, address=address, dob=dob,
                           phone=phone, password=encode(password), roll=roll)
                # print(new)
                db.session.add(new)
                db.session.commit()
                print('created')
                flash('user created successfully', 'success')
                return redirect(url_for('mySign'))
        else:
            flash('Phone no. already exsits', 'danger')
            return redirect(url_for('mySign'))
    err = list(form.errors.keys())
    if err:
        flash(f'{err[0]} {form.errors[err[0]][0].lower()}', 'danger')
    return render_template('signin.html', form=form)
Beispiel #13
0
from getpass import getpass
import sys

from webapp import create_app
from webapp.model import db, User

app = create_app()

with app.app_context():
    username = input("Введите имя: ")

    if User.query.filter(User.username == username).count():
        print("Пользователь с таким именем уже существует!")
        sys.exit(0)

    password1 = getpass('Введите пароль')
    password2 = getpass('Повторите пароль')

    if not password1 == password2:
        print('Пароли не совпадают')
        sys.exit(0)

    new_user = User(username=username, role="admin")
    new_user.set_password(password1)

    db.session.add(new_user)
    db.session.commit()
    print('Создан пользователь с id={}'.format(new_user.id))
Beispiel #14
0
    def post(self):
        """
        Create a new user
        ---
        tags:
          - users
        parameters:
          - in: body
            name: body
            schema:
              id: user_in
              required:
                - username
                - password
              properties:
                username:
                  type: string
                  description: username for user login
                password:
                  type: string
                  description: password for user login
                fname:
                  type: string
                  description: first name of user
                lname:
                  type: string
                  description: last name of user
                email:
                  type: string
                  description: email address of user
        responses:
          201:
            description: User created
            schema:
              id: user_out
          400:
            description: username taken
            schema:
              id: error
              properties:
                error:
                  type: string
                  description: description of error
        """
        # celery test
        # rq = tasks.hello.apply_asyc(args=["Post User"])
        # results = async_result.AsyncResult(str(rq))
        # print results.get()

        un = request.json.get('username', 'guest')
        user = User.query.filter_by(username=un).first()
        pw = str(request.json.get('password', ''))
        if user is not None:
            return jsonify(error='Username Taken'), 400
        if options.get('testEnabled', False):
            # less secure for testing - faster
            pw_hash = bcrypt.hashpw(pw, bcrypt.gensalt(4))
        else:
            pw_hash = bcrypt.hashpw(pw, bcrypt.gensalt(14))
        fname = request.json.get('fname', '')
        lname = request.json.get('lname', '')
        em = request.json.get('email', '')
        hash_id = hashlib.sha256(str(random.getrandbits(256))).hexdigest()
        user_guid = uuid.uuid4()
        team_id = request.json.get('team_id')

        u = User(username=un,
                 email=em,
                 password=pw_hash,
                 secure_id=None,
                 first_name=fname,
                 last_name=lname,
                 hash_id=hash_id,
                 user_guid=user_guid,
                 team_id=team_id)
        db.session.add(u)
        db.session.commit()

        # Building out user to push out
        user = User.query.filter_by(username=un).first()
        return jsonify(user=user.as_json()), 201
Beispiel #15
0
from getpass import getpass
import sys

from webapp import create_app
from webapp.model import User, db

app = create_app()

with app.app_context():
    user_name = input('Enter username: '******'This user name already exists')
        sys.exit(0)

    password = getpass('Enter password: '******'Reenter password: '******'admin')
    new_user.set_password(password)

    db.session.add(new_user)
    db.session.commit()
    print('User with id {} added'.format(new_user.id))
Beispiel #16
0
from getpass import getpass
import sys

from webapp import create_app
from webapp.db import db
from webapp.model import User

app = create_app()

with app.app_context():
    username = input('Введите имя пользователя: ')

    if User.query.filter(User.username == username).count():
        print('Пользователь с таким именем уже существует')
        sys.exit(0)

    password1 = getpass('Введите пароль')
    password2 = getpass('Повторите пароль')

    if not password1 == password2:
        print('Пароли не одинаковые')
        sys.exit(0)

    new_user = User(username=username)
    new_user.set_password(password1)

    db.session.add(new_user)
    db.session.commit()
    print('Совздан пользователь с id={}'.format(new_user.id))
Beispiel #17
0
from webapp.model import db, User

app = create_app()

with app.app_context():
    email = input('Введите ваш e-mail: ')

    if User.query.filter(User.email == email).count():
        print('Такая почта уже используется')
        sys.exit(0)

    username = input('Введите имя: ')

    if User.query.filter(User.username == username).count():
        print('Такой пользотваель уже существует')
        sys.exit(0)

    password1 = getpass('Введите пароль:')
    password2 = getpass('Повторите пароль:')

    if not password1 == password2:
        print('Пароли не совпадают')
        sys.exit(0)

    new_user = User(username=username, role='admin', email=email)
    new_user.set_password(password1)

    db.session.add(new_user)
    db.session.commit()
    print(f'Создан пользователь с id={new_user.id} и почтой {email}')
Beispiel #18
0
from getpass import getpass
import sys

from webapp import create_app
from webapp.model import User, db

app = create_app()

with app.app_context():
    username = input('Введите имя пользователя: ')

    if User.query.filter(User.username == username).count():
        print('Такой пользователь уже есть')
        sys.exit(0)

    password1 = getpass('Введите пароль: ')
    password2 = getpass('Повторите пароль: ')
    if not password1 == password2:
        sys.exit(0)

    new_user = User(username=username, role='user')
    new_user.set_password(password1)

    db.session.add(new_user)
    db.session.commit()

    print("Создан пользователь с ID={}".format(new_user.id))
Beispiel #19
0
from getpass import getpass  # Поле импут не печает вводимое символы
import sys

from webapp import create_app
from webapp.model import db, User

app = create_app()

with app.app_context():
    new_username = input('Введите имя: ')

    if User.query.filter(User.username == new_username).count():
        print('Такой пользователь уже существует')
        sys.exit(0)

    new_password = getpass('Введите пароль: ')
    password_check_on_correct = getpass('Повторите пароль: ')
    if not new_password == password_check_on_correct:
        print('Пароли не одинаковые')
        sys.exit(0)

    new_user = User(username=new_username, role='admin')
    new_user.set_password(new_password)

    db.session.add(new_user)
    db.session.commit()
    print('Создан пользователь {} c id {}'.format(new_user.username,
                                                  new_user.id))
Beispiel #20
0
def num_users_defined():
  return User.select().count()