コード例 #1
0
ファイル: test_models.py プロジェクト: ncc0706/flask-demo
 def test_roles(self):
     """Add a role to a user."""
     role = Role(name='admin')
     role.save()
     user = UserFactory()
     user.roles.append(role)
     user.save()
     assert role in user.roles
コード例 #2
0
ファイル: t_u_role.py プロジェクト: wdpedwin/edu_api_v3
def add_role():
    r1 = Role(name='系统管理员')
    r2 = Role(name='普通用户')

    # 批量添加
    db.session.add_all((r1, r2))
    db.session.commit()
    print(r1.id, r2.id)
コード例 #3
0
ファイル: test_user.py プロジェクト: mszlendak/BasicRestApi
    def test_relationship_user(self):
        with self.app_context():
            role = Role(name="User")
            role1 = Role(name="Moderator")

            user = UserModel("Test", "asdf", [role, role1])

            self.assertEqual(user.roles[0].name, "User")
            self.assertEqual(user.roles[1].name, "Moderator")
コード例 #4
0
    def test_correct_role_create(self):

        with self.app() as c:
            with self.app_context():
                role = Role(name="Moderator")
                role.save_to_db()
                UserModel("Test", "asdf", [role,]).save_to_db()

                r = c.post("/auth", headers = {"Content-Type": "application/json"} , data =json.dumps({"username":"******",
                                                                                                    "password": "******"}))
                auth_key = "JWT {}".format(json.loads(r.data)["access_token"])

                r = c.post("/store/Test", headers={"Authorization" : auth_key})

                self.assertEqual(r.status_code, 201)
                self.assertIsNotNone(StoreModel.find_by_name("Test"))
コード例 #5
0
    def setUp(self):
        super(StoreTest, self).setUp()
        with self.app() as c:
            with self.app_context():
                role = Role(name="Moderator")
                role.save_to_db()
                UserModel("Test", "asdf", [
                    role,
                ]).save_to_db()

                r = c.post("/auth",
                           headers={"Content-Type": "application/json"},
                           data=json.dumps({
                               "username": "******",
                               "password": "******"
                           }))
                self.auth_key = "JWT {}".format(
                    json.loads(r.data)["access_token"])
コード例 #6
0
ファイル: utils.py プロジェクト: jaredigms/COVIDx-server
def check_staff_role():
    staff_exist = db.session.query(
        Role.name).filter_by(name="staff").scalar() is not None

    if not staff_exist:
        payload = {'user_id': '0', 'name': 'staff'}
        role = Role(**payload)
        db.session.add()
        db.session.commit()

        return "staff role has been created!"
コード例 #7
0
ファイル: app_creation.py プロジェクト: xlalon/leoflask
 def on_identity_loaded(sender, identity):
     # Set the identity user object
     identity.user = current_user
     # Add the UserNeed to the identity
     if hasattr(current_user, 'id'):
         identity.provides.add(UserNeed(current_user.id))
     # Assuming the User model has a list of roles, update the
     # identity with the roles that the user provides
     if hasattr(current_user, 'role_id'):
         identity.provides.add(
             RoleNeed(Role.get(current_user.role_id, 'staff')))
コード例 #8
0
    def post(self):
        data = User.parser.parse_args(strict=True)

        if UserModel.find_by_name(data["name"]):
            return {"message": "User already exists"}, 400
        else:
            try:
                UserModel(data["name"], data["password"], [
                    Role.find_by_id(1),
                ]).save_to_db()
            except:
                return {"message": "An error occured"}, 500
            return {"message": "User created"}, 201
コード例 #9
0
    def test_create_item(self):
        with self.app() as c:
            with self.app_context():
                Role(name="User").save_to_db()

                r = c.post("/user",
                           headers={"Content-Type": "application/json"},
                           data=json.dumps({
                               "name": "Test",
                               "password": "******"
                           }))
                self.assertEqual(r.status_code, 201)
                self.assertIsNotNone(UserModel.find_by_name("Test"))
コード例 #10
0
    def test_put_create_user(self):
        with self.app() as c:
            with self.app_context():

                Role(name="User").save_to_db()
                Role(name="Moderator").save_to_db()

                r = c.put("/user",
                          headers={"Content-Type": "application/json"},
                          data=json.dumps({
                              "name": "Test",
                              "password": "******",
                              "roles": ["User", "Moderator"]
                          }))
                self.assertEqual(r.status_code, 201)
                self.assertIsNotNone(UserModel.find_by_name("Test"))
                self.assertEqual(json.loads(r.data),
                                 {"message": "User created"})
                self.assertEqual(
                    UserModel.find_by_name("Test").roles, [
                        Role.find_by_name("User"),
                        Role.find_by_name("Moderator")
                    ])
