Ejemplo n.º 1
0
def test_group_user():
    roles = ['FrontUser', 'Operator', 'Administrator', 'Super']
    msg = {}
    for r in roles:
        role = Role(group=r)
        u = User()
        u.telephone = fake.phone_number()
        u.username = r + '-test'
        u.email = fake.ascii_free_email()
        u.password = '******'
        u.confirm = True
        u.realname = fake.name()
        with open('mxavatar.json', 'r') as f:
            avatar_list = json.load(f)
        u.avatar = choice(avatar_list)
        u.signature = fake.paragraph(nb_sentences=3,
                                     variable_nb_sentences=True)
        u.gender = GenderEnum(randint(1, 3))
        u.join_time = fake.date_this_year(before_today=True, after_today=False)
        u.role = role
        db.session.add(u)
        msg[r] = u.telephone
    try:
        db.session.commit()
    except Exception as e:
        print(e)
        db.session.rollback()
        print('测试用户生成失败!')
        return
    print('测试用户生成成功!')
    print(msg)
Ejemplo n.º 2
0
def create_user():
    """User registration in the system."""

    try:
        data = request.json
        first_name = request.json['first_name']
        last_name = request.json['last_name']
        email = request.json['email']
        password = request.json['password']
        user_info = User.query.filter_by(email=email).first()
        print(user_info)
        if user_info:
            message = "User already exits"
            code = 400
        else:
            password = generate_password_hash(password)
            user = User()
            user.first_name = first_name
            user.last_name = last_name
            user.email = email
            user.password = password
            db.session.add(user)
            db.session.commit()
            message = "User create successfully"
            code = 200
    except Exception as error:
        return jsonify({'message': str(error)}), 400
    return jsonify({'message': message}), code
Ejemplo n.º 3
0
def test_permission_user():
    ps = [
        'LOGIN', 'VIEW_POST', 'PUBLISH_POST', 'PUBLISH_COMMENT', 'LOGIN_CMS',
        'MANAGE_POST', 'MANAGE_COMMENTE', 'BOARDER', 'BANNER', 'FRONTUSER',
        'CMSUSER', 'ADMINER'
    ]
    msg = {}
    for p in ps:
        permissions = Permission.ALL_PERMISSION - getattr(Permission, p)
        role = Role(name='FrontUser', permissions=permissions)
        u = User()
        u.telephone = fake.phone_number()
        u.username = '******' + p
        u.email = fake.ascii_free_email()
        u.password = '******'
        u.confirm = True
        u.realname = 'NOT-' + p
        with open('mxavatar.json', 'r') as f:
            avatar_list = json.load(f)
        u.avatar = choice(avatar_list)
        u.signature = fake.paragraph(nb_sentences=3,
                                     variable_nb_sentences=True)
        u.gender = GenderEnum(randint(1, 4))
        u.join_time = fake.date_this_year(before_today=True, after_today=False)
        u.role = role
        db.session.add(u)
        msg[u.username] = u.telephone
    try:
        db.session.commit()
    except Exception:
        db.session.rollback()
    print('测试用户生成成功!')
    print(msg)
Ejemplo n.º 4
0
def front_user(count=10):
    fake = Faker(locale='zh_CN')
    n = 0
    for i in range(count):
        u = User()
        u.telephone = fake.phone_number()
        u.username = fake.user_name()
        u.email = fake.ascii_free_email()
        u.password = '******'
        u.confirm = choice([True, False])
        u.realname = fake.name()
        with open('mxavatar.json', 'r') as f:
            avatar_list = json.load(f)
        u.avatar = choice(avatar_list)
        u.signature = fake.paragraph(nb_sentences=3,
                                     variable_nb_sentences=True)
        u.gender = GenderEnum(randint(1, 4))
        u.join_time = fake.date_this_year(before_today=True, after_today=False)
        role = Role()
        u.role = role
        db.session.add(u)
        try:
            db.session.commit()
            n += 1
        except Exception:
            db.session.rollback()
    print('Front用户添加成功,共同添加%d个用户' % n)
