Exemplo n.º 1
0
async def modify_client_authority(
        operate_token: str = Depends(verify.oauth2_scheme),
        modify_item: UserVarietyAuthItem = Body(...)):
    operate_user, _ = verify.decipher_user_token(operate_token)
    if not operate_user:
        raise HTTPException(status_code=401, detail="您登录过期了,重新登录后再操作!")
    # 验证expire_date
    try:
        datetime.strptime(modify_item.expire_date, '%Y-%m-%d')
        if not re.match(r'^[A-Z]{1,2}$', modify_item.variety_en):
            raise ValueError("INVALID VARIETY.")
    except Exception:
        raise HTTPException(status_code=400, detail="数据格式有误,修改失败!")
    with MySqlZ() as cursor:
        cursor.execute(
            "SELECT user_id,variety_id FROM user_user_variety WHERE variety_id=%s AND user_id=%s;",
            (modify_item.variety_id, modify_item.modify_user))
        is_exist = cursor.fetchone()
        if is_exist:
            cursor.execute(
                "UPDATE user_user_variety SET expire_date=%(expire_date)s "
                "WHERE user_id=%(modify_user)s AND variety_id=%(variety_id)s;",
                jsonable_encoder(modify_item))
        else:
            cursor.execute(
                "INSERT INTO user_user_variety (user_id, variety_id, variety_en, expire_date) "
                "VALUES (%(modify_user)s,%(variety_id)s,%(variety_en)s,%(expire_date)s);",
                jsonable_encoder(modify_item))

    return {"message": "修改用户品种权限成功!"}
Exemplo n.º 2
0
async def modify_client_authority(operate_token: str = Depends(
    verify.oauth2_scheme),
                                  modify_item: UserClientAuthItem = Body(...)):
    operate_user, _ = verify.decipher_user_token(operate_token)
    if not operate_user:
        raise HTTPException(status_code=401, detail="您登录过期了,重新登录后再操作!")
    # 验证expire_date
    try:
        datetime.strptime(modify_item.expire_date, '%Y-%m-%d')
    except Exception:
        raise HTTPException(status_code=400, detail="数据格式有误,修改失败!")
    with MySqlZ() as cursor:
        cursor.execute(
            "SELECT user_id,client_id FROM user_user_client WHERE client_id=%s AND user_id=%s;",
            (modify_item.client_id, modify_item.modify_user))
        is_exist = cursor.fetchone()
        if is_exist:
            cursor.execute(
                "UPDATE user_user_client SET expire_date=%(expire_date)s "
                "WHERE user_id=%(modify_user)s AND client_id=%(client_id)s;",
                jsonable_encoder(modify_item))
        else:
            cursor.execute(
                "INSERT INTO user_user_client (user_id, client_id, expire_date) "
                "VALUES (%(modify_user)s,%(client_id)s,%(expire_date)s);",
                jsonable_encoder(modify_item))

    return {"message": "修改用户客户端登录权限成功!"}