コード例 #11
0
    def put(self):
        self.parser.add_argument("roles", action='append')
        data = User.parser.parse_args(strict=True)
        user = UserModel.find_by_name(data["name"])
        if user:
            user.name = data["name"]
            user.password = data["password"]
            user.roles = [
                Role.find_by_name(x) for x in data["roles"]
                if Role.find_by_name(x) != None
            ]

            user.save_to_db()

            return {"message": "User updated"}, 200
        else:
            try:
                UserModel(data["name"], data["password"],
                          [Role.find_by_name(x)
                           for x in data["roles"]]).save_to_db()

            except:
                return {"message": "An error occured"}, 500
            return {"message": "User created"}, 201
コード例 #12
0
def init(options, connection_uri, db_password):
    click.echo("Initializing database ...")
    try:
        engine = create_engine(connection_uri, future=True)
        conn = engine.connect()
        conn.execute(sql.text("commit"))
        conn.execute(sql.text("CREATE DATABASE {{cookiecutter.project_name}}"))
        conn.close()
    except Exception as e:
        click.secho("Failed to create database ...", fg="red")
        click.echo(e)
    else:
        click.secho("Database created successfully ...", fg="green")

    try:
        engine = create_engine(connection_uri, future=True)
        conn = engine.connect()
        conn.execute(sql.text("commit"))
        create_user_query = sql.text(
            "CREATE USER {{cookiecutter.project_name}} WITH PASSWORD :password;"
        )
        conn.execute(create_user_query, {"password": db_password})
        conn.close()
    except Exception as e:
        click.secho("Failed to create user ...", fg="red")
        click.echo(e)
    else:
        click.secho(
            "User '{{cookiecutter.project_name}}' created successfully ...",
            fg="green")

    try:
        parsed_uri = urlparse(connection_uri)
        parsed_uri = parsed_uri._replace(
            path="/{{cookiecutter.project_name}}").geturl()
        engine = create_engine(parsed_uri, future=True)
        conn = engine.connect()
        conn.execute(sql.text("commit"))
        conn.execute(
            sql.text(
                "GRANT CONNECT ON DATABASE {{cookiecutter.project_name}} TO {{cookiecutter.project_name}};"
            ))
        conn.execute(
            sql.text(
                "GRANT USAGE ON SCHEMA public TO {{cookiecutter.project_name}};"
            ))
        conn.execute(
            sql.text("""
            GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA public TO {{cookiecutter.project_name}};
            GRANT ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA public TO {{cookiecutter.project_name}};
        """))
        conn.execute(
            sql.text("""
        ALTER DEFAULT PRIVILEGES IN SCHEMA public
        GRANT ALL ON TABLES TO {{cookiecutter.project_name}};
        
        ALTER DEFAULT PRIVILEGES IN SCHEMA public
        GRANT ALL ON SEQUENCES TO {{cookiecutter.project_name}};
        """))
        conn.close()
    except Exception as e:
        click.secho("Failed to assign db privileges ...", fg="red")
        click.echo(e)
    else:
        click.secho(
            "User '{{cookiecutter.project_name}}' given priviledges successfully ...",
            fg="green")

    try:
        parsed_uri = urlparse(connection_uri)
        parsed_uri = parsed_uri._replace(
            path="/{{cookiecutter.project_name}}").geturl()
        engine = create_engine(parsed_uri, future=True)
        UserBase.metadata.create_all(engine)
    except Exception as e:
        click.secho("Failed to implement database models ...", fg="red")
        click.echo(e)
    else:
        click.secho("Database models initialized successfully ...", fg="green")

    if not options.production:
        try:
            parsed_uri = urlparse(connection_uri)
            parsed_uri = parsed_uri._replace(
                path="/{{cookiecutter.project_name}}").geturl()
            engine = create_engine(parsed_uri, future=True)
            session = Session(engine)

            admin_role = Role(title='Admin')
            session.add(admin_role)
            session.commit()
            session.refresh(admin_role)

            resource_all = Resource(name='*')
            session.add(resource_all)
            session.commit()
            session.refresh(resource_all)

            admin_permission = Permission(action='*',
                                          resource_id=resource_all.id)
            session.add(admin_permission)
            session.commit()
            session.refresh(admin_permission)

            admin_policy = Policy(name='Admin',
                                  permission_id=admin_permission.id,
                                  role_id=admin_role.id)
            session.add(admin_policy)
            session.commit()
            session.refresh(admin_policy)

            admin_user = User(first_name='Pratik',
                              last_name='Shivarkar',
                              username='******',
                              phone_number='+19999999998',
                              email='*****@*****.**',
                              role_id=admin_role.id,
                              dob=date(1989, 1, 1))
            admin_user.set_password("reset123")
            session.add(admin_user)
            session.commit()
            session.refresh(admin_user)
        except Exception as e:
            click.secho("Failed to insert development data ...", fg="red")
            click.echo(e)
        else:
            click.secho("Development data added ...", fg="green")
