コード例 #1
0
def index(req):
    """
    2017/05/29 fls
    frist coming
    """
    ret = ResModel()
    ret.msg = '欢迎dr.' + get_ip(req)
    ret.code = ret.ResCode.succ
    return JsonResponse(ret.to_dic())
コード例 #2
0
ファイル: views.py プロジェクト: darkripples/web_frame_server
def content_detail(req, id):
    """
    查询blog明细
    :param req: request
    :param id: id
    :return:
    """

    ret = ResModel()
    ret.msg = req_invalid_check(req)

    v_cnt = 0
    if not req.GET.get("forManage"):
        # 不 通过管理端查询
        # 浏览者信息登记
        try:
            ip = get_ip(req)
            v_cnt = add_visitor(ip,
                                apps.get_app_config('app_blog').name, 'read',
                                id)
        except:
            from traceback import format_exc
            flog.error("记录访客信息失败:%s" % format_exc())

    if ret.msg:
        # 请求合法性校验不通过
        ret.code = ret.ResCode.fail
        ret.data = {}
        return JsonResponse(ret.to_dic())

    ret.code = ret.ResCode.succ

    # todo 权限level的控制
    # 为了统一,驼峰命名,采用原生sql
    with connection() as con:
        # where 条件 and {table1_rlevel}>=0  暂时先屏蔽
        rs = con.execute_sql(
            """select {table1_id},{table1_title},{table1_content},{table1_rcnt},
                to_char({table1_atime}, 'yyyy-mm-dd hh24:mi:ss') as {table1_atime},
                {table1_notes},{table1_bgurl},{table1_rlevel},{table1_type_id},{table1_tags}
            from {table1} where {table1_id}=%(id)s """.format(**SQL_DIC_BLOG),
            {"id": id},
            dicorobj="dict")
        if rs:
            ret.data = rs[0]
            if v_cnt == 1:
                con.execute_sql(
                    "update {table1} set {table1_rcnt}={table1_rcnt}+1 where {table1_id}=%(id)s"
                    .format(**SQL_DIC_BLOG), {"id": id})
        else:
            ret.data = {}
    return JsonResponse(ret.to_dic())
コード例 #3
0
def get_menulist_role(req, role_id=None):
    """
    根据角色获取菜单
    :param req:
    :param role_id:
    :return:
    """
    ret = ResModel()

    ret.msg = req_invalid_check(req)
    if ret.msg:
        # 请求合法性校验不通过
        return JsonResponse(ret.to_dic())

    if not role_id:
        roleMenus = DrRoleMenu.objects.filter()
    else:
        roleMenus = DrRoleMenu.objects.filter(role_id=role_id)

    # ids存储当前角色已有的菜单id
    ids = []
    for row in roleMenus:
        ids.append(row.menu_id)

    tops = DrMenu.objects.filter(Q(pid='')
                                 | Q(pid__isnull=True)).order_by('order_no')

    ret.data = menu_children(tops, ids)
    ret.msg = ''
    ret.code = ret.ResCode.succ
    return JsonResponse(ret.to_dic())
コード例 #4
0
def get_info(req):
    """
    查询信息
    :param req:
    :return:
    """
    ret = ResModel()
    ret.msg = req_invalid_check(req)
    if ret.msg:
        # 请求合法性校验不通过
        return JsonResponse(ret.to_dic())
    # 中间件校验token后赋值USER_ID
    user_id = req.META.get("USER_ID")
    if user_id:
        # 查询用户信息
        with connection() as con:
            user_rs = con.execute_sql("""
                select a.{table1_uname},a.{table1_phone},a.{table1_email},a.{table1_emailsucc},
                    a.{table1_wx},a.{table1_qq},to_char(a.{table1_atime}, 'yyyy-mm-dd hh24:mi:ss') as {table1_atime},
                    b.{table11_sex},b.{table11_himg},b.{table11_introduce},b.{table11_notes},b.{table11_occupation},
                    b.{table11_local}
                from {table1} a,{table11} b 
                where a.{table1_id}=b.{table11_id} and a.{table1_id}=%(uid)s"""
                                      .format(**{
                                          **SQL_DIC_USER,
                                          **SQL_DIC_USERINFO
                                      }), {"uid": user_id},
                                      dicorobj='dict')
            if user_rs and user_rs[0]:
                ret.data = user_rs[0]
    ret.code = ret.ResCode.succ
    ret.msg = ""
    return JsonResponse(ret.to_dic())
コード例 #5
0
def log_out(req):
    """
    登出
    :param req:
    :return:
    """
    ret = ResModel()

    token = req.META.get('HTTP_TOKEN')
    if token:
        # 获取redis缓存数据
        r = RedisCtrl()
        r.del_one(REDIS_KEY_PRE_TOKEN + token)
    ret.code = ret.ResCode.succ
    ret.msg = "已退出登录"
    return JsonResponse(ret.to_dic())
コード例 #6
0
def upload_file(req):
    """
    文件上传
    :param req: pathPre,file
    :return:
    """
    ret = ResModel()
    ret.msg = req_invalid_check(req)
    if ret.msg:
        # 请求合法性校验不通过
        return JsonResponse(ret.to_dic())

    file_obj = req.FILES.get('file')
    if not file_obj:
        ret.msg = '未选择文件'
        return JsonResponse(ret.to_dic())

    # 允许指定类型前缀,以区分不同业务
    path_pre = req.POST.get('pathPre', '')
    # 上传路径
    up_path_pre = settings.UPLOAD_DIR
    # 按日期年月分组
    now_date = fmt_date(fmt=FMT_DATE)
    up_path = path.join(up_path_pre, path_pre, now_date)
    if not path.exists(up_path):
        makedirs(up_path)

    # 重命名,防止重名
    file_type = path.splitext(file_obj.name)[1]
    file_name = str(uuid1()).replace('-', '') + file_type
    # 保存文件
    with open(path.join(up_path, file_name), 'wb') as fp:
        for chunk in file_obj.chunks():
            fp.write(chunk)
    ret.msg = '已上传'
    ret.code = ret.ResCode.succ
    # fileSize单位是字节.fileSize/1024单位即kb;fileSize/1024/1024单位即mb
    ret.data = {"oldName": file_obj.name,
                "newName": path.join(settings.STATIC_ROOT, settings.UPLOAD_ROOT, path_pre, now_date, file_name),
                "fileType": file_type.split(".")[-1], "fileSize": file_obj.size}
    return JsonResponse(ret.to_dic())
