meta/lib/recycledcloud/accounts/user.ex

191 lines
5.6 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, UserToken, UserNotifier}
alias RecycledCloud.Repo
@derive {Inspect, except: [:password]}
schema "users" do
field :username, :string
field :password, :string, virtual: true
field :email, :string, virtual: true
field :confirmed_at, :naive_datetime
timestamps()
end
defp get_dn_for(%User{username: uid}) do
# FIXME
"uid=#{uid},ou=users,dc=recycled,dc=cloud"
end
def get_by_username(username) when is_binary(username) do
local_user = Repo.get_by(User, username: username)
if local_user do
Map.put(local_user, :email, "unknown@domain.tld")
else
query = fn ldap_conn -> Exldap.search_field(ldap_conn, :uid, username) end
case query |> LDAP.execute do
{:ok, []} -> nil
{:ok, result} ->
{:ok, entry} = result |> Enum.fetch(0)
Logger.info("Found #{entry.object_name} in directory. Syncing with \
local database.")
attributes = entry |> Map.get(:attributes) |> Enum.into(%{})
username = attributes
|> Map.get('uid')
|> Enum.at(0)
|> List.to_string
email = attributes
|> Map.get('email')
|> Enum.at(0)
|> List.to_string
case Accounts.register_user(%{username: username, email: email}) do
{:ok, user} -> user
{:error, _} -> nil
end
{:error, err} ->
Logger.warn("LDAP error: #{err}")
nil
end
end
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.
## Options
* `:hash_password` - Hashes the password so it can be stored securely
in the database and ensures the password field is cleared to prevent
leaks in the logs. If password hashing is not needed and clearing the
password field is not desired (like when using this changeset for
validations on a LiveView form), this option can be set to `false`.
Defaults to `true`.
"""
def registration_changeset(user, attrs, opts \\ []) do
user
|> cast(attrs, [:username, :password])
|> validate_email()
#|> validate_password(opts)
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.
## Options
* `:hash_password` - Hashes the password so it can be stored securely
in the database and ensures the password field is cleared to prevent
leaks in the logs. If password hashing is not needed and clearing the
password field is not desired (like when using this changeset for
validations on a LiveView form), this option can be set to `false`.
Defaults to `true`.
"""
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
dn = get_dn_for(user)
query = fn ldap_conn ->
Exldap.verify_credentials(ldap_conn, 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
user_dn = get_dn_for(user)
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