nomad-vault-login/main.py

62 lines
1.6 KiB
Python
Raw Normal View History

2022-09-06 20:13:26 +00:00
import os
from flask import Flask
from flask import request
from hvac import Client
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":
client = Client(VAULT_ADDR)
username, password = request.form["username"], request.form["password"]
2022-10-27 19:56:55 +00:00
client.auth.userpass.login(username, password)
2022-09-06 20:13:26 +00:00
assert client.is_authenticated()
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"]
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)