コード例 #7
0
def modify_info(req):
    """
    修改信息
    :param req:
    :return:
    """
    ret = ResModel()
    ret.msg = req_invalid_check(req)
    if ret.msg:
        # 请求合法性校验不通过
        return JsonResponse(ret.to_dic())
    # 中间件校验token后赋值USER_ID
    user_id = req.META.get("USER_ID")
    if not user_id:
        return JsonResponse(ResModelToLogin().to_dic())

    # 校验用户信息
    with connection() as con:
        user_rs = con.execute_sql(
            """select {table11_id} 
            from {table11} where {table11_id}=%(uid)s""".format(
                **SQL_DIC_USERINFO), {"uid": user_id})
        if (not user_rs) or (not user_rs[0]):
            # 按理说不会走这个if的,若走了,肯定有问题,不必友好提示
            return JsonResponse(ResModelToLogin().to_dic())

    # 获取参数,不取默认值是为了保持数据库的default值
    sex_type = req.POST.get('sexType', DrUserInfo.SEX_TYPE[0][0])
    head_img = req.POST.get('headImg', '')
    user_introduce = req.POST.get('userIntro', '')
    user_notes = req.POST.get('userNotes', '')
    occupation = req.POST.get('userOcc', '')
    user_location = req.POST.get('userLocal', '')
    with connection() as con:
        con.execute_sql(
            """update {table11} 
            set {table11_sex}=%(sex)s,{table11_himg}=%(himg)s,{table11_introduce}=%(intro)s,
                {table11_notes}=%(notes)s,{table11_occupation}=%(occ)s,{table11_local}=%(local)s 
            where {table11_id}=%(uid)s""".format(**SQL_DIC_USERINFO), {
                "uid": user_id,
                "sex": sex_type,
                "himg": head_img,
                "intro": user_introduce,
                "notes": user_notes,
                "occ": occupation,
                "local": user_location
            })

    ret.msg = '已修改'
    ret.code = ret.ResCode.succ
    return JsonResponse(ret.to_dic())
コード例 #8
0
ファイル: views.py プロジェクト: darkripples/web_frame_server
def type_list(req):
    """
    查询blog类别
    :param req: request
    :return:
    """
    ret = ResModel()
    ret.msg = req_invalid_check(req)
    if ret.msg:
        # 请求合法性校验不通过
        ret.code = ret.ResCode.fail
        ret.data = []
        return JsonResponse(ret.to_dic())

    ret.code = ret.ResCode.succ
    with connection() as con:
        ret.data = con.execute_sql(
            """select {table2_type_id}, {table2_type_name} 
            from {table2} order by convert_to({table2_type_name} , 'GB18030') asc"""
            .format(**SQL_DIC_TYPE),
            dicorobj="dict")
    return JsonResponse(ret.to_dic())
コード例 #9
0
ファイル: views.py プロジェクト: darkripples/web_frame_server
def title_value(req):
    """
    查询副标题参数
    :param req: request
    :return:
    """
    ret = ResModel()
    ret.msg = req_invalid_check(req)
    if ret.msg:
        # 请求合法性校验不通过
        ret.code = ret.ResCode.fail
        ret.data = {}
        return JsonResponse(ret.to_dic())

    ret.code = ret.ResCode.succ
    with connection() as con:
        rs = con.execute_sql(
            "select {table1_value} from {table1} where {table1_code}=%(p)s ".
            format(**SQL_DIC_PARAM), {'p': SET_TITLE_CMD},
            dicorobj="dict")
        ret.data = rs[0] if rs else {}
    return JsonResponse(ret.to_dic())
コード例 #10
0
def vcode_sid(req):
    """
    验证码-获取sid
    生成sid及验证码字符串,有效期10分钟
    :param req:
    :return:
    """
    ret = ResModel()
    ret.msg = req_invalid_check(req)
    if ret.msg:
        # 请求合法性校验不通过
        return JsonResponse(ret.to_dic())

    r = RedisCtrl()
    ret.data = str(uuid1()).replace("-", "").lower()
    r.set_one(REDIS_KEY_PRE_SID + ret.data, ValidCodeImg.getRandomStr(5), expt=60 * 10)
    ret.msg = ''
    ret.code = ret.ResCode.succ
    return JsonResponse(ret.to_dic())
コード例 #11
0
def get_display_list(req):
    """
    角色列表-带pid的树形
    :param req:
    :return:
    """
    ret = ResModel()

    ret.msg = req_invalid_check(req)
    if ret.msg:
        # 请求合法性校验不通过
        ret.code = ret.ResCode.fail
        return JsonResponse(ret.to_dic())

    with connection() as con:
        ret.data = con.execute_sql(
            """select a.{tablem_id} as id,a.{tablem_aname} as name,a.{tablem_pid} as p_id 
        from {tablem} a where 1=1 order by a.{tablem_orderno} asc,a.{tablem_id} asc"""
            .format(**SQL_DIC_MENU),
            dicorobj="dict")
    ret.code = ret.ResCode.succ
    ret.msg = ""
    return JsonResponse(ret.to_dic())
コード例 #12
0
def sid_pic(req, sid):
    """
    验证码-根据sid生成图片
    :param req:
    :return:
    """
    ret = ResModel()
    ret.msg = req_invalid_check(req)
    if ret.msg:
        # 请求合法性校验不通过
        return JsonResponse(ret.to_dic())
    r = RedisCtrl()
    verify_code = r.get_one(REDIS_KEY_PRE_SID + sid)
    if not verify_code:
        # 正常情况下get_sid和本函数是无间隔顺序调用的,所以不会出现redis中不存在的情况,不必友好提示
        return JsonResponse(ret.to_dic())

    # 生成验证码图片.
    i = ValidCodeImg(code_count=5, img_format='png')
    img_data, valid_str = i.getValidCodeImg(vcode_str=verify_code)
    ret.data = img_data.decode('utf8')
    ret.msg = ''
    ret.code = ret.ResCode.succ
    return JsonResponse(ret.to_dic())
コード例 #13
0
def wsocket_init(req):
    """
    websocket连接初始化
    https://blog.csdn.net/xianailili/article/details/82180114
    :param req:
    :return:
    """
    ret = ResModel()
    ret.code = ret.ResCode.succ
    ret.msg = ""

    if req.is_websocket():
        # rlock线程锁
        lock = RLock()
        try:
            # 抢占资源
            lock.acquire()

            global WS_OBJ
            w_obj = req.websocket
            WS_OBJ.add(w_obj)

            ret.data = {"nowCnt": len(WS_OBJ), "type": "init"}
            ret_final = dumps(ret.to_dic(), ensure_ascii=False).encode('utf-8')
            w_obj.send(ret_final)
            for m in w_obj:
                if not m:
                    break
                print('客户端消息:', m.decode('utf-8'))
                ret.data = {"nowCnt": len(WS_OBJ), "clientMsg": m.decode('utf-8'), "type": "return"}
                ret_final = dumps(ret.to_dic(), ensure_ascii=False).encode('utf-8')
                w_obj.send(ret_final)
        except:
            pass
        finally:
            # 移除当前在线的websocket对象
            WS_OBJ.remove(w_obj)
            # 释放锁
            lock.release()
コード例 #14
0
def api_websocket_msg(req):
    """
    发送消息-api
    :param req:
    :return:
    """
    ret = ResModel()
    ret.code = ret.ResCode.succ
    ret.msg = ""
    data = loads(req.POST.get("data", "{}"))

    ret.data = {"nowCnt": len(WS_OBJ), "type": "yw", "data": data}
    ret_final = ret.to_dic()
    websocket_send_all(ret_final)
    return JsonResponse(ret_final)