Exemplo n.º 3
0
async def user_token_logged(client: str = Query(...,
                                                min_length=36,
                                                max_length=36),
                            token: str = Depends(verify.oauth2_scheme)):
    user_id, user_code = verify.decipher_user_token(token)
    if not user_id:
        raise HTTPException(status_code=401, detail="登录失败!Token Expired!")
    # 查询用户的有效与能否在此客户端登录
    with MySqlZ() as cursor:
        cursor.execute(
            "SELECT `id`,role,username,note,is_active FROM user_user WHERE id=%s;",
            (user_id, ))
        user_info = cursor.fetchone()
        if not user_info:
            raise HTTPException(status_code=401, detail="登录失败!USER NOT FOUND!")

        cursor.execute(
            "SELECT `id`,is_manager FROM basic_client WHERE machine_uuid=%s;",
            (client, ))
        client_info = cursor.fetchone()
        if not client_info:
            raise HTTPException(status_code=401, detail="登录失败!INVALID CLIENT!")

        today_str = datetime.today().strftime("%Y-%m-%d")
        # 1 创建今日在线的数据库
        cursor.execute(
            "SELECT `id`,online_date FROM user_user_online WHERE `user_id`=%s AND online_date=%s;",
            (user_info["id"], today_str))
        is_today_online = cursor.fetchone()
        if not is_today_online:  # 今日还未登录
            cursor.execute(
                "INSERT INTO user_user_online (user_id,online_date,total_online) VALUES (%s,%s,%s);",
                (user_info["id"], today_str, 0))
        # 2 非超管和运营查询当前用户是否能在这个客户端登录
        if user_info["role"] not in ["superuser", "operator"]:
            cursor.execute(
                "SELECT userclient.id, userclient.user_id FROM user_user_client AS userclient "
                "INNER JOIN basic_client AS clienttb "
                "ON userclient.client_id=clienttb.id AND userclient.user_id=%s AND clienttb.machine_uuid=%s "
                "AND userclient.expire_date>%s;",
                (user_info["id"], client, today_str))
            is_client_accessed = cursor.fetchone()
            if not is_client_accessed:
                raise HTTPException(status_code=403,
                                    detail="Can not login with the client.")
    return {
        "message": "token登录成功!",
        "show_username": user_info["username"],
    }
Exemplo n.º 4
0
async def register(
        is_image_code_passed: bool = Depends(checked_image_code),
        phone: str = Form(...),
        nickname: str = Form(""),
        email: str = Form(""),
        weixin: str = Form(""),
        password: str = Form(...),
):
    if not is_image_code_passed:
        raise HTTPException(status_code=400, detail="Got an error image code.")
    print("phone:%s\n nickname:%s\n password:%s" % (phone, nickname, password))
    time.sleep(3)
    # 将用户信息保存到数据库中
    user_to_save = UserInDB(
        unique_code=verify.generate_user_unique_code(),  # 生成系统号
        username=nickname,
        phone=phone,
        email=email,
        weixin=weixin,
        password_hashed=verify.get_password_hash(password)  # hash用户密码
    )
    with MySqlZ() as cursor:
        cursor.execute(
            "INSERT INTO `user_user` (`unique_code`,`username`,`phone`,`email`,`weixin`,`password_hashed`) "
            "VALUES (%(unique_code)s,%(username)s,%(phone)s,%(email)s,%(weixin)s,%(password_hashed)s);",
            (jsonable_encoder(user_to_save)))
    back_user = User(unique_code=user_to_save.unique_code,
                     username=user_to_save.username,
                     phone=user_to_save.phone,
                     email=user_to_save.email,
                     weixin=user_to_save.weixin)
    return {"message": "注册成功!", "user": back_user}
Exemplo n.º 5
0
async def login_for_access_token(
        is_image_code_passed: bool = Depends(checked_image_code),
        user: User = Depends(get_user_in_db)):
    if not is_image_code_passed:
        raise HTTPException(status_code=400, detail="Got an error image code.")
    if not user:
        raise HTTPException(status_code=401,
                            detail="Incorrect username or password.")
    # 得到通过密码验证的用户,签发token证书
    access_token = verify.create_access_token(
        data={"unique_code": user.unique_code})
    show_username = user.username if user.username else user.phone
    return {
        "show_username": show_username,
        "access_token": access_token,
        "token_type": "bearer"
    }
