View Source AuthToken (AuthToken v0.4.0)

Simplified encrypted authentication tokens using JWE.

Configuration needed:

config :authtoken,

token_key: PUT_KEY_HERE

Generate a token for your user after successful authentication like this:

Examples

token_content = %{userid: user.id}

token = AuthToken.generate_token(token_content)

Summary

Functions

Decrypt an authentication token

Generate a random key for AES128

Generates an encrypted auth token.

Check if token is timedout and not valid anymore

Check if token is stale and needs to be refreshed

Checks a token and refreshes if necessary.

Functions

@spec decrypt_token(Plug.Conn.t()) :: {:ok, String.t()} | {:error}
@spec decrypt_token(String.t()) :: {:ok, String.t()} | {:error}
@spec decrypt_token(nil) :: {:error}

Decrypt an authentication token

Format "bearer: tokengoeshere" and "bearer tokengoeshere" will be accepted and parsed out.

@spec generate_key() :: {:ok, binary()}

Generate a random key for AES128

Examples

iex> AuthToken.generate_key()
{:ok, <<153, 67, 252, 211, 199, 186, 212, 114, 109, 99, 222, 205, 31, 26, 100, 253>>}
Link to this function

generate_token(user_data)

View Source
@spec generate_token(map()) :: {:ok, String.t()}

Generates an encrypted auth token.

Contains an encoded version of the provided map, plus a timestamp for timeout and refresh.

@spec get_config(atom()) :: %{}
@spec is_timedout?(map()) :: boolean()

Check if token is timedout and not valid anymore

@spec needs_refresh?(map()) :: boolean()

Check if token is stale and needs to be refreshed

@spec refresh_token(map()) ::
  {:ok, String.t()} | {:error, :stillfresh} | {:error, :timedout}
@spec refresh_token(String.t()) ::
  {:ok, String.t()} | {:error, :stillfresh} | {:error, :timedout}

Checks a token and refreshes if necessary.

Examples

case AuthToken.refresh_token(token) do
  {:error, :timedout} ->
    # Redirect to login
  {:error, :stillfresh} ->
    # Do nothing
  {:ok, token} ->
    # Check credentials and send back new token
end