· 6 years ago · Jun 21, 2019, 02:02 PM
1######### app.py
2from flask import Flask
3from flask_cors import CORS
4from flask_restful import Api
5from flask_wtf.csrf import CSRFProtect, CSRFError
6
7from x.src.services.config_service import Config
8
9# Create app
10app = Flask(__name__)
11
12# Add CORS
13CORS(app)
14
15# Create API
16errors = {'CSRFError': CSRFError} # Manage errors
17api = Api(app, errors=errors)
18
19# Enable CSRF protection
20csrf = CSRFProtect(app)
21
22# Load .env var
23configs = Config()
24if configs:
25 # Set app and wtf csrf secret
26 app.config['SECRET_KEY'] = configs.get('APP_SECRET_KEY')
27 app.config['WTF_CSRF_SECRET_KEY'] = configs.get('WTF_CSRF_SECRET_KEY')
28
29 # Import others x dependencies here
30 # in order to give them the rights env var configuration
31 from x.config import *
32
33# Serve the app
34if __name__ == '__main__':
35 app.run()
36
37
38
39
40######### login_controller.py
41from flask import session
42from flask_wtf.csrf import generate_csrf
43
44from x.src.controllers import *
45
46
47class LoginController(Resource):
48 """
49 Manage login action.
50 """
51 def get(self):
52 token = generate_csrf()
53 session['csrf_token'] = token
54 resp = {'token': token}
55 return resp, 200
56
57
58
59
60######### csrf.py (di flask-wtf)
61def validate_csrf(data, secret_key=None, time_limit=None, token_key=None):
62 secret_key = _get_config(
63 secret_key, 'WTF_CSRF_SECRET_KEY', current_app.secret_key,
64 message='A secret key is required to use CSRF.'
65 )
66 field_name = _get_config(
67 token_key, 'WTF_CSRF_FIELD_NAME', 'csrf_token',
68 message='A field name is required to use CSRF.'
69 )
70 time_limit = _get_config(
71 time_limit, 'WTF_CSRF_TIME_LIMIT', 3600, required=False
72 )
73
74 if not data:
75 raise ValidationError('The CSRF token is missing.')
76 # Fin qui e' tutto ok
77 # Entra pero' in questo if perche' session non ha piu'
78 # l'attributo csrf_token che avevo impostato prima nel login_controller
79 if field_name not in session:
80 raise ValidationError('The CSRF session token is missing.')