Se crea una autenticacion en el header para limitar el acceso a gethash

This commit is contained in:
aime.rolandi 2025-04-16 13:45:11 -03:00
parent e1ac74edce
commit d72cc1a8bf

View File

@ -4,53 +4,61 @@ defmodule ApiWeb.GetHash do
import Ecto.Query
require Logger
@valid_token "XHg0NWNhN2I3MTljNTRlOGU4NTAwOTljMDYwNTgxNDBmNzc5MTgxMzM3NmJmZTMwOGJjMGM4N2VkMzYwODUwMDFl"
def index(conn, %{"study" => accessionnumber}) do
Envar.load(".env")
Envar.require_env_file(".env")
Logger.info("Accession get hash -> #{accessionnumber}")
if not valid_token?(conn) do
conn
|> put_status(:unauthorized)
|> json(%{error: "Token inválido o ausente"})
else
Logger.info("Accession get hash -> #{accessionnumber}")
studyidentifier = Envar.get("IDENTIFIERFIELD") || "IDSTUDY"
studyidentifier = Envar.get("IDENTIFIERFIELD") || "IDSTUDY"
# En caso de recibir idstudy en get hash -> where: s.accessionnumber == ^String.to_integer(accessionnumber),
# En caso de recibir idstudy en get hash -> where: s.accessionnumber == ^String.to_integer(accessionnumber),
query =
if studyidentifier == "IDSTUDY" do
from s in "study",
join: p in "patient",
on: p.idpatient == s.idpatient,
where: s.accessionnumber == ^accessionnumber,
select: %{
idstudy: s.idstudy,
patientid: p.patientid
}
else
from s in "study",
join: p in "patient",
on: p.idpatient == s.idpatient,
where: s.accessionnumber == ^accessionnumber,
select: %{
accessionnumber: s.accessionnumber,
patientid: p.patientid
}
query =
if studyidentifier == "IDSTUDY" do
from s in "study",
join: p in "patient",
on: p.idpatient == s.idpatient,
where: s.accessionnumber == ^accessionnumber,
select: %{
idstudy: s.idstudy,
patientid: p.patientid
}
else
from s in "study",
join: p in "patient",
on: p.idpatient == s.idpatient,
where: s.accessionnumber == ^accessionnumber,
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
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
@ -63,4 +71,12 @@ defmodule ApiWeb.GetHash do
token
end
defp valid_token?(conn) do
case get_req_header(conn, "authorization") do
["Bearer " <> token] -> token == @valid_token
_ -> false
end
end
end