195 lines
5.8 KiB
Elixir
195 lines
5.8 KiB
Elixir
defmodule RecycledCloud.Accounts.User do
|
|
use Ecto.Schema
|
|
import Ecto.Changeset
|
|
require Logger
|
|
require Exldap
|
|
alias RecycledCloud.{LDAP,Accounts}
|
|
alias RecycledCloud.Accounts.User
|
|
alias RecycledCloud.Repo
|
|
|
|
@derive {Inspect, except: [:password]}
|
|
schema "users" do
|
|
field :username, :string
|
|
field :password, :string, virtual: true
|
|
field :dn, :string, virtual: true
|
|
field :email, :string, virtual: true
|
|
field :confirmed_at, :naive_datetime
|
|
|
|
timestamps()
|
|
end
|
|
|
|
# Note: the returned LDAP values usually are lists of charlist (e.g. `%{'uid'
|
|
# => ['myusername']}`).
|
|
defp get_ldap_attributes(%User{username: uid}), do: get_ldap_attributes(uid)
|
|
defp get_ldap_attributes(uid) do
|
|
query = fn ldap_conn -> Exldap.search_field(ldap_conn, :uid, uid) end
|
|
case query |> LDAP.execute do
|
|
{:ok, []} -> {:error, "could not find matching object"}
|
|
{:ok, [entry]} ->
|
|
attrs = entry
|
|
|> Map.get(:attributes)
|
|
|> Enum.into(%{})
|
|
|> Map.put('dn', entry.object_name)
|
|
{:ok, attrs}
|
|
{:ok, [entry|_]} -> {:error, "found more than one object with uid #{uid}"}
|
|
{:error, err} -> {:error, inspect(err)}
|
|
end
|
|
end
|
|
|
|
def maybe_populate_ldap_attributes(user) do
|
|
# TODO: could be useful to cache this data somehow, perhaps in an ETS
|
|
# table? We query the LDAP server every time we try to fetch an user's
|
|
# data at the moment, which is inefficient.
|
|
|
|
case get_ldap_attributes(user) do
|
|
{:ok, %{'mail' => [raw_email], 'dn' => raw_dn}} ->
|
|
email = List.to_string(raw_email)
|
|
dn = List.to_string(raw_dn)
|
|
user |> Map.put(:email, email) |> Map.put(:dn, dn)
|
|
{:ok, _} ->
|
|
Logger.warn("Malformed LDAP user object")
|
|
user
|
|
{:error, err} ->
|
|
Logger.warn("Error querying LDAP backend: #{err}")
|
|
user
|
|
end
|
|
end
|
|
|
|
def get_by_username(username) when is_binary(username) do
|
|
local_user = Repo.get_by(User, username: username)
|
|
if local_user do
|
|
local_user |> User.maybe_populate_ldap_attributes()
|
|
else
|
|
case get_ldap_attributes(username) do
|
|
{:ok, %{'uid' => [raw_uid], 'mail' => [raw_email], 'dn' => raw_dn}} ->
|
|
uid = List.to_string(raw_uid)
|
|
email = List.to_string(raw_email)
|
|
dn = List.to_string(raw_dn)
|
|
case Accounts.register_user(%{username: uid, email: email, dn: dn}) do
|
|
{:ok, user} ->
|
|
user
|
|
{:error, err} ->
|
|
Logger.warn("Something went wrong importing user from LDAP: #{inspect(err)}")
|
|
nil
|
|
end
|
|
{:error, err} ->
|
|
Logger.warn("Error querying LDAP backend: #{err}")
|
|
nil
|
|
end
|
|
end
|
|
end
|
|
|
|
def get!(id) do
|
|
Repo.get!(User, id) |> User.maybe_populate_ldap_attributes()
|
|
end
|
|
|
|
@doc """
|
|
A user changeset for registration.
|
|
|
|
It is important to validate the length of both email and password.
|
|
Otherwise databases may truncate the email without warnings, which
|
|
could lead to unpredictable or insecure behaviour. Long passwords may
|
|
also be very expensive to hash for certain algorithms.
|
|
"""
|
|
def registration_changeset(user, attrs) do
|
|
user
|
|
|> cast(attrs, [:username, :password, :email, :dn])
|
|
|> validate_email()
|
|
end
|
|
|
|
defp validate_email(changeset) do
|
|
changeset
|
|
|> validate_required([:email])
|
|
|> validate_format(:email, ~r/^[^\s]+@[^\s]+$/, message: "must have the @ sign and no spaces")
|
|
|> validate_length(:email, max: 160)
|
|
end
|
|
|
|
defp validate_password(changeset) do
|
|
changeset
|
|
|> validate_required([:password])
|
|
|> validate_length(:password, min: 6, max: 80)
|
|
#|> validate_format(:password, ~r/[a-z]/, message: "at least one lower case character")
|
|
#|> validate_format(:password, ~r/[A-Z]/, message: "at least one upper case character")
|
|
#|> validate_format(:password, ~r/[!?@#$%^&*_0-9]/, message: "at least one digit or punctuation character")
|
|
end
|
|
|
|
@doc """
|
|
A user changeset for changing the email.
|
|
|
|
It requires the email to change otherwise an error is added.
|
|
"""
|
|
def email_changeset(user, attrs) do
|
|
user
|
|
|> cast(attrs, [:email])
|
|
|> validate_email()
|
|
|> case do
|
|
%{changes: %{email: _}} = changeset -> changeset
|
|
%{} = changeset -> add_error(changeset, :email, "did not change")
|
|
end
|
|
end
|
|
|
|
@doc """
|
|
A user changeset for changing the password.
|
|
"""
|
|
def password_changeset(user, attrs) do
|
|
user
|
|
|> cast(attrs, [:password])
|
|
|> validate_confirmation(:password, message: "does not match password")
|
|
|> validate_password()
|
|
end
|
|
|
|
@doc """
|
|
Confirms the account by setting `confirmed_at`.
|
|
"""
|
|
def confirm_changeset(user) do
|
|
now = NaiveDateTime.utc_now() |> NaiveDateTime.truncate(:second)
|
|
change(user, confirmed_at: now)
|
|
end
|
|
|
|
@doc """
|
|
Verifies the password.
|
|
"""
|
|
def valid_password?(user = %User{username: uid}, password)
|
|
when byte_size(password) > 0 do
|
|
query = fn ldap_conn ->
|
|
Exldap.verify_credentials(ldap_conn, user.dn, password)
|
|
end
|
|
|
|
case query |> LDAP.execute_single do
|
|
:ok -> true
|
|
{:error, _} -> false
|
|
end
|
|
end
|
|
|
|
def valid_password?(_, _) do
|
|
false
|
|
end
|
|
|
|
@doc """
|
|
Validates the current password otherwise adds an error to the changeset.
|
|
"""
|
|
def validate_current_password(changeset, password) do
|
|
if valid_password?(changeset.data, password) do
|
|
changeset
|
|
else
|
|
add_error(changeset, :current_password, "is not valid")
|
|
end
|
|
end
|
|
|
|
def set_password(user, new_password) do
|
|
# Exldap does not properly implement `change_password`, hence we have to
|
|
# fallback on erlang's `:eldap`.
|
|
# See http://erlang.org/doc/man/eldap.html#modify-4
|
|
|
|
query = fn ldap_conn ->
|
|
:eldap.modify_password(
|
|
ldap_conn,
|
|
String.to_charlist(user.dn),
|
|
String.to_charlist(new_password)
|
|
)
|
|
end
|
|
|
|
query |> LDAP.execute_single
|
|
end
|
|
end
|