mirror of
https://github.com/Lost-MSth/Arcaea-server.git
synced 2026-02-08 08:47:32 +08:00
Code refactoring
- Code refactoring mainly for API - Delete a useless option in `setting.py` - Change some constants in Link Play mode
This commit is contained in:
@@ -0,0 +1,10 @@
|
||||
from flask import Blueprint
|
||||
|
||||
from . import users
|
||||
from . import songs
|
||||
from . import token
|
||||
|
||||
bp = Blueprint('api', __name__, url_prefix='/api/v1')
|
||||
bp.register_blueprint(users.bp)
|
||||
bp.register_blueprint(songs.bp)
|
||||
bp.register_blueprint(token.bp)
|
||||
|
||||
@@ -1,156 +1,75 @@
|
||||
import hashlib
|
||||
import base64
|
||||
import time
|
||||
import random
|
||||
from core.sql import Connect
|
||||
import functools
|
||||
|
||||
from core.api_user import APIUser
|
||||
from core.error import ArcError, NoAccess, PostError
|
||||
from core.sql import Connect
|
||||
from setting import Config
|
||||
from flask import jsonify
|
||||
|
||||
from .api_code import error_return
|
||||
|
||||
|
||||
class User():
|
||||
# 用户类,当数据类型用
|
||||
def __init__(self, user_id=None, role='', power=[]):
|
||||
self.user_id = user_id
|
||||
self.role = role
|
||||
self.power = power
|
||||
|
||||
|
||||
def login(auth: str, ip: str):
|
||||
# 登录接口,返回字典和错误码
|
||||
|
||||
try:
|
||||
auth_decode = bytes.decode(base64.b64decode(auth))
|
||||
except:
|
||||
return {}, -100
|
||||
|
||||
if not ':' in auth_decode:
|
||||
return {}, -100
|
||||
|
||||
name, password = auth_decode.split(':', 1)
|
||||
|
||||
with Connect() as c:
|
||||
hash_pwd = hashlib.sha256(password.encode("utf8")).hexdigest()
|
||||
c.execute('''select user_id, password from user where name = :name''', {
|
||||
'name': name})
|
||||
x = c.fetchone()
|
||||
if x is None:
|
||||
return {}, -201
|
||||
if x[1] == '':
|
||||
return {}, -202
|
||||
if hash_pwd != x[1]:
|
||||
return {}, -201
|
||||
|
||||
user_id = str(x[0])
|
||||
now = int(time.time() * 1000)
|
||||
token = hashlib.sha256(
|
||||
(user_id + str(random.randint(10000, 99999)) + str(now)).encode("utf8")).hexdigest()
|
||||
c.execute('''delete from api_login where user_id=?''', (user_id,))
|
||||
c.execute('''insert into api_login values(?,?,?,?)''',
|
||||
(user_id, token, now, ip))
|
||||
|
||||
return {'token': token, 'user_id': user_id}, 0
|
||||
|
||||
|
||||
def logout(user: User):
|
||||
# 登出接口,返回错误码
|
||||
code = 999
|
||||
with Connect() as c:
|
||||
c.execute('''delete from api_login where user_id=?''', (user.user_id,))
|
||||
code = 0
|
||||
|
||||
return code
|
||||
|
||||
|
||||
def id_get_role_id(c, user_id):
|
||||
# user_id获取role_id
|
||||
role_id = 1
|
||||
c.execute('''select role_id from user_role where user_id = :a''',
|
||||
{'a': user_id})
|
||||
x = c.fetchone()
|
||||
if x is not None:
|
||||
role_id = int(x[0])
|
||||
|
||||
return role_id
|
||||
|
||||
|
||||
def role_id_get_role(c, role_id):
|
||||
# role_id获取role
|
||||
role = ''
|
||||
c.execute('''select role_name from role where role_id = :a''',
|
||||
{'a': role_id})
|
||||
x = c.fetchone()
|
||||
if x is not None:
|
||||
role = x[0]
|
||||
|
||||
return role
|
||||
|
||||
|
||||
def api_token_get_id(c, token):
|
||||
# api的token获取user_id
|
||||
user_id = None
|
||||
c.execute('''select user_id from api_login where token = :token''', {
|
||||
'token': token})
|
||||
x = c.fetchone()
|
||||
if x is not None:
|
||||
user_id = x[0]
|
||||
|
||||
return user_id
|
||||
|
||||
|
||||
def get_role_power(c, role_id):
|
||||
# 获取role_id对应power,返回列表
|
||||
|
||||
role_power = []
|
||||
|
||||
c.execute('''select power_name from power where power_id in (select power_id from role_power where role_id=:a)''', {
|
||||
'a': role_id})
|
||||
x = c.fetchall()
|
||||
for i in x:
|
||||
role_power.append(i[0])
|
||||
|
||||
return role_power
|
||||
|
||||
|
||||
def role_required(request, power=[]):
|
||||
# api token验证,写成了修饰器
|
||||
def role_required(request, powers=[]):
|
||||
'''api token验证,写成了修饰器'''
|
||||
def decorator(view):
|
||||
@functools.wraps(view)
|
||||
def wrapped_view(*args, **kwargs):
|
||||
|
||||
try:
|
||||
request.json # 检查请求json格式
|
||||
except:
|
||||
return jsonify({'status': 400, 'code': -1, 'data': {}, 'msg': 'Payload must be a valid json'})
|
||||
return error_return(PostError('Payload must be a valid json', api_error_code=-1), 400)
|
||||
|
||||
if not 'Token' in request.headers:
|
||||
return jsonify({'status': 401, 'code': -1, 'data': {}, 'msg': 'No token'})
|
||||
return error_return(PostError('No token', api_error_code=-1), 401)
|
||||
|
||||
user = User()
|
||||
user = APIUser()
|
||||
if Config.API_TOKEN == request.headers['Token'] and Config.API_TOKEN != '':
|
||||
user.user_id = 0
|
||||
elif power == []:
|
||||
return jsonify({'status': 403, 'code': -1, 'data': {}, 'msg': 'No permission'})
|
||||
elif powers == []:
|
||||
# 无powers则非本地权限(API_TOKEN规定的)无法访问
|
||||
return error_return(NoAccess('No permission', api_error_code=-1), 403)
|
||||
else:
|
||||
with Connect() as c:
|
||||
user.user_id = api_token_get_id(
|
||||
c, request.headers['Token'])
|
||||
if user.user_id is None:
|
||||
return jsonify({'status': 401, 'code': -1, 'data': {}, 'msg': 'No token'})
|
||||
try:
|
||||
user.c = c
|
||||
user.select_user_id_from_api_token(
|
||||
request.headers['Token'])
|
||||
user.select_role_and_powers()
|
||||
|
||||
role_id = id_get_role_id(c, user.user_id)
|
||||
user.role = role_id_get_role(c, role_id)
|
||||
user.role_power = get_role_power(c, role_id)
|
||||
|
||||
f = False
|
||||
for i in power:
|
||||
if i in user.role_power:
|
||||
f = True
|
||||
break
|
||||
if not f:
|
||||
return jsonify({'status': 403, 'code': -1, 'data': {}, 'msg': 'No permission'})
|
||||
if not any([y in [x.power_name for x in user.role.powers] for y in powers]):
|
||||
return error_return(NoAccess('No permission', api_error_code=-1), 403)
|
||||
except ArcError as e:
|
||||
return error_return(e, 401)
|
||||
|
||||
return view(user, *args, **kwargs)
|
||||
|
||||
return wrapped_view
|
||||
return decorator
|
||||
|
||||
|
||||
def request_json_handle(request, required_keys=[], optional_keys=[]):
|
||||
'''
|
||||
提取post参数,返回dict,写成了修饰器\
|
||||
parameters: \
|
||||
`request`: `Request` - 当前请求\
|
||||
`required_keys`: `list` - 必须的参数\
|
||||
`optional_keys`: `list` - 可选的参数
|
||||
'''
|
||||
|
||||
def decorator(view):
|
||||
@functools.wraps(view)
|
||||
def wrapped_view(*args, **kwargs):
|
||||
|
||||
data = {}
|
||||
for key in required_keys:
|
||||
if key not in request.json:
|
||||
return error_return(PostError('Missing parameter: ' + key, api_error_code=-100))
|
||||
data[key] = request.json[key]
|
||||
|
||||
for key in optional_keys:
|
||||
if key in request.json:
|
||||
data[key] = request.json[key]
|
||||
|
||||
return view(data, *args, **kwargs)
|
||||
|
||||
return wrapped_view
|
||||
return decorator
|
||||
|
||||
@@ -1,34 +1,32 @@
|
||||
from core.error import ArcError
|
||||
from flask import jsonify
|
||||
|
||||
|
||||
def code_get_msg(code):
|
||||
# api接口code获取msg,返回字符串
|
||||
msg = {
|
||||
0: '',
|
||||
-1: 'See status code',
|
||||
-2: 'No data',
|
||||
-3: 'No data or user',
|
||||
-4: 'No user_id',
|
||||
-100: 'Wrong post data',
|
||||
-101: 'Wrong data type',
|
||||
-102: 'Wrong query parameter',
|
||||
-103: 'Wrong sort parameter',
|
||||
-104: 'Wrong sort order parameter',
|
||||
-201: 'Wrong username or password',
|
||||
-202: 'User is banned',
|
||||
-203: 'Username exists',
|
||||
-204: 'Email address exists',
|
||||
-999: 'Unknown error'
|
||||
}
|
||||
|
||||
return msg[code]
|
||||
default_error = ArcError('Unknown Error')
|
||||
|
||||
|
||||
def return_encode(code: int = 0, data: dict = {}, status: int = 200, msg: str = ''):
|
||||
# 构造返回,返回jsonify处理过后的response_class
|
||||
if msg == '':
|
||||
msg = code_get_msg(code)
|
||||
if code < 0:
|
||||
return jsonify({'status': status, 'code': code, 'data': {}, 'msg': msg})
|
||||
else:
|
||||
return jsonify({'status': status, 'code': code, 'data': data, 'msg': msg})
|
||||
CODE_MSG = {
|
||||
0: '',
|
||||
-1: 'See status code',
|
||||
-2: 'No data',
|
||||
-3: 'No data or user',
|
||||
-4: 'No user_id',
|
||||
-100: 'Wrong post data',
|
||||
-101: 'Wrong data type',
|
||||
-102: 'Wrong query parameter',
|
||||
-103: 'Wrong sort parameter',
|
||||
-104: 'Wrong sort order parameter',
|
||||
-200: 'No permission',
|
||||
-201: 'Wrong username or password',
|
||||
-202: 'User is banned',
|
||||
-203: 'Username exists',
|
||||
-204: 'Email address exists',
|
||||
-999: 'Unknown error'
|
||||
}
|
||||
|
||||
|
||||
def success_return(data: dict = {}, status: int = 200, msg: str = ''):
|
||||
return jsonify({'code': 0, 'data': data, 'msg': msg}), status
|
||||
|
||||
|
||||
def error_return(e: 'ArcError' = default_error, status: int = 200):
|
||||
return jsonify({'code': e.api_error_code, 'data': {} if e.extra_data is None else e.extra_data, 'msg': CODE_MSG[e.api_error_code] if e.message is None else e.message}), status
|
||||
|
||||
@@ -1,219 +0,0 @@
|
||||
from flask import (
|
||||
Blueprint, request, jsonify
|
||||
)
|
||||
import functools
|
||||
import api.api_auth
|
||||
from . import users
|
||||
import api.songs
|
||||
from .api_code import code_get_msg, return_encode
|
||||
|
||||
|
||||
bp = Blueprint('api', __name__, url_prefix='/api/v1')
|
||||
bp.register_blueprint(users.bp)
|
||||
|
||||
|
||||
class Query():
|
||||
# 查询类,当查询附加参数的数据类型用
|
||||
def __init__(self, limit=-1, offset=0, query={}, sort=[]) -> None:
|
||||
self.limit = limit
|
||||
self.offset = offset
|
||||
self.query = query # {'name': 'admin'}
|
||||
self.sort = sort # [{'column': 'user_id', 'order': 'ASC'}, ...]
|
||||
|
||||
|
||||
def get_query_parameter(request, query_able=[], sort_able=[]):
|
||||
# 提取查询请求参数,返回Query类查询参数,写成修饰器
|
||||
|
||||
def decorator(view):
|
||||
@functools.wraps(view)
|
||||
def wrapped_view(*args, **kwargs):
|
||||
|
||||
re = Query()
|
||||
|
||||
if 'limit' in request.json:
|
||||
try:
|
||||
re.limit = int(request.json['limit'])
|
||||
except:
|
||||
return jsonify({'status': 200, 'code': -101, 'data': {}, 'msg': code_get_msg(-101)})
|
||||
|
||||
if 'offset' in request.json:
|
||||
try:
|
||||
re.offset = int(request.json['offset'])
|
||||
except:
|
||||
return jsonify({'status': 200, 'code': -101, 'data': {}, 'msg': code_get_msg(-101)})
|
||||
if 'query' in request.json:
|
||||
re.query = request.json['query']
|
||||
for i in re.query:
|
||||
if i not in query_able:
|
||||
return jsonify({'status': 200, 'code': -102, 'data': {}, 'msg': code_get_msg(-102)})
|
||||
if 'sort' in request.json:
|
||||
re.sort = request.json['sort']
|
||||
for i in re.sort:
|
||||
if 'column' not in i or i['column'] not in sort_able:
|
||||
return jsonify({'status': 200, 'code': -103, 'data': {}, 'msg': code_get_msg(-103)})
|
||||
if not 'order' in i:
|
||||
i['order'] = 'ASC'
|
||||
else:
|
||||
if i['order'] not in ['ASC', 'DESC']:
|
||||
return jsonify({'status': 200, 'code': -104, 'data': {}, 'msg': code_get_msg(-104)})
|
||||
|
||||
return view(re, *args, **kwargs)
|
||||
|
||||
return wrapped_view
|
||||
return decorator
|
||||
|
||||
|
||||
@bp.route('/')
|
||||
def ping():
|
||||
return return_encode()
|
||||
|
||||
|
||||
@bp.route('/token', methods=['POST'])
|
||||
def token_post():
|
||||
# 登录,获取token
|
||||
# {'auth': `base64(user_id:password)`}
|
||||
|
||||
if 'auth' in request.json:
|
||||
data, code = api.api_auth.login(
|
||||
str(request.json['auth']), request.remote_addr)
|
||||
return return_encode(code, data)
|
||||
else:
|
||||
return return_encode(-1, {}, 401, 'No authentication')
|
||||
|
||||
|
||||
@bp.route('/token', methods=['GET'])
|
||||
@api.api_auth.role_required(request, ['select_me', 'select'])
|
||||
def token_get(user):
|
||||
# 判断登录有效性
|
||||
return return_encode()
|
||||
|
||||
|
||||
@bp.route('/token', methods=['DELETE'])
|
||||
@api.api_auth.role_required(request, ['change_me', 'select_me', 'select'])
|
||||
def token_delete(user):
|
||||
# 登出
|
||||
return return_encode(api.api_auth.logout(user))
|
||||
|
||||
|
||||
@bp.route('/users', methods=['GET'])
|
||||
@api.api_auth.role_required(request, ['select'])
|
||||
@get_query_parameter(request, ['user_id', 'name', 'user_code'], [
|
||||
'user_id', 'name', 'user_code', 'join_date', 'rating_ptt', 'time_played', 'ticket', 'world_rank_score'])
|
||||
def users_get(query, user):
|
||||
# 查询全用户信息
|
||||
|
||||
data = users.get_users(query)
|
||||
|
||||
if not data:
|
||||
return return_encode(-2)
|
||||
|
||||
return return_encode(0, data)
|
||||
|
||||
|
||||
@bp.route('/users/<int:user_id>', methods=['GET'])
|
||||
@api.api_auth.role_required(request, ['select', 'select_me'])
|
||||
def users_user_get(user, user_id):
|
||||
# 查询用户信息
|
||||
|
||||
if user_id == 'me':
|
||||
user_id = user.user_id
|
||||
|
||||
if user_id <= 0:
|
||||
return return_encode(-4)
|
||||
|
||||
if user_id != user.user_id and not 'select' in user.power and user.user_id != 0: # 查别人需要select权限
|
||||
return return_encode(-1, {}, 403, 'No permission')
|
||||
|
||||
data = users.get_user_info(user_id)
|
||||
|
||||
if not data:
|
||||
return return_encode(-3)
|
||||
|
||||
return return_encode(0, data)
|
||||
|
||||
|
||||
@bp.route('/users/<int:user_id>/b30', methods=['GET'])
|
||||
@api.api_auth.role_required(request, ['select', 'select_me'])
|
||||
def users_user_b30_get(user, user_id):
|
||||
# 查询用户b30
|
||||
|
||||
if user_id <= 0:
|
||||
return return_encode(-4)
|
||||
|
||||
if user_id != user.user_id and not 'select' in user.power and user.user_id != 0: # 查别人需要select权限
|
||||
return return_encode(-1, {}, 403, 'No permission')
|
||||
|
||||
data = users.get_user_b30(user_id)
|
||||
|
||||
if data['data'] == []:
|
||||
return return_encode(-3)
|
||||
|
||||
return return_encode(0, data)
|
||||
|
||||
|
||||
@bp.route('/users/<int:user_id>/best', methods=['GET'])
|
||||
@api.api_auth.role_required(request, ['select', 'select_me'])
|
||||
@get_query_parameter(request, ['song_id', 'difficulty'], [
|
||||
'song_id', 'difficulty', 'score', 'time_played', 'rating'])
|
||||
def users_user_best_get(query, user, user_id):
|
||||
# 查询用户所有best成绩
|
||||
|
||||
if user_id <= 0:
|
||||
return return_encode(-4)
|
||||
|
||||
if user_id != user.user_id and not 'select' in user.power and user.user_id != 0: # 查别人需要select权限
|
||||
return return_encode(-1, {}, 403, 'No permission')
|
||||
|
||||
data = users.get_user_best(user_id, query)
|
||||
|
||||
if data['data'] == []:
|
||||
return return_encode(-3)
|
||||
|
||||
return return_encode(0, data)
|
||||
|
||||
|
||||
@bp.route('/users/<int:user_id>/r30', methods=['GET'])
|
||||
@api.api_auth.role_required(request, ['select', 'select_me'])
|
||||
def users_user_r30_get(user, user_id):
|
||||
# 查询用户r30
|
||||
|
||||
if user_id <= 0:
|
||||
return return_encode(-4)
|
||||
|
||||
if user_id != user.user_id and not 'select' in user.power and user.user_id != 0: # 查别人需要select权限
|
||||
return return_encode(-1, {}, 403, 'No permission')
|
||||
|
||||
data = users.get_user_r30(user_id)
|
||||
|
||||
if data['data'] == []:
|
||||
return return_encode(-3)
|
||||
|
||||
return return_encode(0, data)
|
||||
|
||||
|
||||
@bp.route('/songs/<string:song_id>', methods=['GET'])
|
||||
@api.api_auth.role_required(request, ['select', 'select_song_info'])
|
||||
def songs_song_get(user, song_id):
|
||||
# 查询歌曲信息
|
||||
|
||||
data = api.songs.get_song_info(song_id)
|
||||
|
||||
if not data:
|
||||
return return_encode(-2)
|
||||
|
||||
return return_encode(0, data)
|
||||
|
||||
|
||||
@bp.route('/songs', methods=['GET'])
|
||||
@api.api_auth.role_required(request, ['select', 'select_song_info'])
|
||||
@get_query_parameter(request, ['sid', 'name_en', 'name_jp', 'pakset', 'artist'], [
|
||||
'sid', 'name_en', 'name_jp', 'pakset', 'artist', 'date', 'rating_pst', 'rating_prs', 'rating_ftr', 'rating_byn'])
|
||||
def songs_get(query, user):
|
||||
# 查询全歌曲信息
|
||||
|
||||
data = api.songs.get_songs(query)
|
||||
|
||||
if not data:
|
||||
return return_encode(-2)
|
||||
|
||||
return return_encode(0, data)
|
||||
2
latest version/api/constant.py
Normal file
2
latest version/api/constant.py
Normal file
@@ -0,0 +1,2 @@
|
||||
class Constant:
|
||||
QUERY_KEYS = ['limit', 'offset', 'query', 'fuzzy_query', 'sort']
|
||||
@@ -1,57 +1,48 @@
|
||||
from core.sql import Connect
|
||||
from core.sql import Sql
|
||||
from core.error import ArcError, NoData
|
||||
from core.song import Song
|
||||
from core.sql import Connect, Query, Sql
|
||||
from flask import Blueprint, request
|
||||
|
||||
from .api_auth import request_json_handle, role_required
|
||||
from .api_code import error_return, success_return
|
||||
from .constant import Constant
|
||||
|
||||
bp = Blueprint('songs', __name__, url_prefix='/songs')
|
||||
|
||||
|
||||
def get_song_info(song_id):
|
||||
# 查询指定歌曲信息,返回字典
|
||||
r = {}
|
||||
|
||||
with Connect('') as c:
|
||||
c.execute('''select * from chart where song_id=:a''', {'a': song_id})
|
||||
x = c.fetchone()
|
||||
if x:
|
||||
r = {'song_id': x[0],
|
||||
'name': {'name_en': x[1],
|
||||
'name_jp': x[2]},
|
||||
'pakset': x[5],
|
||||
'artist': x[6],
|
||||
'date': x[9],
|
||||
'rating_pst': x[13]/10,
|
||||
'rating_prs': x[14]/10,
|
||||
'rating_ftr': x[15]/10,
|
||||
'rating_byn': x[16]/10,
|
||||
'difficultly_pst': x[17]/2,
|
||||
'difficultly_prs': x[18]/2,
|
||||
'difficultly_ftr': x[19]/2,
|
||||
'difficultly_byn': x[20]/2
|
||||
}
|
||||
|
||||
return r
|
||||
@bp.route('/<string:song_id>', methods=['GET'])
|
||||
@role_required(request, ['select', 'select_song_info'])
|
||||
def songs_song_get(user, song_id):
|
||||
'''查询歌曲信息'''
|
||||
with Connect() as c:
|
||||
try:
|
||||
s = Song(c, song_id).select()
|
||||
return success_return(s.to_dict())
|
||||
except ArcError as e:
|
||||
return error_return(e)
|
||||
return error_return()
|
||||
|
||||
|
||||
def get_songs(query=None):
|
||||
# 查询全部歌曲信息,返回字典列表
|
||||
r = []
|
||||
|
||||
with Connect('') as c:
|
||||
x = Sql.select(c, 'chart', [], query)
|
||||
|
||||
if x:
|
||||
@bp.route('', methods=['GET'])
|
||||
@role_required(request, ['select', 'select_song_info'])
|
||||
@request_json_handle(request, optional_keys=Constant.QUERY_KEYS)
|
||||
def songs_get(data, user):
|
||||
'''查询全歌曲信息'''
|
||||
A = ['song_id', 'name']
|
||||
B = ['song_id', 'name', 'rating_pst',
|
||||
'rating_prs', 'rating_ftr', 'rating_byn']
|
||||
with Connect() as c:
|
||||
try:
|
||||
query = Query(A, A, B).from_data(data)
|
||||
x = Sql(c).select('chart', query=query)
|
||||
r = []
|
||||
for i in x:
|
||||
r.append({'sid': i[0],
|
||||
'name': {'name_en': i[1],
|
||||
'name_jp': i[2]},
|
||||
'pakset': i[5],
|
||||
'artist': i[6],
|
||||
'date': i[9],
|
||||
'rating_pst': i[13]/10,
|
||||
'rating_prs': i[14]/10,
|
||||
'rating_ftr': i[15]/10,
|
||||
'rating_byn': i[16]/10,
|
||||
'difficultly_pst': i[17]/2,
|
||||
'difficultly_prs': i[18]/2,
|
||||
'difficultly_ftr': i[19]/2,
|
||||
'difficultly_byn': i[20]/2
|
||||
})
|
||||
r.append(Song(c).from_list(i))
|
||||
|
||||
return r
|
||||
if not r:
|
||||
raise NoData(api_error_code=-2)
|
||||
|
||||
return success_return([x.to_dict() for x in r])
|
||||
except ArcError as e:
|
||||
return error_return(e)
|
||||
return error_return()
|
||||
|
||||
57
latest version/api/token.py
Normal file
57
latest version/api/token.py
Normal file
@@ -0,0 +1,57 @@
|
||||
from base64 import b64decode
|
||||
|
||||
from core.api_user import APIUser
|
||||
from core.error import ArcError, PostError
|
||||
from core.sql import Connect
|
||||
from flask import Blueprint, request
|
||||
|
||||
from .api_auth import request_json_handle, role_required
|
||||
from .api_code import error_return, success_return
|
||||
|
||||
bp = Blueprint('token', __name__, url_prefix='/token')
|
||||
|
||||
|
||||
@bp.route('', methods=['POST'])
|
||||
@request_json_handle(request, required_keys=['auth'])
|
||||
def token_post(data):
|
||||
'''
|
||||
登录,获取token\
|
||||
{'auth': base64('<user_id>:<password>')}
|
||||
'''
|
||||
try:
|
||||
auth_decode = bytes.decode(b64decode(data['auth']))
|
||||
except:
|
||||
return error_return(PostError(api_error_code=-100))
|
||||
if not ':' in auth_decode:
|
||||
return error_return(PostError(api_error_code=-100))
|
||||
name, password = auth_decode.split(':', 1)
|
||||
|
||||
with Connect() as c:
|
||||
try:
|
||||
user = APIUser(c)
|
||||
user.login(name, password, request.remote_addr)
|
||||
return success_return({'token': user.token, 'user_id': user.user_id})
|
||||
except ArcError as e:
|
||||
return error_return(e)
|
||||
return error_return()
|
||||
|
||||
|
||||
@bp.route('', methods=['GET'])
|
||||
@role_required(request, ['select_me', 'select'])
|
||||
def token_get(user):
|
||||
'''判断登录有效性'''
|
||||
return success_return()
|
||||
|
||||
|
||||
@bp.route('', methods=['DELETE'])
|
||||
@role_required(request, ['change_me', 'select_me', 'select'])
|
||||
def token_delete(user):
|
||||
'''登出'''
|
||||
with Connect() as c:
|
||||
try:
|
||||
user.c = c
|
||||
user.logout()
|
||||
return success_return()
|
||||
except ArcError as e:
|
||||
return error_return(e)
|
||||
return error_return()
|
||||
@@ -1,138 +1,150 @@
|
||||
from flask import (
|
||||
Blueprint, request
|
||||
)
|
||||
from core.error import ArcError, InputError, NoAccess, NoData
|
||||
from core.score import Potential, UserScoreList
|
||||
from core.sql import Connect, Query, Sql
|
||||
from core.user import UserInfo, UserRegister
|
||||
from flask import Blueprint, request
|
||||
|
||||
from .api_code import return_encode
|
||||
from .api_auth import role_required
|
||||
from core.user import UserRegister
|
||||
from core.error import ArcError, PostError
|
||||
from core.sql import Connect
|
||||
from core.sql import Sql
|
||||
import time
|
||||
import web.webscore
|
||||
import server.info
|
||||
from .api_auth import request_json_handle, role_required
|
||||
from .api_code import error_return, success_return
|
||||
from .constant import Constant
|
||||
|
||||
bp = Blueprint('users', __name__, url_prefix='/users')
|
||||
|
||||
|
||||
@bp.route('', methods=['POST'])
|
||||
@role_required(request, ['change'])
|
||||
def users_post(user):
|
||||
# 注册用户
|
||||
@request_json_handle(request, ['name', 'password', 'email'])
|
||||
def users_post(data, _):
|
||||
'''注册一个用户'''
|
||||
with Connect() as c:
|
||||
new_user = UserRegister(c)
|
||||
try:
|
||||
if 'name' in request.json:
|
||||
new_user.set_name(request.json['name'])
|
||||
else:
|
||||
raise PostError('No name provided.')
|
||||
|
||||
if 'password' in request.json:
|
||||
new_user.set_password(request.json['password'])
|
||||
else:
|
||||
raise PostError('No password provided.')
|
||||
|
||||
if 'email' in request.json:
|
||||
new_user.set_email(request.json['email'])
|
||||
else:
|
||||
raise PostError('No email provided.')
|
||||
|
||||
new_user.set_name(data['name'])
|
||||
new_user.set_password(data['password'])
|
||||
new_user.set_email(data['email'])
|
||||
new_user.register()
|
||||
return success_return({'user_id': new_user.user_id, 'user_code': new_user.user_code})
|
||||
except ArcError as e:
|
||||
return return_encode(e.api_error_code)
|
||||
|
||||
return return_encode(0, {'user_id': new_user.user_id, 'user_code': new_user.user_code})
|
||||
return error_return(e)
|
||||
return error_return()
|
||||
|
||||
|
||||
def get_users(query=None):
|
||||
# 获取全用户信息,返回字典列表
|
||||
|
||||
r = []
|
||||
@bp.route('', methods=['GET'])
|
||||
@role_required(request, ['select'])
|
||||
@request_json_handle(request, optional_keys=Constant.QUERY_KEYS)
|
||||
def users_get(data, user):
|
||||
'''查询全用户信息'''
|
||||
A = ['user_id', 'name', 'user_code']
|
||||
B = ['user_id', 'name', 'user_code', 'join_date',
|
||||
'rating_ptt', 'time_played', 'ticket', 'world_rank_score']
|
||||
with Connect() as c:
|
||||
x = Sql.select(c, 'user', [], query)
|
||||
|
||||
if x:
|
||||
try:
|
||||
query = Query(A, A, B).from_data(data)
|
||||
x = Sql(c).select('user', query=query)
|
||||
r = []
|
||||
for i in x:
|
||||
if i[23] != -1:
|
||||
character_id = i[23]
|
||||
else:
|
||||
character_id = i[6]
|
||||
r.append({
|
||||
'user_id': i[0],
|
||||
'name': i[1],
|
||||
'join_date': i[3],
|
||||
'user_code': i[4],
|
||||
'rating_ptt': i[5]/100,
|
||||
'character_id': character_id,
|
||||
'is_char_uncapped': i[8] == 1,
|
||||
'is_char_uncapped_override': i[9] == 1,
|
||||
'is_hide_rating': i[10],
|
||||
'ticket': i[26]
|
||||
})
|
||||
r.append(UserInfo(c).from_list(i))
|
||||
|
||||
return r
|
||||
if not r:
|
||||
raise NoData(api_error_code=-2)
|
||||
|
||||
return success_return([{
|
||||
'user_id': x.user_id,
|
||||
'name': x.name,
|
||||
'join_date': x.join_date,
|
||||
'user_code': x.user_code,
|
||||
'rating_ptt': x.rating_ptt/100,
|
||||
'character_id': x.character.character_id,
|
||||
'is_char_uncapped': x.character.is_uncapped,
|
||||
'is_char_uncapped_override': x.character.is_uncapped_override,
|
||||
'is_hide_rating': x.is_hide_rating,
|
||||
'ticket': x.ticket
|
||||
} for x in r])
|
||||
except ArcError as e:
|
||||
return error_return(e)
|
||||
return error_return()
|
||||
|
||||
|
||||
def get_user_info(user_id):
|
||||
# 获取用户信息,返回字典,其实就是调用user/me信息
|
||||
@bp.route('/<int:user_id>', methods=['GET'])
|
||||
@role_required(request, ['select', 'select_me'])
|
||||
def users_user_get(user, user_id):
|
||||
'''查询用户信息'''
|
||||
if user_id <= 0:
|
||||
return error_return(InputError(api_error_code=-4))
|
||||
# 查别人需要select权限
|
||||
if user_id != user.user_id and user.user_id != 0 and not user.role.has_power('select'):
|
||||
return error_return(NoAccess('No permission', api_error_code=-1), 403)
|
||||
|
||||
r = {}
|
||||
with Connect() as c:
|
||||
r = server.info.get_user_me(c, user_id)
|
||||
|
||||
return r
|
||||
try:
|
||||
u = UserInfo(c, user_id)
|
||||
return success_return(u.to_dict())
|
||||
except ArcError as e:
|
||||
return error_return(e)
|
||||
return error_return()
|
||||
|
||||
|
||||
def get_user_b30(user_id):
|
||||
# 获取用户b30信息,返回字典
|
||||
@bp.route('/<int:user_id>/b30', methods=['GET'])
|
||||
@role_required(request, ['select', 'select_me'])
|
||||
def users_user_b30_get(user, user_id):
|
||||
'''查询用户b30'''
|
||||
if user_id <= 0:
|
||||
return error_return(InputError(api_error_code=-4))
|
||||
# 查别人需要select权限
|
||||
if user_id != user.user_id and user.user_id != 0 and not user.role.has_power('select'):
|
||||
return error_return(NoAccess('No permission', api_error_code=-1), 403)
|
||||
|
||||
r = []
|
||||
with Connect() as c:
|
||||
r = web.webscore.get_user_score(c, user_id, 30)
|
||||
|
||||
bestptt = 0
|
||||
for i in r:
|
||||
if i['rating']:
|
||||
bestptt += i['rating']
|
||||
if 'time_played' in i:
|
||||
i['time_played'] = int(time.mktime(time.strptime(
|
||||
i['time_played'], '%Y-%m-%d %H:%M:%S')))
|
||||
|
||||
return {'user_id': user_id, 'b30_ptt': bestptt / 30, 'data': r}
|
||||
try:
|
||||
x = UserScoreList(c, UserInfo(c, user_id))
|
||||
x.query.limit = 30
|
||||
x.select_from_user()
|
||||
r = x.to_dict_list()
|
||||
rating_sum = sum([i.rating for i in x.scores])
|
||||
return success_return({'user_id': user_id, 'b30_ptt': rating_sum / 30, 'data': r})
|
||||
except ArcError as e:
|
||||
return error_return(e)
|
||||
return error_return()
|
||||
|
||||
|
||||
def get_user_best(user_id, query=None):
|
||||
# 获取用户b30信息,返回字典
|
||||
@bp.route('/<int:user_id>/best', methods=['GET'])
|
||||
@role_required(request, ['select', 'select_me'])
|
||||
@request_json_handle(request, optional_keys=Constant.QUERY_KEYS)
|
||||
def users_user_best_get(data, user, user_id):
|
||||
'''查询用户所有best成绩'''
|
||||
if user_id <= 0:
|
||||
return error_return(InputError(api_error_code=-4))
|
||||
# 查别人需要select权限
|
||||
if user_id != user.user_id and user.user_id != 0 and not user.role.has_power('select'):
|
||||
return error_return(NoAccess('No permission', api_error_code=-1), 403)
|
||||
|
||||
r = []
|
||||
with Connect() as c:
|
||||
x = Sql.select(c, 'best_score', [], query)
|
||||
if x:
|
||||
for i in x:
|
||||
r.append({
|
||||
"song_id": i[1],
|
||||
"difficulty": i[2],
|
||||
"score": i[3],
|
||||
"shiny_perfect_count": i[4],
|
||||
"perfect_count": i[5],
|
||||
"near_count": i[6],
|
||||
"miss_count": i[7],
|
||||
"health": i[8],
|
||||
"modifier": i[9],
|
||||
"time_played": i[10],
|
||||
"best_clear_type": i[11],
|
||||
"clear_type": i[12],
|
||||
"rating": i[13]
|
||||
})
|
||||
|
||||
return {'user_id': user_id, 'data': r}
|
||||
try:
|
||||
x = UserScoreList(c, UserInfo(c, user_id))
|
||||
x.query.from_data(data)
|
||||
x.select_from_user()
|
||||
r = x.to_dict_list()
|
||||
return success_return({'user_id': user_id, 'data': r})
|
||||
except ArcError as e:
|
||||
return error_return(e)
|
||||
return error_return()
|
||||
|
||||
|
||||
def get_user_r30(user_id):
|
||||
# 获取用户r30信息,返回字典
|
||||
@bp.route('/<int:user_id>/r30', methods=['GET'])
|
||||
@role_required(request, ['select', 'select_me'])
|
||||
def users_user_r30_get(user, user_id):
|
||||
'''查询用户r30'''
|
||||
|
||||
if user_id <= 0:
|
||||
return error_return(InputError(api_error_code=-4))
|
||||
# 查别人需要select权限
|
||||
if user_id != user.user_id and user.user_id != 0 and not user.role.has_power('select'):
|
||||
return error_return(NoAccess('No permission', api_error_code=-1), 403)
|
||||
|
||||
r = []
|
||||
with Connect() as c:
|
||||
r, r10_ptt = web.webscore.get_user_recent30(c, user_id)
|
||||
|
||||
return {'user_id': user_id, 'r10_ptt': r10_ptt, 'data': r}
|
||||
try:
|
||||
p = Potential(c, UserInfo(c, user_id))
|
||||
return success_return({'user_id': user_id, 'r10_ptt': p.recent_10 / 10, 'data': p.recent_30_to_dict_list()})
|
||||
except ArcError as e:
|
||||
return error_return(e)
|
||||
return error_return()
|
||||
|
||||
Reference in New Issue
Block a user