예제 #1
0
    def get(self, request):
        """禁用接口"""

        ban_ids = request.GET.get('id')

        if not all([ban_ids]):
            return JsonResponse({'code': RET.PARAMERR, 'message': '参数错误'})

        try:
            ban_ids = json.loads(ban_ids)
        except Exception:
            return JsonResponse({'code': RET.PARAMERR, 'message': '参数错误'})

        # 非可迭代对象和字符串把其变成单元素的列表
        if (not isinstance(ban_ids, Iterable)) or isinstance(ban_ids, str):
            ban_ids = [ban_ids]

        # 过滤掉非整形数据
        ban_ids = list(filter(filter_null, ban_ids))

        if len(ban_ids) == 0:
            return JsonResponse({'code': RET.PARAMERR, 'message': '参数错误'})

        try:
            users = User.objects.filter(id__in=ban_ids)
            if len(users) != len(ban_ids):
                return JsonResponse({'code': RET.PARAMERR, 'message': '存在错误id参数'})

            # 校验广告主和代理商的禁用操作权限
            if request.user.role in [3, 4]:
                slaves = [u.slave for u in MemberShip.objects.filter(master=request.user)]
                users = list(filter(lambda x: x in slaves, users))

                if len(users) != len(ban_ids):
                    logger.info('{}中有无效的id'.format(ban_ids))
                    return JsonResponse({'code': RET.PARAMERR, 'message': '禁用失败,无法禁用他人的隶属账户'})

            for user in users:
                user.is_active = not user.is_active
                user.save()
        except Exception as e:
            logger.warning(e)
            return JsonResponse({'code': RET.DBERR, 'message': '数据库错误'})

        return JsonResponse({'code': RET.OK, 'message': '成功'})
예제 #2
0
    def get(self, request):

        page = request.GET.get('page')
        f_id = request.GET.get('id')
        is_all = request.GET.get('all')
        try:
            page = int(page)
        except TypeError:
            logger.debug('页码错误')
            page = 1
        if f_id is None:
            fornums = Fornum.objects.all().order_by('-update_time')
        else:
            fornums = Fornum.objects.filter(id=f_id)

        pages = 1
        data_length = 0 if is_all is None and f_id is None else 1

        if len(fornums) > 1:
            paginator = Paginator(fornums, settings.PER_PAGE_COUNTS)
            pages = paginator.num_pages
            if page > pages:
                page = 1
            data_length = paginator.count
            fornums_page = paginator.page(page)
        else:
            try:
                fornums_page = [fornums.first()]
            except Exception:
                logger.info('没有该论坛信息')
                return JsonResponse({
                    'code': RET.PARAMERR,
                    'message': '没有该论坛信息'
                })

        data = []

        if len(fornums) == 0:
            fornums_page = []

        if is_all is not None and f_id is None:
            fornums_page = fornums

        for fornum in fornums_page:
            d = {
                'id': fornum.id,
                'title': fornum.title,
                'fornum_name': fornum.fornum_name,
                'description': fornum.description,
                'app_type': fornum.app_type
            }

            data.append(d)

        return JsonResponse({
            'code': RET.OK,
            'message': '成功',
            'data': data,
            'pages': pages,
            'data_length': data_length
        })
