42 lines
990 B
Python
42 lines
990 B
Python
from __future__ import annotations
|
|
|
|
import ipaddress
|
|
|
|
from itsdangerous import BadSignature, URLSafeTimedSerializer
|
|
|
|
from backend.config import settings
|
|
|
|
MAX_AGE = 60 * 60 * 24 * 30 # 30 days
|
|
|
|
|
|
def _serializer() -> URLSafeTimedSerializer:
|
|
return URLSafeTimedSerializer(settings.secret_key, salt="snotes-auth")
|
|
|
|
|
|
def is_lan(ip: str | None) -> bool:
|
|
if not ip:
|
|
return False
|
|
try:
|
|
addr = ipaddress.ip_address(ip)
|
|
except ValueError:
|
|
return False
|
|
for cidr in settings.cidr_list:
|
|
if addr in ipaddress.ip_network(cidr, strict=False):
|
|
return True
|
|
return False
|
|
|
|
|
|
def remote_password_ok(password: str) -> bool:
|
|
return bool(settings.remote_pass) and password == settings.remote_pass
|
|
|
|
|
|
def issue_auth_cookie() -> str:
|
|
return _serializer().dumps("authed")
|
|
|
|
|
|
def check_auth_cookie(token: str) -> bool:
|
|
try:
|
|
return _serializer().loads(token, max_age=MAX_AGE) == "authed"
|
|
except BadSignature:
|
|
return False
|