Exemplo n.º 1
0
    def post(self, **kwargs):
        """获取手机验证码
          ---
          tags:
            - 登录、注册
          parameters:
            - name: phone
              in: body
              type: string
              required: true
          responses:
            200:
              description: A list of colors (may be filtered by palette)
              examples:
                response: {"data": null, "message": "发送成功"}
        """
        phone = kwargs.get("phone")
        user = User.query.filter_by(phone=phone).first()
        user_phone_code = None

        if user:
            user_phone_code = UserPhoneCode.query.filter_by(
                user_id=user.id).first()
            if user_phone_code and get_timestamp(
            ) - user_phone_code.update_time <= 300:
                return json_response(message="验证码请求频繁, 请稍后重试", status=403)
        else:
            user_id = generate_uuid()
            user = User(
                id=user_id,
                phone=phone,
                create_time=get_timestamp(),
                nickname=Conf.get("USER_DISABLE_NICKNAME_PREFIX", 'arrplat_') +
                phone[-4:])
            user_info = UserInfo(user_id=user_id,
                                 head_url=Conf.get("DEFAULT_HEAD_IMAGE", ""),
                                 signature="这个人很懒,什么都没留下")
            db.session.add_all([user, user_info])
            db.session.commit()
        # TODO 验证码先用假的的
        # payload = send_phone_code(phone)
        payload = {"code": "OK", "phone_code": "123456"}
        if payload["code"] == "OK":
            current_timestamp = get_timestamp()
            if not user_phone_code:
                user_phone_code = UserPhoneCode(
                    user_id=user.id,
                    code=payload["phone_code"],
                    create_time=current_timestamp,
                    update_time=current_timestamp,
                    valid_time=600,
                )
            else:
                user_phone_code.code = payload["phone_code"]
                user_phone_code.update_time = current_timestamp
            db.session.add(user_phone_code)
            db.session.commit()
            return json_response(message="获取成功")

        return json_response(message="短信发送失败", status=500)
Exemplo n.º 2
0
    def get(self):
        """获取图片验证码
          ---
          tags:
            - 登录、注册
          responses:
            200:
              description: A list of colors (may be filtered by palette)
              examples:
                response: {"data": {"verify_code_image": "base64图片", "uuid": "x*32"}, "message": "发送成功"}
        """
        valid_code_object = VerifyCodeImg()
        valid_code_bytes, valid_code_string = valid_code_object.get_verify_code_image()
        valid_code_base64_string = base64.b64encode(valid_code_bytes).decode()
        unique_string = generate_uuid()
        redis_0.set("verify_code:" + unique_string, valid_code_string, ex=Conf.get("VERIFY_CODE_EXPIRE", 180))

        return json_response(data={
            "verify_code_image": valid_code_base64_string,
            "uuid": unique_string
        }, message="成功")