예제 #3
0
    def post(self, request):

        json_dict = get_json_data(request)
        if json_dict is None:
            return JsonResponse({"code": RET.PARAMERR, "message": "请使用json格式数据"})

        # 用户名
        username = json_dict.get("user_name")
        # 密码  要md5加密不然不匹配
        password = json_dict.get("password")
        # 验证码
        checkcode = json_dict.get("checkcode")
        # 验证码的uuid
        uuid = json_dict.get('uuid')

        # 校验完整性
        if not all([username, password, uuid, checkcode]):
            return JsonResponse({"code": RET.PARAMERR, "message": "参数不完整"})

        # 如果密码传过来没有做md5加密
        if len(password) != 32:
            logger.info('密码传输没有进行md5加密')
            encoder = hashlib.md5()
            encoder.update(password.encode(encoding='utf-8'))
            password = encoder.hexdigest().lower()

        if len(username) < 4:
            return JsonResponse({"code": RET.USERERR, "message": "密码或账户名错误"})

        # 获取redis链接,校验验证码
        redis_conn = get_redis_connection('default')
        imageCode_server = redis_conn.get('ImageCode:' + uuid)

        try:
            imageCode_server = imageCode_server.decode()
        except Exception:
            logger.debug("验证码过期")
            return JsonResponse({"code": RET.DBERR, "message": "验证码已过期"})

        if not imageCode_server:
            return JsonResponse({"code": RET.DBERR, "message": "验证码已过期"})

        if imageCode_server.lower() != checkcode.lower():
            logger.debug('验证码错误')
            return JsonResponse({"code": RET.USERERR, "message": "验证码输入错误"})

        # 检查用户名密码是否错误
        user = authenticate(username=username.upper(), password=password, is_delete=False)

        if user is None or user.is_delete:
            return JsonResponse({"code": RET.USERERR, "message": "密码或账户名错误"})

        if not user.is_active:
            # 判断账户是否过期
            return JsonResponse({'code': RET.USERERR, "message": "账户已停用"})

        try:
            mem = MemberShip.objects.get(slave=user)
            if mem.end_time < datetime.now():
                # 过期了更改激活标记
                user.is_active = False
                user.save()
                return JsonResponse({'code': RET.USERERR, "message": "账户已停用"})
        except Exception:
            logger.warning('用户{}缺乏隶属信息'.format(request.user.username))
            pass

        if user.role > 3:
            return JsonResponse({'code': RET.USERERR, 'message': '对不起,您没有权限登陆后台管理界面'})

        try:
            ul = UserLogs.objects.create(
                user=user,
                softwareType=-1,
                load_ip=getIPFromDJangoRequest(request)
            )
            ul.save()
        except Exception as e:
            logger.warn(e)

        # 记录登录状态
        login(request, user)

        return JsonResponse({
            "code": RET.OK,
            "message": "登陆成功"
        })
