⚗️ auto disable github auth

This commit is contained in:
yanyongyu 2021-06-14 01:30:24 +08:00
parent 35bcb6a126
commit 0f4abe7b79
3 changed files with 96 additions and 85 deletions

View File

@ -4,7 +4,7 @@
@Author : yanyongyu
@Date : 2021-03-15 20:18:19
@LastEditors : yanyongyu
@LastEditTime : 2021-03-15 22:50:28
@LastEditTime : 2021-06-14 01:25:35
@Description : None
@GitHub : https://github.com/yanyongyu
"""
@ -13,19 +13,22 @@ __author__ = "yanyongyu"
import nonebot
from fastapi import FastAPI
from ..libs.auth import _decode_state, get_token_by_code, set_user_token
try:
from ..libs.auth import _decode_state, get_token_by_code, set_user_token
except ImportError:
pass
else:
app: FastAPI = nonebot.get_driver().server_app
app: FastAPI = nonebot.get_driver().server_app
@app.get("/api/github/auth")
async def auth(code: str, state: str):
try:
username = _decode_state(state)
except Exception:
return {"message": "invalid state"}
if not username:
return {"message": "oauth session expired"}
token = await get_token_by_code(code)
set_user_token(username, token)
return {"message": "ok"}
@app.get("/api/github/auth")
async def auth(code: str, state: str):
try:
username = _decode_state(state)
except Exception:
return {"message": "invalid state"}
if not username:
return {"message": "oauth session expired"}
token = await get_token_by_code(code)
set_user_token(username, token)
return {"message": "ok"}

View File

@ -4,30 +4,34 @@
@Author : yanyongyu
@Date : 2021-03-09 16:06:34
@LastEditors : yanyongyu
@LastEditTime : 2021-03-15 22:16:23
@LastEditTime : 2021-06-14 01:28:43
@Description : None
@GitHub : https://github.com/yanyongyu
"""
__author__ = "yanyongyu"
from nonebot.log import logger
from nonebot import on_command
from nonebot.adapters.cqhttp import Bot, PrivateMessageEvent, GroupMessageEvent
from ...libs.auth import get_auth_link
from ... import github_config as config
auth = on_command("auth", priority=config.github_command_priority)
auth.__doc__ = """
/auth
授权 github 账号
"""
try:
from ...libs.auth import get_auth_link
except ImportError:
logger.warning("Plugin github auth is disabled!")
else:
auth = on_command("auth", priority=config.github_command_priority)
auth.__doc__ = """
/auth
授权 github 账号
"""
@auth.handle()
async def handle_private(bot: Bot, event: PrivateMessageEvent):
await auth.finish("请前往以下链接进行授权:\n" + get_auth_link(event.get_user_id()))
@auth.handle()
async def handle_private(bot: Bot, event: PrivateMessageEvent):
await auth.finish("请前往以下链接进行授权:\n" + get_auth_link(event.get_user_id()))
@auth.handle()
async def handle_group(bot: Bot, event: GroupMessageEvent):
await auth.finish("请私聊我并使用 /auth 命令授权你的 GitHub 账号")
@auth.handle()
async def handle_group(bot: Bot, event: GroupMessageEvent):
await auth.finish("请私聊我并使用 /auth 命令授权你的 GitHub 账号")

View File

