mirror of
https://github.com/kevin-DL/phoenix_api_template.git
synced 2026-01-11 18:54:33 +00:00
Adding the user to the session
This commit is contained in:
27
lib/phoenix_api_template_web/auth/set_user.ex
Normal file
27
lib/phoenix_api_template_web/auth/set_user.ex
Normal file
@@ -0,0 +1,27 @@
|
||||
defmodule PhoenixApiTemplateWeb.Auth.SetUser do
|
||||
import Plug.Conn
|
||||
alias PhoenixApiTemplateWeb.Auth.ErrorResponse
|
||||
alias PhoenixApiTemplate.Accounts
|
||||
|
||||
def init(_options) do
|
||||
end
|
||||
|
||||
def call(conn, _options) do
|
||||
if conn.assigns[:user] do
|
||||
conn
|
||||
else
|
||||
user_id = get_session(conn, :user_id)
|
||||
|
||||
if user_id == nil do
|
||||
raise ErrorResponse.Unauthorized
|
||||
end
|
||||
|
||||
user = Accounts.get_user!(user_id)
|
||||
|
||||
cond do
|
||||
user_id && user -> assign(conn, :user, user)
|
||||
true -> assign(conn, :user, nil)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -29,6 +29,7 @@ defmodule PhoenixApiTemplateWeb.UserController do
|
||||
case Guardian.authenticate(email, password) do
|
||||
{:ok, user, token} ->
|
||||
conn
|
||||
|> Plug.Conn.put_session(:user_id, user.id)
|
||||
|> put_status(:ok)
|
||||
|> render("user_token.json", %{user: user, token: token})
|
||||
|
||||
|
||||
@@ -16,10 +16,12 @@ defmodule PhoenixApiTemplateWeb.Router do
|
||||
|
||||
pipeline :api do
|
||||
plug(:accepts, ["json"])
|
||||
plug :fetch_session
|
||||
end
|
||||
|
||||
pipeline :auth do
|
||||
plug PhoenixApiTemplateWeb.Auth.Pipeline
|
||||
plug PhoenixApiTemplateWeb.Auth.SetUser
|
||||
end
|
||||
|
||||
scope "/api", PhoenixApiTemplateWeb do
|
||||
|
||||
Reference in New Issue
Block a user