예제 #4
0
    def post(self, request):
        """
        创建用户接口
        """
        json_dict = get_json_data(request)
        if json_dict is None:
            return JsonResponse({"code": RET.PARAMERR, "message": "请使用json格式数据"})

        user_name = json_dict.get('adminName')
        name = json_dict.get('name')
        password = json_dict.get('password')
        email = json_dict.get('email')
        role = json_dict.get('adminRole')
        gender = json_dict.get('sex')
        remarks = json_dict.get('remarks')
        telephone = json_dict.get('phone')
        accounts = json_dict.get('accounts')
        end_time = json_dict.get('end_time')

        try:
            # 转换为时间格式
            end_time = datetime.strptime(end_time, '%Y-%m-%d %H:%M:%S')
        except Exception:
            end_time = datetime.now() + timedelta(hours=settings.ACCOUNTS_VALID_HOURS)

        # 可以缺省的参数,给定默认值
        email = '*****@*****.**' if email is None else email
        remarks = "" if remarks is None else remarks
        telephone = '13011111111' if telephone is None else telephone
        gender = 0 if gender is None else gender
        role = 6 if role is None else role
        accounts = 0 if accounts is None else accounts

        name = name if name else user_name

        # 代理商只能开临时账户,临时账户有效期为3个小时
        if request.user.role == 3:
            role = 6
            accounts = 0
            end_time = datetime.now() + timedelta(hours=3)

        # 广告主只能开广告操作员,广告操作员账户有效期要小于等于开户的广告主的有效时间
        if request.user.role == 4:
            role = 5
            accounts = 0
            try:
                slef_end_time = MemberShip.objects.get(slave=request.user).end_time
                # 如果广告操作员有效时间超出广告主有效时间,将其置为广告主的有效操作时间
                if slef_end_time < end_time:
                    end_time = slef_end_time
            except Exception as e:
                logger.error(e)
                return JsonResponse({'code': RET.DBERR, 'message': '数据库错误'})

        # 广告主默认开户数为5
        if role == 4:
            accounts = settings.ACCOUNTS_CREATE_COUNT if accounts is None else accounts

        # 校验参数
        if not all([user_name, password]):
            return JsonResponse({"code": RET.PARAMERR, "message": "参数不完整"})

        # 如果密码传过来没有做md5加密
        if len(password) != 32:
            logger.info('密码没有md5加密传输')
            encoder = hashlib.md5()
            encoder.update(password.encode(encoding='utf-8'))
            password = password.hexdigest().lower()

        if len(user_name) < settings.USERNAME_MIN_LENGTH:
            return JsonResponse({'code': RET.PARAMERR, 'message': '用户名长度不足'})

        # 改大写
        user_name = user_name.upper()

        try:
            gender = int(gender)
            role = int(role)
            accounts = int(accounts)
        except Exception as e:
            logger.debug(e)
            return JsonResponse({'code': RET.PARAMERR, 'message': '参数格式错误'})

        if role > 6 or role < 1:
            logger.warning('用户的role参数错误')
            return JsonResponse({'code': RET.PARAMERR, 'message': '角色参数为[1,6]的数字'})

        f_id = json_dict.get('fornum_id')

        if f_id is None:
            return JsonResponse({'code': RET.PARAMERR, 'message': '参数不足'})

        if not isinstance(f_id, Iterable) or isinstance(f_id, str):
            f_id = [f_id]

        try:
            f_id = list(filter(filter_null, f_id))
        except Exception:
            return JsonResponse({'code': RET.PARAMERR, 'message': '参数错误'})

        if gender not in [0, 1]:
            return JsonResponse({'code': RET.PARAMERR, 'message': '性别必须为0和1'})

        # 检测用户名是否已经存在
        try:
            user = User.objects.get(username=user_name)
        except User.DoesNotExist:
            user = None
        if user is not None:
            logger.debug('用户名重复')
            return JsonResponse({"code": RET.USERERR, "message": "用户名已存在"})

        is_super_user = False
        # 检查用户可以开户个数
        try:
            curr_user = UserInfo.objects.get(user=request.user)
            curr_accounts = curr_user.accounts
            has_accounts = curr_user.has_accounts
        except Exception:
            curr_accounts = -1
            has_accounts = -1
            is_super_user = True

        if curr_accounts == 0:
            logger.warning('越权创建账户')
            return JsonResponse({'code': RET.USERERR, 'message': '您没有权限创建账户'})

        # 检查已开户数是否满足要求
        if curr_accounts > 0:
            # 当前用户创建的在有效期内的账户数量
            # has_accounts = MemberShip.objects.filter(master=request.user, end_time__gt=datetime.now()).count()
            # 当前用户的所有账户数量
            has_accounts = MemberShip.objects.filter(master=request.user).all().count()

            if has_accounts >= curr_accounts:
                logger.debug('超过创建用户的限制')
                # 超出了允许拥有的账户数量
                return JsonResponse({'code': RET.USERERR, 'message': '用户可开户账户数已到上限'})

        try:

            # 开启事务,防止创建表失败还添加了新用户
            with transaction.atomic():
                # 保存用户主表
                user = User.objects.create_user(
                    user_name,
                    email,
                    password,
                    role=role,
                    founder=request.user.id,
                    name=name,
                    update_person=request.user.id
                )
        except Exception as e:
            logger.info(e)
            return JsonResponse({'code': RET.PARAMERR, 'message': '用户名已存在'})

        try:
            with transaction.atomic():
                # 保存用户信息表
                user_info = UserInfo.objects.create(
                    user=user,
                    remarks=remarks,
                    telephone=str(telephone),
                    gender=gender,
                    accounts=accounts,
                    founder=request.user.id,
                    update_person=request.user.id
                )

                # 保存用户关系表
                mem_ship = MemberShip.objects.create(
                    master=request.user,
                    slave=user,
                    end_time=end_time,
                    founder=request.user.id,
                    update_person=request.user.id,
                )

                # 如果不是创建工作人员,记录用户指定的论坛

                fornums = Fornum.objects.filter(id__in=f_id).all()
                if len(fornums) != len(f_id):
                    raise Exception('程序id参数有误')

                if request.user.role > 2:
                    # 操作者不是工作人员,校验其自身的论坛
                    user_ps = UserFornumRelation.objects.filter(user=request.user).all()
                    can_f_ids = [r.fornum.id for r in user_ps]
                    for i in f_id:
                        if int(i) not in can_f_ids:
                            raise Exception('程序id参数有误')

                for fornum in fornums:
                    user_p = UserFornumRelation.objects.create(
                        user=user,
                        fornum=fornum,
                        founder=request.user.id,
                        update_person=request.user.id,
                        update_time=datetime.now()
                    )
                    user_p.save()

                user.save()
                user_info.save()
                mem_ship.save()

                if not is_super_user:
                    # 更新当前用户拥有的账户数
                    curr_user.has_accounts = has_accounts + 1
                    curr_user.save()

        except Exception as e:
            logger.error('创建用户失败:%s' % e)
            return JsonResponse({'code': RET.DBERR, 'message': '数据库错误'})

        return JsonResponse({'code': RET.OK, 'message': '添加成功!'})
