Exemplo n.º 1
0
    def post_user_role():
        """
        关联角色
        :return:
        """
        params_data = request.get_json()['params']
        user_id = params_data['user_id']
        role_ids = params_data['role_ids']

        if not user_id or len(user_id) < 1:
            raise Exception("参数 user_id is blank")

        # 删除旧的用户和角色的关联关系
        PermissionsRelService.del_in_uids(TPermissionsUserRoleRel(), [user_id])
        # 重新关联用户和角色
        if role_ids and len(role_ids) > 0:
            for role_id in role_ids:
                DbHelper.get_db().session.add(
                    TPermissionsUserRoleRel(
                        uid=user_id,
                        rid=role_id,
                        create_time=DateUtils.get_current_time(),
                        last_update_time=DateUtils.get_current_time()))
        return make_response(
            json.dumps(ResponseCode.response(), ensure_ascii=False))
Exemplo n.º 2
0
 def post_role_group():
     """
     更新角色和用户组的关联关系
     :return:
     """
     params_data = request.get_json()['params']
     role_id = params_data['role_id']
     group_ids = params_data['group_ids']
     if not role_id or len(role_id) < 1:
         raise Exception("参数 role_id is blank")
     # 删除角色和用户组的关联关系
     PermissionsRelService.del_in_roleids(TPermissionsRoleGroupRel(),
                                          [role_id])
     # 删除角色和用户的关联关系
     PermissionsRelService.del_in_roleids(TPermissionsUserRoleRel(),
                                          [role_id])
     # 删除角色和资源的关联关系
     PermissionsRelService.del_in_roleids(TPermissionsResRoleRel(),
                                          [role_id])
     # 重新关联
     if group_ids and len(group_ids) > 0:
         for group_id in group_ids:
             DbHelper.get_db().session.add(
                 TPermissionsRoleGroupRel(
                     rid=role_id,
                     gid=group_id,
                     create_time=DateUtils.get_current_time(),
                     last_update_time=DateUtils.get_current_time()))
     return make_response(
         json.dumps(ResponseCode.response(), ensure_ascii=False))
Exemplo n.º 3
0
    def post_user_group():
        """
        更新用户和用户组的关联关系
        :return:
        """
        params_data = request.get_json()['params']
        user_id = params_data['user_id']
        group_ids = params_data['group_ids']
        if not user_id or len(user_id) < 1:
            raise Exception("参数 user_id is blank")

        # 删除用户和角色的关联关系
        PermissionsRelService.del_in_uids(TPermissionsUserRoleRel(), [user_id])
        # 清空老的用户和用户组之间的关联关系
        PermissionsRelService.del_in_uids(TPermissionsUserGroupRel(),
                                          [user_id])
        # 重新关联
        if group_ids and len(group_ids) > 0:
            for group_id in group_ids:
                DbHelper.get_db().session.add(
                    TPermissionsUserGroupRel(
                        uid=user_id,
                        gid=group_id,
                        create_time=DateUtils.get_current_time(),
                        last_update_time=DateUtils.get_current_time()))
        return make_response(
            json.dumps(ResponseCode.response(), ensure_ascii=False))
Exemplo n.º 4
0
 def execute_upd(model, fv, ids):
     sql = 'update {0} '.format(model.get_table_name())
     for k, v in fv.items():
         if v:
             sql += " set {0}='{1}',".format(k, v)
     sql = sql[:-1]
     sql += ' where 1=1 ' + Rule.rule_in('id', ids)
     info('curdHelper', 'update sql:' + sql)
     DbHelper.get_db().session.execute(sql)
Exemplo n.º 5
0
 def del_relation(models):
     """
     批量删除关联关系
     :param models: 关联关系模型列表
     :return:
     """
     for i, model in enumerate(models):
         DbHelper.get_db().session.delete(model)
     DbHelper.get_db().session.commit()
Exemplo n.º 6
0
 def insert_relations(models):
     """
     批量插入关联关系
     :param models: 关联关系模型列表
     :return: void
     """
     for i, model in enumerate(models):
         DbHelper.get_db().session.add(model)
     DbHelper.get_db().session.commit()
 def post_resource():
     """
     修改权限资源
     :return:
     """
     params_data = request.get_json()['params']
     params_data['last_update_time'] = DateUtils.get_current_time()
     DbHelper.get_db().session.query(TPermissionsResource).filter_by(id=params_data['id']).update(params_data)
     DbHelper.get_db().session.commit()
     return make_response(json.dumps(ResponseCode.response(), ensure_ascii=False))
 def get_group():
     """
     获取用户组列表
     :return:
     """
     model = TPermissionsGroup()
     rows = CRUDHelper.execute_select(model, {})
     DbHelper.get_db().session.close()
     data = {"rows": PermissionsGroupService.gen_group_tree(rows)}
     return make_response(
         json.dumps(ResponseCode.response(data=data), ensure_ascii=False))
Exemplo n.º 9
0
 def delete_example():
     """
     删除
     :return: json
     """
     params_data = json.loads(request.args.get('ids'))
     DbHelper.get_db().session.execute(
         SqlHelper.gen_del_sql(TExample(), params_data))
     DbHelper.get_db().session.commit()
     return make_response(
         json.dumps(ResponseCode.response(), ensure_ascii=False))
Exemplo n.º 10
0
 def put_example():
     """
     新增
     :return: json
     """
     params_data = request.get_json()['params']
     example = TExample()
     example.set_attr_by_dist(params_data)
     example.create_time = DateUtils.get_current_time()
     example.last_update_time = example.create_time
     DbHelper.get_db().session.add(example)
     DbHelper.get_db().session.commit()
     return make_response(
         json.dumps(ResponseCode.response(), ensure_ascii=False))
Exemplo n.º 11
0
 def get_user():
     """
     获取用户列表
     :return:
     """
     params = request.values.get('params')
     conditions = json.loads(params)
     model = TPermissionsUser()
     rows = CRUDHelper.execute_select(model, conditions)
     total = CRUDHelper.execute_select_count(model, conditions)
     DbHelper.get_db().session.close()
     data = {"total": total, "rows": rows}
     return make_response(
         json.dumps(ResponseCode.response(data=data), ensure_ascii=False))
    def put_resource():
        """
        新增权限资源
        :return:
        """
        params_data = request.get_json()['params']
        params_data['pid'] = params_data['pid'] if params_data['pid'] else Constants.ROOT_PID

        resource = TPermissionsResource()
        resource.set_attr_by_dist(params_data)
        resource.create_time = DateUtils.get_current_time()
        resource.last_update_time = resource.create_time
        DbHelper.get_db().session.add(resource)
        DbHelper.get_db().session.commit()
        return make_response(json.dumps(ResponseCode.response(), ensure_ascii=False))
Exemplo n.º 13
0
 def put_user():
     """
     新增用户
     :return:
     """
     params_data = request.get_json()['params']
     user = TPermissionsUser()
     user.set_attr_by_dist(params_data)
     user.password = generate_password_hash(user.password)
     user.create_time = DateUtils.get_current_time()
     user.last_update_time = user.create_time
     user.salt = uuidUtils.gen_uuid()
     DbHelper.get_db().session.add(user)
     DbHelper.get_db().session.commit()
     return make_response(
         json.dumps(ResponseCode.response(), ensure_ascii=False))
    def put_group():
        """
        新增用户组
        :return:
        """
        params_data = request.get_json()['params']
        params_data['pid'] = params_data['pid'] if params_data[
            'pid'] else Constants.ROOT_PID

        group = TPermissionsGroup()
        group.set_attr_by_dist(params_data)
        group.create_time = DateUtils.get_current_time()
        group.last_update_time = group.create_time
        DbHelper.get_db().session.add(group)
        DbHelper.get_db().session.commit()
        return make_response(
            json.dumps(ResponseCode.response(), ensure_ascii=False))
 def post_group_resources():
     params_data = request.get_json()['params']
     params_data = params_data['params']
     group_id = params_data['group_id']
     res_ids = params_data['res_ids']
     if not group_id:
         raise Exception('param group_id is none')
     PermissionsRelService.del_in_groupids(model=TPermissionsResGroupRel(),
                                           groupids=[group_id])
     for i, rid in enumerate(res_ids):
         DbHelper.get_db().session.add(
             TPermissionsResGroupRel(
                 rid=rid,
                 gid=group_id,
                 valid_status=Constants.VALID_STATUS_Y,
                 create_time=DateUtils.get_current_time(),
                 last_update_time=DateUtils.get_current_time()))
     return make_response(
         json.dumps(ResponseCode.response(), ensure_ascii=False))
Exemplo n.º 16
0
 def execute_select(model, conditions):
     result_set = DbHelper.get_db().session.execute(
         SqlHelper.gen_select_sql(model.get_table_name(), conditions)).fetchall()
     rows = []
     fields = model.__dict__
     for i, row in enumerate(result_set):
         obj = {}
         for j, field in enumerate(fields):
             if field in row.keys():
                 obj[field] = str(row[field])
         rows.append(obj)
     return rows
Exemplo n.º 17
0
 def post_role_resource():
     """
     重新关联资源
     :return:
     """
     params_data = request.get_json()['params']
     role_id = params_data['role_id']
     res_ids = params_data['res_ids']
     if not role_id:
         raise Exception('param role_id is none')
     PermissionsRelService.del_in_roleids(model=TPermissionsResRoleRel(),
                                          rids=[role_id])
     for i, rid in enumerate(res_ids):
         DbHelper.get_db().session.add(
             TPermissionsResRoleRel(
                 res_id=rid,
                 role_id=role_id,
                 valid_status=Constants.VALID_STATUS_Y,
                 create_time=DateUtils.get_current_time(),
                 last_update_time=DateUtils.get_current_time()))
     return make_response(
         json.dumps(ResponseCode.response(), ensure_ascii=False))
