nomad-vault-login/main.py

71 lines
1.8 KiB
Python
Raw Normal View History

2022-09-06 20:13:26 +00:00
import os
from flask import Flask
2022-11-04 21:40:32 +00:00
from flask import Response
2022-09-06 20:13:26 +00:00
from flask import request
from hvac import Client
2022-11-15 20:59:37 +00:00
from hvac.exceptions import InvalidRequest
2022-09-06 20:13:26 +00:00
2022-09-12 04:22:37 +00:00
BIND_HOST = os.getenv("BIND_HOST", "0.0.0.0")
BIND_PORT = int(os.getenv("BIND_PORT", "5000"))
2022-09-06 20:13:26 +00:00
VAULT_ADDR = os.getenv("VAULT_ADDR", "http://127.0.0.1:8200")
NOMAD_ROLE = os.getenv("NOMAD_ROLE", "admin")
app = Flask(__name__)
2022-09-12 04:22:37 +00:00
@app.route("/")
2022-09-06 20:13:26 +00:00
def root():
# TODO: Render a basic page that checks for existance of token in local storage and displays form
return f"""
<html>
<body>
<a href="/login">Login</a>
</form>
</html>
"""
@app.route("/login", methods=["POST", "GET"])
def login():
if request.method == "GET":
return f"""
<html>
<body>
<form action="/login" method="POST">
2022-09-07 17:57:58 +00:00
<p>Username <input type="text" name="username"/></p>
<p>Password <input type="password" name="password"/></p>
<p>Role <input type="text" name="role" value="admin"/></p>
<p><input type="submit" value="Submit"/></p>
2022-09-06 20:13:26 +00:00
</form>
</html>
"""
elif request.method == "POST":
username, password = request.form["username"], request.form["password"]
2022-11-04 21:40:32 +00:00
client = Client(VAULT_ADDR)
2022-11-15 20:59:37 +00:00
try:
client.auth.userpass.login(username, password)
except InvalidRequest:
return Response(response="Unauthorized", status=401)
2022-11-04 21:40:32 +00:00
if not client.is_authenticated():
return Response(response="Unauthorized", status=401)
2022-09-07 17:57:58 +00:00
role = request.form.get("role")
nomad_creds = client.read(f"nomad/creds/{role or NOMAD_ROLE}")
2022-09-06 20:13:26 +00:00
nomad_token = nomad_creds["data"]["secret_id"]
2022-11-04 21:40:32 +00:00
2022-09-06 20:13:26 +00:00
return f"""
<html><head>
2022-09-07 17:57:58 +00:00
<script>localStorage.setItem("nomadTokenSecret", "{nomad_token}"); window.location.replace("/ui/settings/tokens");</script>
2022-09-06 20:13:26 +00:00
</head>
2022-09-07 17:57:58 +00:00
<body>Logged in. Go <a href="/ui/settings/tokens">back to Nomad</a></body></html>
2022-09-06 20:13:26 +00:00
"""
2022-09-12 04:22:37 +00:00
app.run(host=BIND_HOST, port=BIND_PORT)