로그인 상태 유지와 다마고치 수정 화면 정리
This commit is contained in:
1 parent
80d332a79c
commit
40615838ac
33 files changed
+248
-73
No files matched your search
+20
-12
@@ -65,11 +65,14 @@ class Members:
|
||||
def session(self, handler, user, extra=None):
|
||||
token = secrets.token_hex(32)
|
||||
with self.db() as db:
|
||||
name = db.execute('SELECT username FROM users WHERE id=?', (user,)).fetchone()['username']
|
||||
lifetime = 28800 if name == self.config()['username'].lower() else 604800
|
||||
db.execute('DELETE FROM sessions WHERE expires<?', (time.time(),))
|
||||
db.execute('INSERT INTO sessions VALUES(?,?,?)', (hashlib.sha256(token.encode()).hexdigest(), user, time.time() + 7 * 86400))
|
||||
handler.reply(200, dict(ok=True, **(extra or {})), headers={'Set-Cookie': f'{COOKIE}={token}; Path=/api; HttpOnly; Secure; SameSite=Strict; Max-Age=604800'})
|
||||
db.execute('INSERT INTO sessions VALUES(?,?,?)', (hashlib.sha256(token.encode()).hexdigest(), user, time.time() + lifetime))
|
||||
handler.clear_admin_session()
|
||||
handler.reply(200, dict(ok=True, **(extra or {})), headers={'Set-Cookie': [f'{COOKIE}={token}; Path=/api; HttpOnly; Secure; SameSite=Strict; Max-Age={lifetime}', 'tama_admin=; Path=/api; HttpOnly; Secure; SameSite=Strict; Max-Age=0']})
|
||||
|
||||
def rate(self, handler, action):
|
||||
def rate(self, handler, action, limit=None):
|
||||
ip = handler.headers.get('X-Real-IP', handler.client_address[0])
|
||||
key = (ip, action)
|
||||
with self.lock:
|
||||
@@ -78,7 +81,7 @@ class Members:
|
||||
if not self.attempts[k]:
|
||||
del self.attempts[k]
|
||||
attempts = self.attempts.setdefault(key, [])
|
||||
if len(attempts) >= (5 if action == 'register' else 12) or len(self.attempts) > 10000:
|
||||
if len(attempts) >= (limit or (5 if action == 'register' else 12)) or len(self.attempts) > 10000:
|
||||
handler.reply(429, {'error': '시도가 많습니다. 15분 뒤 다시 시도하세요.'})
|
||||
return False
|
||||
attempts.append(time.time())
|
||||
@@ -133,11 +136,11 @@ class Members:
|
||||
h.reply(200, row['data'], 'application/octet-stream', {'Content-Disposition': 'attachment; filename="paradise-personal-' + row['sha'][:12] + '.bin"'}); return
|
||||
h.reply(404, {'error': '페이지가 없습니다.'})
|
||||
|
||||
def post(self, h, path):
|
||||
def post(self, h, path, admin_only=False):
|
||||
public = path in ['/api/member/register', '/api/member/login', '/api/member/recover']
|
||||
admin = path.startswith('/api/admin/')
|
||||
user = self.user(h)
|
||||
if (admin and not h.authorized()) or (not admin and not public and not user):
|
||||
if (admin and not h.authorized()) or (not admin and not public and not user and path != '/api/member/logout'):
|
||||
h.close_connection = True
|
||||
h.reply(401, {'error': '로그인이 필요합니다.'}); return
|
||||
if path == '/api/member/files':
|
||||
@@ -178,10 +181,12 @@ class Members:
|
||||
raise ValueError('요청 형식이 잘못되었습니다.')
|
||||
if public:
|
||||
action = path.rsplit('/', 1)[1]
|
||||
if not self.rate(h, action): return
|
||||
username = self.username(body.get('username'))
|
||||
if not self.rate(h, action, 8 if admin_only else None): return
|
||||
cfg = self.config()
|
||||
is_admin = username == cfg['username'].lower()
|
||||
supplied_name = body.get('username')
|
||||
normalized = supplied_name.strip().lower() if isinstance(supplied_name, str) else ''
|
||||
is_admin = normalized == cfg['username'].lower()
|
||||
username = normalized if is_admin else self.username(normalized)
|
||||
if action == 'register':
|
||||
password = self.password(body.get('password'))
|
||||
if is_admin: raise ValueError('예약된 관리자 아이디입니다.')
|
||||
@@ -206,12 +211,14 @@ class Members:
|
||||
raise ValueError('아이디 또는 비밀번호가 다릅니다.')
|
||||
stored = cfg['passwordHash'] if is_admin else record['password'] if record else cfg['passwordHash']
|
||||
valid = self.check_password(supplied, stored)
|
||||
if not valid or (not is_admin and not record) or (record and record['disabled']):
|
||||
raise ValueError('아이디 또는 비밀번호가 다르거나 사용할 수 없는 계정입니다.')
|
||||
if not valid or (admin_only and not is_admin) or (not is_admin and not record) or (record and record['disabled']):
|
||||
h.reply(401, {'error': '아이디 또는 비밀번호가 다르거나 사용할 수 없는 계정입니다.'}); return
|
||||
if is_admin and not record:
|
||||
with self.db() as db:
|
||||
db.execute('INSERT OR IGNORE INTO users(id,username,password,recovery,created) VALUES(?,?,?,?,?)', (secrets.token_hex(16), username, '', '', self.now()))
|
||||
record = db.execute('SELECT * FROM users WHERE username=?', (username,)).fetchone()
|
||||
with self.lock:
|
||||
self.attempts.pop((h.headers.get('X-Real-IP', h.client_address[0]), 'login'), None)
|
||||
self.session(h, record['id']); return
|
||||
password = self.password(body.get('newPassword'))
|
||||
code = body.get('recoveryCode', '')
|
||||
@@ -228,7 +235,8 @@ class Members:
|
||||
self.session(h, record['id'], {'recoveryCode': recovery}); return
|
||||
if path == '/api/member/logout':
|
||||
with self.db() as db: db.execute('DELETE FROM sessions WHERE token=?', (self.token(h),))
|
||||
h.reply(200, {'ok': True}, headers={'Set-Cookie': COOKIE + '=; Path=/api; HttpOnly; Secure; SameSite=Strict; Max-Age=0'}); return
|
||||
h.clear_admin_session()
|
||||
h.reply(200, {'ok': True}, headers={'Set-Cookie': [name + '=; Path=/api; HttpOnly; Secure; SameSite=Strict; Max-Age=0' for name in [COOKIE, 'tama_admin']]}); return
|
||||
if path == '/api/member/file':
|
||||
with self.db() as db:
|
||||
if body.get('action') == 'delete':
|
||||
|
||||
Reference in new issue
Block a user