# Flask Authorization library

Allows to manage the user/role model for any flask microservice

#### Using extension

```python
from flask import Flask
from flask_api_auth import Authentication

app = Flask(__name__)
Authentication(app, '/api/v1') # Second parameter is url_prefix
app.run()
```

#### Available decorators

Use `requires_auth` decorator for protect endpoints. Force apiuser and apikey parameters, validates the key and add the user to the request. Optionally, you can add a 'role' parameter to enforce that the user has that parameter.

```python
form flask_api_auth.decorators import requires_auth

@requires_auth()
def get(self):
...
```
#### Models

This extension provides two models: `APIUser` and `APIRole`. In order to save the information on a datasource you need to provide a `Manager` following the `flask_api_auth.managers.BaseManager` class.
After creating the manager in your app, you need to create two settings `ROLE_MANAGER` and `APIUSER_MANAGER` with the full class path to the manager.
Flask-api-auth will assign that manager to the corresponding model.

```python
"""
We should have the settings app.config['ROLE_MANAGER'] and app.config['APIUSER_MANAGER']
"""
Authentication(app, '/api/v1')
```

---
# Contribute

#### Clone the repo in the expected location:

```
$ cd ~/code/
$ git clone git@github.com:natgeo/flask-api-auth.git
```

#### Create a virtual env:

```
$ cd ~/code/flask-api-auth/
$ mkvirtualenv flask-api-auth
$ echo 'cd ~/code/flask-api-auth' >> $WORKON_HOME/flask-api-auth/bin/postactivate
$ workon flask-api-auth
$ add2virtualenv .
```

#### Install the requirements:

```
$ pip install -r requirements.txt
```

#### Run test:

```
$ pip install tox
$ tox
```

#### Commands:
Commands are based on Flask-CLI and the package requires this environment
variables in order to get application context and get the proper managers
for APIUser and APIRole.

Please make sure to have this environment variables:
```
# Example for project-distribution
APP_CONFIG=distribution.settings
FLASK_APP=/code/distribution/__init__.py
```

* Create APIUser
```
# flask create-apiuser <username> <key> <comma-separed-roles>
$ flask create-apiuser natgeo_user 1234 admin
$ flask create-apiuser natgeo_user 1234 admin,staff
```
* Create APIRole
```
# flask create-apirole <role_name> <valid_json between single quotes>
flask create-apirole admin '{"read_only": "true"}'
```
