Source

garter / garter / csrf.py

Full commit
from flask import abort, request, session

def csrf(app):
    @app.before_request
    def csrf_protect():
        if request.method == "POST":
            csrf_token = session.pop('_csrf_token', None)
            if not csrf_token or csrf_token != request.form.get('_csrf_token'):
                abort(400)
    
    def generate_csrf_token():
        if '_csrf_token' not in session:
            session['_csrf_token'] = some_random_string()
        return session['_csrf_token']
    
    app.jinja_env.globals['csrf_token'] = generate_csrf_token