예제 #1
0
async def login_access_token(
    *,
    db: Session = Depends(deps.get_db),
    user_info: user_schema.UserEmailAuth,
) -> Any:
    """
    用户JWT登录
    :param db:
    :param user_info:
    :return:
    """

    # 验证用户
    user = curd_user.authenticate(db,
                                  email=user_info.username,
                                  password=user_info.password)
    if not user:
        logger.info(
            f"用户邮箱认证错误: email{user_info.username} password:{user_info.password}"
        )
        return response_code.resp_4003(message="username or password error")
    elif not curd_user.is_active(user):
        return response_code.resp_4003(message="User email not activated")

    access_token_expires = timedelta(
        minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES)

    # 登录token 只存放了user.id
    return response_code.resp_200(
        data={
            "token":
            security.create_access_token(user.id,
                                         expires_delta=access_token_expires),
        })
예제 #2
0
파일: user.py 프로젝트: CoderCharm/chat
async def get_dialog_list(*,
                          db: Session = Depends(get_db),
                          token_data: Union[str,
                                            Any] = Depends(check_jwt_token)):
    sql_query_friends = f"""SELECT * from chat_user_relation WHERE user_id='{token_data.get("sub")}' or friend_id='{token_data.get("sub")}'"""
    query_user = db.execute(sql_query_friends)

    # 查询所有的好友
    user_friends = query_user.fetchall()

    # 添加user_id 或者 friend_id
    friends_list = []
    for i in user_friends:
        friends_list.append(i[1])
        friends_list.append(i[2])

    # 去掉重复的id
    friends_list = list(set(friends_list))
    friends_list.remove(token_data.get("sub"))

    # 查询所有的好友信息
    friends_info_list = []
    for user_id in friends_list:
        # 后续可以考虑 redis缓存 好友信息避免好友多的时候 查询慢
        # 查询用户信息
        sql_user_info = f"""SELECT user_id,nickname,avatar from chat_user WHERE user_id='{user_id}'"""
        query_user_info = db.execute(sql_user_info)
        user_info_res = query_user_info.fetchone()
        friends_info_list.append({
            "userId": user_info_res.user_id,
            "nickname": user_info_res.nickname,
            "avatar": user_info_res.avatar
        })

    return response_code.resp_200(data={"friendsInfoList": friends_info_list})
예제 #3
0
파일: user.py 프로젝트: CoderCharm/chat
async def user_auth(*,
                    db: Session = Depends(get_db),
                    username: str = Body(...),
                    password: str = Body(...)):
    """
    简单模拟登录
    :param db;
    :param username:
    :param password:
    :return:
    """
    sql_query_user = f"SELECT user_id, hashed_password from chat_user WHERE username='******'"
    query_user = db.execute(sql_query_user)

    user_res = query_user.fetchone()
    if not user_res:
        return response_code.resp_5000(message="用户名或者密码错误")

    verify_res = verify_password(password, user_res.hashed_password)
    if not verify_res:
        return response_code.resp_5000(message="用户名或者密码错误")

    access_token_expires = timedelta(
        minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES)

    return response_code.resp_200(
        data={
            "token":
            create_access_token(user_res.user_id,
                                expires_delta=access_token_expires),
        })
async def add_job_to_scheduler(
        request: Request,
        *,
        seconds: int = Body(120, title="循环间隔时间/秒,默认120s", embed=True),
        job_id: str = Body(..., title="任务id", embed=True),
):
    """
    简易的任务调度演示 可自行参考文档 https://apscheduler.readthedocs.io/en/stable/
    三种模式
    date: use when you want to run the job just once at a certain point of time
    interval: use when you want to run the job at fixed intervals of time
    cron: use when you want to run the job periodically at certain time(s) of day
    :param request:
    :param seconds:
    :param job_id:
    :return:
    """
    res = request.app.state.schedule.get_job(job_id=job_id)
    if res:
        return response_code.resp_4001(message=f"{job_id} job already exists")

    schedule_job = request.app.state.schedule.add_job(
        demo_task,
        'interval',
        args=(job_id, ),
        seconds=seconds,  # 循环间隔时间 秒
        id=job_id,  # job ID
        next_run_time=datetime.now()  # 立即执行
    )
    return response_code.resp_200(data={"id": schedule_job.id})