@ -4,7 +4,7 @@
@Author : yanyongyu
@Date : 2021-03-15 23:14:16
@LastEditors : yanyongyu
@LastEditTime : 2021-05-30 21:05:44
@LastEditTime : 2021-06-14 01:27:27
@Description : None
@GitHub : https://github.com/yanyongyu
"""
@ -22,67 +22,71 @@ from nonebot.adapters.cqhttp import GROUP_ADMIN, GROUP_OWNER, PRIVATE_FRIEND
from src.utils import allow_cancel
from ... import github_config as config
from ...libs.auth import get_user_token
from ...libs.hook import create_hook, has_hook, create_hook_url
REPO_REGEX: str = r"^(?P<owner>[a-zA-Z0-9][a-zA-Z0-9\-]*)/(?P<repo>[a-zA-Z0-9_\-\.]+)$"
# disable plugin if token not provided
try:
from ...libs.auth import get_user_token
from ...libs.hook import create_hook, has_hook, create_hook_url
except ImportError:
logger.warning("Plugin github subscribe disabled!")
else:
subscribe = on_command("subscribe",
priority=config.github_command_priority,
permission=SUPERUSER | GROUP_ADMIN | GROUP_OWNER |
PRIVATE_FRIEND)
subscribe.__doc__ = """
/subscribe owner/repo
订阅仓库事件需要权限
"""
REPO_REGEX: str = r"^(?P<owner>[a-zA-Z0-9][a-zA-Z0-9\-]*)/(?P<repo>[a-zA-Z0-9_\-\.]+)$"
subscribe.args_parser(allow_cancel)
subscribe = on_command("subscribe",
priority=config.github_command_priority,
permission=SUPERUSER | GROUP_ADMIN | GROUP_OWNER |
PRIVATE_FRIEND)
subscribe.__doc__ = """
/subscribe owner/repo
订阅仓库事件需要权限
"""
subscribe.args_parser(allow_cancel)
@subscribe.handle()
async def handle_arg(bot: Bot, event: MessageEvent, state: T_State):
arg = event.get_plaintext().strip()
if arg:
state["full_name"] = arg
@subscribe.handle()
async def handle_arg(bot: Bot, event: MessageEvent, state: T_State):
arg = event.get_plaintext().strip()
if arg:
state["full_name"] = arg
@subscribe.got("full_name", prompt="订阅仓库的全名?(e.g. owner/repo)")
async def process_repo(bot: Bot, event: MessageEvent, state: T_State):
name = state["full_name"]
matched = re.match(REPO_REGEX, name)
if not matched:
await subscribe.reject(f"仓库名 {name} 不合法!请重新发送或取消")
owner = matched.group("owner")
repo_name = matched.group("repo")
@subscribe.got("full_name", prompt="订阅仓库的全名?(e.g. owner/repo)")
async def process_repo(bot: Bot, event: MessageEvent, state: T_State):
name = state["full_name"]
matched = re.match(REPO_REGEX, name)
if not matched:
await subscribe.reject(f"仓库名 {name} 不合法!请重新发送或取消")
owner = matched.group("owner")
repo_name = matched.group("repo")
token = get_user_token(event.get_user_id())
if not token:
await subscribe.finish(f"请先使用 /auth 命令授权你的 GitHub 账号")
return
try:
if not await has_hook(f"{owner}/{repo_name}", token):
url = create_hook_url(f"{owner}/{repo_name}")
await create_hook(
f"{owner}/{repo_name}", {
"url": url,
"content_type": "json",
"insecure_ssl": not config.github_self_ssl
}, token, ["issues", "issue_comment", "pull_request"])
except TimeoutException:
await subscribe.finish(f"获取仓库数据超时!请尝试重试")
return
except HTTPStatusError as e:
if e.response.status_code == 403:
await subscribe.finish(f"你无权操作仓库 {owner}/{repo_name}")
token = get_user_token(event.get_user_id())
if not token:
await subscribe.finish(f"请先使用 /auth 命令授权你的 GitHub 账号")
return
elif e.response.status_code == 404:
await subscribe.reject(f"仓库名 {owner}/{repo_name} 不存在!请重新发送或取消")
return
logger.opt(colors=True,
exception=e).error(f"github_subscribe: create_hook")
await subscribe.finish("订阅仓库时发生错误,请联系开发者或重试")
return
# TODO: subscribe repo with (repo, user, bot) info
await subscribe.finish(f"成功订阅仓库 {owner}/{repo_name}")
try:
if not await has_hook(f"{owner}/{repo_name}", token):
url = create_hook_url(f"{owner}/{repo_name}")
await create_hook(
f"{owner}/{repo_name}", {
"url": url,
"content_type": "json",
"insecure_ssl": not config.github_self_ssl
}, token, ["issues", "issue_comment", "pull_request"])
except TimeoutException:
await subscribe.finish(f"获取仓库数据超时!请尝试重试")
return
except HTTPStatusError as e:
if e.response.status_code == 403:
await subscribe.finish(f"你无权操作仓库 {owner}/{repo_name}")
return
elif e.response.status_code == 404:
await subscribe.reject(f"仓库名 {owner}/{repo_name} 不存在!请重新发送或取消")
return
logger.opt(colors=True,
exception=e).error(f"github_subscribe: create_hook")
await subscribe.finish("订阅仓库时发生错误,请联系开发者或重试")
return
# TODO: subscribe repo with (repo, user, bot) info
await subscribe.finish(f"成功订阅仓库 {owner}/{repo_name}")