示例#1
0
def user_permission_get():
    # 初始化返回内容
    response_json = {"code": 200, "msg": "", "data": {}}

    # 取出传入参数值
    requestvalue_id = int(flask.request.headers["UserId"])

    # 查询
    userdata = ApiCheck.check_user(user_id=requestvalue_id)
    if userdata["exist"] is False:
        return ApiError.requestfail_error("账户不存在")
    elif userdata["exist"] is True and userdata["userStatus"] == 0:
        return ApiError.requestfail_error("账户未激活")
    elif userdata["exist"] is True and userdata["userStatus"] == 1:
        pass
    elif userdata["exist"] is True and userdata["userStatus"] == -1:
        return ApiError.requestfail_error("账户已禁用")
    else:
        return ApiError.requestfail_error("账户信息校验异常")

    # 查询权限信息
    rp = ApiCheck.check_role_permission(userdata['userRoleId'])
    if rp["exist"] is True:
        response_json["data"]["permission"] = rp["rolePermission"]
    elif rp["exist"] is False:
        response_json["data"]["permission"] = {}
    else:
        return ApiError.requestfail_server("角色权限信息处理异常")

    # 定义msg
    response_json["msg"] = "token有效"
    # 最后返回内容
    return response_json
示例#2
0
def token_get():
    # 初始化返回内容
    response_json = {
        "code": 200,
        "msg": "",
        "data": {}
    }

    # 取出传入参数值
    requestvalue_userid = int(flask.request.headers["UserId"])

    requestvalue_token = flask.request.args["user_token"]

    # 2.校验账户是否存在
    userdata = ApiCheck.check_user(requestvalue_userid)
    if userdata["exist"] is False:
        return ApiError.requestfail_error("账户不存在")
    elif userdata["exist"] is True and userdata["userStatus"] == 0:
        return ApiError.requestfail_error("账户未激活")
    elif userdata["exist"] is True and userdata["userStatus"] == 1:
        pass
    elif userdata["exist"] is True and userdata["userStatus"] == -1:
        return ApiError.requestfail_error("账户已禁用")
    else:
        return ApiError.requestfail_error("账户信息校验异常")

    # 3.校验令牌是否有效
    tc = ApiCheck.check_token(
        requestvalue_mail,
        requestvalue_token
    )
    if tc["exist"] is True and tc["valid"] is True:
        pass
    elif tc["exist"] is True and tc["valid"] is False:
        return ApiError.requestfail_error("token已过期")
    elif tc["exist"] is False:
        return ApiError.requestfail_error("token错误")
    else:
        return ApiError.requestfail_server("token校验失败")

    # 定义msg
    response_json["msg"] = "token有效"
    # 最后返回内容
    return response_json
