Ejemplo n.º 1
0
def register():
    """判断为新用户,新用户注册,需要结合传递过来的邮箱(邮箱要唯一)以及邮箱验证码,用户名(唯一)和密码

    :return: json结果
    """
    if request.method == "POST":
        email = request.form.get("email", type=str, default="")
        username = request.form.get("username", type=str, default="")
        passwd = request.form.get("passwd", type=str, default="")
        capture = request.form.get("capture", type=str, default="")
        # 用户名,密码,验证码, 邮箱为空
        if not (username and passwd and email and capture):
            code = "-1"
            msg = "用户输入了空参数"
        # 查询本地是否有同名用户名和邮箱
        else:
            # 本地数据库不存在已注册相关用户名和邮箱信息,核实验证码注册
            if not DB_Sync.exist_UserName_email(username, email):
                captureCode = DB_Sync.query_redis_Capture(
                    email)  # 如果email没找到,capturecode为None而不是""
                if captureCode == capture:
                    code = "0"
                    msg = "注册成功"

                    # 新用户写入数据库
                    # 先对用户密码加密,需要盐
                    salt = create_Salt()
                    passwd = computePW(passwd, salt)
                    # 新用户入库
                    isOk = DB_Sync.sync_redis_insert(username, passwd, salt,
                                                     email)
                    if not isOk:
                        code = "-1"
                        msg = "新用户注册入库失败"
                    else:
                        # 刷新同步到redis
                        DB_Sync.refresh_redis(username)
                        session['isLogin'] = True
                        session['username'] = username
                        # 最后创建该用户的文件夹
                        iscreate, user_home_str = User_Action.create_user_homedir(
                            username)
                        if iscreate:
                            logger.info("为新注册用户%s创建文件夹成功" % username)
                        else:
                            logger.error("为新注册用户%s创建文件夹失败" % username)
                else:
                    code = "-1"
                    msg = "验证码失效或错误"
            # 本地已存在相关信息用户信息
            else:
                code = "-1"
                msg = "用户名或邮箱已存在,请重新输入"
    else:
        code = '-1'
        msg = '{} Method is not allowed !'.format(request.method)
    resp = jsonify(code=code, msg=msg)
    resp.set_cookie("datetime", getlocaltime())
    return resp
Ejemplo n.º 2
0
def updatePWD():
    """Post方式用户更新密码,需要核实用户登录状态,用原来的salt加密后新密码入库,并要求重新登录。

    :return: json结果
    """
    username = session.get("username")
    if session.get("isLogin") and username is not None:
        # 处于登录的状态的时候,重新生成密码存储到mysql而且同步刷新Redis
        old_pwd = request.form.get("old_passwd", type=str, default="")
        new_pwd = request.form.get("new_passwd", type=str, default="")
        # 下面获取该用户原始数据进行验证
        result = DB_Sync.query_redis(username)
        print("查询用户本地结果为:", result)
        localPW = result["data"]["USER_PASSWD"]
        salt = result["data"]["USER_SALT"]
        # 用户原始密码输入正确,允许修改mysql然后同步redis
        print('计算结果:', computePW(old_pwd, salt))
        if checkPW(computePW(old_pwd, salt), localPW):
            # 用原来的盐加密生成新的用户密码
            compute_new_pwd = computePW(new_pwd, salt)
            isOK = DB_Sync.sync_redis_insert(username, compute_new_pwd, salt)
            if isOK:
                resp = jsonify(code="0", msg="密码修改成功,请用新的密码登录")
                resp.set_cookie("datetime", getlocaltime())
                logger.warning("%s用户修改密码成功,并退出登录" % username)
                # 修改了密码后,需要重新登录,应该清除session数据。然后刷新redis,不然会导致login时候的redis用之前的
                DB_Sync.refresh_redis(username)
                session["isLogin"] = False
                session.clear()
            else:
                resp = jsonify(code="-1", msg="密码修改失败,请重试")
                print("{0}用户修改密码失败,原密码:{1}|新密码:{2}".format(
                    username, localPW, compute_new_pwd))
                logger.warning("%s用户修改密码失败" % username)
        else:
            # 传递过来的用户原始密码为假
            resp = jsonify(code="-1", msg="您原始密码输入有误,请重新输入")
            logger.error("%s用户修改密码失败,原始密码不正确" % username)
    else:
        # 该用户已经退出登录了,不处于登录状态
        resp = jsonify(code="1", msg="您当前不处于登录状态,请先登录")
        logger.warning("%s用户当前处于非登录状态,修改密码失败" % username)
    return resp