コード例 #15
0
def save_menulist_role(req, role_id):
    """
    保存角色下的菜单
    :param req:
    :param role_id:
    :return:
    """
    ret = ResModel()

    ret.msg = req_invalid_check(req)
    if ret.msg:
        # 请求合法性校验不通过
        return JsonResponse(ret.to_dic())

    # 中间件校验token后赋值USER_ID
    mod_user_id = req.META.get("USER_ID")
    mids = req.POST.get('ids', '')

    # 先删除要保存或修改的角色菜单,然后再添加
    sql_ins = """insert into {tablerm}({tablerm_id},{tablerm_rid},{tablerm_mid},{tablerm_upduid}, {tablerm_atime})
        values(%(rmid)s, %(rid)s, %(mid)s, %(uid)s, %(atime)s)
    """
    now_date = fmt_date()
    # 开启事务
    with connection() as con:
        con.execute_sql(
            "delete from {tablerm} where {tablerm_rid}=%(rid)s".format(
                **SQL_DIC_ROLEMENU), {"rid": role_id})
        if mids:
            for mid in mids.split(","):
                con.execute_sql(
                    sql_ins.format(**SQL_DIC_ROLEMENU), {
                        "rmid": str(uuid1()).replace('-', ''),
                        "rid": role_id,
                        "mid": mid,
                        "uid": mod_user_id,
                        "atime": now_date
                    })
    ret.msg = '已保存'
    ret.code = ret.ResCode.succ
    return JsonResponse(ret.to_dic())
コード例 #16
0
def log_in_openid(req, yw_name, openid):
    """
    根据openid登录
        1.查询redis是否存在该openid用户:
            1.1.存在则直接return
            1.2.不存在则查询db:
                a.获取用户信息存入redis后return
                b.无用户信息则return空,可走注册流程
    :param req:
    :param yw_name:
    :param openid:
    :return:
    """
    ret = ResModel()

    app_idsecret = MINI_PROGRAM_APP_CONF.get(yw_name)
    if not app_idsecret:
        ret.msg = '未配置的应用名称'
        return JsonResponse(ret.to_dic())

    ret.msg = ''
    ret.code = ret.ResCode.succ

    app_id, app_secret = app_idsecret

    user_obj = None
    r = RedisCtrl()
    token = r.get_one(app_id + openid)
    if token:
        user_obj = r.get_one(token)
    else:
        with connection() as con:
            sql = """select a.{table1_id}, a.{table1_uname}, a.{table1_pwd}, a.{table1_salt},
            a.{table1_wx}, a.{table1_qq}, a.{table1_phone}, a.{table1_email} 
            from {table1} a, {tableo} b
            where a.{table1_id}=b.{tableo_uid} 
                and b.{tableo_aid}=%(appid)s 
                and b.{tableo_oid}=%(oid)s 
            """.format(**{**SQL_DIC_USER, **SQL_DIC_USEROPENID})
            user_rs = con.execute_sql(sql, {"appid": app_id, "oid": openid})
            if user_rs and user_rs[0]:
                user_obj = user_rs[0]
            else:
                ret.msg = '用户信息不存在'

    if user_obj:
        # 记录登录日志
        add_visitor(get_ip(req), apps.get_app_config('app_mf').name, 'login', user_obj.id)

        # 组织可见的user_info
        user_info = {"id": user_obj.id, "username": user_obj.userName}

        # 生成登录token
        # 存入缓存格式:   token:user_info
        token_tmp = create_token(user_info, expt=-1)
        # 存入缓存格式:   appid+openid:token
        r.set_one(app_id + openid, token_tmp)

        ret.data = {"token": token_tmp, "userInfo": user_info}
    else:
        ret.data = {}
    return JsonResponse(ret.to_dic())
コード例 #17
0
def get_allmenu2list(req):
    """
    get_allmenu2list
    :param req:
    :return:
    """
    ret = ResModel()

    ret.msg = req_invalid_check(req)
    if ret.msg:
        # 请求合法性校验不通过
        return JsonResponse(ret.to_dic())
    # 中间件校验token后赋值USER_ID
    user_id = req.META.get("USER_ID")
    sql = """select *
        from
            (select
                 prt.{tablem_id}        {tablem_id},
                 prt.{tablem_sname},
                 prt.{tablem_aname},
                 prt.{tablem_href},
                 prt.{tablem_icon},
                 prt.{tablem_orderno}    {tablem_orderno},
                 chd.{tablem_id}         child_id,
                 chd.{tablem_sname}      child_show_name,
                 chd.{tablem_aname}      child_alias_name,
                 chd.{tablem_href}       child_href,
                 chd.{tablem_icon}       child_icon,
                 chd.{tablem_orderno}    child_order_no,
                 chd.{tablem_pid}        child_parent_id
             from {tablem} prt
                      left join {tablem} chd on chd.{tablem_pid} = prt.{tablem_id}
             where prt.{tablem_pid} is null
                or prt.{tablem_pid} = '') menu
        where
                menu.child_id in (
                select rm.{tablerm_mid}
                from
                    {table1} u,
                    {table3} ur,
                    {tablerm} rm
                where
                    u.{table1_id} = ur.{table3_uid}
                  and ur.{table3_rid} = rm.{tablerm_rid}
                  and u.{table1_id} = %(uid)s)
           or (menu.{tablem_id} in (
            select rm.{tablerm_mid}
            from
                {table1} u,
                {table3} ur,
                {tablerm} rm
            where
                u.{table1_id} = ur.{table3_uid}
              and ur.{table3_rid} = rm.{tablerm_rid}
              and u.{table1_id} = %(uid)s) and (menu.child_id is null or menu.child_id = ''))
        order by menu.{tablem_orderno}, menu.child_order_no
    """
    ret.data = []
    menuIdLst = []
    with connection() as con:
        menu_list = con.execute_sql(
            sql.format(
                **{
                    **SQL_DIC_MENU,
                    **SQL_DIC_ROLEMENU,
                    **SQL_DIC_USER,
                    **SQL_DIC_USERROLE
                }), {"uid": user_id})
        for row in menu_list:
            if row.id in menuIdLst:
                continue
            menuIdLst.append(row.id)
            menuObj = {
                "menuId": row.id,
                "showName": row.showName,
                "aliasName": row.aliasName,
                "href": row.href,
                "icon": row.icon,
                "orderNo": row.orderNo
            }
            if row.childId:
                menuObj["hasChildren"] = True
                parentId = row.id
                children = []
                for child in menu_list:
                    if parentId == child.childParentId:
                        childObj = {
                            "menuId": child.childId,
                            "showName": child.childShowName,
                            "aliasName": child.childAliasName,
                            "href": child.childHref,
                            "icon": child.childIcon,
                            "orderNo": child.childOrderNo
                        }
                        children.append(childObj)

                menuObj["children"] = children
            else:
                menuObj["hasChildren"] = False
            ret.data.append(menuObj)
    ret.msg = ''
    ret.code = ret.ResCode.succ
    return JsonResponse(ret.to_dic())