Exemplo n.º 3
0
    def put(self, entity_id: str, data_id: str, data: dict):
        """页面某一块section数据-修改

          ---
          tags:
            - page页面数据
          parameters:
            - name: entity_id
              in: path
              type: string
              required: true
              enum: ['12363708151a46879f3efb76780c5ba9']
              description: 实例id
            - name: data_id
              in: path
              type: string
              required: true
              enum: ['12363708151a46879f3efb76780c5ba9']
              description: 要修改的数据id
            - name: data
              in: body
              type: object
              required: true
              example: {"name": "xxx", "description": "xxxx"}
              description: 数据
            - name: org_id
              in: querystring
              type: string
              required: false
              description: 组织id
          responses:
            200:
              description:  成功
              examples:
                response: {"message": "ok"}
        """
        try:
            table_name, condition = self.get_table_name(entity_id=entity_id,
                                                        data_id=data_id)
        except Exception as e:
            _ = e
            return json_response(message=str(e), status=404)

        # 检验数据
        message, status = self.verify_field(entity_id, data, table_name,
                                            data_id)
        if status != 0:
            return json_response(message=message, status=status)

        # TODO 该部分与psot接口重复度高 可复用
        # 查询是否有多对多关系 更新关联表 先删后加
        entity_fields = EntityField.query.filter_by(entity_id=entity_id,
                                                    foreign_type=2).all()
        insert_sql_foreign_all = []
        delete_sql_foreign_all = []
        for field in entity_fields:
            # foreign_type = field.foreign_type
            field_key = field.key
            foreign_table_name = field.foreign_table_name
            foreign_our_key = field.foreign_our_key
            foreign_their_key = field.foreign_their_key

            # 关联表先删除数据
            delete_sql = "DELETE FROM %s WHERE %s='%s'" % (
                foreign_table_name, foreign_our_key, data_id)
            delete_sql_foreign_all.append(delete_sql)
            if field_key in data.keys():
                # 多个的值
                key_values = data[field_key]
                # 主表不用再插入
                data.pop(field_key)
                if not key_values:
                    continue
            else:
                # 没数据
                continue

            field_str_foreign = 'id,' + foreign_our_key + ',' + foreign_their_key
            value_str_foreign = ','.join("('%s','%s','%s')" %
                                         (generate_uuid(), data_id, v)
                                         for v in key_values)
            insert_sql_foreign = "INSERT INTO %s (%s) VALUES %s;" % (
                foreign_table_name, field_str_foreign, value_str_foreign)
            insert_sql_foreign_all.append(insert_sql_foreign)

        # 查询是否有update_time
        entity_fields_all = EntityField.query.filter_by(
            entity_id=entity_id).all()
        int_timestamp = pendulum.now('Asia/Shanghai').int_timestamp
        for field in entity_fields_all:
            field_key = field.key
            # if field_key == 'create_time':
            #     data[field_key] = int_timestamp
            if field_key == 'update_time':
                data[field_key] = int_timestamp
        field_list = list()
        for key, value in data.items():
            if isinstance(value, list) or isinstance(value, dict):
                continue
            field_list.append('%s=:%s' % (key, key))
        field_str = ','.join(field_list)
        update_sql = "UPDATE %s SET %s WHERE %s;" % (table_name, field_str,
                                                     condition)

        try:
            # 更新主表
            db.session.execute(update_sql, data)
            # 关联表先删除数据
            for sql in delete_sql_foreign_all:
                db.session.execute(sql)
            # 再插入关联表
            for sql in insert_sql_foreign_all:
                db.session.execute(sql)
        except Exception as e:
            _ = e
            print(e)
            db.session.rollback()
            return json_response(message="数据修改失败", status=500)
        else:
            db.session.commit()
            return json_response(message="ok")
Exemplo n.º 4
0
    def post(self, entity_id: str, data: dict):
        """页面某一块section数据添加

          ---
          tags:
            - page页面数据
          parameters:
            - name: entity_id
              in: path
              type: string
              required: true
              enum: ['12363708151a46879f3efb76780c5ba9']
              description: 实例id
            - name: data
              in: body
              type: string
              required: true
              enum: [{"name": "123", 'age': 13}]
              description: 数据体
            - name: org_id
              in: body
              type: string
              required: false
              description: 组织id
          responses:
            200:
              description:  成功
              examples:
                response: {"message": "ok"}
        """
        try:
            table_name, _ = self.get_table_name(entity_id=entity_id)
        except Exception as e:
            _ = e
            return json_response(message=str(e), status=404)

        try:
            # 关联表会用到
            data_id = generate_uuid()
            data["id"] = data_id

            # 检验数据
            message, status = self.verify_field(entity_id, data, table_name)
            if status != 0:
                return json_response(message=message, status=status)

            # 查询是否有多对多关系 存储关联表
            entity_fields = EntityField.query.filter_by(entity_id=entity_id,
                                                        foreign_type=2).all()
            insert_sql_foreign_all = []
            for field in entity_fields:
                # foreign_type = field.foreign_type
                field_key = field.key
                foreign_table_name = field.foreign_table_name
                foreign_our_key = field.foreign_our_key
                foreign_their_key = field.foreign_their_key

                if field_key in data.keys():
                    # 多个的值
                    key_values = data[field_key]
                    # 主表不用再插入
                    data.pop(field_key)
                    if not key_values:
                        continue
                else:
                    # 没数据
                    continue

                field_str_foreign = 'id,' + foreign_our_key + ',' + foreign_their_key
                value_str_foreign = ','.join("('%s','%s','%s')" %
                                             (generate_uuid(), data_id, v)
                                             for v in key_values)
                insert_sql_foreign = "INSERT INTO %s (%s) VALUES %s;" % (
                    foreign_table_name, field_str_foreign, value_str_foreign)
                insert_sql_foreign_all.append(insert_sql_foreign)
                # 不能先执行 会有外键问题
                # db.session.execute(insert_sql_foreign)

            # 查询是否有create_time或者别的字段
            entity_fields_all = EntityField.query.filter_by(
                entity_id=entity_id).all()
            int_timestamp = pendulum.now('Asia/Shanghai').int_timestamp
            for field in entity_fields_all:
                field_key = field.key
                if field_key == 'create_time':
                    data[field_key] = int_timestamp
                if field_key == 'update_time':
                    data[field_key] = int_timestamp

            # 主表数据
            field_dict = dict()
            for key, value in data.items():
                if isinstance(value, list) or isinstance(value, dict):
                    continue
                field_dict[key] = value
            field_str = ",".join(field_dict.keys())
            value_str = ",".join(
                [":%s" % field for field in field_dict.keys()])
            insert_sql = "INSERT INTO %s(%s) VALUE(%s);" % (
                table_name, field_str, value_str)

            # 主表数据先插入 否则关联表外键有问题
            db.session.execute(insert_sql, data)
            # 再插入关联表
            for sql in insert_sql_foreign_all:
                db.session.execute(sql)
            # db.session.commit()
        except Exception as e:
            _ = e
            print(e)
            db.session.rollback()
            return json_response(message="数据添加失败,%s" % str(e), status=500)
        else:
            db.session.commit()
            return json_response(message='ok')