예제 #5
0
    def post(self, request):
        """删除接口"""
        json_dict = get_json_data(request)
        if json_dict is None:
            return JsonResponse({'code': RET.PARAMERR, 'message': '请使用json格式数据'})

        if request.user.role > 2:
            return JsonResponse({'code': RET.USERERR, 'message': '您没有删除账号的权限'})

        del_ids = json_dict.get('id')

        if del_ids is None:
            return JsonResponse({'code': RET.PARAMERR, 'message': '参数错误'})

        # 删除单个拿到的id是单独的一个字符串,将其变成列表用in删除s
        if (not isinstance(del_ids, Iterable)) or isinstance(del_ids, str):
            del_ids = [del_ids]

        # 过滤掉非整形数据
        del_ids = list(filter(filter_null, del_ids))

        if len(del_ids) == 0:
            return JsonResponse({'code': RET.PARAMERR, 'message': '参数错误'})

        users = User.objects.filter(id__in=del_ids)

        if len(users) != len(del_ids):
            logger.info('{}中参数存在错误'.format(del_ids))
            return JsonResponse({'code': RET.DBERR, 'message': 'id存在错误,删除失败'})

        # 校验广告主和代理商的删除操作权限
        if request.user.role in [3, 4]:
            slaves = [u.slave for u in MemberShip.objects.filter(master=request.user)]
            users = list(filter(lambda x: x in slaves, users))

            if len(users) != len(del_ids):
                logger.warning('存在越权删除现象,可能接口正在被攻击')
                return JsonResponse({'code': RET.PARAMERR, 'message': '删除失败,无法删除他人的隶属账户'})

        operators = [user for user in users if user.role < 3]

        if operators and request.user.role > 1:
            return JsonResponse({'code': RET.USERERR, 'message': '没有删除同事的权限'})

        remove_users = [user for user in users]

        # 代理商账户删除一切相关账户,管理员账户不删相关账户
        users = [user for user in users if user.role > 2]

        while True:
            # 循环搜索要删除的层级用户
            mems = MemberShip.objects.filter(master__in=users)
            if len(mems) < 1: break
            slaves = [mem.slave for mem in mems]
            for mem in mems:
                mem.is_delete = True
                mem.save()
            remove_users += slaves
            users = slaves

        for m in MemberShip.objects.filter(slave__in=remove_users):
            m.is_delete = True
            m.save()
        for m in Machine.objects.filter(user__in=remove_users):
            m.is_delete = True
            m.save()
        UserFornumRelation.objects.filter(user__in=remove_users).delete()

        for ui in UserInfo.objects.filter(user__in=remove_users):
            ui.is_delete = True
            ui.save()

        for user in remove_users:
            user.is_delete = True
            user.save()

        return JsonResponse({'code': RET.OK, 'message': '删除成功'})
예제 #6
0
    def get(self, request):
        q = request.GET.get('q')
        page = request.GET.get('page')
        if request.user.role <= 2:
            users = User.objects.filter(models.Q(name__icontains=q) | models.Q(username__icontains=q)).all()
        else:
            mems = MemberShip.objects.filter(master=request.user).all()
            mems = mems.filter(models.Q(slave__name__icontains=q) | models.Q(slave__username__icontains=q))
            users = [mem.slave for mem in mems]

        data = []

        try:
            page = int(page)
        except TypeError:
            page = 1

        # 每页10条数据
        paginator = Paginator(users, settings.PER_PAGE_COUNTS)

        if (page > paginator.num_pages) or (page < 0):
            page = 1

        users = paginator.page(page)

        for user in users:

            # 论坛信息展示
            ufrs = UserFornumRelation.objects.filter(user=user).all()
            u_fornums = []
            for ufr in ufrs:
                f = {
                    'fornum_name': ufr.fornum.fornum_name,
                    'fornum_id': ufr.fornum.id,
                    'fornum_code': ufr.fornum.title
                }
                u_fornums.append(f)

            try:
                mem = MemberShip.objects.get(slave=user)
                remain_days = (mem.end_time - datetime.now()).days
                remain_days = remain_days if remain_days >= 0 else -1
                end_date = mem.end_time.strftime("%Y年%m月%d日 %H:%M")
                parent_name = mem.master.name
                parent_id = mem.master.id
                parent_role = mem.master.role
                remarks = user.userinfo_set.first().remarks
            except MemberShip.DoesNotExist:
                logger.info("%s没有隶属关系信息" % user.username)
                remain_days = -1
                end_date = -1
                parent_id = -1
                parent_name = ''
                parent_role = -1
                remarks = ""
            try:
                d = {
                    'parent_name': parent_name,
                    'parent_role': parent_role,
                    'parent_id': parent_id,
                    'id': user.id,
                    'username': user.username,
                    'name': user.name,
                    'email': user.email,
                    'role': user.role,
                    'remain_days': remain_days,
                    'remarks': remarks,
                    'join_date': user.date_joined.strftime("%Y年%m月%d日 %H:%M"),
                    'end_date': end_date,
                    'is_in_use': user.is_active,
                    'fornums': u_fornums
                }
            except Exception as e:
                logger.error(e)
                continue
            data.append(d)

        return JsonResponse({'code': RET.OK, 'message': '成功', 'data': data, 'pages': paginator.num_pages,
                             'data_length': paginator.count})
