Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add specs to Plug.BasicAuth #1181

Merged
merged 2 commits into from
Oct 30, 2023
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 8 additions & 3 deletions lib/plug/basic_auth.ex
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,8 @@ defmodule Plug.BasicAuth do
strings with only alphanumeric characters and space

"""
def basic_auth(conn, options \\ []) do
@spec basic_auth(Plug.Conn.t(), [auth_option]) :: Plug.Conn.t() when auth_option: {:username, String.t()} | {:password, String.t()} | {:realm, String.t()}
def basic_auth(%Plug.Conn{} = conn, options \\ []) when is_list(options) do
username = Keyword.fetch!(options, :username)
password = Keyword.fetch!(options, :password)

Expand All @@ -116,7 +117,8 @@ defmodule Plug.BasicAuth do

See the module docs for examples.
"""
def parse_basic_auth(conn) do
@spec parse_basic_auth(Plug.Conn.t()) :: {user :: String.t(), password :: String.t()} | :error
def parse_basic_auth(%Plug.Conn{} = conn) do
with ["Basic " <> encoded_user_and_pass] <- get_req_header(conn, "authorization"),
{:ok, decoded_user_and_pass} <- Base.decode64(encoded_user_and_pass),
[user, pass] <- :binary.split(decoded_user_and_pass, ":") do
Expand All @@ -134,6 +136,7 @@ defmodule Plug.BasicAuth do
put_req_header(conn, "authorization", encode_basic_auth("hello", "world"))

"""
@spec encode_basic_auth(String.t(), String.t()) :: String.t()
def encode_basic_auth(user, pass) when is_binary(user) and is_binary(pass) do
"Basic " <> Base.encode64("#{user}:#{pass}")
end
Expand All @@ -150,8 +153,10 @@ defmodule Plug.BasicAuth do
* `:realm` - the authentication realm. The value is not fully
sanitized, so do not accept user input as the realm and use
strings with only alphanumeric characters and space

"""
def request_basic_auth(conn, options \\ []) when is_list(options) do
@spec request_basic_auth(Plug.Conn.t(), [option]) :: Plug.Conn.t() when option: {:realm, String.t()}
def request_basic_auth(%Plug.Conn{} = conn, options \\ []) when is_list(options) do
realm = Keyword.get(options, :realm, "Application")
escaped_realm = String.replace(realm, "\"", "")

Expand Down
Loading