Skip to content

Commit

Permalink
Fix refresh_token
Browse files Browse the repository at this point in the history
  • Loading branch information
houtianze committed Nov 29, 2021
1 parent 9ff6701 commit b61692d
Show file tree
Hide file tree
Showing 8 changed files with 109 additions and 40 deletions.
7 changes: 6 additions & 1 deletion .vscode/settings.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,5 +4,10 @@
"**/.project": true,
"**/.settings": true,
"**/.factorypath": true
},
"java.completion.enabled": false,

"files.watcherExclude": {
"**/target": true
}
}
}
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ TL;DR
**如果有人想帮助搭国内建授权服务器的话,请按以下步骤进行:**

1. Clone <https://github.com/houtianze/bypyoauth> 并用任意值配置好环境变量后成功运行服务
2. Fork 此repo,并把你的新服务器地址加到这里 <https://github.com/houtianze/bypy/blob/master/bypy/const.py#L164-L173>
2. Fork 此repo,并把你的新服务器地址加到这里 <https://github.com/houtianze/bypy/blob/master/bypy/res/auth.json>
3. 创建拉取请求,然后通过 [![Join the chat at https://gitter.im/houtianze/bypy](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/houtianze/bypy?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) 或者在拉取请求里留下你的联系方式
4. 我测试新服务器可以使用后,通过Gitter/邮件把Secret Key发给你,你用正确的配置启动授权服务器
5. 新的授权服务器配置好后我合并拉取请求
Expand Down
97 changes: 72 additions & 25 deletions bypy/bypy.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,12 @@
raw_input = input
pickleload = partial(pickle.load, encoding="bytes")

try:
import importlib.resources as pkg_resources
except ImportError:
# Try backported to PY<37 `importlib_resources`.
import importlib_resources as pkg_resources

from . import const
from . import gvar
from . import printer_console
Expand Down Expand Up @@ -317,6 +323,9 @@ def __init__(self,
# so if any code using this class can check the current verbose / debug level
cached.verbose = self.verbose = verbose
cached.debug = self.debug = debug

self.__load_auth_server_list()

if not cached.usecache:
pinfo("Forced hash recalculation, hash cache won't be used")

Expand Down Expand Up @@ -984,20 +993,29 @@ def __local_auth_act(self, r, args):
def __repr_timeout(self):
return self.__timeout if self.__timeout else 'infinite'

# NO longer in use
# def __update_auth_server_list(self):
# try:
# r = requests.get('https://raw.githubusercontent.com/houtianze/bypy/master/update/auth.json')
# if r.status_code == 200:
# try:
# j = r.json()
# const.AuthServerList = j['AuthServerList']
# except ValueError:
# self.pd("Invalid response for auth servers update, skipping.")
# else:
# self.pd("HTTP Status {} while updating auth servers, skipping.".format(r.status_code))
# except:
# self.pd("Error occurred while updating auth servers, skipping.")
def __load_auth_server_list(self):
# https://stackoverflow.com/a/20885799/404271
from . import res
j = json.loads(pkg_resources.read_text(res, 'auth.json'))
self.pd('Auth servers loaded: {}'.format(j))
self.AuthServerList = j['AuthServerList']
self.RefreshServerList = j['RefreshServerList']

def __update_auth_server_list(self):
try:
r = requests.get('https://raw.githubusercontent.com/houtianze/bypy/master/bypy/res/auth.json')
if r.status_code == 200:
try:
j = r.json()
self.pd('Auth servers updated: {}'.format(j))
self.AuthServerList = j['AuthServerList']
self.RefreshServerList = j['RefreshServerList']
except ValueError:
self.pd("Invalid response for auth servers update, skipping.")
else:
self.pd("HTTP Status {} while updating auth servers, skipping.".format(r.status_code))
except:
self.pd("Error occurred while updating auth servers, skipping.")

def __auth(self):
params = {
Expand Down Expand Up @@ -1025,8 +1043,8 @@ def __auth(self):
if not self.debug:
perr = nop

# self.__update_auth_server_list()
for auth in const.AuthServerList:
self.__update_auth_server_list()
for auth in self.AuthServerList:
(url, retry, msg) = auth
pr(msg)
result = self.__get(url, pars, self.__server_auth_act, retry = retry, addtoken = False)
Expand Down Expand Up @@ -1093,15 +1111,44 @@ def __refresh_token_act(self, r, args):
return self.__store_json(r)

def __refresh_token(self):
pr('Refreshing, please be patient, it may take upto {} seconds...'.format(self.__repr_timeout()))
# How silly am I to have used server for token refresh -
# We DON'T need any server for refreshing token, we have refresh_token already after auth.
pars = {
'grant_type' : 'refresh_token',
'refresh_token' : self.__json['refresh_token'],
'client_secret' : self.__secretkey,
'client_id' : self.__apikey}
return self.__post(const.TokenUrl, pars, self.__refresh_token_act)
if self.__use_server_auth:
pr('Refreshing, please be patient, it may take upto {} seconds...'.format(self.__repr_timeout()))

pars = {
'bypy_version' : const.__version__,
'refresh_token' : self.__json['refresh_token'] }

result = None
# TODO: hacky
global perr
savedperr = perr
if not self.debug:
perr = nop
self.__update_auth_server_list()
for refresh in self.RefreshServerList:
(url, retry, msg) = refresh
pr(msg)
result = self.__get(url, pars, self.__refresh_token_act, retry = retry, addtoken = False)
if result == const.ENoError:
break
if not self.debug:
perr = savedperr

if result == const.ENoError:
pr("Token successfully refreshed")
else:
perr("Token-refreshing on all the servers failed")
self.__prompt_clean()
sys.exit(result)

return result
else:
pars = {
'grant_type' : 'refresh_token',
'refresh_token' : self.__json['refresh_token'],
'client_secret' : self.__secretkey,
'client_id' : self.__apikey}
return self.__post(const.TokenUrl, pars, self.__refresh_token_act)

def __walk_normal_file(self, dir):
#dirb = dir.encode(FileSystemEncoding)
Expand Down
11 changes: 0 additions & 11 deletions bypy/const.py
Original file line number Diff line number Diff line change
Expand Up @@ -161,17 +161,6 @@
MaxSlicePieces = 1024
MaxListEntries = 1000 # https://github.com/houtianze/bypy/issues/285

### Auth servers
VercelUrl = 'https://bypyoauthsanic.vercel.app/api'
VercelRedirectUrl = VercelUrl + '/auth'
AliyunUrl = 'https://8.142.131.121'
AliyunRedirectUrl = AliyunUrl + '/auth'
AuthServerList = [
# url, retry?, message
(VercelRedirectUrl, False, "Authorizing with the Vercel server ..."),
(AliyunRedirectUrl, False, "Vercel server failed. Last resort: authorizing with the Aliyun server ..."),
]

### public static properties
HelpMarker = "Usage:"

Expand Down
Empty file added bypy/res/__init__.py
Empty file.
26 changes: 26 additions & 0 deletions bypy/res/auth.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
{
"AuthServerList": [
[
"https://bypyoauthsanic.vercel.app/api/auth",
false,
"Authorizing with the Vercel server ..."
],
[
"https://8.142.131.12/auth",
false,
"Vercel server failed. Last resort: authorizing with the Aliyun server ..."
]
],
"RefreshServerList": [
[
"https://bypyoauthsanic.vercel.app/api/refresh",
false,
"Refreshing with the Vercel server ..."
],
[
"https://8.142.131.12/refresh",
false,
"Vercel server failed. Last resort: refreshing with the Aliyun server ..."
]
]
}
1 change: 1 addition & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,4 @@
requests
requests-toolbelt
multiprocess
importlib-resources
5 changes: 3 additions & 2 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ def getmeta(path, encoding = 'utf8'):
author_email = '[email protected]',
download_url = 'https://github.com/houtianze/bypy/tarball/' + meta['version'],
#packages=find_packages(),
packages = ['bypy', 'bypy.test'],
packages = ['bypy', 'bypy.res', 'bypy.test'],
package_data = {
'bypy' : ['*.rst', 'bypy/*.pem']
},
Expand Down Expand Up @@ -80,7 +80,8 @@ def getmeta(path, encoding = 'utf8'):
install_requires = [
'requests>=2.10.0',
'requests-toolbelt>=0.8.0',
'multiprocess>=0.70.0'],
'multiprocess>=0.70.0',
'importlib-resources>=5.4.0'],
include_package_data = True,
**meta
)
Expand Down

0 comments on commit b61692d

Please sign in to comment.