Ejemplo n.º 3
0
def forgetPWD():
    """用户名和邮箱以及邮箱的验证码和新密码,查询本地用户名和邮箱是否对应,是发送验证码,然后检验验证码

    :return: json结果
    """
    email = request.form.get("email", type=str, default="")
    username = request.form.get("username", type=str, default="")
    captureCode = request.form.get("capture", type=str, default="")
    new_passwd = request.form.get("new_passwd", type=str, default="")
    # 本地数据库无对应数据,修改不了
    if not DB_Sync.exist_UserName_email(username, email):
        code = "-1"
        msg = "用户名或者邮箱错误"
    # 本地有数据可以修改,核对验证码
    else:
        # 判断根据邮箱查到的用户名是否一致,避免修改他人的数据
        # 验证码一致,而且email和用户名也对应.(默认不考虑用户忘记用户名的情况)
        isConsist = DB_Sync.is_consistent(email, username)
        if captureCode == DB_Sync.query_redis_Capture(email) and isConsist:
            result = DB_Sync.query_redis(username)
            # 根据用户名查询到了结果(salt)
            print(result)
            salt = result["data"]['USER_SALT']
            compute_new_pwd = computePW(new_passwd, salt)
            isOK = DB_Sync.sync_redis_insert(username, compute_new_pwd, salt,
                                             email)
            print("is ok", isOK)
            if isOK:
                code = "0"
                msg = "密码重置成功,请用新的密码登录"
                logger.info("%s用户密码修改成功" % username)
                # 修改密码后需要清除session数据
                session["isLogin"] = False
                session.clear()
                if DB_Sync.refresh_redis(username):
                    print("redis刷新成功...")
                else:
                    print("redis刷新失败...")
            else:
                code = "-1"
                msg = "密码重置失败,请重试"
                print("{0}用户重置密码失败".format(username))
                logger.error("%s用户重置密码失败" % username)
        else:
            code = "-1"
            msg = ("验证码失效" if isConsist else "用户名密码不一致")
            logger.error("%s用户重置密码失败,原因:%s" % (username, msg))
    resp = jsonify(code=code, msg=msg)
    resp.set_cookie("datetime", getlocaltime())
    return resp
Ejemplo n.º 4
0
def itSpiderID():
    """ 根据url hash为一个值作为任务id,存在session中,id值返回给前端。同时开个线程去爬取。

    :return: json结果
    """
    username = request.form.get('username')
    it_url = request.form.get('spiderurl', type=str, default='')
    # 是否处于登录状态
    if session.get('username') == username and session.get('isLogin'):
        #  判断是否是super权限以及被人为锁定状态
        result = DB_Sync.query_redis(username)
        userlock = result['data']['USER_LOCK']
        if userlock == 0:
            # 给出用户的文件夹路径,用来保存爬取后的txt
            user_spider_path = User_Action.user_rootFile_dir + \
                r'\{0}'.format(username)
            # 生成任务id
            task_id = computePW(it_url, '')
            task_id = task_id[:17]
            session['task_id'] = task_id  # 任务id存到session里面
            # 创建线程去爬取而不阻塞当前执行
            try:
                threadWorker(handleITSpider,
                             username=username,
                             url=it_url,
                             path=user_spider_path)
            except Exception as e:
                logger.error('%s用户启动threadWorker失败,原因是%s' % (username, e))
            code = "0"
            msg = "已收到爬取请求"
            data = task_id
            return jsonify(code=code, msg=msg, data=data)
        else:
            return abort(401)
    else:
        code = "-1"
        msg = "您当前不处于登录状态,请先登录"
        return jsonify(code=code, msg=msg)
Ejemplo n.º 5
0
def login():
    """ 前端登录请求post请求,从数据库中验证params完整性和正确性,并设置相应的cookies和session

    :return: json结果
    """
    logintime = ""
    if request.method == 'POST':
        # 这里进行了折衷的处理为了实现登录顶掉他人登录的需求.(人性化的做法应该是提示在他处登录,询问要不要踢掉或者在其他地方先推出,这边在登陆)
        quit()
        print(request.form.get("username", type=str, default=""))
        # 判断用户名密码是否正确
        username = request.form.get("username", type=str, default="")
        passwd = request.form.get("passwd", type=str, default="")
        if username == "" or passwd == "":
            code = "-1"
            msg = "用户名或密码为空或不合法"
        # 用户名不空查询后端数据
        else:
            result = DB_Sync.query_redis(username)
            # 用户不存在
            if result["code"] == "-1":
                code = "-1"
                msg = "用户名或密码错误"
            # 用户存在 result["code"]返回0,1
            else:
                salt = ""
                # 判断密码是否正确
                if result["data"] != "":
                    salt = result["data"]["USER_SALT"]
                    localPW = result["data"]["USER_PASSWD"]
                print("redis data", result["data"])
                print("computePasswd", computePW(passwd, salt))
                # 验算用户传递的密码是否和数据库中保存的一致
                isConsistent = checkPW(computePW(passwd, salt), localPW)
                # 密码输入正确
                if isConsistent:
                    code = "0"
                    msg = "登录验证成功"
                    session["logintime"] = getlocaltime()
                    if session.get("isLogin"):
                        logger.warning("%s用户登录失败,原因是已在其他地方登录" % username)
                        return jsonify(code="-1", msg="您已在其他地方登录")
                    session["isLogin"] = True
                    session["username"] = username
                    logintime = getlocaltime()
                    logger.info("%s用户登录成功" % username)
                # 密码输入错误
                else:
                    code = "-1"
                    msg = "用户名或密码错误"
                    logger.warning("%s用户登录输入密码错误,登录失败" % username)
        resp = jsonify(code=code, msg=msg)
        resp.set_cookie('datetime', getlocaltime())
        resp.set_cookie('logintime', logintime)
        resp.set_cookie('username',
                        request.form.get("username", type=str, default="null"),
                        expires=max_ageTime)  # max_age单位是秒,过期时间
        return resp
    # 如果是其他请求方法
    else:
        resp = jsonify(code='-1',
                       msg='{} Method is not allowed !'.format(request.method))
        resp.set_cookie('datetime', getlocaltime())
        resp.set_cookie('logintime', logintime)
        resp.set_cookie('username',
                        request.form.get("username", type=str, default="null"),
                        expires=max_ageTime)  # max_age单位是秒,过期时间
        return resp