GitHub OAuth

This commit is contained in:
Benny
2023-02-08 20:55:26 +01:00
parent f9e41adc0b
commit 0735109034
4 changed files with 79 additions and 4 deletions

Submodule YYeTsFE updated: a937b23016...451b6ac37f

View File

@@ -1184,3 +1184,26 @@ class SpamProcessMongoResource(Mongo):
api = f"https://api.telegram.org/bot{token}/sendMessage"
resp = requests.post(api, json=data).json()
logging.info("Telegram response: %s", resp)
class OAuthRegisterResource(Mongo):
def add_user(self, username, ip, browser):
# username = "Benny"
user = self.db["users"].find_one({"username": username})
if user and user.get("password"):
# 直接注册的用户
return {"status": "fail", "message": "第三方登录失败,用户名已存在"}
elif user:
# 已存在的oauth用户
return {"status": "success", "message": "欢迎回来,即将跳转首页", "username": username}
else:
# 第一次oauth登录假定一定会成功
# TODO GitHub可以改用户名的但是uid不会变也许需要加unique index
self.db["users"].insert_one({
"username": username,
"date": ts_date(),
"ip": ip,
"browser": browser,
"oldUser": True
})
return {"status": "success", "message": "第三方登录成功,即将跳转首页", "username": username}

View File

@@ -21,10 +21,13 @@ from concurrent.futures import ThreadPoolExecutor
from datetime import date, timedelta
from hashlib import sha1
from http import HTTPStatus
from urllib.parse import urlencode
import filetype
import requests
import zhconv
from tornado import escape, gen, web
from tornado.auth import OAuth2Mixin
from tornado.concurrent import run_on_executor
from database import CaptchaResource, Redis
@@ -1000,3 +1003,51 @@ class SpamProcessHandler(BaseHandler):
@gen.coroutine
def delete(self):
self.write(self.process("ban_spam"))
class GitHubOAuth2LoginHandler(BaseHandler, OAuth2Mixin):
_OAUTH_AUTHORIZE_URL = "https://github.com/login/oauth/authorize"
_OAUTH_ACCESS_TOKEN_URL = "https://github.com/login/oauth/access_token"
_OAUTH_API_REQUEST_URL = "https://api.github.com/user"
class_name = f"OAuthRegisterResource"
github_client_id = os.getenv("GITHUB_CLIENT_ID")
github_client_secret = os.getenv("GITHUB_CLIENT_SECRET")
redirect_uri = os.getenv("GITHUB_REDIRECT_URI")
def add_oauth_user(self, username):
ip = self.get_real_ip()
browser = self.request.headers['user-agent']
response = self.instance.add_user(username, ip, browser)
return response
def get(self):
code = self.get_argument('code', None)
if code:
access = self.get_authenticated_user(code)
resp = requests.get(
self._OAUTH_API_REQUEST_URL,
headers={"Authorization": "Bearer {}".format(access["access_token"])}
).json()
username = resp["login"]
logging.info("User %s login with GitHub now...", username)
result = self.add_oauth_user(username)
if result["status"] == "success":
self.set_secure_cookie("username", username, 365)
self.redirect("/login?" + urlencode(result))
else:
self.authorize_redirect(
redirect_uri=self.redirect_uri,
client_id=self.github_client_id,
scope=[],
response_type='code')
def get_authenticated_user(self, code):
body = {
"client_id": self.github_client_id,
"client_secret": self.github_client_secret,
"code": code,
}
return requests.post(self._OAUTH_ACCESS_TOKEN_URL, data=body, headers={"Accept": "application/json"}).json()

View File

@@ -26,9 +26,9 @@ from handler import (AnnouncementHandler, BlacklistHandler, CaptchaHandler,
CategoryHandler, CommentChildHandler, CommentHandler,
CommentNewestHandler, CommentReactionHandler,
DBDumpHandler, DoubanHandler, DoubanReportHandler,
GrafanaIndexHandler, GrafanaQueryHandler,
GrafanaSearchHandler, IndexHandler, LikeHandler,
MetricsHandler, NameHandler, NotFoundHandler,
GitHubOAuth2LoginHandler, GrafanaIndexHandler,
GrafanaQueryHandler, GrafanaSearchHandler, IndexHandler,
LikeHandler, MetricsHandler, NameHandler, NotFoundHandler,
NotificationHandler, ResourceHandler,
ResourceLatestHandler, SpamProcessHandler, TopHandler,
UserEmailHandler, UserHandler)
@@ -69,6 +69,7 @@ class RunServer:
(r'/api/notification', NotificationHandler),
(r'/api/category', CategoryHandler),
(r'/api/admin/spam', SpamProcessHandler),
(r'/auth/github', GitHubOAuth2LoginHandler),
(r'/(.*\.html|.*\.js|.*\.css|.*\.png|.*\.jpg|.*\.ico|.*\.gif|.*\.woff2|.*\.gz|.*\.zip|'
r'.*\.svg|.*\.json|.*\.txt)',