コード例 #18
0
def reset_phone_email(req, code_way, sid):
    """
    更换/添加手机号、email
    :param req:
    :param code_way: smscode.短信验证码;emailcode.email验证码
    :param sid:
    :return:
    """
    ret = ResModel()
    ret.msg = req_invalid_check(req)
    if ret.msg:
        # 请求合法性校验不通过
        return JsonResponse(ret.to_dic())
    # 中间件校验token后赋值USER_ID
    user_id = req.META.get("USER_ID")
    if not user_id:
        ret.msg = "用户信息不存在"
        return JsonResponse(ret.to_dic())

    # 图形验证码or短信验证码
    auth_code = req.POST.get('authCode', '').upper()
    # 新phone或者新email
    new_aim = req.POST.get('newAim', '')
    if not auth_code:
        ret.msg = '验证码不可空'
        return JsonResponse(ret.to_dic())
    if not new_aim:
        ret.msg = '参数异常'
        return JsonResponse(ret.to_dic())

    # 获取redis缓存数据
    r = RedisCtrl()
    verify_code = r.get_one(REDIS_KEY_PRE_SID + sid)
    if not verify_code:
        ret.msg = '验证码已过期'
        return JsonResponse(ret.to_dic())

    if code_way == 'emailcode':
        # 登录方式.emailcode.email验证码
        user_code = r.get_one(REDIS_KEY_PRE_EMAILCODE + new_aim)
        ret.msg = '该email验证码已过期'
        sub_sql = "{table1_email}=%(new)s,{table1_emailsucc}='" + DrUser.EMAIL_SUCC[
            1][0] + "',"
    elif code_way == 'smscode':
        # 登录方式.smscode.短信验证码
        user_code = r.get_one(REDIS_KEY_PRE_SMSCODE + new_aim)
        ret.msg = '该手机号验证码已过期'
        sub_sql = "{table1_phone}=%(new)s,"
    else:
        # 其他code_way,反馈失败
        return JsonResponse(ret.to_dic())

    # 校验验证码
    if not user_code:
        # 验证码不存在
        return JsonResponse(ret.to_dic())
    if user_code != auth_code:
        # 校验验证码
        ret.msg = '验证码错误'
        # 记录错误次数,多次失败则需重新请求sid
        err_cnt = r.get_one(REDIS_KEY_PRE_CODEERR + user_id)
        if not err_cnt:
            err_cnt = 1
            r.set_one(REDIS_KEY_PRE_CODEERR + user_id,
                      str(err_cnt),
                      expt=60 * 5)
        else:
            err_cnt = int(err_cnt) + 1
            r.set_one(REDIS_KEY_PRE_CODEERR + user_id,
                      str(err_cnt),
                      expt=60 * 5)
        if int(err_cnt) >= 10:
            # 尝试次数大于10次,则需重新发送sms
            r.del_one(REDIS_KEY_PRE_SMSCODE + user_id)
            r.del_one(REDIS_KEY_PRE_EMAILCODE + user_id)
            r.del_one(REDIS_KEY_PRE_CODEERR + user_id)
            # 同一个验证码尝试次数过多
            flog.warning(f"[{user_id}]用户的{code_way}验证码尝试次数过多")
            ret.msg = '验证码错误,请重新加载'
        return JsonResponse(ret.to_dic())

    # 设置
    with connection() as con:
        con.execute_sql(
            "update {table1} set " + sub_sql +
            ",{table1_utime}=%(ut)s where {table1_id}=%(uid)s".format(
                **SQL_DIC_USER), {
                    "new": new_aim,
                    "uid": user_id,
                    "ut": fmt_date()
                })

    ret.msg = '已修改'
    ret.code = ret.ResCode.succ
    return JsonResponse(ret.to_dic())
コード例 #19
0
def sms_log_in(req, sid, vcode):
    """
    登录-短信验证码发送
    短信验证码有效期5分钟
    :param req:
    :param sid:
    :param vcode:
    :return:
    """
    ret = ResModel()
    ret.msg = req_invalid_check(req)
    if ret.msg:
        # 请求合法性校验不通过
        return JsonResponse(ret.to_dic())
    phone = req.POST.get('phone', '')
    if not phone:
        ret.msg = '参数异常'
        return JsonResponse(ret.to_dic())

    # 校验
    r = RedisCtrl()
    verify_code = r.get_one(REDIS_KEY_PRE_SID + sid)
    if not verify_code:
        ret.msg = '验证码已过期'
        return JsonResponse(ret.to_dic())
    if verify_code.upper() != vcode.upper():
        ret.msg = '验证码错误'
        # 记录错误次数,多次失败则需重新请求sid
        err_cnt = r.get_one(REDIS_KEY_PRE_SIDERR + sid)
        if not err_cnt:
            err_cnt = 1
            r.set_one(REDIS_KEY_PRE_SIDERR + sid, str(err_cnt), expt=60 * 5)
        else:
            err_cnt = int(err_cnt) + 1
            r.set_one(REDIS_KEY_PRE_SIDERR + sid, str(err_cnt), expt=60 * 5)
        if int(err_cnt) >= 10:
            # 尝试次数大于10次,则需重新请求sid
            r.del_one(REDIS_KEY_PRE_SID + sid)
            r.del_one(REDIS_KEY_PRE_SIDERR + sid)
        return JsonResponse(ret.to_dic())

    # 校验用户是否存在
    with connection() as con:
        user_rs = con.execute_sql(
            """select {table1_id}, {table1_uname}, {table1_pwd}, {table1_salt}, 
                {table1_wx}, {table1_qq}, {table1_phone}, {table1_email} 
            from {table1} 
            where {table1_phone}=%(phone)s """.format(**SQL_DIC_USER), {"phone": phone}
        )
        if (not user_rs) or (not user_rs[0]):
            ret.msg = '当前用户信息不存在'
            return JsonResponse(ret.to_dic())

    # 短信验证码发送
    sms_code = "%06d" % randint(0, 999999)
    r.set_one(REDIS_KEY_PRE_SMSCODE + phone, sms_code, expt=60 * 5)
    sms_ret = sms_send(phone, {"code": sms_code}, ALI_SMS_TMPL_COMMON_CODE, "登录验证码")
    flog.debug(f"登录验证码发送:{sms_ret}")

    ret.msg = '已发送'
    ret.code = ret.ResCode.succ
    return JsonResponse(ret.to_dic())