Exemplo n.º 6
0
async def get_user_in_db(phone: str = Form(...),
                         password: str = Form(...),
                         client_uuid: str = Form(...),
                         user_code: str = Form("")):
    # 解码phone和password
    phone = base64.b64decode(phone.encode('utf-8')).decode('utf-8')
    password = base64.b64decode(password.encode('utf-8')).decode('utf-8')
    with MySqlZ() as cursor:
        cursor.execute(
            "SELECT `id`,`user_code`,`username`,`phone`,`email`,`password_hashed`,`role` "
            "FROM `user_user` WHERE (`phone`=%s OR `user_code`=%s) AND `is_active`=1;",
            (phone, user_code))
        user_dict = cursor.fetchone()
        if not user_dict:  # 数据库中没有查询到用户
            return None
        # 如果有用户,修改登录时间
        cursor.execute(
            "UPDATE `user_user` SET `recent_login`=%s WHERE `id`=%s;",
            (datetime.today(), user_dict["id"]))
        if not verify.verify_password(
                password, user_dict["password_hashed"]):  # 将查询到的密码验证
            return None
        # 如果密码验证通过,
        today_str = datetime.today().strftime("%Y-%m-%d")
        # 非超管和运营查询当前用户是否能在这个客户端登录
        if user_dict["role"] not in ["superuser", "operator"]:
            cursor.execute(
                "SELECT userclient.id, userclient.user_id FROM user_user_client AS userclient "
                "INNER JOIN basic_client AS clienttb "
                "ON userclient.client_id=clienttb.id AND userclient.user_id=%s AND clienttb.machine_uuid=%s "
                "AND userclient.expire_date>%s AND clienttb.is_active=1;",
                (user_dict["id"], client_uuid, today_str))
            is_client_accessed = cursor.fetchone()
            if not is_client_accessed:
                raise HTTPException(status_code=403,
                                    detail="Can not login with the client.")

    return User(**user_dict)
Exemplo n.º 7
0
async def user_authenticate_module(module_item: ModuleItem = Body(...)):
    if not module_item.user_token:
        raise HTTPException(
            status_code=403,
            detail="您还未登录,登录后在进行操作!")  # 403 -> reply.error() = 201
    user_id, user_code = verify.decipher_user_token(
        module_item.user_token)  # 解析用户信息
    if not user_id:
        raise HTTPException(status_code=403, detail="您登录已过期,请重新登录后再进行操作!")
    # 查询客户端类型和用户的身份信息
    with MySqlZ() as cursor:
        cursor.execute(
            "SELECT `id`,is_manager,is_active FROM basic_client WHERE machine_uuid=%s;",
            (module_item.client_uuid, ))
        client_info = cursor.fetchone()
        cursor.execute(
            "SELECT `id`,role,is_active FROM user_user WHERE id=%s;",
            (user_id, ))
        user_info = cursor.fetchone()

        if not client_info or not client_info["is_active"]:
            detail_message = "进入「{}」失败:\n无效客户端,无法进行这个操作!".format(
                module_item.module_text)
            raise HTTPException(
                status_code=401,
                detail=detail_message)  # 403 -> reply.error() = 204

        if not user_info or not user_info["is_active"]:
            detail_message = "进入「{}」失败:\n无效用户,无法进行这个操作!".format(
                module_item.module_text)
            raise HTTPException(status_code=401, detail=detail_message)

        if user_info["role"] in ["superuser", "operator"]:
            return {
                "message": "验证成功!",
                "authenticate": True,
                "module_id": module_item.module_id,
                "module_text": module_item.module_text,
            }

        if client_info["is_manager"] and module_item.module_id >= "0":
            return {
                "message": "验证成功!",
                "authenticate": True,
                "module_id": module_item.module_id,
                "module_text": module_item.module_text,
            }

        # 查询用户是否有权限进入相应模块
        today_str = datetime.today().strftime("%Y-%m-%d")
        cursor.execute(
            "SELECT `id`,user_id,module_id FROM user_user_module "
            "WHERE user_id=%s AND module_id=%s AND expire_date>%s;",
            (user_id, module_item.module_id, today_str))
        is_accessed = cursor.fetchone()
        if not is_accessed:
            detail_message = "还没有「{}」的权限,请联系管理员进行开通!".format(
                module_item.module_text)
            raise HTTPException(status_code=401, detail=detail_message)
        else:
            return {
                "message": "验证成功!",
                "authenticate": True,
                "module_id": module_item.module_id,
                "module_text": module_item.module_text,
            }