# CSRF TOKEN
<https://docs-python.ru/packages/veb-frejmvork-flask-python/rasshirenie-flask-wtf/>

Устанавливаем `Flask-WTF extension`
```
# app.__init__
...
from flask_wtf.csrf import CSRFProtect
csrf = CSRFProtect(app)
```
CSRF защита требует установки `SECRET_KEY` в конфигурации `config.py`.  
`WTF_CSRF_SECRET_KEY` конфигурируется отдельно в том же файле.  

Использование в HTML
```
# html
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}"/>
```

`AJAX request, CSRF token should be added using the X-CSRFToken header.`

`Although not recommended, some routes could be exempted from the csrf protection using @csrf.exempt decorator.`

## Примеры
```python
# Flask code

@app.route('/api/get/system/all', methods=('POST',))
def get_system_all():
    if request.method == 'POST':
        csrf.protect()
        r = Response('{"result": "success", "message": "Ok"}')
        r.headers['Content-Type'] = 'application/json; charset=utf-8;'
        return r
```

```js
# javascript

async function send_request(){
    let user = {
          name: 'John',
          surname: 'Smith'
        };

        let response = await fetch(GET_SYSTEMS_URL, {
          method: 'POST',
          headers: {
              'Content-Type': 'application/json;charset=utf-8',
              'X-CSRFToken': CSRF_TOKEN
          },
          body: JSON.stringify(user)
        });

        let result = await response.json();
        alert(result.message);
}
```