コード例 #20
0
def sms_reset_phone(req, sid, vcode):
    """
    发送短信验证码-更换/添加手机号
    :param req:
    :param sid:
    :param vcode:
    :return:
    """
    ret = ResModel()
    ret.msg = req_invalid_check(req)
    if ret.msg:
        # 请求合法性校验不通过
        return JsonResponse(ret.to_dic())
    # 中间件校验token后赋值USER_ID
    user_id = req.META.get("USER_ID")
    if not user_id:
        ret.msg = "用户信息不存在"
        return JsonResponse(ret.to_dic())
    phone = req.POST.get("phone")
    if not phone:
        ret.msg = "请输入新手机号"
        return JsonResponse(ret.to_dic())

    # 校验
    r = RedisCtrl()
    verify_code = r.get_one(REDIS_KEY_PRE_SID + sid)
    if not verify_code:
        ret.msg = '验证码已过期'
        return JsonResponse(ret.to_dic())
    if verify_code.upper() != vcode.upper():
        ret.msg = '验证码错误'
        # 记录错误次数,多次失败则需重新请求sid
        err_cnt = r.get_one(REDIS_KEY_PRE_SIDERR + sid)
        if not err_cnt:
            err_cnt = 1
            r.set_one(REDIS_KEY_PRE_SIDERR + sid, str(err_cnt), expt=60 * 5)
        else:
            err_cnt = int(err_cnt) + 1
            r.set_one(REDIS_KEY_PRE_SIDERR + sid, str(err_cnt), expt=60 * 5)
        if int(err_cnt) >= 10:
            # 尝试次数大于10次,则需重新请求sid
            r.del_one(REDIS_KEY_PRE_SID + sid)
            r.del_one(REDIS_KEY_PRE_SIDERR + sid)
        return JsonResponse(ret.to_dic())

    # 查询用户信息
    with connection() as con:
        user_rs = con.execute_sql(
            "select {table1_id} from {table1} where {table1_id}=%(uid)s".
            format(**SQL_DIC_USER), {"uid": user_id})
        if not user_rs:
            ret.msg = "用户信息不存在"
            return JsonResponse(ret.to_dic())
        # 新手机号重复性校验
        user_rs2 = con.execute_sql(
            "select {table1_id} from {table1} where {table1_phone}=%(phone)s".
            format(**SQL_DIC_USER), {"phone": phone})
        if user_rs2:
            ret.msg = "该手机号已被使用"
            return JsonResponse(ret.to_dic())

    # 短信验证码发送
    sms_code = "%06d" % randint(0, 999999)
    r.set_one(REDIS_KEY_PRE_SMSCODE + phone, sms_code, expt=60 * 5)
    sms_ret = sms_send(phone, {"code": sms_code}, ALI_SMS_TMPL_RESET_PHONE,
                       "修改手机号验证码")
    flog.debug(f"修改手机号验证码发送:{sms_ret}")

    ret.msg = '已发送'
    ret.code = ret.ResCode.succ
    return JsonResponse(ret.to_dic())
コード例 #21
0
def email_reset_email(req, sid, vcode):
    """
    发送email验证码-更换/添加email
    :param req:
    :param sid:
    :param vcode:
    :return:
    """
    ret = ResModel()
    ret.msg = req_invalid_check(req)
    if ret.msg:
        # 请求合法性校验不通过
        return JsonResponse(ret.to_dic())
    # 中间件校验token后赋值USER_ID
    user_id = req.META.get("USER_ID")
    if not user_id:
        ret.msg = "用户信息不存在"
        return JsonResponse(ret.to_dic())
    email = req.POST.get("email")
    if not email:
        ret.msg = "请输入新EMAIL"
        return JsonResponse(ret.to_dic())

    # 校验
    r = RedisCtrl()
    verify_code = r.get_one(REDIS_KEY_PRE_SID + sid)
    if not verify_code:
        ret.msg = '验证码已过期'
        return JsonResponse(ret.to_dic())
    if verify_code.upper() != vcode.upper():
        ret.msg = '验证码错误'
        # 记录错误次数,多次失败则需重新请求sid
        err_cnt = r.get_one(REDIS_KEY_PRE_SIDERR + sid)
        if not err_cnt:
            err_cnt = 1
            r.set_one(REDIS_KEY_PRE_SIDERR + sid, str(err_cnt), expt=60 * 5)
        else:
            err_cnt = int(err_cnt) + 1
            r.set_one(REDIS_KEY_PRE_SIDERR + sid, str(err_cnt), expt=60 * 5)
        if int(err_cnt) >= 10:
            # 尝试次数大于10次,则需重新请求sid
            r.del_one(REDIS_KEY_PRE_SID + sid)
            r.del_one(REDIS_KEY_PRE_SIDERR + sid)
        return JsonResponse(ret.to_dic())

    # 查询用户信息
    with connection() as con:
        user_rs = con.execute_sql(
            "select {table1_id} from {table1} where {table1_id}=%(uid)s".
            format(**SQL_DIC_USER), {"uid": user_id})
        if not user_rs:
            ret.msg = "用户信息不存在"
            return JsonResponse(ret.to_dic())
        # 新email重复性校验
        user_rs2 = con.execute_sql(
            "select {table1_id} from {table1} where {table1_email}=%(email)s".
            format(**SQL_DIC_USER), {"email": email})
        if user_rs2:
            ret.msg = "该email已被使用"
            return JsonResponse(ret.to_dic())

    # email验证码发送
    email_code = "%06d" % randint(0, 999999)
    r.set_one(REDIS_KEY_PRE_EMAILCODE + email, email_code, expt=60 * 6)
    send_ret = email_send([email], EMAIL_MODPHONE_TITLE,
                          EMAIL_MODPHONE_CONT % email_code)
    flog.debug(email + f"重置密码时发送email验证码err:{send_ret}")

    ret.msg = '已发送'
    ret.code = ret.ResCode.succ
    return JsonResponse(ret.to_dic())
コード例 #22
0
def email_reset_pwd(req, sid, vcode):
    """
    修改密码-发送email验证码
    :param req:
    :param sid:
    :param vcode:
    :return:
    """
    ret = ResModel()
    ret.msg = req_invalid_check(req)
    if ret.msg:
        # 请求合法性校验不通过
        return JsonResponse(ret.to_dic())
    # 中间件校验token后赋值USER_ID
    user_id = req.META.get("USER_ID")
    if not user_id:
        ret.msg = "用户信息不存在"
        return JsonResponse(ret.to_dic())

    # 校验
    r = RedisCtrl()
    verify_code = r.get_one(REDIS_KEY_PRE_SID + sid)
    if not verify_code:
        ret.msg = '验证码已过期'
        return JsonResponse(ret.to_dic())
    if verify_code.upper() != vcode.upper():
        ret.msg = '验证码错误'
        # 记录错误次数,多次失败则需重新请求sid
        err_cnt = r.get_one(REDIS_KEY_PRE_SIDERR + sid)
        if not err_cnt:
            err_cnt = 1
            r.set_one(REDIS_KEY_PRE_SIDERR + sid, str(err_cnt), expt=60 * 5)
        else:
            err_cnt = int(err_cnt) + 1
            r.set_one(REDIS_KEY_PRE_SIDERR + sid, str(err_cnt), expt=60 * 5)
        if int(err_cnt) >= 10:
            # 尝试次数大于10次,则需重新请求sid
            r.del_one(REDIS_KEY_PRE_SID + sid)
            r.del_one(REDIS_KEY_PRE_SIDERR + sid)
        return JsonResponse(ret.to_dic())

    # 查询用户信息
    with connection() as con:
        user_rs = con.execute_sql(
            "select {table1_id}, {table1_email} from {table1} where {table1_id}=%(uid)s"
            .format(**SQL_DIC_USER), {"uid": user_id})
        if user_rs and user_rs[0]:
            user_obj = user_rs[0]
            if not user_obj.email:
                ret.msg = "您未绑定email地址"
                return JsonResponse(ret.to_dic())
        else:
            ret.msg = "用户信息不存在"
            return JsonResponse(ret.to_dic())

    # email验证码发送
    email_code = "%06d" % randint(0, 999999)
    r.set_one(REDIS_KEY_PRE_EMAILCODE + user_obj.id, email_code, expt=60 * 6)
    email_send([user_obj.email], EMAIL_MODPWD_TITLE,
               EMAIL_MODPWD_CONT % email_code)

    ret.msg = '已发送'
    ret.code = ret.ResCode.succ
    return JsonResponse(ret.to_dic())
