Introduce support for 3rd-party auth (OAuth2 & LDAP)
Signed-off-by: Thomas Citharel <tcit@tcit.fr>
This commit is contained in:
@@ -124,7 +124,11 @@ defmodule Mobilizon.GraphQL.Resolvers.Config do
|
||||
},
|
||||
rules: Config.instance_rules(),
|
||||
version: Config.instance_version(),
|
||||
federating: Config.instance_federating()
|
||||
federating: Config.instance_federating(),
|
||||
auth: %{
|
||||
ldap: Config.ldap_enabled?(),
|
||||
oauth_providers: Config.oauth_consumer_strategies()
|
||||
}
|
||||
}
|
||||
end
|
||||
end
|
||||
|
||||
@@ -202,10 +202,12 @@ defmodule Mobilizon.GraphQL.Resolvers.Person do
|
||||
"""
|
||||
def register_person(_parent, args, _resolution) do
|
||||
with {:ok, %User{} = user} <- Users.get_user_by_email(args.email),
|
||||
{:no_actor, nil} <- {:no_actor, Users.get_actor_for_user(user)},
|
||||
user_actor <- Users.get_actor_for_user(user),
|
||||
no_actor <- is_nil(user_actor),
|
||||
{:no_actor, true} <- {:no_actor, no_actor},
|
||||
args <- Map.put(args, :user_id, user.id),
|
||||
args <- save_attached_pictures(args),
|
||||
{:ok, %Actor{} = new_person} <- Actors.new_person(args) do
|
||||
{:ok, %Actor{} = new_person} <- Actors.new_person(args, true) do
|
||||
{:ok, new_person}
|
||||
else
|
||||
{:error, :user_not_found} ->
|
||||
|
||||
@@ -9,6 +9,7 @@ defmodule Mobilizon.GraphQL.Resolvers.User do
|
||||
alias Mobilizon.Actors.Actor
|
||||
alias Mobilizon.Crypto
|
||||
alias Mobilizon.Federation.ActivityPub
|
||||
alias Mobilizon.Service.Auth.Authenticator
|
||||
alias Mobilizon.Storage.{Page, Repo}
|
||||
alias Mobilizon.Users.{Setting, User}
|
||||
|
||||
@@ -59,18 +60,16 @@ defmodule Mobilizon.GraphQL.Resolvers.User do
|
||||
Login an user. Returns a token and the user
|
||||
"""
|
||||
def login_user(_parent, %{email: email, password: password}, _resolution) do
|
||||
with {:ok, %User{confirmed_at: %DateTime{}} = user} <- Users.get_user_by_email(email),
|
||||
{:ok, %{access_token: access_token, refresh_token: refresh_token}} <-
|
||||
Users.authenticate(%{user: user, password: password}) do
|
||||
{:ok, %{access_token: access_token, refresh_token: refresh_token, user: user}}
|
||||
else
|
||||
{:ok, %User{confirmed_at: nil} = _user} ->
|
||||
{:error, "User account not confirmed"}
|
||||
case Authenticator.authenticate(email, password) do
|
||||
{:ok,
|
||||
%{access_token: _access_token, refresh_token: _refresh_token, user: _user} =
|
||||
user_and_tokens} ->
|
||||
{:ok, user_and_tokens}
|
||||
|
||||
{:error, :user_not_found} ->
|
||||
{:error, "No user with this email was found"}
|
||||
|
||||
{:error, :unauthorized} ->
|
||||
{:error, _error} ->
|
||||
{:error, "Impossible to authenticate, either your email or password are invalid."}
|
||||
end
|
||||
end
|
||||
@@ -82,7 +81,7 @@ defmodule Mobilizon.GraphQL.Resolvers.User do
|
||||
with {:ok, user, _claims} <- Auth.Guardian.resource_from_token(refresh_token),
|
||||
{:ok, _old, {exchanged_token, _claims}} <-
|
||||
Auth.Guardian.exchange(refresh_token, ["access", "refresh"], "access"),
|
||||
{:ok, refresh_token} <- Users.generate_refresh_token(user) do
|
||||
{:ok, refresh_token} <- Authenticator.generate_refresh_token(user) do
|
||||
{:ok, %{access_token: exchanged_token, refresh_token: refresh_token}}
|
||||
else
|
||||
{:error, message} ->
|
||||
@@ -151,7 +150,7 @@ defmodule Mobilizon.GraphQL.Resolvers.User do
|
||||
{:check_confirmation_token, Email.User.check_confirmation_token(token)},
|
||||
{:get_actor, actor} <- {:get_actor, Users.get_actor_for_user(user)},
|
||||
{:ok, %{access_token: access_token, refresh_token: refresh_token}} <-
|
||||
Users.generate_tokens(user) do
|
||||
Authenticator.generate_tokens(user) do
|
||||
{:ok,
|
||||
%{
|
||||
access_token: access_token,
|
||||
@@ -192,10 +191,15 @@ defmodule Mobilizon.GraphQL.Resolvers.User do
|
||||
def send_reset_password(_parent, args, _resolution) do
|
||||
with email <- Map.get(args, :email),
|
||||
{:ok, %User{locale: locale} = user} <- Users.get_user_by_email(email, true),
|
||||
{:can_reset_password, true} <-
|
||||
{:can_reset_password, Authenticator.can_reset_password?(user)},
|
||||
{:ok, %Bamboo.Email{} = _email_html} <-
|
||||
Email.User.send_password_reset_email(user, Map.get(args, :locale, locale)) do
|
||||
{:ok, email}
|
||||
else
|
||||
{:can_reset_password, false} ->
|
||||
{:error, "This user can't reset their password"}
|
||||
|
||||
{:error, :user_not_found} ->
|
||||
# TODO : implement rate limits for this endpoint
|
||||
{:error, "No user with this email was found"}
|
||||
@@ -209,10 +213,10 @@ defmodule Mobilizon.GraphQL.Resolvers.User do
|
||||
Reset the password from an user
|
||||
"""
|
||||
def reset_password(_parent, %{password: password, token: token}, _resolution) do
|
||||
with {:ok, %User{} = user} <-
|
||||
with {:ok, %User{email: email} = user} <-
|
||||
Email.User.check_reset_password_token(password, token),
|
||||
{:ok, %{access_token: access_token, refresh_token: refresh_token}} <-
|
||||
Users.authenticate(%{user: user, password: password}) do
|
||||
Authenticator.authenticate(email, password) do
|
||||
{:ok, %{access_token: access_token, refresh_token: refresh_token, user: user}}
|
||||
end
|
||||
end
|
||||
@@ -295,10 +299,12 @@ defmodule Mobilizon.GraphQL.Resolvers.User do
|
||||
def change_password(
|
||||
_parent,
|
||||
%{old_password: old_password, new_password: new_password},
|
||||
%{context: %{current_user: %User{password_hash: old_password_hash} = user}}
|
||||
%{context: %{current_user: %User{} = user}}
|
||||
) do
|
||||
with {:current_password, true} <-
|
||||
{:current_password, Argon2.verify_pass(old_password, old_password_hash)},
|
||||
with {:can_change_password, true} <-
|
||||
{:can_change_password, Authenticator.can_change_password?(user)},
|
||||
{:current_password, {:ok, %User{}}} <-
|
||||
{:current_password, Authenticator.login(user.email, old_password)},
|
||||
{:same_password, false} <- {:same_password, old_password == new_password},
|
||||
{:ok, %User{} = user} <-
|
||||
user
|
||||
@@ -306,7 +312,7 @@ defmodule Mobilizon.GraphQL.Resolvers.User do
|
||||
|> Repo.update() do
|
||||
{:ok, user}
|
||||
else
|
||||
{:current_password, false} ->
|
||||
{:current_password, _} ->
|
||||
{:error, "The current password is invalid"}
|
||||
|
||||
{:same_password, true} ->
|
||||
@@ -323,10 +329,12 @@ defmodule Mobilizon.GraphQL.Resolvers.User do
|
||||
end
|
||||
|
||||
def change_email(_parent, %{email: new_email, password: password}, %{
|
||||
context: %{current_user: %User{email: old_email, password_hash: password_hash} = user}
|
||||
context: %{current_user: %User{email: old_email} = user}
|
||||
}) do
|
||||
with {:current_password, true} <-
|
||||
{:current_password, Argon2.verify_pass(password, password_hash)},
|
||||
with {:can_change_password, true} <-
|
||||
{:can_change_password, Authenticator.can_change_email?(user)},
|
||||
{:current_password, {:ok, %User{}}} <-
|
||||
{:current_password, Authenticator.login(user.email, password)},
|
||||
{:same_email, false} <- {:same_email, new_email == old_email},
|
||||
{:email_valid, true} <- {:email_valid, Email.Checker.valid?(new_email)},
|
||||
{:ok, %User{} = user} <-
|
||||
@@ -347,7 +355,7 @@ defmodule Mobilizon.GraphQL.Resolvers.User do
|
||||
|
||||
{:ok, user}
|
||||
else
|
||||
{:current_password, false} ->
|
||||
{:current_password, _} ->
|
||||
{:error, "The password provided is invalid"}
|
||||
|
||||
{:same_email, true} ->
|
||||
@@ -377,14 +385,24 @@ defmodule Mobilizon.GraphQL.Resolvers.User do
|
||||
end
|
||||
end
|
||||
|
||||
def delete_account(_parent, %{password: password}, %{
|
||||
context: %{current_user: %User{password_hash: password_hash} = user}
|
||||
def delete_account(_parent, args, %{
|
||||
context: %{current_user: %User{email: email} = user}
|
||||
}) do
|
||||
case {:current_password, Argon2.verify_pass(password, password_hash)} do
|
||||
{:current_password, true} ->
|
||||
with {:user_has_password, true} <- {:user_has_password, Authenticator.has_password?(user)},
|
||||
{:confirmation_password, password} when not is_nil(password) <-
|
||||
{:confirmation_password, Map.get(args, :password)},
|
||||
{:current_password, {:ok, _}} <-
|
||||
{:current_password, Authenticator.authenticate(email, password)} do
|
||||
do_delete_account(user)
|
||||
else
|
||||
# If the user hasn't got any password (3rd-party auth)
|
||||
{:user_has_password, false} ->
|
||||
do_delete_account(user)
|
||||
|
||||
{:current_password, false} ->
|
||||
{:confirmation_password, nil} ->
|
||||
{:error, "The password provided is invalid"}
|
||||
|
||||
{:current_password, _} ->
|
||||
{:error, "The password provided is invalid"}
|
||||
end
|
||||
end
|
||||
|
||||
@@ -39,6 +39,7 @@ defmodule Mobilizon.GraphQL.Schema.ConfigType do
|
||||
end
|
||||
|
||||
field(:rules, :string, description: "The instance's rules")
|
||||
field(:auth, :auth, description: "The instance auth methods")
|
||||
end
|
||||
|
||||
object :terms do
|
||||
@@ -132,6 +133,16 @@ defmodule Mobilizon.GraphQL.Schema.ConfigType do
|
||||
field(:groups, :boolean)
|
||||
end
|
||||
|
||||
object :auth do
|
||||
field(:ldap, :boolean, description: "Whether or not LDAP auth is enabled")
|
||||
field(:oauth_providers, list_of(:oauth_provider), description: "List of oauth providers")
|
||||
end
|
||||
|
||||
object :oauth_provider do
|
||||
field(:id, :string, description: "The provider ID")
|
||||
field(:label, :string, description: "The label for the auth provider")
|
||||
end
|
||||
|
||||
object :config_queries do
|
||||
@desc "Get the instance config"
|
||||
field :config, :config do
|
||||
|
||||
@@ -52,6 +52,8 @@ defmodule Mobilizon.GraphQL.Schema.UserType do
|
||||
|
||||
field(:locale, :string, description: "The user's locale")
|
||||
|
||||
field(:provider, :string, description: "The user's login provider")
|
||||
|
||||
field(:disabled, :boolean, description: "Whether the user is disabled")
|
||||
|
||||
field(:participations, :paginated_participant_list,
|
||||
|
||||
@@ -13,6 +13,7 @@ defmodule Mobilizon.Actors do
|
||||
alias Mobilizon.Media.File
|
||||
alias Mobilizon.Service.Workers
|
||||
alias Mobilizon.Storage.{Page, Repo}
|
||||
alias Mobilizon.Users
|
||||
|
||||
alias Mobilizon.Federation.ActivityPub
|
||||
|
||||
@@ -189,14 +190,19 @@ defmodule Mobilizon.Actors do
|
||||
Creates a new person actor.
|
||||
"""
|
||||
@spec new_person(map) :: {:ok, Actor.t()} | {:error, Ecto.Changeset.t()}
|
||||
def new_person(args) do
|
||||
def new_person(args, default_actor \\ false) do
|
||||
args = Map.put(args, :keys, Crypto.generate_rsa_2048_private_key())
|
||||
|
||||
with {:ok, %Actor{} = person} <-
|
||||
with {:ok, %Actor{id: person_id} = person} <-
|
||||
%Actor{}
|
||||
|> Actor.registration_changeset(args)
|
||||
|> Repo.insert() do
|
||||
Events.create_feed_token(%{user_id: args["user_id"], actor_id: person.id})
|
||||
Events.create_feed_token(%{user_id: args.user_id, actor_id: person.id})
|
||||
|
||||
if default_actor do
|
||||
user = Users.get_user!(args.user_id)
|
||||
Users.update_user(user, %{default_actor_id: person_id})
|
||||
end
|
||||
|
||||
{:ok, person}
|
||||
end
|
||||
|
||||
@@ -186,6 +186,24 @@ defmodule Mobilizon.Config do
|
||||
def anonymous_reporting?,
|
||||
do: Application.get_env(:mobilizon, :anonymous)[:reports][:allowed]
|
||||
|
||||
@spec oauth_consumer_strategies() :: list({atom(), String.t()})
|
||||
def oauth_consumer_strategies do
|
||||
[:auth, :oauth_consumer_strategies]
|
||||
|> get([])
|
||||
|> Enum.map(fn strategy ->
|
||||
case strategy do
|
||||
{id, label} when is_atom(id) -> %{id: id, label: label}
|
||||
id when is_atom(id) -> %{id: id, label: nil}
|
||||
end
|
||||
end)
|
||||
end
|
||||
|
||||
@spec oauth_consumer_enabled? :: boolean()
|
||||
def oauth_consumer_enabled?, do: oauth_consumer_strategies() != []
|
||||
|
||||
@spec ldap_enabled? :: boolean()
|
||||
def ldap_enabled?, do: get([:ldap, :enabled], false)
|
||||
|
||||
def instance_resource_providers do
|
||||
types = get_in(Application.get_env(:mobilizon, Mobilizon.Service.ResourceProviders), [:types])
|
||||
|
||||
|
||||
@@ -40,14 +40,18 @@ defmodule Mobilizon.Users.User do
|
||||
:confirmation_token,
|
||||
:reset_password_sent_at,
|
||||
:reset_password_token,
|
||||
:default_actor_id,
|
||||
:locale,
|
||||
:unconfirmed_email,
|
||||
:disabled
|
||||
:disabled,
|
||||
:provider
|
||||
]
|
||||
@attrs @required_attrs ++ @optional_attrs
|
||||
|
||||
@registration_required_attrs @required_attrs ++ [:password]
|
||||
|
||||
@auth_provider_required_attrs @required_attrs ++ [:provider]
|
||||
|
||||
@password_change_required_attrs [:password]
|
||||
@password_reset_required_attrs @password_change_required_attrs ++
|
||||
[:reset_password_token, :reset_password_sent_at]
|
||||
@@ -67,6 +71,7 @@ defmodule Mobilizon.Users.User do
|
||||
field(:unconfirmed_email, :string)
|
||||
field(:locale, :string, default: "en")
|
||||
field(:disabled, :boolean, default: false)
|
||||
field(:provider, :string)
|
||||
|
||||
belongs_to(:default_actor, Actor)
|
||||
has_many(:actors, Actor)
|
||||
@@ -116,6 +121,16 @@ defmodule Mobilizon.Users.User do
|
||||
)
|
||||
end
|
||||
|
||||
@doc false
|
||||
@spec auth_provider_changeset(t, map) :: Ecto.Changeset.t()
|
||||
def auth_provider_changeset(%__MODULE__{} = user, attrs) do
|
||||
user
|
||||
|> changeset(attrs)
|
||||
|> cast_assoc(:default_actor)
|
||||
|> put_change(:confirmed_at, DateTime.utc_now() |> DateTime.truncate(:second))
|
||||
|> validate_required(@auth_provider_required_attrs)
|
||||
end
|
||||
|
||||
@doc false
|
||||
@spec send_password_reset_changeset(t, map) :: Ecto.Changeset.t()
|
||||
def send_password_reset_changeset(%__MODULE__{} = user, attrs) do
|
||||
|
||||
@@ -15,13 +15,6 @@ defmodule Mobilizon.Users do
|
||||
alias Mobilizon.Storage.{Page, Repo}
|
||||
alias Mobilizon.Users.{Setting, User}
|
||||
|
||||
alias Mobilizon.Web.Auth
|
||||
|
||||
@type tokens :: %{
|
||||
required(:access_token) => String.t(),
|
||||
required(:refresh_token) => String.t()
|
||||
}
|
||||
|
||||
defenum(UserRole, :user_role, [:administrator, :moderator, :user])
|
||||
|
||||
defenum(NotificationPendingNotificationDelay, none: 0, direct: 1, one_hour: 5, one_day: 10)
|
||||
@@ -41,6 +34,18 @@ defmodule Mobilizon.Users do
|
||||
end
|
||||
end
|
||||
|
||||
@spec create_external(String.t(), String.t()) :: {:ok, User.t()} | {:error, Ecto.Changeset.t()}
|
||||
def create_external(email, provider) do
|
||||
with {:ok, %User{} = user} <-
|
||||
%User{}
|
||||
|> User.auth_provider_changeset(%{email: email, provider: provider})
|
||||
|> Repo.insert() do
|
||||
Events.create_feed_token(%{user_id: user.id})
|
||||
|
||||
{:ok, user}
|
||||
end
|
||||
end
|
||||
|
||||
@doc """
|
||||
Gets a single user.
|
||||
Raises `Ecto.NoResultsError` if the user does not exist.
|
||||
@@ -75,6 +80,16 @@ defmodule Mobilizon.Users do
|
||||
end
|
||||
end
|
||||
|
||||
@doc """
|
||||
Gets an user by its email.
|
||||
"""
|
||||
@spec get_user_by_email!(String.t(), boolean | nil) :: User.t()
|
||||
def get_user_by_email!(email, activated \\ nil) do
|
||||
email
|
||||
|> user_by_email_query(activated)
|
||||
|> Repo.one!()
|
||||
end
|
||||
|
||||
@doc """
|
||||
Get an user by its activation token.
|
||||
"""
|
||||
@@ -267,52 +282,6 @@ defmodule Mobilizon.Users do
|
||||
@spec count_users :: integer
|
||||
def count_users, do: Repo.one(from(u in User, select: count(u.id)))
|
||||
|
||||
@doc """
|
||||
Authenticate an user.
|
||||
"""
|
||||
@spec authenticate(User.t()) :: {:ok, tokens} | {:error, :unauthorized}
|
||||
def authenticate(%{user: %User{password_hash: password_hash} = user, password: password}) do
|
||||
# Does password match the one stored in the database?
|
||||
if Argon2.verify_pass(password, password_hash) do
|
||||
{:ok, _tokens} = generate_tokens(user)
|
||||
else
|
||||
{:error, :unauthorized}
|
||||
end
|
||||
end
|
||||
|
||||
@doc """
|
||||
Generates access token and refresh token for an user.
|
||||
"""
|
||||
@spec generate_tokens(User.t()) :: {:ok, tokens}
|
||||
def generate_tokens(user) do
|
||||
with {:ok, access_token} <- generate_access_token(user),
|
||||
{:ok, refresh_token} <- generate_refresh_token(user) do
|
||||
{:ok, %{access_token: access_token, refresh_token: refresh_token}}
|
||||
end
|
||||
end
|
||||
|
||||
@doc """
|
||||
Generates access token for an user.
|
||||
"""
|
||||
@spec generate_access_token(User.t()) :: {:ok, String.t()}
|
||||
def generate_access_token(user) do
|
||||
with {:ok, access_token, _claims} <-
|
||||
Auth.Guardian.encode_and_sign(user, %{}, token_type: "access") do
|
||||
{:ok, access_token}
|
||||
end
|
||||
end
|
||||
|
||||
@doc """
|
||||
Generates refresh token for an user.
|
||||
"""
|
||||
@spec generate_refresh_token(User.t()) :: {:ok, String.t()}
|
||||
def generate_refresh_token(user) do
|
||||
with {:ok, refresh_token, _claims} <-
|
||||
Auth.Guardian.encode_and_sign(user, %{}, token_type: "refresh") do
|
||||
{:ok, refresh_token}
|
||||
end
|
||||
end
|
||||
|
||||
@doc """
|
||||
Gets a settings for an user.
|
||||
|
||||
|
||||
93
lib/service/auth/authenticator.ex
Normal file
93
lib/service/auth/authenticator.ex
Normal file
@@ -0,0 +1,93 @@
|
||||
defmodule Mobilizon.Service.Auth.Authenticator do
|
||||
@moduledoc """
|
||||
Module to handle authentification (currently through database or LDAP)
|
||||
"""
|
||||
alias Mobilizon.Users
|
||||
alias Mobilizon.Users.User
|
||||
alias Mobilizon.Web.Auth.Guardian
|
||||
|
||||
@type tokens :: %{
|
||||
required(:access_token) => String.t(),
|
||||
required(:refresh_token) => String.t()
|
||||
}
|
||||
|
||||
@type tokens_with_user :: %{
|
||||
required(:access_token) => String.t(),
|
||||
required(:refresh_token) => String.t(),
|
||||
required(:user) => User.t()
|
||||
}
|
||||
|
||||
def implementation do
|
||||
Mobilizon.Config.get(
|
||||
Mobilizon.Service.Auth.Authenticator,
|
||||
Mobilizon.Service.Auth.MobilizonAuthenticator
|
||||
)
|
||||
end
|
||||
|
||||
@callback login(String.t(), String.t()) :: {:ok, User.t()} | {:error, any()}
|
||||
@spec login(String.t(), String.t()) :: {:ok, User.t()} | {:error, any()}
|
||||
def login(email, password), do: implementation().login(email, password)
|
||||
|
||||
@callback can_change_email?(User.t()) :: boolean
|
||||
def can_change_email?(%User{} = user), do: implementation().can_change_email?(user)
|
||||
|
||||
@callback can_change_password?(User.t()) :: boolean
|
||||
def can_change_password?(%User{} = user), do: implementation().can_change_password?(user)
|
||||
|
||||
@spec has_password?(User.t()) :: boolean()
|
||||
def has_password?(%User{provider: provider}), do: is_nil(provider) or provider == "ldap"
|
||||
|
||||
@spec can_reset_password?(User.t()) :: boolean()
|
||||
def can_reset_password?(%User{} = user), do: has_password?(user) && can_change_password?(user)
|
||||
|
||||
@spec authenticate(String.t(), String.t()) :: {:ok, tokens_with_user()}
|
||||
def authenticate(email, password) do
|
||||
with {:ok, %User{} = user} <- login(email, password),
|
||||
{:ok, %{access_token: access_token, refresh_token: refresh_token}} <-
|
||||
generate_tokens(user) do
|
||||
{:ok, %{access_token: access_token, refresh_token: refresh_token, user: user}}
|
||||
end
|
||||
end
|
||||
|
||||
@doc """
|
||||
Generates access token and refresh token for an user.
|
||||
"""
|
||||
@spec generate_tokens(User.t()) :: {:ok, tokens}
|
||||
def generate_tokens(user) do
|
||||
with {:ok, access_token} <- generate_access_token(user),
|
||||
{:ok, refresh_token} <- generate_refresh_token(user) do
|
||||
{:ok, %{access_token: access_token, refresh_token: refresh_token}}
|
||||
end
|
||||
end
|
||||
|
||||
@doc """
|
||||
Generates access token for an user.
|
||||
"""
|
||||
@spec generate_access_token(User.t()) :: {:ok, String.t()}
|
||||
def generate_access_token(user) do
|
||||
with {:ok, access_token, _claims} <-
|
||||
Guardian.encode_and_sign(user, %{}, token_type: "access") do
|
||||
{:ok, access_token}
|
||||
end
|
||||
end
|
||||
|
||||
@doc """
|
||||
Generates refresh token for an user.
|
||||
"""
|
||||
@spec generate_refresh_token(User.t()) :: {:ok, String.t()}
|
||||
def generate_refresh_token(user) do
|
||||
with {:ok, refresh_token, _claims} <-
|
||||
Guardian.encode_and_sign(user, %{}, token_type: "refresh") do
|
||||
{:ok, refresh_token}
|
||||
end
|
||||
end
|
||||
|
||||
@spec fetch_user(String.t()) :: User.t() | {:error, :user_not_found}
|
||||
def fetch_user(nil), do: {:error, :user_not_found}
|
||||
|
||||
def fetch_user(email) when not is_nil(email) do
|
||||
with {:ok, %User{} = user} <- Users.get_user_by_email(email, true) do
|
||||
user
|
||||
end
|
||||
end
|
||||
end
|
||||
180
lib/service/auth/ldap_authenticator.ex
Normal file
180
lib/service/auth/ldap_authenticator.ex
Normal file
@@ -0,0 +1,180 @@
|
||||
# Portions of this file are derived from Pleroma:
|
||||
# Pleroma: A lightweight social networking server
|
||||
# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/>
|
||||
# SPDX-License-Identifier: AGPL-3.0-only
|
||||
|
||||
defmodule Mobilizon.Service.Auth.LDAPAuthenticator do
|
||||
@moduledoc """
|
||||
Authenticate Mobilizon users through LDAP accounts
|
||||
"""
|
||||
alias Mobilizon.Service.Auth.{Authenticator, MobilizonAuthenticator}
|
||||
alias Mobilizon.Users
|
||||
alias Mobilizon.Users.User
|
||||
|
||||
require Logger
|
||||
|
||||
import Authenticator,
|
||||
only: [fetch_user: 1]
|
||||
|
||||
@behaviour Authenticator
|
||||
@base MobilizonAuthenticator
|
||||
|
||||
@connection_timeout 10_000
|
||||
@search_timeout 10_000
|
||||
|
||||
def login(email, password) do
|
||||
with {:ldap, true} <- {:ldap, Mobilizon.Config.get([:ldap, :enabled])},
|
||||
%User{} = user <- ldap_user(email, password) do
|
||||
{:ok, user}
|
||||
else
|
||||
{:error, {:ldap_connection_error, _}} ->
|
||||
# When LDAP is unavailable, try default authenticator
|
||||
@base.login(email, password)
|
||||
|
||||
{:ldap, _} ->
|
||||
@base.login(email, password)
|
||||
|
||||
error ->
|
||||
error
|
||||
end
|
||||
end
|
||||
|
||||
def can_change_email?(%User{provider: provider}), do: provider != "ldap"
|
||||
|
||||
def can_change_password?(%User{provider: provider}), do: provider != "ldap"
|
||||
|
||||
defp ldap_user(email, password) do
|
||||
ldap = Mobilizon.Config.get(:ldap, [])
|
||||
host = Keyword.get(ldap, :host, "localhost")
|
||||
port = Keyword.get(ldap, :port, 389)
|
||||
ssl = Keyword.get(ldap, :ssl, false)
|
||||
sslopts = Keyword.get(ldap, :sslopts, [])
|
||||
|
||||
options =
|
||||
[{:port, port}, {:ssl, ssl}, {:timeout, @connection_timeout}] ++
|
||||
if sslopts != [], do: [{:sslopts, sslopts}], else: []
|
||||
|
||||
case :eldap.open([to_charlist(host)], options) do
|
||||
{:ok, connection} ->
|
||||
try do
|
||||
ensure_eventual_tls(connection, ldap)
|
||||
|
||||
base = Keyword.get(ldap, :base)
|
||||
uid_field = Keyword.get(ldap, :uid, "cn")
|
||||
|
||||
# We first need to find the LDAP UID/CN for this specif email
|
||||
with uid when is_binary(uid) <- search_user(connection, ldap, base, uid_field, email),
|
||||
# Then we can verify the user's password
|
||||
:ok <- bind_user(connection, base, uid_field, uid, password) do
|
||||
case fetch_user(email) do
|
||||
%User{} = user ->
|
||||
user
|
||||
|
||||
_ ->
|
||||
register_user(email)
|
||||
end
|
||||
else
|
||||
{:error, error} ->
|
||||
{:error, error}
|
||||
|
||||
error ->
|
||||
{:error, error}
|
||||
end
|
||||
after
|
||||
:eldap.close(connection)
|
||||
end
|
||||
|
||||
{:error, error} ->
|
||||
Logger.error("Could not open LDAP connection: #{inspect(error)}")
|
||||
{:error, {:ldap_connection_error, error}}
|
||||
end
|
||||
end
|
||||
|
||||
@spec bind_user(any(), String.t(), String.t(), String.t(), String.t()) ::
|
||||
User.t() | any()
|
||||
defp bind_user(connection, base, uid, field, password) do
|
||||
bind = "#{uid}=#{field},#{base}"
|
||||
Logger.debug("Binding to LDAP with \"#{bind}\"")
|
||||
:eldap.simple_bind(connection, bind, password)
|
||||
end
|
||||
|
||||
@spec search_user(any(), Keyword.t(), String.t(), String.t(), String.t()) ::
|
||||
String.t() | {:error, :ldap_registration_missing_attributes} | any()
|
||||
defp search_user(connection, ldap, base, uid, email) do
|
||||
# We may need to bind before performing the search
|
||||
res =
|
||||
if Keyword.get(ldap, :require_bind_for_search, true) do
|
||||
admin_field = Keyword.get(ldap, :bind_uid)
|
||||
admin_password = Keyword.get(ldap, :bind_password)
|
||||
bind_user(connection, base, uid, admin_field, admin_password)
|
||||
else
|
||||
:ok
|
||||
end
|
||||
|
||||
if res == :ok do
|
||||
do_search_user(connection, base, uid, email)
|
||||
else
|
||||
res
|
||||
end
|
||||
end
|
||||
|
||||
# Search an user by uid to find their CN
|
||||
@spec do_search_user(any(), String.t(), String.t(), String.t()) ::
|
||||
String.t() | {:error, :ldap_registration_missing_attributes} | any()
|
||||
defp do_search_user(connection, base, uid, email) do
|
||||
with {:ok, {:eldap_search_result, [{:eldap_entry, _, attributes}], _}} <-
|
||||
:eldap.search(connection, [
|
||||
{:base, to_charlist(base)},
|
||||
{:filter, :eldap.equalityMatch(to_charlist("mail"), to_charlist(email))},
|
||||
{:scope, :eldap.wholeSubtree()},
|
||||
{:attributes, [to_charlist(uid)]},
|
||||
{:timeout, @search_timeout}
|
||||
]),
|
||||
{:uid, {_, [uid]}} <- {:uid, List.keyfind(attributes, to_charlist(uid), 0)} do
|
||||
:erlang.list_to_binary(uid)
|
||||
else
|
||||
{:ok, {:eldap_search_result, [], []}} ->
|
||||
Logger.info("Unable to find user with email #{email}")
|
||||
{:error, :ldap_search_email_not_found}
|
||||
|
||||
{:cn, err} ->
|
||||
Logger.error("Could not find LDAP attribute CN: #{inspect(err)}")
|
||||
{:error, :ldap_searcy_missing_attributes}
|
||||
|
||||
error ->
|
||||
error
|
||||
end
|
||||
end
|
||||
|
||||
@spec register_user(String.t()) :: User.t() | any()
|
||||
defp register_user(email) do
|
||||
case Users.create_external(email, "ldap") do
|
||||
{:ok, %User{} = user} ->
|
||||
user
|
||||
|
||||
error ->
|
||||
error
|
||||
end
|
||||
end
|
||||
|
||||
@spec ensure_eventual_tls(any(), Keyword.t()) :: :ok
|
||||
defp ensure_eventual_tls(connection, ldap) do
|
||||
if Keyword.get(ldap, :tls, false) do
|
||||
:application.ensure_all_started(:ssl)
|
||||
|
||||
case :eldap.start_tls(
|
||||
connection,
|
||||
Keyword.get(ldap, :tlsopts, []),
|
||||
@connection_timeout
|
||||
) do
|
||||
:ok ->
|
||||
:ok
|
||||
|
||||
error ->
|
||||
Logger.error("Could not start TLS: #{inspect(error)}")
|
||||
end
|
||||
end
|
||||
|
||||
:ok
|
||||
end
|
||||
end
|
||||
39
lib/service/auth/mobilizon_authenticator.ex
Normal file
39
lib/service/auth/mobilizon_authenticator.ex
Normal file
@@ -0,0 +1,39 @@
|
||||
defmodule Mobilizon.Service.Auth.MobilizonAuthenticator do
|
||||
@moduledoc """
|
||||
Authenticate Mobilizon users through database accounts
|
||||
"""
|
||||
alias Mobilizon.Users.User
|
||||
|
||||
alias Mobilizon.Service.Auth.Authenticator
|
||||
|
||||
import Authenticator,
|
||||
only: [fetch_user: 1]
|
||||
|
||||
@behaviour Authenticator
|
||||
|
||||
def login(email, password) do
|
||||
require Logger
|
||||
|
||||
with {:user, %User{password_hash: password_hash, provider: nil} = user}
|
||||
when not is_nil(password_hash) <-
|
||||
{:user, fetch_user(email)},
|
||||
{:acceptable_password, true} <-
|
||||
{:acceptable_password, not (is_nil(password) || password == "")},
|
||||
{:checkpw, true} <- {:checkpw, Argon2.verify_pass(password, password_hash)} do
|
||||
{:ok, user}
|
||||
else
|
||||
{:user, {:error, :user_not_found}} ->
|
||||
{:error, :user_not_found}
|
||||
|
||||
{:acceptable_password, false} ->
|
||||
{:error, :bad_password}
|
||||
|
||||
{:checkpw, false} ->
|
||||
{:error, :bad_password}
|
||||
end
|
||||
end
|
||||
|
||||
def can_change_email?(%User{provider: provider}), do: is_nil(provider)
|
||||
|
||||
def can_change_password?(%User{provider: provider}), do: is_nil(provider)
|
||||
end
|
||||
82
lib/web/controllers/auth_controller.ex
Normal file
82
lib/web/controllers/auth_controller.ex
Normal file
@@ -0,0 +1,82 @@
|
||||
defmodule Mobilizon.Web.AuthController do
|
||||
use Mobilizon.Web, :controller
|
||||
|
||||
alias Mobilizon.Service.Auth.Authenticator
|
||||
alias Mobilizon.Users
|
||||
alias Mobilizon.Users.User
|
||||
require Logger
|
||||
plug(:put_layout, false)
|
||||
|
||||
plug(Ueberauth)
|
||||
|
||||
def request(conn, %{"provider" => provider} = _params) do
|
||||
redirect(conn, to: "/login?code=Login Provider not found&provider=#{provider}")
|
||||
end
|
||||
|
||||
def callback(
|
||||
%{assigns: %{ueberauth_failure: fails}} = conn,
|
||||
%{"provider" => provider} = _params
|
||||
) do
|
||||
Logger.warn("Unable to login user with #{provider} #{inspect(fails)}")
|
||||
|
||||
redirect(conn, to: "/login?code=Error with Login Provider&provider=#{provider}")
|
||||
end
|
||||
|
||||
def callback(
|
||||
%{assigns: %{ueberauth_auth: %Ueberauth.Auth{strategy: strategy} = auth}} = conn,
|
||||
_params
|
||||
) do
|
||||
email = email_from_ueberauth(auth)
|
||||
[_, _, _, strategy] = strategy |> to_string() |> String.split(".")
|
||||
strategy = String.downcase(strategy)
|
||||
|
||||
user =
|
||||
with {:valid_email, false} <- {:valid_email, is_nil(email) or email == ""},
|
||||
{:error, :user_not_found} <- Users.get_user_by_email(email),
|
||||
{:ok, %User{} = user} <- Users.create_external(email, strategy) do
|
||||
user
|
||||
else
|
||||
{:ok, %User{} = user} ->
|
||||
user
|
||||
|
||||
{:error, error} ->
|
||||
{:error, error}
|
||||
|
||||
error ->
|
||||
{:error, error}
|
||||
end
|
||||
|
||||
with %User{} = user <- user,
|
||||
{:ok, %{access_token: access_token, refresh_token: refresh_token}} <-
|
||||
Authenticator.generate_tokens(user) do
|
||||
Logger.info("Logged-in user \"#{email}\" through #{strategy}")
|
||||
|
||||
render(conn, "callback.html", %{
|
||||
access_token: access_token,
|
||||
refresh_token: refresh_token,
|
||||
user: user
|
||||
})
|
||||
else
|
||||
err ->
|
||||
Logger.warn("Unable to login user \"#{email}\" #{inspect(err)}")
|
||||
redirect(conn, to: "/login?code=Error with Login Provider&provider=#{strategy}")
|
||||
end
|
||||
end
|
||||
|
||||
# Github only give public emails as part of the user profile,
|
||||
# so we explicitely request all user emails and filter on the primary one
|
||||
defp email_from_ueberauth(%Ueberauth.Auth{
|
||||
strategy: Ueberauth.Strategy.Github,
|
||||
extra: %Ueberauth.Auth.Extra{raw_info: %{user: %{"emails" => emails}}}
|
||||
})
|
||||
when length(emails) > 0,
|
||||
do: emails |> Enum.find(& &1["primary"]) |> (& &1["email"]).()
|
||||
|
||||
defp email_from_ueberauth(%Ueberauth.Auth{
|
||||
extra: %Ueberauth.Auth.Extra{raw_info: %{user: %{"email" => email}}}
|
||||
})
|
||||
when not is_nil(email) and email != "",
|
||||
do: email
|
||||
|
||||
defp email_from_ueberauth(_), do: nil
|
||||
end
|
||||
@@ -150,6 +150,10 @@ defmodule Mobilizon.Web.Router do
|
||||
get("/groups/me", PageController, :index, as: "my_groups")
|
||||
|
||||
get("/interact", PageController, :interact)
|
||||
|
||||
get("/auth/:provider", AuthController, :request)
|
||||
get("/auth/:provider/callback", AuthController, :callback)
|
||||
post("/auth/:provider/callback", AuthController, :callback)
|
||||
end
|
||||
|
||||
scope "/proxy/", Mobilizon.Web do
|
||||
|
||||
29
lib/web/views/auth_view.ex
Normal file
29
lib/web/views/auth_view.ex
Normal file
@@ -0,0 +1,29 @@
|
||||
defmodule Mobilizon.Web.AuthView do
|
||||
@moduledoc """
|
||||
View for the auth routes
|
||||
"""
|
||||
|
||||
use Mobilizon.Web, :view
|
||||
alias Mobilizon.Service.Metadata.Instance
|
||||
alias Phoenix.HTML.Tag
|
||||
import Mobilizon.Web.Views.Utils
|
||||
|
||||
def render("callback.html", %{
|
||||
conn: conn,
|
||||
access_token: access_token,
|
||||
refresh_token: refresh_token,
|
||||
user: %{id: user_id, email: user_email, role: user_role, default_actor_id: user_actor_id}
|
||||
}) do
|
||||
info_tags = [
|
||||
Tag.tag(:meta, name: "auth-access-token", content: access_token),
|
||||
Tag.tag(:meta, name: "auth-refresh-token", content: refresh_token),
|
||||
Tag.tag(:meta, name: "auth-user-id", content: user_id),
|
||||
Tag.tag(:meta, name: "auth-user-email", content: user_email),
|
||||
Tag.tag(:meta, name: "auth-user-role", content: user_role),
|
||||
Tag.tag(:meta, name: "auth-user-actor-id", content: user_actor_id)
|
||||
]
|
||||
|
||||
tags = Instance.build_tags() ++ info_tags
|
||||
inject_tags(tags, get_locale(conn))
|
||||
end
|
||||
end
|
||||
Reference in New Issue
Block a user