endpoint to register

This commit is contained in:
2023-02-18 09:29:20 +00:00
parent 0d2d460189
commit 931e22d0f7
5 changed files with 28 additions and 9 deletions

View File

@@ -49,8 +49,9 @@ defmodule PhoenixApiTemplate.Profiles do
{:error, %Ecto.Changeset{}} {:error, %Ecto.Changeset{}}
""" """
def create_profile(attrs \\ %{}) do def create_profile(user, attrs \\ %{}) do
%Profile{} user
|> Ecto.build_assoc(:profile)
|> Profile.changeset(attrs) |> Profile.changeset(attrs)
|> Repo.insert() |> Repo.insert()
end end

View File

@@ -1,8 +1,11 @@
defmodule PhoenixApiTemplateWeb.UserController do defmodule PhoenixApiTemplateWeb.UserController do
use PhoenixApiTemplateWeb, :controller use PhoenixApiTemplateWeb, :controller
alias PhoenixApiTemplateWeb.Auth.Guardian
alias PhoenixApiTemplate.Accounts alias PhoenixApiTemplate.Accounts
alias PhoenixApiTemplate.Accounts.User alias PhoenixApiTemplate.Accounts.User
alias PhoenixApiTemplate.Profiles
alias PhoenixApiTemplate.Profiles.Profile
action_fallback(PhoenixApiTemplateWeb.FallbackController) action_fallback(PhoenixApiTemplateWeb.FallbackController)
@@ -11,11 +14,13 @@ defmodule PhoenixApiTemplateWeb.UserController do
render(conn, "index.json", users: users) render(conn, "index.json", users: users)
end end
def create(conn, %{"user" => user_params}) do def create(conn, %{"user" => %{"profile" => profile_params} = user_params}) do
with {:ok, %User{} = user} <- Accounts.create_user(user_params) do with {:ok, %User{} = user} <- Accounts.create_user(user_params),
{:ok, token, _claims} <- Guardian.encode_and_sign(user),
{:ok, %Profile{} = _profile} <- Profiles.create_profile(user, profile_params) do
conn conn
|> put_status(:created) |> put_status(:created)
|> render("show.json", user: user) |> render("user_token.json", user: user, token: token)
end end
end end

View File

@@ -9,5 +9,6 @@ defmodule PhoenixApiTemplateWeb.Router do
pipe_through(:api) pipe_through(:api)
get("/", DefaultController, :index) get("/", DefaultController, :index)
post("/register", UserController, :create)
end end
end end

View File

@@ -17,4 +17,12 @@ defmodule PhoenixApiTemplateWeb.UserView do
hashed_password: user.hashed_password hashed_password: user.hashed_password
} }
end end
def render("user_token.json", %{user: user, token: token}) do
%{
id: user.id,
email: user.email,
token: token
}
end
end end

View File

@@ -1,10 +1,14 @@
POST http://localhost:4000/api/users HTTP/1.1 POST http://localhost:4000/api/register HTTP/1.1
content-type: application/json content-type: application/json
{ {
"quotation": { "user": {
"author": "Dennis Ritchie", "email": "test4@yopmail.com",
"text": "The only way to learn a new programming language is by writing programs in it" "hashed_password": "yolo",
"profile": {
"display_name": "test user"
}
} }
} }