コード例 #13
0
ファイル: manage.py プロジェクト: mszlendak/BasicRestApi
def seed_db():
    """Seeds the database."""
    Role(name="User").save_to_db()
    Role(name="Moderator").save_to_db()
    Role(name="Administrator").save_to_db()
    UserModel("Admin", "admin", [x for x in Role.query.all()]).save_to_db()
コード例 #14
0
ファイル: account.py プロジェクト: kdyq007/qblog
def role(action=None):
    user = User.query.get(g.user.uid)
    if not user:
        flash(_("the user is null or no permission"), "warn")
        return redirect(request.referrer)
    roles = Role.query.filter().all()
    if request.method == "POST":
        if action == "new_role":
            role_name = request.form.get("role-name")
            role = Role.query.filter(Role.role_name == role_name).first()
            if not role:
                role = Role()
                role.role_name = role_name
                db.session.add(role)
                try:
                    db.session.commit()
                except Exception as e:
                    db.session.rollback()
                    current_app.logger.warn("add a new role error, %s" %
                                            str(e))
                    flash(_("add a new role error"), "error")
            else:
                flash(_("this role is existed"), "warn")
            return redirect(request.referrer)
        elif action == "assign_role":
            users = request.form.get("users", "")
            roles = request.form.get("roles", "")
            users = users.strip().split(";")
            roles = roles.strip().split(";")
            current_app.logger.info(users)
            if not roles[-1]:
                roles.pop(-1)
            if not users[0] or not roles[0]:
                return make_response(
                    json.dumps(dict(code=400, message="check input")))

            role_ids = [
                Role.query.filter(Role.role_name == role).first().rid
                for role in roles if role
            ]
            user_ids = [
                User.query.filter(User.username == user).first().uid
                for user in users
                if User.query.filter(User.username == user).first()
            ]
            for user_id in user_ids:
                for role_id in role_ids:
                    user_role = UserRole.query.filter(
                        UserRole.uid == user_id,
                        UserRole.rid == role_id).first()
                    if not user_role:
                        user_role = UserRole()
                        user_role.uid = user_id
                        user_role.rid = role_id
                        db.session.add(user_role)
            try:
                db.session.commit()
            except Exception as e:
                db.session.rollback()
                current_app.logger.warn("assign role error, {0:s}".format(
                    str(e)))
                flash(_("assign role error"), "error")
                return make_response(json.dumps(dict(code=400,
                                                     message=str(e))))
            return make_response(json.dumps(dict(code=200)))
        elif action in ("all_users", "all_roles"):
            username = request.form.get("username", "").strip()
            rolename = request.form.get("rolename", "").strip()
            current_app.logger.info(username + rolename)
            user = User.query.filter(User.username == username).first()
            role = Role.query.filter(Role.role_name == rolename).first()
            user_role = None
            if user and role:
                user_role = UserRole.query.filter(
                    UserRole.uid == user.uid,
                    UserRole.rid == role.rid).first()
            if not user_role:
                return make_response(
                    json.dumps(
                        dict(code=400, message="the role is not existed")))
            db.session.delete(user_role)
            try:
                db.session.commit()
            except Exception as e:
                db.session.rollback()
                flash(_("delete role error"), "error")
                current_app.logger.error(str(e))
                return make_response(
                    json.dumps(dict(code=400, message="delete role error")))
            return make_response(json.dumps(dict(code=200)))
    elif request.method == "GET":
        if action == "del_role":
            role_id = request.args.get("role_id")
            if role_id:
                role_id = int(role_id)
            role = Role.query.filter(Role.rid == role_id).first()
            if not role:
                flash(_("role is not existed"), "warn")
            db.session.delete(role)
            try:
                db.session.commit()
            except Exception as e:
                db.session.rollback()
                current_app.logger.warn("del role is error, %s" % str(e))
                flash("del role cannot be deleted")
            return redirect(request.referrer)
        elif action == "role_users":
            role_id = request.args.get("role_id")
            if role_id:
                role_id = int(role_id)
            role = Role.query.filter(Role.rid == role_id).first()
            if not role:
                flash(_("role is not existed"), "warn")
            role_users = UserRole.query.filter(UserRole.rid == role_id).all()
            users = [
                User.query.filter(User.uid == role_user.uid).first()
                for role_user in role_users
            ]
            return make_response(json.dumps(users))
        elif action == "all_users":
            users = User.query.filter().all()
            roles = [user.rolenames for user in users]
            return render_template("account/s_roles_user.html",
                                   users=users,
                                   roles=roles)

        elif action == "all_roles":
            role_id = request.args.get("role_id")
            if role_id:
                role_id = int(role_id)
                role = Role.query.filter(Role.rid == role_id).first()
                role_users = UserRole.query.filter(
                    UserRole.rid == role_id).all()
                users = [
                    User.query.filter(User.uid == role_user.uid).first()
                    for role_user in role_users
                ]
                return render_template("account/s_roles_manager_user.html",
                                       users=users,
                                       role=role)
            return render_template("account/s_roles_manager.html", roles=roles)

    return render_template("account/s_roles_home.html", roles=roles)