forget-cancellare-vecchi-toot/lib/auth.py

53 lines
1.2 KiB
Python
Raw Normal View History

2017-08-25 10:50:11 +02:00
from flask import g, redirect, jsonify, make_response, abort, request
2017-08-12 01:04:22 +02:00
from functools import wraps
2017-08-29 14:46:32 +02:00
2017-08-12 01:04:22 +02:00
def require_auth(fun):
@wraps(fun)
def wrapper(*args, **kwargs):
if not g.viewer:
2017-08-12 01:04:22 +02:00
return redirect('/')
return fun(*args, **kwargs)
return wrapper
2017-08-29 14:46:32 +02:00
2017-08-12 01:04:22 +02:00
def require_auth_api(fun):
@wraps(fun)
def wrapper(*args, **kwargs):
if not g.viewer:
2017-08-29 14:46:32 +02:00
return make_response((
jsonify(status='error', error='not logged in'),
403))
2017-08-12 01:04:22 +02:00
return fun(*args, **kwargs)
return wrapper
2017-08-25 10:50:11 +02:00
def csrf(fun):
@wraps(fun)
def wrapper(*args, **kwargs):
if request.form.get('csrf-token') != g.viewer.csrf_token:
return abort(403)
return fun(*args, **kwargs)
return wrapper
def set_session_cookie(session, response, secure=True):
response.set_cookie(
'forget_sid', session.id,
max_age=60*60*48,
httponly=True,
secure=secure)
def get_viewer_session():
from model import Session
sid = request.cookies.get('forget_sid', None)
if sid:
return Session.query.get(sid)
def get_viewer():
session = get_viewer_session()
if session:
return session.account