コード例 #23
0
def reset_pwd(req, code_way, sid):
    """
    重置密码
    :param req:
    :param code_way: smscode.短信验证码;emailcode.email验证码
    :param sid:
    :return:
    """
    ret = ResModel()
    ret.msg = req_invalid_check(req)
    if ret.msg:
        # 请求合法性校验不通过
        return JsonResponse(ret.to_dic())
    # 中间件校验token后赋值USER_ID
    user_id = req.META.get("USER_ID")
    if not user_id:
        ret.msg = "用户信息不存在"
        return JsonResponse(ret.to_dic())

    # 图形验证码or短信验证码
    auth_code = req.POST.get('authCode', '').upper()
    new_pwd = req.POST.get('newPwd', '').upper()
    if not auth_code:
        ret.msg = '验证码不可空'
        return JsonResponse(ret.to_dic())
    if not new_pwd:
        ret.msg = '新密码不可空'
        return JsonResponse(ret.to_dic())

    # 获取redis缓存数据
    r = RedisCtrl()
    verify_code = r.get_one(REDIS_KEY_PRE_SID + sid)
    if not verify_code:
        ret.msg = '验证码已过期'
        return JsonResponse(ret.to_dic())

    if code_way == 'emailcode':
        # 登录方式.emailcode.email验证码
        user_code = r.get_one(REDIS_KEY_PRE_EMAILCODE + user_id)
    elif code_way == 'smscode':
        # 登录方式.smscode.短信验证码
        user_code = r.get_one(REDIS_KEY_PRE_SMSCODE + user_id)
    else:
        # 其他code_way,反馈失败
        return JsonResponse(ret.to_dic())

    # 校验验证码
    if not user_code:
        # 短信验证码不存在
        ret.msg = '验证码已过期'
        return JsonResponse(ret.to_dic())
    if user_code != auth_code:
        # 校验验证码
        ret.msg = '验证码错误'
        # 记录错误次数,多次失败则需重新请求sid
        err_cnt = r.get_one(REDIS_KEY_PRE_CODEERR + user_id)
        if not err_cnt:
            err_cnt = 1
            r.set_one(REDIS_KEY_PRE_CODEERR + user_id,
                      str(err_cnt),
                      expt=60 * 5)
        else:
            err_cnt = int(err_cnt) + 1
            r.set_one(REDIS_KEY_PRE_CODEERR + user_id,
                      str(err_cnt),
                      expt=60 * 5)
        if int(err_cnt) >= 10:
            # 尝试次数大于10次,则需重新发送sms
            r.del_one(REDIS_KEY_PRE_SMSCODE + user_id)
            r.del_one(REDIS_KEY_PRE_EMAILCODE + user_id)
            r.del_one(REDIS_KEY_PRE_CODEERR + user_id)
            # 同一个验证码尝试次数过多
            flog.warning(f"重置密码时[{user_id}]用户的验证码尝试次数过多")
            ret.msg = '验证码错误,请重新加载'
        return JsonResponse(ret.to_dic())

    # 设置密码
    p = PwdCtrl()
    salt = p.get_salt()
    pwd = p.create_md5(src_str=new_pwd, salt=salt)
    with connection() as con:
        con.execute_sql(
            """update {table1} set {table1_pwd}=%(pwd)s,{table1_salt}=%(salt)s ,{table1_utime}=%(ut)s
        where {table1_id}=%(uid)s""".format(**SQL_DIC_USER), {
                "pwd": pwd,
                "uid": user_id,
                "salt": salt,
                "ut": fmt_date()
            })
    ret.msg = '已修改密码'
    ret.code = ret.ResCode.succ
    return JsonResponse(ret.to_dic())
コード例 #24
0
def del_obj(req):
    """
    删除
    :param req:
    :return:
    """
    ret = ResModel()

    ret.msg = req_invalid_check(req)
    if ret.msg:
        # 请求合法性校验不通过
        ret.code = ret.ResCode.fail
        return JsonResponse(ret.to_dic())

    mid = req.POST.get('id')
    if not mid:
        ret.code = ret.ResCode.fail
        ret.msg = "未查询到记录"
        return JsonResponse(ret.to_dic())

    rs = DrMenu.objects.filter(id=mid)
    if not rs:
        ret.code = ret.ResCode.fail
        ret.msg = "未查询到记录"
        return JsonResponse(ret.to_dic())
    rs.delete()

    ret.code = ret.ResCode.succ
    ret.msg = "已删除"
    return JsonResponse(ret.to_dic())