예제 #7
0
    def post(self, request):
        """
        通过用户role获取用户信息
        post方式,Json格式传递
        role参数,可为数组或int类型,数组类型为多个角色
        """
        page = request.GET.get('page')
        json_dict = get_json_data(request)
        if json_dict is None:
            return JsonResponse({'code': RET.PARAMERR, 'message': '请使用json格式数据'})

        role = json_dict.get('role')

        if request.user.role < 2:

            if not role:
                return JsonResponse({'code': RET.PARAMERR, 'message': '缺少必要参数'})

            if not isinstance(role, Iterable) or isinstance(role, str):
                role = [role]

            role = list(filter(filter_null, role))
            role = [int(i) for i in role]

            if not role:
                return JsonResponse({'code': RET.PARAMERR, 'message': '参数错误'})

            users = User.objects.filter(role__in=role).order_by('-is_active', '-date_joined')
        else:
            mems = MemberShip.objects.filter(master=request.user)
            users = [mem.slave for mem in mems]

        try:
            page = int(page)
        except TypeError:
            logger.info('页码错误')
            page = 1

        # 每页10条数据
        paginator = Paginator(users, settings.PER_PAGE_COUNTS)

        if (page > paginator.num_pages) or (page < 0):
            page = 1

        users = paginator.page(page)

        data = []

        for user in users:

            if user.is_delete:
                continue

            # 论坛信息展示
            ufrs = UserFornumRelation.objects.filter(user=user)
            u_fornums = []
            for ufr in ufrs:
                f = {
                    'fornum_name': ufr.fornum.fornum_name,
                    'fornum_id': ufr.fornum.id,
                    'fornum_code': ufr.fornum.title,
                    'app_type':ufr.fornum.app_type,
                }
                u_fornums.append(f)

            try:
                mem_info = MemberShip.objects.get(slave=user)
            except Exception:
                remain_days = -1
                end_date = -1
            else:
                remain_days = (mem_info.end_time - datetime.now()).days
                end_date = mem_info.end_time.strftime("%Y年%m月%d日 %H:%M")
                remain_days = remain_days if remain_days >= 0 else -1

            # 父级账户信息展示
            try:
                mem = MemberShip.objects.get(slave=user)
                parent_name = mem.master.name
                parent_id = mem.master.id
                parent_role = mem.master.role
                remarks = user.userinfo_set.first().remarks
            except MemberShip.DoesNotExist:
                logger.info('%d缺少隶属关系' % user.id)
                parent_name = ''
                parent_id = -1
                parent_role = -1
                remarks = ''
            try:
                d = {
                    'parent_role': parent_role,
                    'parent_name': parent_name,
                    'parent_id': parent_id,
                    'id': user.id,
                    'username': user.username,
                    'name': user.name,
                    'email': user.email,
                    'role': user.role,
                    'remarks': remarks,
                    'remain_days': remain_days,
                    'join_date': user.date_joined.strftime("%Y年%m月%d日 %H:%M"),
                    'end_date': end_date,
                    'is_in_use': user.is_active,
                    'fornums': u_fornums
                }
            except Exception as e:
                logger.error(e)
                continue

            data.append(d)

        return JsonResponse({'code': RET.OK, 'message': '成功', 'data': data, 'pages': paginator.num_pages,
                             'data_length': paginator.count})