async def items_test(
        request: Request,
        *,
        db: Session = Depends(deps.get_db),
) -> Any:
    """
    用户登录
    :param request:
    :param db:
    :return:
    """
    await request.app.state.redis.set("test_items", 123, expire=30)
    # 等待 redis读取
    redis_test = await request.app.state.redis.get("test_items")

    # 用不惯orm查询的可以手撸sql 使用 from sqlalchemy import text 可以自动转义字符 避免sql注入
    test_sql = "SELECT * from admin_user WHERE id>=:id"
    admin_user_res = db.execute(text(test_sql), {"id": 1}).fetchall()

    # 手动序列化查询后的结果集
    admin_user_info = serialize_sqlalchemy_obj(admin_user_res)

    return response_code.resp_200(
        data={
            "items": "ok",
            "admin_user_info": admin_user_info,
            "redis_test": redis_test
        })
async def remove_schedule(request: Request,
                          job_id: str = Body(..., title="job_id", embed=True)):
    res = request.app.state.schedule.get_job(job_id=job_id)
    if not res:
        return response_code.resp_4001(message=f"not found job {job_id}")

    request.app.state.schedule.remove_job(job_id)

    return response_code.resp_200()
예제 #7
0
async def get_user_info(
    *, current_user: auth.AdminUser = Depends(deps.get_current_user)) -> Any:
    """
    获取用户信息
    :param current_user:
    :return:
    """
    return response_code.resp_200(data={
        "nickname": current_user.nickname,
        "avatar": current_user.avatar
    })
async def get_target_sync(request: Request,
                          job_id: str = Query(..., title="任务id")):
    job = request.app.state.schedule.get_job(job_id=job_id)

    if not job:
        return response_code.resp_4001(message=f"not found job {job_id}")

    return response_code.resp_200(
        data={
            "job_id": job.id,
            "func_name": job.func_ref,
            "func_args": job.args,
            "cron_model": str(job.trigger),
            "next_run": str(job.next_run_time)
        })
async def get_scheduled_syncs(request: Request):
    """
    获取所有job
    :return:
    """
    schedules = []
    for job in request.app.state.schedule.get_jobs():
        schedules.append({
            "job_id": job.id,
            "func_name": job.func_ref,
            "func_args": job.args,
            "cron_model": str(job.trigger),
            "next_run": str(job.next_run_time)
        })

    return response_code.resp_200(data=schedules)
예제 #10
0
파일: user.py 프로젝트: CoderCharm/chat
async def get_user_info(*,
                        db: Session = Depends(get_db),
                        token_data: Union[str,
                                          Any] = Depends(check_jwt_token)):
    sql_query_user = f"""SELECT nickname, avatar from chat_user WHERE user_id='{token_data.get("sub")}'"""
    query_user = db.execute(sql_query_user)

    user_info = query_user.fetchone()

    return response_code.resp_200(
        data={
            "authInfo": {
                "userId": token_data.get("sub"),
                "nickname": user_info.nickname,
                "avatar": user_info.avatar
            }
        })
예제 #11
0
async def upload_image(file: UploadFile = File(...), ):

    # 本地存储临时方案,一般生产都是使用第三方云存储OSS(如七牛云, 阿里云)
    save_dir = f"{settings.BASE_PATH}/app/static/img"
    if not os.path.exists(save_dir):
        os.mkdir(save_dir)
    try:
        suffix = Path(file.filename).suffix

        with NamedTemporaryFile(delete=False, suffix=suffix,
                                dir=save_dir) as tmp:
            shutil.copyfileobj(file.file, tmp)
            tmp_file_name = Path(tmp.name).name
    finally:
        file.file.close()

    return response_code.resp_200(
        data={"image": f"/static/img/{tmp_file_name}"})