-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathapp.py
More file actions
68 lines (56 loc) · 1.62 KB
/
Copy pathapp.py
File metadata and controls
68 lines (56 loc) · 1.62 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
#!/usr/bin/env python3
"""
Route module for the API
"""
from os import getenv
from api.v1.views import app_views
from flask import Flask, jsonify, abort, request
from flask_cors import (CORS, cross_origin)
import os
from api.v1.auth.auth import Auth
from api.v1.auth.basic_auth import BasicAuth
app = Flask(__name__)
app.register_blueprint(app_views)
CORS(app, resources={r"/api/v1/*": {"origins": "*"}})
auth = None
auth_type = getenv('AUTH_TYPE', 'auth')
if auth_type == 'auth':
auth = Auth()
if auth_type == 'basic_auth':
auth = BasicAuth()
@app.errorhandler(401)
def unauthorized(error) -> str:
"""Unauthorized handler.
"""
return jsonify({"error": "Unauthorized"}), 401
@app.errorhandler(403)
def forbidden(error) -> str:
"""Forbidden handler.
"""
return jsonify({"error": "Forbidden"}), 403
@app.errorhandler(404)
def not_found(error) -> str:
""" Not found handler
"""
return jsonify({"error": "Not found"}), 404
@app.before_request
def authenticate_user():
"""Authenticates a user before processing a request.
"""
if auth:
excluded_paths = [
'/api/v1/status/',
'/api/v1/unauthorized/',
'/api/v1/forbidden/',
]
if auth.require_auth(request.path, excluded_paths):
auth_header = auth.authorization_header(request)
user = auth.current_user(request)
if auth_header is None:
abort(401)
if user is None:
abort(403)
if __name__ == "__main__":
host = getenv("API_HOST", "0.0.0.0")
port = getenv("API_PORT", "5000")
app.run(host=host, port=port)