Last active
August 29, 2015 14:20
-
-
Save alanpeabody/b567bbdbcd6ad8c5ab4d to your computer and use it in GitHub Desktop.
Plug 101 - Part 2
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| defmodule Authenticate do | |
| import Plug.Conn | |
| def call(conn, _opts) do | |
| case get_req_header(conn, "authorization") do | |
| ["Bearer " <> token] -> authenticate(conn, token) | |
| _ -> reject(conn, "Bearer token missing") | |
| end | |
| end | |
| defp authenticate(conn, token) do | |
| case User.find_by_token(token) do | |
| nil -> reject(conn, "Invalid token - user not found") | |
| user -> assign(conn, :current_user, user) | |
| end | |
| end | |
| defp reject(conn, reason) do | |
| conn | |
| |> send_resp(401, reason) | |
| |> halt | |
| end | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment