2023-08-26 15:41:11 +12:00
|
|
|
import random
|
2024-10-21 16:14:34 +13:00
|
|
|
from datetime import timedelta
|
2024-01-15 17:26:57 +13:00
|
|
|
from unicodedata import normalize
|
2023-08-26 15:41:11 +12:00
|
|
|
|
2024-08-01 16:24:36 +08:00
|
|
|
from flask import current_app
|
|
|
|
|
|
|
|
from app import cache
|
2024-10-21 16:14:34 +13:00
|
|
|
from app.models import Site, utcnow
|
2024-09-15 19:30:45 +12:00
|
|
|
from app.utils import get_request
|
2024-08-01 16:24:36 +08:00
|
|
|
|
2023-08-26 15:41:11 +12:00
|
|
|
|
|
|
|
# Return a random string of 6 letter/digits.
|
|
|
|
def random_token(length=6) -> str:
|
|
|
|
return "".join(
|
|
|
|
[random.choice('0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ') for x in range(length)])
|
2024-01-15 17:26:57 +13:00
|
|
|
|
|
|
|
|
|
|
|
def normalize_utf(username):
|
|
|
|
return normalize('NFKC', username)
|
2024-08-01 16:24:36 +08:00
|
|
|
|
|
|
|
|
|
|
|
def ip2location(ip: str):
|
|
|
|
""" city, region and country for the requester, using the ipinfo.io service """
|
|
|
|
if ip is None or ip == '':
|
|
|
|
return {}
|
|
|
|
ip = '208.97.120.117' if ip == '127.0.0.1' else ip
|
|
|
|
# test
|
|
|
|
data = cache.get('ip_' + ip)
|
|
|
|
if data is None:
|
|
|
|
if not current_app.config['IPINFO_TOKEN']:
|
|
|
|
return {}
|
|
|
|
url = 'http://ipinfo.io/' + ip + '?token=' + current_app.config['IPINFO_TOKEN']
|
2024-09-15 19:30:45 +12:00
|
|
|
response = get_request(url)
|
2024-08-01 16:24:36 +08:00
|
|
|
if response.status_code == 200:
|
|
|
|
data = response.json()
|
|
|
|
cache.set('ip_' + ip, data, timeout=86400)
|
|
|
|
else:
|
|
|
|
return {}
|
|
|
|
|
|
|
|
if 'postal' in data:
|
|
|
|
postal = data['postal']
|
|
|
|
else:
|
|
|
|
postal = ''
|
|
|
|
return {'city': data['city'], 'region': data['region'], 'country': data['country'], 'postal': postal,
|
|
|
|
'timezone': data['timezone']}
|
2024-10-21 16:14:34 +13:00
|
|
|
|
|
|
|
|
|
|
|
def no_admins_logged_in_recently():
|
|
|
|
a_week_ago = utcnow() - timedelta(days=7)
|
|
|
|
for user in Site.admins():
|
|
|
|
if user.last_seen > a_week_ago:
|
|
|
|
return False
|
|
|
|
|
|
|
|
for user in Site.staff():
|
|
|
|
if user.last_seen > a_week_ago:
|
|
|
|
return False
|
|
|
|
|
|
|
|
return True
|