Exemplo n.º 5
0
    def post(self, org_id, **kwargs):
        """组织员工
          ---
          tags:
            - 组织部门雇员
          parameters:
            - name: org_id
              in: url
              type: string
              required: true
              description: 组织ID
            - name: phone
              in: body
              type: string
              required: true
              description: 员工手机号
            - name: department_id_list
              in: body
              type: array
              required: false
              description: 部门ID列表
            - name: job_title
              in: body
              type: string
              required: true
              description: 员工岗位
            - name: superior_id
              in: body
              type: string
              required: true
              description: 直属人ID
            - name: role_id_list
              in: body
              type: array
              required: false
              description: 角色ID列表
            - name: is_able
              in: body
              type: int
              required: false
              description: 是否启用,可以不传,默认为禁用
          responses:
            status:
              description: 返回的状态码信息
              examples:
                response: {'data': null, 'status': {422: '手机号非法', 404: '没有找到直属人', 200: '发送短信通知加入或者通知邀请', 500: '加入失败', 409: '已存在该组织'}}
                """
        phone = kwargs['phone']
        department_id_list = kwargs.get('department_id_list')
        job_title = kwargs['job_title']
        superior_id = kwargs.get('superior_id')
        role_id_list = kwargs.get('role_id_list')
        is_able = kwargs.get('is_able')

        current_user_obj = get_current_user()

        is_phone = valid_phone(phone)
        if not is_phone:
            return json_response(None, message='手机号非法', status=422)
        superior_obj = None
        if superior_id:
            superior_obj = OrgStaff.query.filter(
                OrgStaff.id == superior_id, OrgStaff.org_id == org_id).first()
            if not superior_obj:
                return json_response(None, message='直属人未找到', status=404)
        org_obj = Organization.query.get_or_404(org_id)
        user_obj = User.query.filter(User.phone == phone).first()
        if user_obj:
            user_id = user_obj.id
            org_staff_obj = OrgStaff.query.filter(
                OrgStaff.org_id == org_id,
                OrgStaff.user_id == user_obj.id).first()
            if org_staff_obj:
                return json_response(None, message='该人员已存在当前组织', status=409)
        else:
            temp_user_id = generate_uuid()
            temp_user_obj = User(
                id=temp_user_id,
                phone=phone,
                nickname=config['system']['USER_DISABLE_NICKNAME_PREFIX'] +
                phone[-4:],
                create_time=time.time(),
                is_invite_status=1)
            temp_user_info_obj = UserInfo(user_id=temp_user_id, )

            org_req_obj = OrgRequest(sender_id=current_user_obj.id,
                                     message='邀请您到我们的组织',
                                     create_time=time.time(),
                                     org_id=org_id)
            db.session.add_all(
                [temp_user_obj, temp_user_info_obj, org_req_obj])
            user_id = temp_user_id
            # try:
            # 未注册的用户  发短信通知邀请
            # send_sms(generate_uuid(), phone, "山泉", "SMS_152655055", {'code': f'www.xx.com/xx'})

        staff_uuid = generate_uuid()
        # 已注册 发短信通知,直接拉进来
        org_staff_obj = OrgStaff(
            id=staff_uuid,
            user_id=user_id,
            job_title=job_title,
            is_able=is_able if is_able in [0, 1] else 0,
            superior_id=superior_obj.id if superior_obj else None,
            org_id=org_id)
        db.session.add(org_staff_obj)
        if department_id_list:
            for dep in department_id_list:
                org_dep_obj = OrgDepartmentStaff(org_department_id=dep,
                                                 staff_id=staff_uuid)
                db.session.add(org_dep_obj)
        if role_id_list:
            for role in role_id_list:
                staff_role_obj = OrgStaffRole(staff_id=staff_uuid,
                                              org_role_config_id=role)
                db.session.add(staff_role_obj)
        message_obj = Message(
            title='邀请信息',
            content=f'{current_user_obj.nickname}邀请您加入组织:{org_obj.name}',
            send_time=time.time(),
            message_type=4,  # 邀请消息
            organization_id=org_obj.id,
            user_id=user_obj.id)
        db.session.add(message_obj)
        try:
            db.session.commit()
            return json_response(None, message='加入成功,将以短信形式通知该员工', status=200)
        except Exception as e:
            _ = e
            db.session.rollback()
            return json_response(None, message=f'加入失败,{e}', status=500)
