2025-04-16 10:03:13 -03:00

63 lines
1.5 KiB
Elixir

defmodule ApiWeb.GetHash do
use ApiWeb, :controller
alias Api.Repo
import Ecto.Query
require Logger
def index(conn, %{"study" => study}) do
Envar.load(".env")
Envar.require_env_file(".env")
studyidentifier = Envar.get("IDENTIFIERFIELD") || "IDSTUDY"
query =
if studyidentifier == "IDSTUDY" do
from s in "study",
join: p in "patient",
on: p.idpatient == s.idpatient,
where: s.idstudy == ^String.to_integer(study),
select: %{
idstudy: s.idstudy,
patientid: p.patientid
}
else
from s in "study",
join: p in "patient",
on: p.idpatient == s.idpatient,
where: s.accessionnumber == ^study,
select: %{
accessionnumber: s.accessionnumber,
patientid: p.patientid
}
end
case Repo.one(query) do
nil ->
conn
|> put_status(:not_found)
|> json(%{error: "Estudio no encontrado"})
res ->
vencimiento = DateTime.add(DateTime.utc_now(), 2 * 24 * 60 * 60, :second)
json_data = Map.put(res, :vencimiento, vencimiento)
token = generate_token(json_data)
conn
|> put_status(:ok)
|> json(%{hash: token})
end
end
def generate_token(json) do
json_string = Jason.encode!(json)
query = "select encrypt('#{json_string}'::bytea, '1nf0rm3', 'aes')::text"
token = Repo.query!(query).rows |> hd() |> hd()
token = Base.encode64(token)
token
end
end