# Auth tutorial for setting up basic user auth with `put_session()`
## Deps used
```bash
# Admin auth
{:basic_auth, "~> 2.2.2"},
# Password hashing
{:bcrypt_elixir, "~> 2.0"}
```
## Setup
Start off by running `mix deps.get`
### User Schema
Make sure that you have some context that is like `Accounts.User` with `email:unique` and `password_hash` and that you have `Accounts` module with `get_user!(id)`... etc.
Remember when we wrote `user = Accounts.get_by_email(auth_params["email"])` we need to define that fn
Open `accounts.ex` and add this fn after `get_user!(id)`
```elixir
def get_by_email(nil), do: nil
def get_by_email(email), do: User |> Repo.get_by(email: email)
```
**NOTE** We will use advantage of pattern matching and create two fn-s just in case we get `nil`
#### Update `user_controller.ex`
##### Part 1 (update params)
In `UserController``show`, `edit`, `update` and `delete` second param is trying to pattern match for `%{"id" => id}` but since we are going to get user data from `conn.asssigns.current_user` go ahead and replace `%{"id" => id}` with `_params`
```elixir
def FN(conn, %{"id" => id}) do
...
end
# CHANGE TO
def FN(conn, _params) do
...
end
```
*Do that for all 4 of them*
##### Part 2 (update user data)
We are still in `UserController` and fn's `show`, `edit`, `update` and `delete` are using that `id` that we just removed, to obtain user data. We are going to change that now
```elixir
# Change
user = Accounts.get_user!(id)
# Into
user = conn.assigns.current_user
```
### Set `conn.assigns.current_user`
Now we need to assign `current_user` to `@conn`. But how?
Read more to find out. :)
#### Setting up Auth Plug
You remember that `/helpers` folder that we created earlier? Open it and create new file inside, called `plug_auth.ex` and put this code inside.
```elixir
defmodule TutorialWeb.Helpers.AuthGuest do
import Plug.Conn
import Phoenix.Controller
alias Tutorial.Accounts
def init(default), do: default
def call(conn, _opts) do
user_id = get_session(conn, :current_user_id)
auth_reply(conn, user_id)
end
defp auth_reply(conn, nil) do
conn
|> put_flash(:error, "You have to sign in first!")
|> redirect(to: "/sign-in")
|> halt()
end
defp auth_reply(conn, user_id) do
user = Accounts.get_user!(user_id)
conn
|> assign(:current_user, user)
end
end
```
After that add this code into your `router.ex`
```elixir
pipeline :auth do
plug TutorialWeb.Helpers.AuthGuest
end
```
And add that pipeline in `pipe_through` for scope you want to require logged user