request parsing fix

This commit is contained in:
r8zavetr8v 2024-09-11 00:25:50 +03:00
parent 312be30733
commit 032ea859fb
3 changed files with 41 additions and 36 deletions

View File

@ -1,11 +0,0 @@
{
"body": {
"content": "",
"file": false,
"fileSize": false
},
"headers": {},
"method": "GET",
"title": "New HTTP Request",
"url": ""
}

View File

@ -8,6 +8,7 @@ defmodule DrainCloudCoreWeb.AuthController do
def register(conn = %Plug.Conn{}, _params) do
req = Request.from_request(conn)
Log.debug("new register request: #{req}")
model = Request.to_model(req)
@ -31,22 +32,10 @@ defmodule DrainCloudCoreWeb.AuthController.RegisterRequest do
alias DrainCloudCore.Auth.Users, as: User
alias DrainCloudCoreWeb.Errors.InvalidArgumentException, as: InvalidArgumentException
def from_request(conn) do
res = Plug.Conn.read_body(conn)
:logger.warning(Kernel.inspect(res))
def from_request(conn = %Plug.Conn{}) do
:logger.debug("[from_request] incoming request: #{Kernel.inspect(conn.params)}")
case res do
{:error, _} ->
raise "failed to read request body: #{:error}"
{_, data, _} ->
req = Poison.decode!(data, as: %Request{})
validate_request(req)
req
_ ->
raise "failed to read request body. unexpected result #{Kernel.inspect(res)}"
end
validate_and_build(conn.params)
end
def to_model(req = %Request{}) do
@ -56,20 +45,43 @@ defmodule DrainCloudCoreWeb.AuthController.RegisterRequest do
}
end
defp validate_request(req = %Request{}) do
if String.length(req.login) < 3 do
defp validate_and_build(req) do
validate(req)
|> build
end
defp validate(req) do
validate_login(req)
|> validate_password
end
defp validate_login(req) do
if String.length(Map.get(req, "login")) >= 3 do
req
else
raise InvalidArgumentException, %{
message: "login must be 3 symbols at minimum",
args: ["login"]
}
end
end
defp validate_password(req) do
if String.length(Map.get(req, "password")) >= 8 do
req
else
if String.length(req.password) < 8 do
raise InvalidArgumentException, %{
message: "password must be 8 symbols at minimum",
args: ["password"]
}
end
end
defp build(req) do
%Request{
login: Map.get(req, "login"),
password: Map.get(req, "password")
}
end
defimpl String.Chars, for: DrainCloudCoreWeb.AuthController.RegisterRequest do

View File

@ -2,11 +2,15 @@ defmodule DrainCloudCoreWeb.Errors.InvalidArgumentException do
alias __MODULE__, as: InvalidArgumentException
defexception [:message, :args]
@impl true
def exception(%{message: message, args: args}) do
%InvalidArgumentException{message: message, args: args}
end
@impl true
def exception(term) do
case term do
[] -> %InvalidArgumentException{}
{message, args} -> %InvalidArgumentException{message: message, args: args}
_ -> %InvalidArgumentException{message: "Error: " <> term}
end
end