コード例 #25
0
def modify_pwd(req):
    """
    修改密码
    :param req:
    :return:
    """
    ret = ResModel()
    ret.msg = req_invalid_check(req)
    if ret.msg:
        # 请求合法性校验不通过
        return JsonResponse(ret.to_dic())
    # 中间件校验token后赋值USER_ID
    user_id = req.META.get("USER_ID")
    if not user_id:
        return JsonResponse(ResModelToLogin().to_dic())

    old_pwd = req.POST.get('oldPwd', '').upper()
    new_pwd = req.POST.get('newPwd', '').upper()
    if (not old_pwd) or (not new_pwd):
        ret.msg = "请求参数缺失"
        return JsonResponse(ret.to_dic())

    # db前校验
    r = RedisCtrl()
    if r.get_one(REDIS_KEY_PRE_PWDERR + user_id + "_ERR"):
        ret.msg = "原密码错误,请" + str(
            r.get_ex_time(REDIS_KEY_PRE_PWDERR + user_id + "_ERR")) + "秒后再尝试"
        return JsonResponse(ret.to_dic())

    # 校验用户信息
    with connection() as con:
        user_rs = con.execute_sql(
            """select {table1_pwd},{table1_salt}
                from {table1} where {table1_id}=%(uid)s""".format(
                **SQL_DIC_USER), {"uid": user_id})
        if (not user_rs) or (not user_rs[0]):
            # 按理说不会走这个if的,若走了,肯定有问题,不必友好提示
            return JsonResponse(ResModelToLogin().to_dic())
        user_rs = user_rs[0]

    # 密码校验
    p = PwdCtrl()
    if user_rs.pwdValue.upper() != p.create_md5(src_str=old_pwd,
                                                salt=user_rs.pwdSalt):
        # 密码校验不通过
        ret.msg = '原密码错误'
        # 错误次数,5分钟内,不可大于等于10次
        err_cnt = r.get_one(REDIS_KEY_PRE_PWDERR + user_id)
        if not err_cnt:
            err_cnt = 1
            r.set_one(REDIS_KEY_PRE_PWDERR + user_id,
                      str(err_cnt),
                      expt=60 * 5)
        else:
            err_cnt = int(err_cnt) + 1
            r.set_one(REDIS_KEY_PRE_PWDERR + user_id,
                      str(err_cnt),
                      expt=60 * 5)
        if int(err_cnt) >= 10:
            r.del_one(REDIS_KEY_PRE_PWDERR + user_id)
            # 同一个手机号验证码尝试次数过多
            flog.warning(f"修改密码时ID[{user_id}]用户的原密码尝试次数过多")
            r.set_one(REDIS_KEY_PRE_PWDERR + user_id + "_ERR",
                      "ERR",
                      expt=60 * 5)
            ret.msg = '原密码错误,请重新加载'
        return JsonResponse(ret.to_dic())

    # 修改
    salt = p.get_salt()
    pwd = p.create_md5(new_pwd, salt=salt)
    with connection() as con:
        con.execute_sql(
            """update {table1} set {table1_pwd}=%(pwd)s,{table1_salt}=%(salt)s
                where {table1_id}=%(uid)s""".format(**SQL_DIC_USER), {
                "uid": user_id,
                "pwd": pwd,
                "salt": salt
            })

    ret.msg = '已修改'
    ret.code = ret.ResCode.succ
    return JsonResponse(ret.to_dic())
コード例 #26
0
def save_obj(req, mod_type):
    """
    保存
    :param req:
    :param mod_type:
    :return:
    """
    ret = ResModel()

    ret.msg = req_invalid_check(req)
    if ret.msg:
        # 请求合法性校验不通过
        ret.code = ret.ResCode.fail
        return JsonResponse(ret.to_dic())

    mod_user_id = req.META.get('USER_ID')
    mid = req.POST.get("id")
    aname = req.POST.get("aliasName")
    icon = req.POST.get("icon")
    sname = req.POST.get("showName")
    pid = req.POST.get("parentId")
    href = req.POST.get("href")
    order_no = req.POST.get("orderNo")

    if pid and (not DrMenu.objects.filter(id=pid)):
        ret.code = ret.ResCode.fail
        ret.msg = "未查询到父节点"
        return JsonResponse(ret.to_dic())

    if mod_type == 'upd':
        # 修改
        rs = DrMenu.objects.filter(id=mid)
        if not rs:
            ret.code = ret.ResCode.fail
            ret.msg = "未查询到该记录"
            return JsonResponse(ret.to_dic())
        rs.update(pid=pid,
                  show_name=sname,
                  alias_name=aname,
                  href=href,
                  icon=icon,
                  order_no=order_no,
                  upd_user_id=mod_user_id)
    else:
        # 新增
        DrMenu.objects.create(id=str(uuid1()).replace('-', ''),
                              pid=pid,
                              show_name=sname,
                              alias_name=aname,
                              href=href,
                              icon=icon,
                              order_no=order_no,
                              upd_user_id=mod_user_id,
                              add_time=timezone.now())
    ret.code = ret.ResCode.succ
    ret.msg = "已保存"
    return JsonResponse(ret.to_dic())
コード例 #27
0
ファイル: views.py プロジェクト: darkripples/web_frame_server
def save_blog(req, mod_type):
    """
    保存
    :param req:
    :param mod_type: add/upd
    :return:
    """
    ret = ResModel()

    ret.msg = req_invalid_check(req)
    if ret.msg:
        # 请求合法性校验不通过
        ret.code = ret.ResCode.fail
        return JsonResponse(ret.to_dic())

    # 入参的非空校验
    post_data = req.POST
    post_dic = {
        'title': post_data.get('title', ""),
        'title_notes': post_data.get('titleNotes', ""),
        'blog_type': post_data.get('blogType', ""),
        'blog_tags': post_data.get('blogTags', ""),
        'content': post_data.get('content', ""),
    }
    if "" in post_dic.values():
        ret.msg = '缺失字段:' + list(post_dic.keys())[list(
            post_dic.values()).index("")]
        return JsonResponse(ret.to_dic())

    # 可空的入参
    post_dic['id'] = post_data.get('id', '')
    post_dic['read_level'] = int(post_data.get('rLevel', '-1'))
    img_url = post_data.get('bgUrl')
    if not img_url:
        post_dic['bg_url'] = ""
    else:
        if img_url.startswith("/static"):
            post_dic['bg_url'] = img_url
        else:
            post_dic['bg_url'] = '/%s' % img_url.replace("\\", "/")

    # 字段长度校验
    for k, v in post_dic.items():
        length_ = BlogContent._meta.get_field(k).max_length
        if length_ and length_ < len(v):
            ret.msg = '内容超长:' + BlogContent._meta.get_field(k).verbose_name
            return JsonResponse(ret.to_dic())

    if not BlogType.objects.filter(type_id=post_dic["blog_type"]):
        ret.code = ret.ResCode.fail
        ret.msg = "类型不合法"
        return JsonResponse(ret.to_dic())

    post_dic["upd_time"] = timezone.now()
    # 登录用户信息
    token = req.META.get('HTTP_TOKEN')
    r = RedisCtrl()
    user_info = r.get_one(REDIS_KEY_PRE_TOKEN + token)
    if user_info:
        user_info = loads(user_info)
    else:
        # 冗余校验
        ret = ResModelToLogin()
        return JsonResponse(ret.to_dic())

    if mod_type == 'upd':
        # 修改
        rs = BlogContent.objects.filter(id=post_dic['id'])
        if not rs:
            ret.code = ret.ResCode.fail
            ret.msg = "未查询到该记录"
            return JsonResponse(ret.to_dic())
        post_dic["upd_account"] = user_info["account"]
        post_dic["upd_name"] = user_info["username"]
        rs.update(**post_dic)
    else:
        # 新增
        # insert
        post_dic["id"] = str(uuid1()).replace('-', '')
        post_dic["add_time"] = post_dic["upd_time"]
        post_dic["auth_account"] = user_info["account"]
        post_dic["auth_name"] = user_info["username"]
        BlogContent.objects.create(**post_dic)

    ret.code = ret.ResCode.succ
    ret.msg = "已保存"
    return JsonResponse(ret.to_dic())
