asciinema.org/lib/asciinema/auth.ex

47 lines
1.2 KiB
Elixir
Raw Normal View History

2016-10-08 15:34:51 +00:00
defmodule Asciinema.Auth do
2017-06-22 10:01:54 +00:00
import Plug.Conn
2016-10-08 15:34:51 +00:00
alias Asciinema.{Repo, User}
2017-06-22 10:01:54 +00:00
@user_key "warden.user.user.key"
2017-06-23 12:38:43 +00:00
@one_year_in_secs 31557600
2016-10-08 15:34:51 +00:00
def init(opts) do
opts
end
2017-06-23 10:55:15 +00:00
def call(%Plug.Conn{assigns: %{current_user: %User{}}} = conn, _opts) do
conn
end
2016-10-08 15:34:51 +00:00
def call(conn, _opts) do
2017-06-22 10:01:54 +00:00
user_id = get_session(conn, @user_key)
2016-10-08 15:34:51 +00:00
user = user_id && Repo.get(User, user_id)
2017-06-22 10:01:54 +00:00
assign(conn, :current_user, user)
2016-10-08 15:34:51 +00:00
end
2017-06-12 09:52:50 +00:00
2017-06-23 12:38:43 +00:00
def login(conn, %User{id: id, auth_token: auth_token} = user) do
2017-06-22 11:37:50 +00:00
conn
|> put_session(@user_key, id)
2017-06-23 12:38:43 +00:00
|> put_resp_cookie("auth_token", auth_token, max_age: @one_year_in_secs)
2017-06-22 11:37:50 +00:00
|> assign(:current_user, user)
end
2017-06-12 09:52:50 +00:00
def get_basic_auth(conn) do
2017-06-22 10:01:54 +00:00
with ["Basic " <> auth] <- get_req_header(conn, "authorization"),
auth = String.replace(auth, ~r/^%/, ""), # workaround for 1.3.0-1.4.0 client bug
2017-06-12 09:52:50 +00:00
{:ok, username_password} <- Base.decode64(auth),
[username, password] <- String.split(username_password, ":") do
{username, password}
else
2017-06-12 10:08:28 +00:00
_ -> nil
2017-06-12 09:52:50 +00:00
end
end
def put_basic_auth(conn, nil, nil) do
conn
end
def put_basic_auth(conn, username, password) do
auth = Base.encode64("#{username}:#{password}")
2017-06-22 10:01:54 +00:00
put_req_header(conn, "authorization", "Basic " <> auth)
end
2016-10-08 15:34:51 +00:00
end