Exemplo n.º 6
0
    def post(self, **kwargs):
        """创建组织
          ---
          tags:
            - 组织
          parameters:
            - name: name
              in: body
              type: string
              required: true
            - name: unique_id
              in: body
              type: string
              required: true
            - name: description
              in: body
              type: string
              required: true
            - name: group_type
              in: body
              type: string
              example: GOV Company Personal
            - name: address
              in: body
              type: string
          responses:
            200:
              description: A list of colors (may be filtered by palette)
              examples:
                response: {"data": null, "message": "组织添加成功"}
        """
        unique_id = kwargs.get("unique_id")

        if unique_id:
            exist_unique_id = db.session.query(Organization.id).filter(
                Organization.unique_id == unique_id).first()
            if exist_unique_id:
                return json_response(message="组织ID已经存在", status=403)

        user = get_current_user()
        org_id = generate_uuid()
        org_department_id = generate_uuid()
        staff_id = generate_uuid()

        organization = Organization()
        for key, value in kwargs.items():
            setattr(organization, key, value)
        organization.own_user_id = user.id
        organization.id = org_id

        org_staff = OrgStaff(id=staff_id,
                             org_id=org_id,
                             user_id=user.id,
                             job_title="组织创建人")

        org_department = OrgDepartment(id=org_department_id,
                                       org_id=org_id,
                                       name="大本营")

        org_department_staff = OrgDepartmentStaff(
            org_department_id=org_department_id, staff_id=staff_id)

        result = db.session.query(
            Application.id).filter(Application.title == "组织管理").first()
        org_application = None
        if result:
            org_application = OrgApplication(application_id=result.id,
                                             organization_id=org_id,
                                             status=1)

        try:
            db.session.add(organization)
            db.session.add(org_department)
            db.session.add(org_staff)
            db.session.add(org_department_staff)
            if org_application:
                db.session.add(org_application)
            db.session.commit()
        except Exception as e:
            _ = e
            print(e)
            db.session.rollback()
            return json_response(message="组织添加失败", status=403)
        else:
            return json_response(message="组织添加成功")
Exemplo n.º 7
0
    def post(self, **kwargs):
        """用户名 密码 注册
          ---
          tags:
            - 登录、注册
          parameters:
            - name: phone
              in: body
              type: string
              required: false
              description: 手机号
            - name: username
              in: body
              type: string
              required: true
              description: 用户名
            - name: password
              in: body
              type: string
              required: true
              description: 密码
        """
        phone = kwargs.get('phone', None)
        username = kwargs.get('username')
        password = kwargs.get('password')

        if phone and not valid_phone(phone):
            return json_response(message="无效的手机号", status=403)
        elif len(username) < 4:
            return json_response(message="用户名不能小于三位", status=403)
        if len(password) < 8:
            return json_response(message="密码最少需要八位", status=403)

        if phone:
            user = User.query.filter_by(phone=phone).first()
            if user:
                return json_response(message="该手机号已注册", status=409)
        user = User.query.filter_by(username=username).first()
        if user:
            return json_response(message="该用户名已注册", status=409)\

        try:
            salt = bcrypt.gensalt()
            new_password = bcrypt.hashpw(password.encode(), salt)
            user_id = generate_uuid()
            user = User(
                id=user_id,
                phone=phone,
                username=username,
                password=new_password.decode(),
                salt=salt.decode(),
                nickname=username,
                create_time=time.time()
            )

            user_info = UserInfo(
                user_id=user_id,
                head_url=Conf.get("DEFAULT_HEAD_IMAGE", ""),
                signature="这个人很懒,什么都没留下"
            )
            db.session.add_all([user, user_info])
            db.session.commit()
            return json_response(None, message='注册成功', status=200)
        except Exception as e:
            _ = e
            db.session.rollback()
            return json_response(None, message=f'注册失败{_}', status=500)