Exemplo n.º 18
0
class BasicModel(object):
    __tablename__ = None
    id = DbHelper.get_db().Column(DbHelper.get_db().BigInteger(), primary_key=True)
    valid_status = DbHelper.get_db().Column(DbHelper.get_db().String(5), nullable=False, default='N')
    create_time = DbHelper.get_db().Column(DbHelper.get_db().DATETIME(), nullable=False)
    last_update_time = DbHelper.get_db().Column(DbHelper.get_db().DATETIME(), nullable=False)

    def get_table_name(self):
        return self.__tablename__

    def row_to_model(self, row):
        """
        通过数据库查出的行转换为Model
        :return:
        """
        attr_map = self.__dict__
        for k, v in attr_map.items():
            if k.startswith('_'):
                continue
            value = getattr(row, k)
            self.__setattr__(k, value)

    def to_json(self):
        """
        将对象属性装换为json
        :return: dict
        """
        attr_map = self.__dict__
        attr_json = {}
        for k, v in attr_map.items():
            if k.startswith('_'):
                continue
            value = getattr(self, k)
            attr_json[k] = str(value)
        return attr_json

    def set_attr_by_dist(self, dist):
        """
        根据给定的字典设置属性值
        :param dist: 字典
        :return: void
        """
        if not dist or len(dist.keys()) < 1:
            info("basic", "param dist is empty or null")
            return
        for k, v in dist.items():
            if v:
                setattr(self, k, v)
Exemplo n.º 19
0
    def put_session():
        """
        登录session
        :return:
        """
        params_data = request.get_json()['params']
        username = params_data['username']
        password = params_data['pass']

        row_user_info = DbHelper.get_db().session.query(TPermissionsUser).filter_by(
            login_name=username, valid_status=Constants.VALID_STATUS_Y).first()
        # 如果查不到
        if not row_user_info:
            # 返回用户不存在提示信息
            return make_response(
                json.dumps(ResponseCode.response(res_json=Code.ACCOUNT_NOT_EXISTS), ensure_ascii=False))
        # 如果存在,则检查密码
        user_model = TPermissionsUser()
        user_model.row_to_model(row_user_info)
        if not user_model.check_password(password):
            return make_response(
                json.dumps(ResponseCode.response(res_json=Code.LOGIN_PASS_ERROR), ensure_ascii=False))
        # 用户名密码正确,生成token
        salt = user_model.salt
        payload = {
            'user': {"username": user_model.login_name, "password": user_model.password},
            'aud': salt,
            'exp': datetime.datetime.utcnow() + datetime.timedelta(seconds=int(SysConfHelper.get_item('jwt', 'exp')))
        }
        token = jwt.encode(payload, SysConfHelper.get_item('jwt', 'secret_key'), algorithm='HS256')
        user = user_model.to_json()
        # 权限资源
        nav_menus = PermissionsResourceService.resources_by_user(uid=user['id'], res_type=Constants.RES_TYPE_MENU)
        # f_uris = PermissionsResourceService.resources_by_user(uid=user['id'],
        #                                                    user_type=user_type, res_type=Constants.RES_TYPE_FURI)
        uris = PermissionsResourceService.resources_by_user(uid=user['id'], res_type=Constants.RES_TYPE_URI)

        data = dict()
        data['token'] = str(bytes(token), encoding='utf-8')
        data['user'] = json.dumps(user)
        data['salt'] = salt
        data['nav_menus'] = json.dumps(nav_menus)
        # data['f_uris'] = json.dumps(f_uris)
        data['uris'] = json.dumps(uris)
        data['upd_resource_time'] = DateUtils.get_current_time()
        return make_response(
            json.dumps(ResponseCode.response(data=data), ensure_ascii=False))
Exemplo n.º 20
0
 def execute_delete_by_conditions(model, conditions):
     DbHelper.get_db().session.execute(SqlHelper.gen_condition_del_sql(model.get_table_name(), conditions))
Exemplo n.º 21
0
 def execute_delete_by_field_in(model, value_in_list, field_name='id'):
     DbHelper.get_db().session.execute(SqlHelper.gen_del_sql(model, value_in_list, field_name=field_name))
Exemplo n.º 22
0
 def execute_select_count(model, conditions):
     result_set = DbHelper.get_db().session.execute(
         SqlHelper.gen_select_sql(model.get_table_name(), conditions, True)).first()
     return result_set[0] if result_set else 0
Exemplo n.º 23
0
from flask import Flask

from app_router import app_router
from com.lzy.project.admin.helper.db_helper import DbHelper

app = Flask(__name__)
app.register_blueprint(app_router, url_prefix='/api/admin')


DbHelper.init_db(app)

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000)
Exemplo n.º 24
0
def internal_500_error(error):
    DbHelper.get_db().session.rollback()
    return make_response(json.dumps(ResponseCode.response(500, "服务器错误")))