Tailscale Authentication: if we're connecting within the tailnet, use that

This commit is contained in:
bluepython508
2024-05-19 15:55:07 +01:00
parent b83ef03030
commit 61c2500348
3 changed files with 20 additions and 2 deletions

View File

@@ -1,5 +1,6 @@
defmodule SsoBsnWeb.Router do
use SsoBsnWeb, :router
use SsoBsnWeb, :verified_routes
import SsoBsnWeb.UserAuth
@@ -47,9 +48,21 @@ defmodule SsoBsnWeb.Router do
end
## Authentication routes
defp ts_auth(conn, _) do
ip = conn.req_headers |> Map.new |> Map.get("x-real-ip")
case System.cmd("tailscale", ["whois", "--json", ip], stderr_to_stdout: true) do
{json, 0} ->
username = Jason.decode!(json)["UserProfile"]["DisplayName"]
user = SsoBsn.Accounts.get_user_by_username(username)
login_token = SsoBsn.Accounts.generate_user_login_token(user)
conn |> redirect(to: if next = conn.query_params["next"] do ~p"/users/log_in/#{login_token}?next=#{next}" else ~p"/users/log_in/#{login_token}" end) |> halt()
{_, 1} ->
conn
end
end
scope "/", SsoBsnWeb do
pipe_through [:browser, :redirect_if_user_is_authenticated]
pipe_through [:browser, :redirect_if_user_is_authenticated, :ts_auth]
live_session :redirect_if_user_is_authenticated,
on_mount: [{SsoBsnWeb.UserAuth, :redirect_if_user_is_authenticated}] do
@@ -57,6 +70,10 @@ defmodule SsoBsnWeb.Router do
live "/users/log_in", UserLoginLive, :new
end
end
scope "/", SsoBsnWeb do
pipe_through [:browser, :redirect_if_user_is_authenticated]
get "/users/log_in/:token", UserSessionController, :login
end