authsense v1.0.0 Authsense.Service
Functions for working with models or changesets.
Summary
Functions
Checks if someone can authenticate with a given username/password pair
Returns the user associated with these credentials. Returns the User record
on success, or false on error
Updates an Ecto.Changeset to generate a hashed password
Loads a user by a given identity field value. Returns a nil on failure
Functions
Checks if someone can authenticate with a given username/password pair.
Credentials can be given as either an Ecto changeset or a tuple.
# Changeset:
%User{}
|> change(%{ email: "[email protected]", password: "password" })
|> authenticate()
# Tuple:
authenticate({ "[email protected]", "password" })
Returns {:ok, user} on success, or {:error, changeset} on failure. If
used as a tuple, it returns {:error, nil} on failure.
Typically used within a login action.
def login_create(conn, %{"user" => user_params}) do
changeset = User.changeset(%User{}, user_params)
case authenticate(changeset) do
{:ok, user} ->
conn
|> Auth.put_current_user(user)
|> put_flash(:info, "Welcome.")
|> redirect(to: "/")
{:error, changeset} ->
render(conn, "login.html", changeset: changeset)
end
end
It’s also possible to add opts as a second parameter, which may contain a keyword scope.
Scope can be lambda that returns an Ecto.Queryable, an Ecto.Query, or an Ecto.Queryable
This will override the model with a prepared queryable.
%User{}
|> change(%{ email: "[email protected]", password: "password})
|> authenticate([scope: User |> where(:field_for_filtering, ^somevar))
Returns the user associated with these credentials. Returns the User record
on success, or false on error.
Accepts both { email, password } tuples and Ecto.Changesets.
authenticate_user(changeset)
authenticate_user({ email, password })
Updates an Ecto.Changeset to generate a hashed password.
If the changeset has :password in it, it will be hashed and stored as
:hashed_password. (Fields can be configured in Authsense.)
changeset
|> generate_hashed_password()
It’s typically used in a model’s changeset/2 function.
defmodule Example.User do
use Example.Web, :model
def changeset(model, params \ []) do
model
|> cast(params, [:email, :password, :password_confirmation])
|> generate_hashed_password()
|> validate_confirmation(:password, message: "password confirmation doesn't match")
|> unique_constraint(:email)
end
end
Loads a user by a given identity field value. Returns a nil on failure.
get_user("[email protected]") #=> %User{...}