Debian Codegraph @

examples/basic_auth.py

raw symbols SCIP
1 """
2 An example that uses HTTP Basic Auth to protect the /apidocs and
3 /apispec_1.json endpoints.
4
5 In this example the login credentials to view the Swagger docs are as follows:
6
7 Username: guest
8 Password: secret
9
10 Failing to provide the right credentials results in a 401 Unauthorized
11 response from all the Flasgger endpoints.
12 """
13 from flask import Flask, request, redirect, Response, jsonify
14 from functools import wraps
15
16 from flasgger import Swagger
17
18 def requires_basic_auth(f):
19 """Decorator to require HTTP Basic Auth for your endpoint."""
20
21 def check_auth(username, password):
22 return username == "guest" and password == "secret"
23
24 def authenticate():
25 return Response(
26 "Authentication required.", 401,
27 {"WWW-Authenticate": "Basic realm='Login Required'"},
28 )
29
30 @wraps(f)
31 def decorated(*args, **kwargs):
32 # NOTE: This example will require Basic Auth only when you run the
33 # app directly. For unit tests, we can't block it from getting the
34 # Swagger specs so we just allow it to go thru without auth.
35 # The following two lines of code wouldn't be needed in a normal
36 # production environment.
37 if __name__ != "__main__":
38 return f(*args, **kwargs)
39
40 auth = request.authorization
41 if not auth or not check_auth(auth.username, auth.password):
42 return authenticate()
43 return f(*args, **kwargs)
44
45 return decorated
46
47 app = Flask(__name__)
48 app.config["SWAGGER"] = {
49 "title": "Swagger Basic Auth App",
50 "uiversion": 2,
51 }
52 swag = Swagger(app,
53 decorators=[ requires_basic_auth ],
54 template={
55 "swagger": "2.0",
56 "info": {
57 "title": "Swagger Basic Auth App",
58 "version": "1.0",
59 },
60 "consumes": [
61 "application/json",
62 ],
63 "produces": [
64 "application/json",
65 ],
66 },
67 )
68
69 @app.route("/echo/<name>", methods=["GET", "POST"])
70 def echo(name):
71 """
72 Echo back the name and any posted parameters.
73 ---
74 tags:
75 - echo
76 parameters:
77 - in: path
78 name: name
79 type: string
80 required: true
81 - in: body
82 name: body
83 description: JSON parameters.
84 schema:
85 properties:
86 first_name:
87 type: string
88 description: First name.
89 example: Alice
90 last_name:
91 type: string
92 description: Last name.
93 example: Smith
94 dob:
95 type: string
96 format: date
97 description: Date of birth.
98 example: 1990-01-01
99 comment:
100 type: string
101 description: Something arbitrary.
102 example: Hello world
103 responses:
104 200:
105 description: OK.
106 """
107 data = {
108 "url_name": name,
109 "json": request.json,
110 }
111 return jsonify(data)
112
113 @app.route("/")
114 def index():
115 return redirect("/apidocs")
116
117 if __name__ == "__main__":
118 app.run(debug=True)