MarseyWorld/files/routes/wrappers.py

189 lines
5.9 KiB
Python
Raw Normal View History

2022-07-29 22:07:08 +00:00
import time
2023-06-29 15:56:16 +00:00
import secrets
import user_agents
[DO NOT MERGE] import detanglation (#442) * move Base definition to files.classes.__init__.py * fix ImportError * move userpage listing to users.py * don't import the app from classes * consts: set default values to avoid crashes consts: warn if the secret key is the default config value * card view: sneed (user db schema) * cloudflare: use DEFAULT_CONFIG_VALUE * const: set default values * decouple media.py from __main__ * pass database to avoid imports * import cleanup and import request not in const, but in the requests mega import * move asset_submissions site check to __init__ * asset submissions feature flag * flag * g.is_tor * don't import request where it's not needed * i think this is fine * mail: move to own routes and helper * wrappers * required wrappers move * unfuck wrappers a bit * move snappy quotes and marseys to stateful consts * marsify * :pepodrool: * fix missing import * import cache * ...and settings.py * and static.py * static needs cache * route * lmao all of the jinja shit was in feeds.py amazing * classes should only import what they need from flask * import Response * hdjbjdhbhjf * ... * dfdfdfdf * make get a non-required import * isort imports (mostly) * but actually * configs * reload config on import * fgfgfgfg * config * config * initialize snappy and test * cookie of doom debug * edfjnkf * xikscdfd * debug config * set session cookie domain, i think this fixes the can't login bug * sdfbgnhvfdsghbnjfbdvvfghnn * hrsfxgf * dump the entire config on a request * kyskyskyskyskyskyskyskyskys * duifhdskfjdfd * dfdfdfdfdfdfdfdfdfdfdfdf * dfdfdfdf * imoprt all of the consts beacuse fuck it * 😭 * dfdfdfdfdfdfsdasdf * print the entire session * rffdfdfjkfksj * fgbhffh * not the secret keys * minor bug fixes * be helpful in the warning * gfgfgfg * move warning lower * isort main imports (i hope this doesn't fuck something up) * test * session cookie domain redux * dfdfdfd * try only importing Flask * formkeys fix * y * :pepodrool: * route helper * remove before flight * dfdfdfdfdf * isort classes * isort helpers * move check_for_alts to routehelpers and also sort imports and get rid of unused ones * that previous commit but actkally * readd the cache in a dozen places they were implicitly imported * use g.is_tor instead of request.headers. bla bla bla * upgrade streamers to their own route file * get rid of unused imports in __main__ * fgfgf * don't pull in the entire ORM where we don't need it * features * explicit imports for the get helper * explicit imports for the get helper redux * testing allroutes * remove unused import * decouple flask from classes * syntax fix also remember these have side fx for some reason (why?) * move side effects out of the class * posts * testing on devrama * settings * reloading * settingssdsdsds * streamer features * site settings * testing settings on devrama * import * fix modlog * remove debug stuff * revert commit 67275b21ab6e2f2520819e84d10bfc1c746a15b6 * archiveorg to _archiveorg * skhudkfkjfd * fix cron for PCM * fix bugs that snekky wants me to * Fix call to realbody passing db, standardize kwarg * test * import check_for_alts from the right place * cloudflare * testing on devrama * fix cron i think * shadow properly * tasks * Remove print which will surely be annoying in prod. * v and create new session * use files.classes * make errors import little and fix rare 500 in /allow_nsfw * Revert "use files.classes" This reverts commit 98c10b876cf86ce058b7fb955cf1ec0bfb9996c6. * pass v to media functions rather than using g * fix * dfdfdfdfd * cleanup, py type checking is dumb so don't use it where it causes issues * Fix some merge bugs, add DEFAULT_RATELIMIT to main. * Fix imports on sqlalchemy expressions. * `from random import random` is an error. * Fix replies db param. * errors: fix missing import * fix rare 500: only send to GIFT_NOTIF_ID if it exists, and send them the right text * Fix signup formkey. * fix 2 500s * propagate db to submissions * fix replies * dfdfdfdf * Fix verifiedcolor. * is_manual * can't use getters outside of an app context * don't attempt to do gumroad on sites where it's not enabled * don't attempt to do gumraod on sites's where it's unnecessary * Revert "don't attempt to do gumroad on sites where it's not enabled" This reverts commit 6f8a6331878655492dfaf1907b27f8be513c14d3. * fix 500 * validate media type Co-authored-by: TLSM <duolsm@outlook.com>
2022-11-15 09:19:08 +00:00
from flask import g, request, session
from files.classes.clients import ClientAuth
from files.helpers.alerts import *
from files.helpers.config.const import *
[DO NOT MERGE] import detanglation (#442) * move Base definition to files.classes.__init__.py * fix ImportError * move userpage listing to users.py * don't import the app from classes * consts: set default values to avoid crashes consts: warn if the secret key is the default config value * card view: sneed (user db schema) * cloudflare: use DEFAULT_CONFIG_VALUE * const: set default values * decouple media.py from __main__ * pass database to avoid imports * import cleanup and import request not in const, but in the requests mega import * move asset_submissions site check to __init__ * asset submissions feature flag * flag * g.is_tor * don't import request where it's not needed * i think this is fine * mail: move to own routes and helper * wrappers * required wrappers move * unfuck wrappers a bit * move snappy quotes and marseys to stateful consts * marsify * :pepodrool: * fix missing import * import cache * ...and settings.py * and static.py * static needs cache * route * lmao all of the jinja shit was in feeds.py amazing * classes should only import what they need from flask * import Response * hdjbjdhbhjf * ... * dfdfdfdf * make get a non-required import * isort imports (mostly) * but actually * configs * reload config on import * fgfgfgfg * config * config * initialize snappy and test * cookie of doom debug * edfjnkf * xikscdfd * debug config * set session cookie domain, i think this fixes the can't login bug * sdfbgnhvfdsghbnjfbdvvfghnn * hrsfxgf * dump the entire config on a request * kyskyskyskyskyskyskyskyskys * duifhdskfjdfd * dfdfdfdfdfdfdfdfdfdfdfdf * dfdfdfdf * imoprt all of the consts beacuse fuck it * 😭 * dfdfdfdfdfdfsdasdf * print the entire session * rffdfdfjkfksj * fgbhffh * not the secret keys * minor bug fixes * be helpful in the warning * gfgfgfg * move warning lower * isort main imports (i hope this doesn't fuck something up) * test * session cookie domain redux * dfdfdfd * try only importing Flask * formkeys fix * y * :pepodrool: * route helper * remove before flight * dfdfdfdfdf * isort classes * isort helpers * move check_for_alts to routehelpers and also sort imports and get rid of unused ones * that previous commit but actkally * readd the cache in a dozen places they were implicitly imported * use g.is_tor instead of request.headers. bla bla bla * upgrade streamers to their own route file * get rid of unused imports in __main__ * fgfgf * don't pull in the entire ORM where we don't need it * features * explicit imports for the get helper * explicit imports for the get helper redux * testing allroutes * remove unused import * decouple flask from classes * syntax fix also remember these have side fx for some reason (why?) * move side effects out of the class * posts * testing on devrama * settings * reloading * settingssdsdsds * streamer features * site settings * testing settings on devrama * import * fix modlog * remove debug stuff * revert commit 67275b21ab6e2f2520819e84d10bfc1c746a15b6 * archiveorg to _archiveorg * skhudkfkjfd * fix cron for PCM * fix bugs that snekky wants me to * Fix call to realbody passing db, standardize kwarg * test * import check_for_alts from the right place * cloudflare * testing on devrama * fix cron i think * shadow properly * tasks * Remove print which will surely be annoying in prod. * v and create new session * use files.classes * make errors import little and fix rare 500 in /allow_nsfw * Revert "use files.classes" This reverts commit 98c10b876cf86ce058b7fb955cf1ec0bfb9996c6. * pass v to media functions rather than using g * fix * dfdfdfdfd * cleanup, py type checking is dumb so don't use it where it causes issues * Fix some merge bugs, add DEFAULT_RATELIMIT to main. * Fix imports on sqlalchemy expressions. * `from random import random` is an error. * Fix replies db param. * errors: fix missing import * fix rare 500: only send to GIFT_NOTIF_ID if it exists, and send them the right text * Fix signup formkey. * fix 2 500s * propagate db to submissions * fix replies * dfdfdfdf * Fix verifiedcolor. * is_manual * can't use getters outside of an app context * don't attempt to do gumroad on sites where it's not enabled * don't attempt to do gumraod on sites's where it's unnecessary * Revert "don't attempt to do gumroad on sites where it's not enabled" This reverts commit 6f8a6331878655492dfaf1907b27f8be513c14d3. * fix 500 * validate media type Co-authored-by: TLSM <duolsm@outlook.com>
2022-11-15 09:19:08 +00:00
from files.helpers.get import get_account
2022-11-30 18:09:31 +00:00
from files.helpers.logging import log_file
2023-06-29 16:14:24 +00:00
from files.helpers.settings import *
from files.helpers.cloudflare import *
2023-08-02 07:47:49 +00:00
from files.routes.routehelpers import validate_formkey, check_session_id
from files.__main__ import app, limiter
2023-02-26 08:49:09 +00:00
def rpath(n):
2023-02-26 01:42:39 +00:00
return request.path
2023-01-21 04:39:46 +00:00
def get_ID():
if request.headers.get("Authorization"):
x = request.headers.get("Authorization")
elif session.get("lo_user"):
x = session.get("lo_user")
else:
2023-08-15 12:53:52 +00:00
check_session_id()
x = f"logged_out-{session['session_id']}"
2023-02-22 17:27:33 +00:00
2023-01-21 04:39:46 +00:00
return f'{SITE}-{x}'
2023-06-29 15:56:16 +00:00
def calc_users():
g.loggedin_counter = 0
g.loggedout_counter = 0
g.loggedin_chat = 0
v = getattr(g, 'v', None) if g else None
2023-07-14 09:20:33 +00:00
if has_request_context and g and g.desires_auth and not g.is_api_or_xhr:
loggedin = cache.get(LOGGED_IN_CACHE_KEY) or {}
loggedout = cache.get(LOGGED_OUT_CACHE_KEY) or {}
2023-09-17 20:58:08 +00:00
g.loggedin_chat = cache.get('loggedin_chat') or 0
2023-07-14 09:20:33 +00:00
timestamp = int(time.time())
2023-06-29 15:56:16 +00:00
2023-08-02 07:47:49 +00:00
check_session_id()
2023-06-29 15:56:16 +00:00
2023-07-14 09:20:33 +00:00
if v:
if session["session_id"] in loggedout: del loggedout[session["session_id"]]
loggedin[v.id] = timestamp
else:
ua = str(user_agents.parse(g.agent))
if 'spider' not in ua.lower() and 'bot' not in ua.lower():
loggedout[session["session_id"]] = (timestamp, ua)
2023-06-29 15:56:16 +00:00
2023-07-14 09:20:33 +00:00
loggedin = {k: v for k, v in loggedin.items() if (timestamp - v) < LOGGEDIN_ACTIVE_TIME}
loggedout = {k: v for k, v in loggedout.items() if (timestamp - v[0]) < LOGGEDIN_ACTIVE_TIME}
cache.set(LOGGED_IN_CACHE_KEY, loggedin, timeout=86400)
cache.set(LOGGED_OUT_CACHE_KEY, loggedout, timeout=86400)
2023-07-14 09:20:33 +00:00
g.loggedin_counter = len(loggedin)
g.loggedout_counter = len(loggedout)
2023-06-29 15:56:16 +00:00
2024-09-26 09:38:54 +00:00
if SITE != 'watchpeopledie.tv':
if g.loggedin_counter + g.loggedout_counter > 2000:
if not get_setting('under_attack'):
set_setting('under_attack', True)
set_security_level('under_attack')
else:
if get_setting('under_attack'):
set_setting('under_attack', False)
set_security_level('high')
2024-05-16 22:51:07 +00:00
2023-07-07 20:46:49 +00:00
return ''
2023-06-29 15:56:16 +00:00
2022-05-04 23:09:46 +00:00
def get_logged_in_user():
2023-03-11 09:56:32 +00:00
if hasattr(g, 'v') and g.v: return g.v
g.desires_auth = True
2022-05-04 23:09:46 +00:00
v = None
token = request.headers.get("Authorization","").strip()
if token:
2023-03-16 06:27:58 +00:00
client = g.db.query(ClientAuth).filter(ClientAuth.access_token == token).one_or_none()
2023-01-01 11:36:20 +00:00
if client:
2022-05-04 23:09:46 +00:00
v = client.user
v.client = client
else:
lo_user = session.get("lo_user")
if lo_user:
id = int(lo_user)
v = get_account(id, graceful=True)
2022-11-28 01:48:53 +00:00
if v:
2022-11-28 19:41:08 +00:00
v.client = None
2022-05-04 23:09:46 +00:00
nonce = session.get("login_nonce", 0)
if nonce < v.login_nonce or v.id != id:
session.pop("lo_user")
v = None
2022-05-04 23:09:46 +00:00
if v and request.method != "GET":
submitted_key = request.values.get("formkey")
2024-05-25 00:36:34 +00:00
if v:
g.username = v.username
2022-11-28 19:41:08 +00:00
if not validate_formkey(v, submitted_key):
v = None
2022-11-28 01:48:53 +00:00
else:
session.pop("lo_user")
2024-05-16 21:07:31 +00:00
if request.path not in {'/contact', '/reply', '/socket.io/'} and v and v.is_underage:
2024-08-11 20:11:04 +00:00
stop(406)
2024-05-16 20:17:52 +00:00
2023-09-14 16:15:12 +00:00
if request.method != "GET" and get_setting('read_only_mode') and not (v and v.admin_level >= PERMS['BYPASS_SITE_READ_ONLY_MODE']):
2024-08-11 20:11:04 +00:00
stop(403, "Site is in read-only mode right now. It will be back shortly!")
2023-03-25 21:35:13 +00:00
if get_setting('offline_mode') and not (v and v.admin_level >= PERMS['SITE_OFFLINE_MODE']):
2024-08-11 20:11:04 +00:00
stop(403, "Site is in offline mode right now. It will be back shortly!")
2022-05-04 23:09:46 +00:00
2022-05-26 00:54:05 +00:00
g.v = v
2023-08-22 21:46:43 +00:00
if v:
2023-10-05 11:47:43 +00:00
g.username = v.username
2022-05-25 18:59:24 +00:00
2023-08-11 13:22:25 +00:00
if not v and SITE == 'rdrama.net' and request.headers.get("Cf-Ipcountry") == 'EG':
2024-08-11 20:11:04 +00:00
stop(403, "rdrama.net is only available to visitors from the United States and Europe!")
2023-06-01 13:05:07 +00:00
g.is_api_or_xhr = bool((v and v.client) or request.headers.get("xhr"))
2023-09-17 19:16:05 +00:00
g.is_tor = (request.headers.get("cf-ipcountry") == "T1" and not (v and v.truescore >= 1000))
2024-04-17 15:53:49 +00:00
if v and not IS_MUSICAL_EVENT():
2023-10-04 18:58:00 +00:00
session.pop("event_music", None)
2023-09-28 23:58:09 +00:00
g.show_nsfw = SITE_NAME == 'WPD' or (v and not v.nsfw_warnings) or session.get('nsfw_cookies', 0) >= int(time.time())
2022-05-04 23:09:46 +00:00
return v
def auth_desired(f):
def wrapper(*args, **kwargs):
2022-10-11 13:19:55 +00:00
v = get_logged_in_user()
2022-05-04 23:09:46 +00:00
return make_response(f(*args, v=v, **kwargs))
wrapper.__name__ = f.__name__
return wrapper
def auth_desired_with_logingate(f):
def wrapper(*args, **kwargs):
2022-10-11 13:19:55 +00:00
v = get_logged_in_user()
if not v and get_setting('login_required'):
2024-08-11 20:11:04 +00:00
stop(401, "You need to login to perform this action!")
2022-05-04 23:09:46 +00:00
2024-08-28 12:44:15 +00:00
# if not v and get_setting('under_attack'):
# stop(418)
if request.path.startswith('/logged_out'):
2022-09-20 00:51:01 +00:00
redir = request.full_path.replace('/logged_out','')
if not redir: redir = '/'
return redirect(redir)
return make_response(f(*args, v=v, **kwargs))
wrapper.__name__ = f.__name__
return wrapper
def auth_required(f):
2022-05-04 23:09:46 +00:00
def wrapper(*args, **kwargs):
2022-10-11 13:19:55 +00:00
v = get_logged_in_user()
2023-07-24 11:06:42 +00:00
if not v:
2024-08-11 20:11:04 +00:00
stop(401, "You need to login to perform this action!")
2023-09-14 20:04:30 +00:00
if v.is_permabanned and request.method == "POST" and request.path not in {'/contact','/reply','/logout'} and not request.path.startswith('/delete/'):
2024-08-11 20:11:04 +00:00
stop(403, "You can't perform this action while permabanned!")
2022-05-04 23:09:46 +00:00
return make_response(f(*args, v=v, **kwargs))
wrapper.__name__ = f.__name__
return wrapper
def admin_level_required(x):
def wrapper_maker(f):
def wrapper(*args, **kwargs):
2022-10-11 13:19:55 +00:00
v = get_logged_in_user()
2023-07-24 11:06:42 +00:00
if not v:
2024-08-11 20:11:04 +00:00
stop(401, "You need to login to perform this action!")
2023-07-24 11:06:42 +00:00
if v.admin_level < x:
2024-08-11 20:11:04 +00:00
stop(403, "Your admin-level is not sufficient enough for this action!")
2022-12-27 01:54:19 +00:00
if x and SITE != 'devrama.net' and not IS_LOCALHOST and not v.mfa_secret:
2024-08-11 20:11:04 +00:00
stop(403, "You need to enable two-factor authentication to use admin features!")
2022-10-11 13:43:57 +00:00
return make_response(f(*args, v=v, **kwargs))
2022-05-04 23:09:46 +00:00
wrapper.__name__ = f.__name__
return wrapper
return wrapper_maker
def feature_required(x):
def wrapper_maker(f):
def wrapper(*args, **kwargs):
2024-08-11 20:11:04 +00:00
if not FEATURES[x]: stop(404)
2022-10-11 13:19:55 +00:00
return make_response(f(*args, **kwargs))
wrapper.__name__ = f.__name__
return wrapper
2022-10-11 07:29:24 +00:00
return wrapper_maker