示例#3
0
def token_post():
    # 初始化返回内容
    response_json = {
        "code": 200,
        "msg": "",
        "data": {
            "user_id": 0,
            "access_token": ''
        }
    }

    # 取出传入参数值
    requestvalue_name = flask.request.json["login_name"]
    requestvalue_password = flask.request.json["login_password"]
    requestvalue_check = flask.request.json["is_checked"]

    # 尝试从mysql中查询
    try:
        uinfo_mysql = model_mysql_userinfo.query.filter_by(
            userLoginName=requestvalue_name).first()
    except:
        return route.error_msgs[500]['msg_db_error']
    else:
        if uinfo_mysql is None:
            return route.error_msgs[201]['msg_no_user']
        elif uinfo_mysql.userStatus == 1:
            pass
        elif uinfo_mysql.userStatus == 0:
            return route.error_msgs[201]['msg_need_register']
        elif uinfo_mysql.userStatus == -1:
            return route.error_msgs[201]['msg_user_forbidden']
        else:
            return route.error_msgs[201]['msg_status_error']

    # 3.校验账户密码是否正确
    if requestvalue_password != uinfo_mysql.userPassword:
        return ApiError.requestfail_error("登陆密码错误")

    # 刷新token
    user_token = str(
        uuid.uuid3(
            uuid.NAMESPACE_DNS,
            str(uinfo_mysql.userId) +
            str(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'))))

    if requestvalue_check:
        t = (datetime.datetime.now() +
             datetime.timedelta(days=30)).strftime('%Y-%m-%d %H:%M:%S')
    else:
        t = (datetime.datetime.now() +
             datetime.timedelta(days=1)).strftime('%Y-%m-%d %H:%M:%S')
    model_redis_usertoken.set(
        uinfo_mysql.userId, "{\"userToken\":\"" + user_token + "\"," +
        "\"validTime\":\"" + t + "\"}")
    response_json["data"]["access_token"] = user_token

    response_json["data"]["user_id"] = uinfo_mysql.userId

    # 6.返回信息
    response_json["msg"] = "账户登陆成功"
    logmsg = "手动登陆请求处理完毕"
    api_logger.info(logmsg)
    # 最后返回内容
    return response_json
示例#4
0
def user_password_reset_apply_post():
    # 初始化返回内容
    response_json = {"code": 200, "msg": "", "data": {}}

    # 取出传入参数值
    requestvalue_mail = flask.request.json["mail_address"]

    # 校验邮箱地址格式
    mail_reg = '^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$'
    if not re.search(mail_reg, requestvalue_mail):
        return route.error_msgs[201]['msg_illegal_format']

    # 2.校验账户是否存在
    try:
        uinfo_mysql = model_mysql_userinfo.query.filter(
            or_(model_mysql_userinfo.userEmail == requestvalue_mail,
                model_mysql_userinfo.userNewEmail ==
                requestvalue_mail)).first()
    except Exception as e:
        logmsg = "数据库中账户信息读取失败,失败原因:" + repr(e)
        api_logger.error(logmsg)
        return route.error_msgs[500]['msg_db_error']
    else:
        if uinfo_mysql is None:
            return route.error_msgs[201]['msg_no_user']
        elif uinfo_mysql.userStatus == 1:
            pass
        elif uinfo_mysql.userStatus == 0:
            return route.error_msgs[201]['msg_need_register']
        elif uinfo_mysql.userStatus == -1:
            return route.error_msgs[201]['msg_user_forbidden']
        else:
            return route.error_msgs[201]['msg_status_error']

    # 检查通过
    # 查询关键操作唯一标识符
    odata = ApiCheck.check_operate(appconfig.get("operation_alias",
                                                 "register"))
    if odata["exist"] is True:
        pass
    elif odata["exist"] is False:
        return ApiError.requestfail_error("关键操作别名不存在")
    else:
        return ApiError.requestfail_server("操作处理异常")

    # 查库,将之前未进行重置密码操作的记录全部置为无效
    try:
        data = model_mysql_useroperationrecord.query.filter_by(
            userId=uinfo_mysql.userId,
            operationId=odata["operationId"],
            recordStatus=0).all()
    except Exception as e:
        logmsg = "mysql中账户操作数据查询失败,失败原因:" + repr(e)
        api_logger.error(logmsg)
        return route.error_msgs[500]['msg_db_error']
    for d in data:
        d.recordStatus = -1
    try:
        mysqlpool.session.commit()
    except Exception as e:
        logmsg = "mysql中账户操作数据更新失败,失败原因:" + repr(e)
        api_logger.error(logmsg)
        return route.error_msgs[500]['msg_db_error']
    # 生成操作码
    code = str(
        uuid.uuid3(
            uuid.NAMESPACE_DNS, requestvalue_mail +
            str(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'))))
    # 将内容入库
    insertdata = model_mysql_useroperationrecord(
        userId=uinfo_mysql.userId,
        operationId=odata["operationId"],
        recordCode=code,
        recordStatus=0,
        recordValidTime=(
            datetime.datetime.now() +
            datetime.timedelta(days=1)).strftime('%Y-%m-%d %H:%M:%S'))
    try:
        mysqlpool.session.add(insertdata)
        mysqlpool.session.commit()
    except Exception as e:
        logmsg = "mysql中账户操作数据新增失败,失败原因:" + repr(e)
        api_logger.error(logmsg)
        return route.error_msgs[500]['msg_db_error']
    # 发送重置密码邮件
    publicmailer.sendmail_reset_password(uinfo_mysql.userId, requestvalue_mail,
                                         code, odata["operationId"])

    # 定义msg
    response_json["msg"] = "操作成功,请查收重置密码邮件"
    # 最后返回内容
    return response_json
示例#5
0
def new_user_info_post():
    # 初始化返回内容
    response_json = {"code": 200, "msg": "", "data": {}}

    # 取出传入参数值
    requestvalue_mail = flask.request.json["mail_address"]

    # 校验邮箱地址格式
    mail_reg = '^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$'
    if not re.search(mail_reg, requestvalue_mail):
        return route.error_msgs[201]['msg_illegal_format']

    # 2.校验账户是否存在
    try:
        uinfo_mysql = model_mysql_userinfo.query.filter(
            or_(model_mysql_userinfo.userEmail == requestvalue_mail,
                model_mysql_userinfo.userNewEmail ==
                requestvalue_mail)).first()
    except Exception as e:
        logmsg = "数据库中账户信息读取失败,失败原因:" + repr(e)
        api_logger.error(logmsg)
        return route.error_msgs[500]['msg_db_error']
    else:
        if uinfo_mysql is None:
            pass
        elif uinfo_mysql.userStatus == 0:
            pass
        elif uinfo_mysql.userStatus in [-2, -1, 1]:
            return route.error_msgs[201]['msg_mail_exist']
        else:
            return route.error_msgs[201]['msg_status_error']

    # 3.如果账户不存在,则数据库以及缓存中插入未激活状态的账户数据以及对应的未完成的操作记录
    if uinfo_mysql is None:
        # 查询关键操作唯一标识符
        odata = ApiCheck.check_operate(
            appconfig.get("operation_alias", "register"))
        if odata["exist"] is True:
            pass
        elif odata["exist"] is False:
            return route.error_msgs[500]['msg_server_error']
        else:
            return route.error_msgs[500]['msg_server_error']

        # 在库中插入账户未激活的信息
        # 先插入mysql
        newuser = model_mysql_userinfo(userEmail=requestvalue_mail,
                                       userStatus=0,
                                       userAddTime=datetime.datetime.now())
        try:
            mysqlpool.session.add(newuser)
            mysqlpool.session.commit()
        except Exception as e:
            logmsg = "数据库新增账户数据失败,失败原因:" + repr(e)
            api_logger.error(logmsg)
            return ApiError.requestfail_server(logmsg)

        # 生成操作码
        code = str(
            uuid.uuid3(
                uuid.NAMESPACE_DNS, requestvalue_mail +
                str(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'))))
        # 发送包含账户信息确认页链接的邮件
        # 先发送邮件,成功后再记录数据
        # 保证过滤掉不存在的邮件地址
        send_result_flag, send_result_type = publicmailer.sendmail_register(
            newuser.userId, requestvalue_mail, code, odata["operationId"])
        print(odata["operationId"])
        # 如果发送失败,则返回错误信息
        if send_result_flag is False:
            if send_result_type == -1:
                return ApiError.requestfail_server("SMTP服务器连接失败")
            elif send_result_type == 1 or send_result_type == 2:
                return ApiError.requestfail_server("公共邮箱登陆失败")
            elif send_result_type == 3:
                return ApiError.requestfail_error("邮件发送失败,请检查邮箱地址")

        # 将操作码数据写入mysql
        insertdata = model_mysql_useroperationrecord(
            userId=newuser.userId,
            operationId=odata["operationId"],
            recordCode=code,
            recordStatus=0,
            recordValidTime=(
                datetime.datetime.now() +
                datetime.timedelta(days=1)).strftime('%Y-%m-%d %H:%M:%S'))
        try:
            mysqlpool.session.add(insertdata)
            mysqlpool.session.commit()
        except Exception as e:
            logmsg = "数据库新增申请账户记录数据失败,失败原因:" + repr(e)
            api_logger.error(logmsg)
            return ApiError.requestfail_server(logmsg)
    # 4.如果账户存在但状态为未激活,则将先前的账户操作记录数据置为无效,然后插入新的未完成的操作记录
    elif uinfo_mysql.userStatus == 0:
        # 查询关键操作唯一标识符
        odata = ApiCheck.check_operate(
            appconfig.get("operation_alias", "register"))
        if odata["exist"] is True:
            pass
        elif odata["exist"] is False:
            return ApiError.requestfail_error("关键操作别名不存在")
        else:
            return ApiError.requestfail_server("操作处理异常")

        # 生成操作码
        code = str(
            uuid.uuid3(
                uuid.NAMESPACE_DNS, requestvalue_mail +
                str(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'))))
        # 发送包含账户信息确认页链接的邮件
        send_result_flag, send_result_type = publicmailer.sendmail_register(
            uinfo_mysql.userId, requestvalue_mail, code, odata["operationId"])
        # 如果发送失败,则返回错误信息
        if send_result_flag is False:
            if send_result_type == -1:
                return ApiError.requestfail_server("SMTP服务器连接失败")
            elif send_result_type == 1 or send_result_type == 2:
                return ApiError.requestfail_server("公共邮箱登陆失败")
            elif send_result_type == 3:
                return ApiError.requestfail_error("邮件发送失败,请检查邮箱地址")
        # 查询mysql中的操作记录
        try:
            rdata_mysql = model_mysql_useroperationrecord.query.filter_by(
                userId=uinfo_mysql.userId,
                operationId=odata["operationId"],
                recordStatus=0).all()
        except Exception as e:
            logmsg = "账户操作记录数据查询失败,失败原因:" + repr(e)
            api_logger.error(logmsg)
            return ApiError.requestfail_server(logmsg)
        # 如果查询到了,则全部置为无效
        if rdata_mysql is not None:
            for d in rdata_mysql:
                d.recordStatus = -1
            try:
                mysqlpool.session.commit()
            except Exception as e:
                logmsg = "账户操作记录数据更新失败,失败原因:" + repr(e)
                api_logger.error(logmsg)
                return ApiError.requestfail_server(logmsg)
        # 将新操作码数据写入mysql
        insertdata = model_mysql_useroperationrecord(
            userId=uinfo_mysql.userId,
            operationId=odata["operationId"],
            recordCode=code,
            recordStatus=0,
            recordValidTime=(
                datetime.datetime.now() +
                datetime.timedelta(days=1)).strftime('%Y-%m-%d %H:%M:%S'))
        try:
            mysqlpool.session.add(insertdata)
            mysqlpool.session.commit()
        except Exception as e:
            logmsg = "账户操作记录数据新增失败,失败原因:" + repr(e)
            api_logger.error(logmsg)
            return ApiError.requestfail_server(logmsg)
    # 5.如果账户存在且状态不为未激活,则将告知前端账户已存在
    else:
        return ApiError.requestfail_error("账户已存在")
    # 定义msg
    response_json["msg"] = "操作成功,请查收账户注册邮件"
    # 最后返回内容
    return response_json
示例#6
0
def new_user_info_put():
    # 初始化返回内容
    response_json = {"code": 200, "msg": "", "data": {}}

    # 取出参数
    rq_file_url = flask.request.json['file_url']
    rq_user_id = flask.request.json['user_id']
    rq_mail_address = flask.request.json['mail_address']
    rq_login_name = flask.request.json['login_name']
    rq_record_code = flask.request.json['record_code']
    rq_nick_name = flask.request.json['nick_name']
    rq_operation_id = flask.request.json['operation_id']
    rq_new_password = flask.request.json['new_password']

    # mail_address
    mail_reg = '^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$'
    if not re.search(mail_reg, rq_mail_address):
        return route.error_msgs[301]['msg_value_type_error']
    # login_name
    name_reg = '^[a-zA-Z][a-z0-9A-Z_]{1,19}$'
    if not re.search(name_reg, rq_login_name):
        return route.error_msgs[301]['msg_value_type_error']

    # 2.校验账户是否存在
    userdata = ApiCheck.check_user(rq_user_id)
    if userdata["exist"] is False:
        return ApiError.requestfail_error("账户不存在")
    elif userdata["exist"] is True and userdata["userStatus"] == 0:
        pass
    elif userdata["exist"] is True and userdata["userStatus"] == 1:
        return ApiError.requestfail_error("账户已激活")
    elif userdata["exist"] is True and userdata["userStatus"] == -1:
        return ApiError.requestfail_error("账户已禁用")
    else:
        return ApiError.requestfail_error("账户信息校验异常")

    # 3.校验操作码是否有效
    codeexist, codevalid = ApiCheck.check_code(userdata["userId"],
                                               rq_record_code, rq_operation_id)
    if codeexist is False:
        return ApiError.requestfail_error("操作码错误或不存在")
    elif codeexist is True and codevalid == 0:
        return ApiError.requestfail_error("操作码过期")
    elif codeexist is True and codevalid == 1:
        pass
    else:
        return ApiError.requestfail_server("操作码校验异常")

    # 4.修改账户昵称、登录密码、注册时间、账户状态、头像地址
    # 登录名不可重复
    # 首先判断登录名是否已存在
    try:
        user = model_mysql_userinfo.query.filter_by(
            userLoginName=rq_login_name).first()
    except Exception as e:
        api_logger.error(repr(e))
        return route.error_msgs[500]['msg_db_error']
    else:
        if user is None:
            try:
                user = model_mysql_userinfo.query.filter_by(
                    userId=userdata["userId"]).first()
            except Exception as e:
                logmsg = "/infoConfirm.json账户信息读取失败,失败原因:" + repr(e)
                api_logger.error(logmsg)
                return ApiError.requestfail_server(logmsg)
            user.userLoginName = rq_login_name
            user.userNickName = rq_nick_name
            user.userPassword = rq_new_password
            user.userRegisterTime = datetime.datetime.now()
            user.userStatus = 1
            user.userHeadIconUrl = rq_file_url
            # 尝试写入mysql
            try:
                mysqlpool.session.commit()
            # except IntegrityError as e1:
            #     logmsg = "/infoConfirm.json账户信息存入数据库失败,失败原因:" + repr(e)
            #     api_logger.error(logmsg)
            #     return ApiError.requestfail_server(logmsg)
            except Exception as e:
                logmsg = "/infoConfirm.json账户信息存入数据库失败,失败原因:" + repr(e)
                api_logger.error(logmsg)
                return ApiError.requestfail_server(logmsg)

            # 6.将操作记录置为已完成
            try:
                record = model_mysql_useroperationrecord.query.filter_by(
                    userId=user.userId,
                    operationId=rq_operation_id,
                    recordStatus=0).first()
            except Exception as e:
                logmsg = "/infoConfirm.json操作记录信息读取失败,失败原因:" + repr(e)
                api_logger.error(logmsg)
                return ApiError.requestfail_server(logmsg)
            record.recordStatus = 1
            # 尝试写入mysql
            try:
                mysqlpool.session.commit()
            except Exception as e:
                logmsg = "/infoConfirm.json操作记录信息更新失败,失败原因:" + repr(e)
                api_logger.error(logmsg)
                return ApiError.requestfail_server(logmsg)

            # 7.发送注册成功邮件
            send_result_flag, send_result_type = publicmailer.sendmail_register_success(
                rq_mail_address)
            # 如果发送失败,则返回错误信息
            if send_result_flag is False:
                if send_result_type == -1:
                    return ApiError.requestfail_server("SMTP服务器连接失败")
                elif send_result_type == 1 or send_result_type == 2:
                    return ApiError.requestfail_server("公共邮箱登陆失败")
                elif send_result_type == 3:
                    return ApiError.requestfail_error("邮件发送失败,请检查邮箱地址")
        else:
            return route.error_msgs[201]['msg_user_exist']

    # 8.返回成功信息
    # 定义msg
    response_json["msg"] = "操作成功,请查收账户注册邮件"
    # 最后返回内容
    return response_json
示例#7
0
def user_mail_put():
    # 初始化返回内容
    response_json = {
        "code": 200,
        "msg": "",
        "data": {}
    }

    # 校验通过后赋值
    requestvalue_userid = flask.request.json["user_id"]
    requestvalue_mail = flask.request.json["mail_address"]
    requestvalue_newmail = flask.request.json["new_mail_address"]
    requestvalue_recordcode = flask.request.json["record_code"]
    requestvalue_operationid = flask.request.json["operation_id"]

    # 2.校验账户状态
    userdata = ApiCheck.check_user(requestvalue_userid)
    if userdata["exist"] is False:
        return ApiError.requestfail_error("账户不存在")
    elif userdata["exist"] is True and userdata["userStatus"] == 1:
        pass
    elif userdata["exist"] is True and userdata["userStatus"] == 0:
        return ApiError.requestfail_error("账户未激活")
    elif userdata["exist"] is True and userdata["userStatus"] == -1:
        return ApiError.requestfail_error("账户已禁用")
    else:
        return ApiError.requestfail_error("账户信息校验异常")

    # 3.校验操作类型和操作码
    codeexist, codevalid = ApiCheck.check_code(
        requestvalue_userid,
        requestvalue_recordcode,
        requestvalue_operationid
    )
    if codeexist is False:
        return ApiError.requestfail_error("操作码错误或不存在")
    elif codeexist is True and codevalid == 0:
        return ApiError.requestfail_error("操作码过期")
    elif codeexist is True and codevalid == 1:
        pass
    else:
        return ApiError.requestfail_server("操作码校验异常")

    # 6.校验所修改邮箱地址是否正确
    try:
        uinfo_mysql = model_mysql_userinfo.query.filter_by(userId=requestvalue_userid).first()
    except Exception as e:
        logmsg = "mysql中账户信息读取失败,失败原因:" + repr(e)
        api_logger.error(logmsg)
        return route.error_msgs[500]['msg_db_error']
    if uinfo_mysql.userNewEmail == requestvalue_newmail:
        pass
    else:
        return ApiError.requestfail_error("新邮箱地址错误")

    # 8.修改所旧邮箱为新邮箱,然后清空新邮箱记录
    uinfo_mysql.userEmail = requestvalue_newmail
    uinfo_mysql.userNewEmail = None
    try:
        mysqlpool.session.commit()
    except Exception as e:
        logmsg = "mysql中账户邮箱绑定数据更新失败,失败原因:" + repr(e)
        api_logger.error(logmsg)
        return route.error_msgs[500]['msg_db_error']

    # 11.将修改绑定邮箱的记录修改为已完成
    try:
        uodata = model_mysql_useroperationrecord.query.filter_by(
            userId=userdata["userId"],
            operationId=requestvalue_operationid,
            recordStatus=0
        ).first()
        uodata.recordStatus = 1
        mysqlpool.session.commit()
    except Exception as e:
        logmsg = "mysql中账户操作记录更新失败,失败原因:" + repr(e)
        api_logger.error(logmsg)
        return route.error_msgs[500]['msg_db_error']

    # 12.发送修改绑定邮箱成功邮件
    publicmailer.sendmail_changemail_success(
        requestvalue_newmail
    )
    # 定义msg
    response_json["msg"] = "操作成功,请到新邮箱中查收修改成功邮件"
    # 最后返回内容
    return response_json
示例#8
0
def user_password_post():
    # 初始化返回内容
    response_json = {"code": 200, "msg": "", "data": {}}

    # 校验通过后赋值
    requestvalue_userid = flask.request.json["user_id"]
    requestvalue_recordcode = flask.request.json["record_code"]
    requestvalue_operationid = flask.request.json["operation_id"]
    requestvalue_password = flask.request.json["new_password"]

    # 2.校验账户状态
    userdata = ApiCheck.check_user(requestvalue_userid)
    if userdata["exist"] is False:
        return ApiError.requestfail_error("账户不存在")
    elif userdata["exist"] is True and userdata["userStatus"] == 1:
        pass
    elif userdata["exist"] is True and userdata["userStatus"] == 0:
        return ApiError.requestfail_error("账户未激活")
    elif userdata["exist"] is True and userdata["userStatus"] == -1:
        return ApiError.requestfail_error("账户已禁用")
    else:
        return ApiError.requestfail_error("账户信息校验异常")

    # 3.校验操作类型和操作码
    codeexist, codevalid = ApiCheck.check_code(userdata["userId"],
                                               requestvalue_recordcode,
                                               requestvalue_operationid)
    if codeexist is False:
        return ApiError.requestfail_error("操作码错误或不存在")
    elif codeexist is True and codevalid == 0:
        return ApiError.requestfail_error("操作码过期")
    elif codeexist is True and codevalid == 1:
        pass
    else:
        return ApiError.requestfail_server("操作码校验异常")

    # 4.重置密码
    # 先修改mysql中的登录密码
    try:
        uinfo_mysql = model_mysql_userinfo.query.filter_by(
            userId=userdata["userId"]).first()
    except Exception as e:
        logmsg = "mysql中账户信息读取失败,失败原因:" + repr(e)
        api_logger.error(logmsg)
        return route.error_msgs[500]['msg_db_error']
    uinfo_mysql.userPassword = requestvalue_password
    try:
        mysqlpool.session.commit()
    except Exception as e:
        logmsg = "mysql中账户密码更新失败,失败原因:" + repr(e)
        api_logger.error(logmsg)
        return route.error_msgs[500]['msg_db_error']

    # 5.将重置密码的记录置为已完成
    try:
        uodata = model_mysql_useroperationrecord.query.filter_by(
            userId=userdata["userId"],
            operationId=requestvalue_operationid,
            recordStatus=0).first()
    except Exception as e:
        logmsg = "mysql中账户操作记录读取失败,失败原因:" + repr(e)
        api_logger.error(logmsg)
        return route.error_msgs[500]['msg_db_error']
    uodata.recordStatus = 1
    try:
        mysqlpool.session.commit()
    except Exception as e:
        logmsg = "mysql中账户操作记录更新失败,失败原因:" + repr(e)
        api_logger.error(logmsg)
        return route.error_msgs[500]['msg_db_error']

    # 6.发送重置密码成功邮件
    publicmailer.sendmail_reset_password_success(uinfo_mysql.userEmail)
    # 定义msg
    response_json["msg"] = "操作成功,请查收重置密码邮件"
    # 最后返回内容
    return response_json
示例#9
0
def role_permission_put():
    """
        修改角色配置信息-api路由
        ----校验
        1.校验传参
        2.校验账户是否存在
        3.校验账户操作令牌
        4.校验角色是否存在
        5.校验角色权限是否可变更
        ----操作
        6.mysql逐条变更角色权限
        7.刷新redis中的该角色的权限缓存数据
    """
    # 初始化返回内容
    response_json = {"code": 200, "msg": "", "data": {}}
    """
        1.校验传参
        取出请求参数
    """
    requestvalue_roleid = int(flask.request.json["role_id"])
    requestvalue_roledescription = flask.request.json["role_description"]
    # role_permission
    if "role_permission" not in flask.request.json:
        return ApiError.requestfail_nokey("role_permission")
    requestvalue_permission = flask.request.json["role_permission"]

    # 检查通过
    # 检查必传项内容格式
    # role_permission
    if type(requestvalue_permission) is not dict:
        return ApiError.requestfail_value("role_permission")
    """
        检查role_permission格式
        # 1.最上层为dict,已检查
        # 2.最上层dict内为多个子dict
        # 3.子dict内需至少包含id/has,用以更新权限数据
        # 4.子dict的component为dict
        # 5.子dict的component中的dict内至少包含id/has,用以更新权限数据
    """
    for rp in requestvalue_permission:
        if type(requestvalue_permission[rp]) is not dict:
            return ApiError.requestfail_value("role_permission")
        if "id" not in requestvalue_permission[rp] or type(
                requestvalue_permission[rp]
            ["id"]) is not int or requestvalue_permission[rp]["id"] < 1:
            return ApiError.requestfail_value("role_permission")
        if "has" not in requestvalue_permission[rp] or type(
                requestvalue_permission[rp]["has"]) is not bool:
            return ApiError.requestfail_value("role_permission")
        if type(requestvalue_permission[rp]["component"]) is not dict:
            return ApiError.requestfail_value("role_permission")
        cf = ApiCheck.check_function(rp, 0)
        if cf['exist'] is False:
            return ApiError.requestfail_value("role_permission")
        elif cf['exist'] is None:
            return ApiError.requestfail_error("角色权限信息校验异常")
        for rpc in requestvalue_permission[rp]["component"]:
            if type(requestvalue_permission[rp]["component"][rpc]) is not dict:
                return ApiError.requestfail_value("role_permission")
            if "id" not in requestvalue_permission[rp]["component"][
                    rpc] or type(requestvalue_permission[rp]["component"][rpc]
                                 ["id"]) is not int or requestvalue_permission[
                                     rp]["component"][rpc]["id"] < 1:
                return ApiError.requestfail_value("role_permission")
            if "has" not in requestvalue_permission[rp]["component"][
                    rpc] or type(requestvalue_permission[rp]["component"][rpc]
                                 ["has"]) is not bool:
                return ApiError.requestfail_value("role_permission")
            cf = ApiCheck.check_function(rpc, rp)
            if cf['exist'] is False:
                return ApiError.requestfail_value("role_permission")
            elif cf['exist'] is None:
                return ApiError.requestfail_error("角色权限信息校验异常")
    """
        6.mysql逐条变更角色权限
        先变更page的再变更部件的
    """
    for functionid_page in requestvalue_permission:
        """
            1.首先到rolePermission表中校验page的权限记录是否存在
            2.如果存在,再判断当前值和所要修改的值是否一致,不一致则update,否则pass
            3.且更新的时候,如果是从1改成0,则顺带要把该page下所有的部件权限全部改为0
            4.如果不存在,则insert
            5.然后更新component的权限配置,和page一样,有则改之无则insert
        """
        # 尝试获取某role的page权限配置数据
        try:
            """
                当使用filter时,数据筛选条件写条件表达式:A.a == b|A.a>b|A.a<b,且列需要写成表.列
                当使用filter_by时,数据筛选条件写关键字表达式:a=b,列直接写列名即可
                后续统一使用filter
            """
            pg_data = model_mysql_rolepermission.query.filter(
                model_mysql_rolepermission.roleId == requestvalue_roleid,
                model_mysql_rolepermission.functionId ==
                functionid_page).first()
        except Exception as e:
            logmsg = "数据库中角色的page访问权限获取失败:" + repr(e)
            api_logger.error(logmsg)
            return route.error_msgs[500]['msg_db_error']
        else:
            """
                如果获取到了,且数据库中记录的hasPermission字段值和传入的page的has值不等
                1==Ture
                2==False
                0==False
            """
            # 如果page的权限数据有并且权限数据和传入的不一致
            page_has = requestvalue_permission[functionid_page]["has"]
            if pg_data and pg_data.hasPermission != page_has:
                # 当数据库中记录的page权限配置为1时,要将数据改为0
                if pg_data.hasPermission == 1:
                    pg_data.hasPermission = 0
                    mysqlpool.session.commit()
                    # 然后查询page下的component权限配置
                    for functionid_component in requestvalue_permission[
                            functionid_page]["component"]:
                        try:
                            cp_data = model_mysql_rolepermission.query.filter(
                                model_mysql_rolepermission.roleId ==
                                requestvalue_roleid,
                                model_mysql_rolepermission.functionId ==
                                functionid_component).first()
                        except Exception as e:
                            logmsg = "数据库中角色的页面下功能访问权限获取失败:" + repr(e)
                            api_logger.error(logmsg)
                            return route.error_msgs[500]['msg_db_error']
                        else:
                            if cp_data:
                                cp_data.hasPermission = 0
                            else:
                                cp_data = model_mysql_rolepermission(
                                    roleId=requestvalue_roleid,
                                    functionId=functionid_component,
                                    hasPermission=0)
                                mysqlpool.session.add(cp_data)
                        mysqlpool.session.commit()
                else:
                    # 当数据库中记录的page权限配置为0时,要将数据改为1
                    pg_data.hasPermission = 1
                    mysqlpool.session.commit()
                    # 然后根据传入component权限配置数据,修改数据库中对应的数据
                    for functionid_component in requestvalue_permission[
                            functionid_page]["component"]:
                        component_has = requestvalue_permission[
                            functionid_page]["component"][
                                functionid_component]["has"]
                        try:
                            cp_data = model_mysql_rolepermission.query.filter(
                                model_mysql_rolepermission.roleId ==
                                requestvalue_roleid,
                                model_mysql_rolepermission.functionId ==
                                functionid_component).first()
                        except Exception as e:
                            logmsg = "数据库中角色的页面下功能访问权限获取失败:" + repr(e)
                            api_logger.error(logmsg)
                            return route.error_msgs[500]['msg_db_error']
                        else:
                            # 如果component的权限配置数据有,并且数据库中记录的权限配置和传入的数据不一致
                            if cp_data and cp_data.hasPermission != component_has:
                                # 修改数据库中的值
                                cp_data.hasPermission = 0 if cp_data.hasPermission == 1 else 1
                                mysqlpool.session.commit()
                            # 如果component的权限配置数据有,并且数据库中记录的权限配置和传入的数据一致
                            elif cp_data and cp_data.hasPermission == component_has:
                                pass
                            # 如果component的权限配置数据没有
                            else:
                                # 新增component权限配置数据
                                cp_data = model_mysql_rolepermission(
                                    roleId=requestvalue_roleid,
                                    functionId=functionid_component,
                                    hasPermission=1 if component_has else 0)
                                mysqlpool.session.add(cp_data)
                                mysqlpool.session.commit()
            # 如果page的权限数据有并且和传入的一致
            elif pg_data and pg_data.hasPermission == page_has:
                # 校验component的权限配置
                # 然后根据传入component权限配置数据,修改数据库中对应的数据
                for functionid_component in requestvalue_permission[
                        functionid_page]["component"]:
                    component_has = requestvalue_permission[functionid_page][
                        "component"][functionid_component]["has"]
                    try:
                        cp_data = model_mysql_rolepermission.query.filter(
                            model_mysql_rolepermission.roleId ==
                            requestvalue_roleid,
                            model_mysql_rolepermission.functionId ==
                            functionid_component).first()
                    except Exception as e:
                        logmsg = "数据库中角色的页面下功能访问权限获取失败:" + repr(e)
                        api_logger.error(logmsg)
                        return route.error_msgs[500]['msg_db_error']
                    else:
                        # 如果component的权限配置数据有,并且数据库中记录的权限配置和传入的数据不一致
                        if cp_data and cp_data.hasPermission != component_has:
                            # 修改数据库中的值
                            cp_data.hasPermission = 0 if cp_data.hasPermission == 1 else 1
                            mysqlpool.session.commit()
                        # 如果component的权限配置数据有,并且数据库中记录的权限配置和传入的数据一致
                        elif cp_data and cp_data.hasPermission == component_has:
                            pass
                        # 如果component的权限配置数据没有
                        else:
                            # 新增component权限配置数据
                            cp_data = model_mysql_rolepermission(
                                roleId=requestvalue_roleid,
                                functionId=functionid_component,
                                hasPermission=1 if component_has else 0)
                            mysqlpool.session.add(cp_data)
                            mysqlpool.session.commit()
            # 如果page的权限数据无
            else:
                # 新增page权限数据
                pg_data = model_mysql_rolepermission(
                    roleId=requestvalue_roleid,
                    functionId=functionid_page,
                    hasPermission=1 if page_has else 0)
                mysqlpool.session.add(pg_data)
                mysqlpool.session.commit()
                # 遍历传入的page下component的functionId
                for functionid_component in requestvalue_permission[
                        functionid_page]["component"]:
                    component_has = requestvalue_permission[functionid_page][
                        "component"][functionid_component]["has"]
                    try:
                        cp_data = model_mysql_rolepermission.query.filter(
                            model_mysql_rolepermission.roleId ==
                            requestvalue_roleid,
                            model_mysql_rolepermission.functionId ==
                            functionid_component).first()
                    except Exception as e:
                        logmsg = "数据库中角色的页面下功能访问权限获取失败:" + repr(e)
                        api_logger.error(logmsg)
                        return route.error_msgs[500]['msg_db_error']
                    else:
                        # 如果component权限配置数据有且和传入的不一致
                        if cp_data and cp_data.hasPermission != component_has:
                            # 修改
                            cp_data.hasPermission = 0 if cp_data.hasPermission == 1 else 1
                            mysqlpool.session.commit()
                        # 如果component权限配置数据有且和传入的一致
                        elif cp_data and cp_data.hasPermission == component_has:
                            pass
                        # 如果component权限配置数据无
                        else:
                            # 新增component权限配置数据
                            cp_data = model_mysql_rolepermission(
                                roleId=requestvalue_roleid,
                                functionId=functionid_component,
                                hasPermission=1 if component_has else 0,
                            )
                            mysqlpool.session.add(cp_data)
                            mysqlpool.session.commit()
    # 更新角色说明
    try:
        model_mysql_roleinfo.query.filter(
            model_mysql_roleinfo.roleId == requestvalue_roleid).update({
                model_mysql_roleinfo.roleDescription:
                requestvalue_roledescription,
                model_mysql_roleinfo.roleUpdateTime:
                datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
            })
        mysqlpool.session.commit()
    except Exception as e:
        db_logger.error("数据库中角色的更新时间更新失败:" + repr(e))
        return route.error_msgs[500]['msg_db_update_error']
    """
        7.刷新redis中的该角色的权限缓存数据
    """
    # 尝试去mysql中查询最新的角色权限配置数据
    try:
        role_page_permission_data = mysqlpool.session.query(
            model_mysql_rolepermission, model_mysql_rolepermission.functionId,
            model_mysql_functioninfo.functionAlias).join(
                model_mysql_functioninfo, model_mysql_rolepermission.functionId
                == model_mysql_functioninfo.functionId).filter(
                    model_mysql_rolepermission.roleId == requestvalue_roleid,
                    model_mysql_functioninfo.functionType == 1,
                    model_mysql_rolepermission.hasPermission == 1).all()
        logmsg = "数据库中角色权限信息修改后页面权限配置信息读取成功"
        api_logger.debug(logmsg)
    except Exception as e:
        logmsg = "数据库中角色权限信息修改后页面权限配置信息读取失败,失败原因:" + repr(e)
        api_logger.error(logmsg)
        return route.error_msgs[500]['msg_db_error']
    else:
        """拼接待缓存的权限数据
            格式:
            permission = {
                "1": {
                    "id": 1,
                    "alias": "AAA",
                    "component": {
                        "2": {
                            "id": 2,
                            "alias": "BBB"
                        },
                        "4": {
                            "id": 4,
                            "alias": "DDD"
                        }
                    }
                }
            }
        """
        permission = {}
        for page_permission in role_page_permission_data:
            permission[str(page_permission.functionId)] = {
                "id": page_permission.functionId,
                "alias": page_permission.functionAlias,
                "component": {}
            }
            try:
                role_component_permission_data = mysqlpool.session.query(
                    model_mysql_rolepermission,
                    model_mysql_rolepermission.functionId,
                    model_mysql_functioninfo.functionAlias).join(
                        model_mysql_functioninfo,
                        model_mysql_rolepermission.functionId ==
                        model_mysql_functioninfo.functionId).filter(
                            model_mysql_rolepermission.roleId ==
                            requestvalue_roleid,
                            model_mysql_functioninfo.rootId ==
                            page_permission.functionId,
                            model_mysql_functioninfo.functionType == 2,
                            model_mysql_rolepermission.hasPermission ==
                            1).all()
                logmsg = "数据库中角色权限信息修改后功能权限配置信息读取成功"
                api_logger.debug(logmsg)
            except Exception as e:
                logmsg = "数据库中角色权限信息修改后功能权限配置信息读取失败,失败原因:" + repr(e)
                api_logger.error(logmsg)
                return route.error_msgs[500]['msg_db_error']
            else:
                for component_permission in role_component_permission_data:
                    permission[str(
                        page_permission.functionId)]["component"][str(
                            component_permission.functionId)] = {
                                "id": component_permission.functionId,
                                "alias": component_permission.functionAlias
                            }
        # 然后将需缓存的内容缓存至redis的rolePermission
        # 需缓存内容:
        # key=roleId
        # value=permission
        try:
            model_redis_rolepermission.set(requestvalue_roleid,
                                           json.dumps(permission))
        except Exception as e:
            logmsg = "缓存库中角色权限信息写入失败,失败原因:" + repr(e)
            api_logger.error(logmsg)
            return route.error_msgs[500]['msg_db_error']

    # 将缓存中的旧数据替换为新数据
    try:
        role_api_auth_data = mysqlpool.session.query(
            model_mysql_rolepermission, model_mysql_apiinfo.apiUrl,
            model_mysql_rolepermission.hasPermission).join(
                model_mysql_functionorg, model_mysql_functionorg.functionId ==
                model_mysql_rolepermission.functionId).join(
                    model_mysql_apiinfo, model_mysql_apiinfo.apiId ==
                    model_mysql_functionorg.apiId).filter(
                        model_mysql_rolepermission.roleId ==
                        requestvalue_roleid).all()
        logmsg = "数据库中角色权限信息修改后页面权限配置信息读取成功"
        api_logger.debug(logmsg)
    except Exception as e:
        logmsg = "数据库中角色权限信息修改后页面权限配置信息读取失败,失败原因:" + repr(e)
        api_logger.error(logmsg)
        return route.error_msgs[500]['msg_db_error']
    else:
        """
            拼接待缓存的权限数据
            格式:
            auth = {
                roleId: {
                    "/api/management/role/getRoleList.json": 1,
                    "/api/management/role/searchRole.json": 0
                }
            }
        """
        auth = {}
        for auth_data in role_api_auth_data:
            auth[auth_data.apiUrl] = auth_data.hasPermission

        # 然后将需缓存的内容缓存至redis的apiAuth
        # 需缓存内容:
        # key=roleId
        # value=auth
        try:
            model_redis_apiauth.set(requestvalue_roleid, json.dumps(auth))
        except Exception as e:
            logmsg = "缓存库中角色权限信息写入失败,失败原因:" + repr(e)
            api_logger.error(logmsg)
            return route.error_msgs[500]['msg_db_error']

    # 8.返回成功信息
    response_json["msg"] = "操作成功"
    # 最后返回内容
    return response_json