コード例 #28
0
def log_in(req, code_way, sid):
    """
    log_in
    :param req:
    :param code_way: smscode.短信验证码;piccode.图形验证码
    :param sid: 验证码会话sid
    :return:
    """
    ret = ResModel()
    ret.msg = req_invalid_check(req)
    if ret.msg:
        # 请求合法性校验不通过
        ret.code = ret.ResCode.fail
        return JsonResponse(ret.to_dic())

    # 获取redis缓存数据
    r = RedisCtrl()
    verify_code = r.get_one(REDIS_KEY_PRE_SID + sid)
    if not verify_code:
        ret.msg = '验证码已过期'
        return JsonResponse(ret.to_dic())

    # 图形验证码or短信验证码
    auth_code = req.POST.get('authCode', '').upper()
    # 用户账户,若为短信方式,则该字段为手机号;图形验证码的话,该字段可以是account、email、phone
    user_acc = req.POST.get('userAcc', '')
    # 密码为为md5加密的值
    pwd = req.POST.get('pwd', '').upper()
    # 是否需校验密码
    need_check_pwd = False

    if code_way == 'piccode':
        # 登录方式.piccode.图形验证码
        # 校验验证码
        if (not settings.DEBUG) and (verify_code.upper() != auth_code):
            # 是否为debug模式,非debug模式,需校验验证码
            ret.msg = '验证码错误'
            return JsonResponse(ret.to_dic())
        need_check_pwd = True
    elif code_way == 'smscode':
        # 登录方式.smscode.短信验证码
        sms_code = r.get_one(REDIS_KEY_PRE_SMSCODE + user_acc)
        if not sms_code:
            # 短信验证码不存在
            ret.msg = '验证码已过期'
            return JsonResponse(ret.to_dic())
        if (not settings.DEBUG) and (sms_code != auth_code):
            # 是否为debug模式,非debug模式,需校验验证码
            ret.msg = '短信验证码错误'
            # 记录错误次数,多次失败则需重新请求sid
            err_cnt = r.get_one(REDIS_KEY_PRE_CODEERR + user_acc)
            if not err_cnt:
                err_cnt = 1
                r.set_one(REDIS_KEY_PRE_CODEERR + user_acc, str(err_cnt), expt=60 * 5)
            else:
                err_cnt = int(err_cnt) + 1
                r.set_one(REDIS_KEY_PRE_CODEERR + user_acc, str(err_cnt), expt=60 * 5)
            if int(err_cnt) >= 10:
                # 尝试次数大于10次,则需重新发送sms
                r.del_one(REDIS_KEY_PRE_SMSCODE + user_acc)
                r.del_one(REDIS_KEY_PRE_CODEERR + user_acc)
                # 同一个手机号验证码尝试次数过多
                flog.warning(f"短信验证码登录时[{user_acc}]用户的短信验证码尝试次数过多")
                ret.msg = '短信验证码错误,请重新加载'
            return JsonResponse(ret.to_dic())
    else:
        # 其他code_way,反馈失败
        return JsonResponse(ret.to_dic())

    # 查询用户信息
    with connection() as con:
        user_rs = con.execute_sql(
            """select {table1_id}, {table1_account}, {table1_uname}, {table1_pwd}, {table1_salt},
            {table1_wx}, {table1_qq}, {table1_phone}, {table1_email} 
            from {table1} 
            where ( {table1_account}=%(user_acc)s or {table1_phone}=%(user_acc)s or {table1_email}=%(user_acc)s)""".format(
                **SQL_DIC_USER),
            {"user_acc": user_acc}
        )
        if user_rs and user_rs[0]:
            user_obj = user_rs[0]
            # 获取用户角色
            role_rs = con.execute_sql(
                """select a.{tabler_id} as id from {tabler} a, {table3} b 
                where a.{tabler_id}=b.{table3_rid}
                    and b.{table3_uid}=%(uid)s""".format(**{**SQL_DIC_ROLES, **SQL_DIC_USERROLE}),
                {"uid": user_obj.id})
            roles = ','.join([i.id for i in role_rs])
        else:
            # 需校验密码的话,提示语要隐晦一些
            ret.msg = '用户名或密码错误' if need_check_pwd else '用户信息不存在'
            return JsonResponse(ret.to_dic())

    if need_check_pwd:
        # 接下来校验account-pwd 或 phone-pwd 或 email-pwd
        db_pwd = user_obj.pwdValue or ''
        db_salt = user_obj.pwdSalt
        # 密码校验
        p = PwdCtrl()
        if db_pwd.upper() != p.create_md5(src_str=pwd, salt=db_salt):
            # 密码校验不通过
            ret.msg = '用户名或密码错误'
            return JsonResponse(ret.to_dic())

    # 记录登录日志
    add_visitor(get_ip(req), apps.get_app_config('app_dr').name, 'login', user_obj.id)

    # 组织可见的user_info
    user_info = {"id": user_obj.id, "username": user_obj.userName, "account": user_obj.account}

    # 生成登录token
    # redis中额外放入元素roles等;但是不必返回前端
    user_info_redis = {**user_info}
    user_info_redis["roles"] = roles
    token = create_token(user_info_redis)
    ret.data = {"token": token, "referer": req.META.get("HTTP_REFERER"), "userInfo": user_info}

    ret.msg = f'欢迎{user_obj.userName}'
    ret.code = ret.ResCode.succ
    return JsonResponse(ret.to_dic())
コード例 #29
0
ファイル: views.py プロジェクト: darkripples/web_frame_server
def del_blog(req, blog_id):
    """
    删除blog
    :param req:
    :param blog_id:
    :return:
    """
    ret = ResModel()

    ret.msg = req_invalid_check(req)
    if ret.msg:
        # 请求合法性校验不通过
        ret.code = ret.ResCode.fail
        return JsonResponse(ret.to_dic())

    rs = BlogContent.objects.filter(id=blog_id)
    if not rs:
        ret.code = ret.ResCode.fail
        ret.msg = "未查询到记录"
        return JsonResponse(ret.to_dic())

    rs.delete()

    ret.code = ret.ResCode.succ
    ret.msg = "已删除"
    return JsonResponse(ret.to_dic())
コード例 #30
0
def del_obj(req):
    """
    删除role记录
    :param req:
    :return:
    """
    ret = ResModel()

    ret.msg = req_invalid_check(req)
    if ret.msg:
        # 请求合法性校验不通过
        ret.code = ret.ResCode.fail
        return JsonResponse(ret.to_dic())

    mod_user_id = req.META.get('USER_ID')
    rid = req.POST.get('id')
    if not rid:
        ret.code = ret.ResCode.fail
        ret.msg = "未查询记录"
        return JsonResponse(ret.to_dic())

    DrRoles.objects.filter(id=rid).delete()

    ret.code = ret.ResCode.succ
    ret.msg = "已删除"
    return JsonResponse(ret.to_dic())