Ejemplo n.º 5
0
    def create_user(self, data, is_active=True):
        valid_input, valid_input_message = self.validate_signup_payload(data)
        if not valid_input:
            return {"success": valid_input, "message": valid_input_message}
        is_exists, exists_message = self.check_user_existence(
            data["email"], data["phone"])
        if is_exists:
            return {"success": True, "message": exists_message}

        try:
            hash_text = data["email"] + data["phone"] + data["full_name"]
            hash_object = hashlib.md5(hash_text)
            unique_hash = hash_object.hexdigest()
            try:
                validation = Schema({
                    'full_name':
                    And(basestring,
                        lambda n: 30 >= len(n) >= 3,
                        error="Minimum 3 Characters are Required"),
                    'email':
                    And(basestring,
                        lambda n: len(n) >= 3,
                        error="Minimum 3 Characters are Required"),
                    'phone':
                    And(basestring,
                        lambda n: len(n) >= 6,
                        error="Minimum 6 Characters are Required"),
                    "password":
                    And(basestring,
                        lambda n: len(n) >= 6,
                        error="Minimum 6 Characters are Required")
                }).validate(data)
            except SchemaError as e:
                error = e.message
                return {"success": False, "message": error}

            account_create = User()
            user_id = str(uuid.uuid4())
            account_create.username = user_id
            account_create.email = data['email']
            account_create.phone = data['phone']
            account_create.full_name = data['full_name']
            account_create.is_active = is_active
            account_create.password = self.pwd_context.encrypt(
                data['password'])
            account_create.token = self.generate_api_token(unique_hash)
            account_create.save()

            return {"success": True, "message": "Created User Successfully"}

        except Exception as e:
            print(traceback.format_exc())
Ejemplo n.º 6
0
Archivo: user.py Proyecto: ap13p/elearn
def user_create():
    form = UserForm(request.form)
    form.action = url_for('admin:user:create')
    form.level.choices = get_level()
    if form.validate_on_submit():
        user = User()
        user.email = form.email.data
        user.password = form.password.data
        user.no_induk = form.no_induk.data
        level = Level.get(Level.id == form.level.data)
        jenkel = form.profile.jenis_kelamin.data
        nama = form.profile.nama.data
        profile = Profile.create(nama=nama, jenis_kelamin=jenkel)
        user.level = level
        user.profile = profile
        user.save()
        return redirect(url_for('admin:user:list'))
    if form.errors:
        print form.errors
    return render_template('admin/user/create.html', form=form)
Ejemplo n.º 7
0
def users():
    form1 = AddUserForm(prefix="form1")
    form2 = EditUserForm(prefix="form2")
    # 添加用户
    if request.method == 'POST' and request.path == '/users':
        # 验证
        if not form1.validate_on_submit():
            flash({'error': form1.errors})
            return redirect(request.url)
        username = form1.username.data  # 账号名
        select = form1.select.data  # 所选权限
        user = User(name=username, authority=select)
        # 设置密码
        user.password = form1.password2.data
        # 尝试添加到数据库
        try:
            db.session.add(user)
            db.session.commit()
            # ‘success’、‘info’、‘warning’、‘error’
            flash({'success': u'添加成功!'})
            record_operation_log(operation=u'添加用户:' + str(user.id),
                                 module=u'用户',
                                 result=u'成功',
                                 user_id=current_user.id)
        except Exception as e:
            flash({'error': u'添加用户失败'})
            db.session.rollback()
            record_operation_log(operation=u'添加用户:' + username,
                                 module=u'用户',
                                 result=u'失败',
                                 user_id=current_user.id)
    # 修改用户
    if request.method == 'POST' and request.path == '/users/edit':
        # 验证
        if not form2.validate_on_submit():
            flash({'error': form2.errors})
            return redirect('/users')
        user_id = form2.user_id.data  # u_id
        user = User.query.filter_by(id=user_id).first()
        try:
            user.name = form2.username.data  # 账号名
            user.authority = form2.select.data  # 所选权限
            db.session.flush()
            flash({'success': u'修改成功!'})
            record_operation_log(operation=u'修改用户:' + str(user_id),
                                 module=u'用户',
                                 result=u'成功',
                                 user_id=current_user.id)
        except Exception as e:
            db.session.rollback()
            flash({'error': u'操作数据库失败,请检查用户名!'})
            record_operation_log(operation=u'修改用户:' + str(user_id),
                                 module=u'用户',
                                 result=u'失败',
                                 user_id=current_user.id)
    # 删除用户
    if request.method == 'DELETE':
        id_list = request.get_json().get('data')
        print(id_list)
        if len(id_list) == 0:
            print('-------------------')
            return jsonify({'warning': u'未选择!'})
        try:
            for id_ in id_list:
                db.session.delete(User.query.filter_by(id=id_).first())
                db.session.commit()
                record_operation_log(operation=u'删除用户:' + id_,
                                     module=u'用户',
                                     result=u'成功',
                                     user_id=current_user.id)
            return jsonify({'success': u'删除成功!'})
        except Exception as e:
            db.session.rollback()
            record_operation_log(operation=u'删除用户:' + str(id_list),
                                 module=u'用户',
                                 result=u'失败',
                                 user_id=current_user.id)
            return jsonify({'error': u'删除失败!'})

    return render_template('users/users.html', form1=form1, form2=form2)