로그인 상태 유지와 다마고치 수정 화면 정리
This commit is contained in:
1 parent
80d332a79c
commit
40615838ac
33 files changed
+248
-73
No files matched your search
+15
-27
@@ -149,11 +149,15 @@ class Handler(BaseHTTPRequestHandler):
|
||||
self.send_header('X-Content-Type-Options', 'nosniff')
|
||||
self.send_header('X-Robots-Tag', 'noindex')
|
||||
for key, val in (headers or {}).items():
|
||||
self.send_header(key, val)
|
||||
for value in val if isinstance(val, list) else [val]:
|
||||
self.send_header(key, value)
|
||||
self.end_headers()
|
||||
self.wfile.write(body)
|
||||
|
||||
def authorized(self):
|
||||
user = members().user(self)
|
||||
if user and user['username'] == config()['username'].lower():
|
||||
return True
|
||||
cookie = self.headers.get('Cookie', '')
|
||||
match = re.search(r'(?:^|;\s*)tama_admin=([a-f0-9]{64})(?:;|$)', cookie)
|
||||
token = match.group(1) if match else None
|
||||
@@ -163,6 +167,12 @@ class Handler(BaseHTTPRequestHandler):
|
||||
del SESSIONS[key]
|
||||
return bool(token and token in SESSIONS)
|
||||
|
||||
def clear_admin_session(self):
|
||||
match = re.search(r'(?:^|;\s*)tama_admin=([a-f0-9]{64})(?:;|$)', self.headers.get('Cookie', ''))
|
||||
with LOCK:
|
||||
if match:
|
||||
SESSIONS.pop(match[1], None)
|
||||
|
||||
def body(self, limit):
|
||||
if self.headers.get('Transfer-Encoding'):
|
||||
raise ValueError('지원하지 않는 전송 방식입니다.')
|
||||
@@ -236,6 +246,10 @@ class Handler(BaseHTTPRequestHandler):
|
||||
|
||||
def post(self):
|
||||
path = self.path
|
||||
if path == '/api/login':
|
||||
return members().post(self, '/api/member/login', admin_only=True)
|
||||
if path == '/api/admin/logout':
|
||||
return members().post(self, '/api/member/logout')
|
||||
if path.startswith('/api/member/') or path == '/api/admin/members':
|
||||
return members().post(self, path)
|
||||
if path == '/api/device-backups':
|
||||
@@ -257,32 +271,6 @@ class Handler(BaseHTTPRequestHandler):
|
||||
self.close_connection = True
|
||||
return self.reply(401, {'error': '관리자 로그인이 필요합니다.'})
|
||||
body = json.loads(self.body(4096))
|
||||
if path == '/api/login':
|
||||
ip = self.headers.get('X-Real-IP', self.client_address[0])
|
||||
with LOCK:
|
||||
# Bound the table as well as the number of guesses per client.
|
||||
for key in list(ATTEMPTS):
|
||||
ATTEMPTS[key] = [t for t in ATTEMPTS[key] if t > time.time() - 900]
|
||||
if not ATTEMPTS[key]:
|
||||
del ATTEMPTS[key]
|
||||
tries = ATTEMPTS.setdefault(ip, [])
|
||||
if len(tries) >= 8 or len(ATTEMPTS) > 10000:
|
||||
return self.reply(429, {'error': '로그인 시도가 많습니다. 15분 뒤 다시 시도하세요.'})
|
||||
cfg = config()
|
||||
if body.get('username') != cfg['username'] or not password_ok(str(body.get('password', '')), cfg['passwordHash']):
|
||||
tries.append(time.time())
|
||||
return self.reply(401, {'error': '아이디 또는 비밀번호가 다릅니다.'})
|
||||
ATTEMPTS.pop(ip, None)
|
||||
token = secrets.token_hex(32)
|
||||
SESSIONS[token] = time.time() + 28800
|
||||
return self.reply(200, {'ok': True}, headers={'Set-Cookie': 'tama_admin=' + token + '; Path=/api; HttpOnly; Secure; SameSite=Strict; Max-Age=28800'})
|
||||
if path == '/api/admin/logout':
|
||||
cookie = self.headers.get('Cookie', '')
|
||||
match = re.search(r'tama_admin=([a-f0-9]{64})', cookie)
|
||||
with LOCK:
|
||||
if match:
|
||||
SESSIONS.pop(match.group(1), None)
|
||||
return self.reply(200, {'ok': True}, headers={'Set-Cookie': 'tama_admin=; Path=/api; HttpOnly; Secure; SameSite=Strict; Max-Age=0'})
|
||||
if path == '/api/admin/settings':
|
||||
with LOCK:
|
||||
cfg = config()
|
||||
|
||||
+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