Separate Web modules related to Federation

This commit is contained in:
rustra 2020-01-23 00:55:07 +01:00
parent 47d32d2b18
commit a239d1e0b0
42 changed files with 279 additions and 337 deletions

View File

@ -662,9 +662,7 @@ defmodule Mobilizon.Federation.ActivityPub do
{:ok, comments, total_comments} = Events.list_public_comments_for_actor(actor, page, limit)
event_activities = Enum.map(events, &event_to_activity/1)
comment_activities = Enum.map(comments, &comment_to_activity/1)
activities = event_activities ++ comment_activities
%{elements: activities, total: total_events + total_comments}
@ -740,13 +738,8 @@ defmodule Mobilizon.Federation.ActivityPub do
defp check_for_tombstones(%{url: url}), do: Tombstone.find_tombstone(url)
defp check_for_tombstones(_), do: nil
@spec update_event(Event.t(), map(), map()) ::
{:ok, Event.t(), Activity.t()} | any()
defp update_event(
%Event{} = old_event,
args,
additional
) do
@spec update_event(Event.t(), map(), map()) :: {:ok, Event.t(), Activity.t()} | any()
defp update_event(%Event{} = old_event, args, additional) do
with args <- prepare_args_for_event(args),
{:ok, %Event{} = new_event} <- Events.update_event(old_event, args),
{:ok, true} <- Cachex.del(:activity_pub, "event_#{new_event.uuid}"),
@ -763,8 +756,7 @@ defmodule Mobilizon.Federation.ActivityPub do
end
end
@spec update_actor(Actor.t(), map(), map()) ::
{:ok, Actor.t(), Activity.t()} | any()
@spec update_actor(Actor.t(), map, map) :: {:ok, Actor.t(), Activity.t()} | any
defp update_actor(%Actor{} = old_actor, args, additional) do
with {:ok, %Actor{} = new_actor} <- Actors.update_actor(old_actor, args),
actor_as_data <- Convertible.model_to_as(new_actor),
@ -777,12 +769,8 @@ defmodule Mobilizon.Federation.ActivityPub do
end
end
@spec accept_follow(Follower.t(), map()) ::
{:ok, Follower.t(), Activity.t()} | any()
defp accept_follow(
%Follower{} = follower,
additional
) do
@spec accept_follow(Follower.t(), map) :: {:ok, Follower.t(), Activity.t()} | any
defp accept_follow(%Follower{} = follower, additional) do
with {:ok, %Follower{} = follower} <- Actors.update_follower(follower, %{approved: true}),
follower_as_data <- Convertible.model_to_as(follower),
update_data <-
@ -804,12 +792,8 @@ defmodule Mobilizon.Federation.ActivityPub do
end
end
@spec accept_join(Participant.t(), map()) ::
{:ok, Participant.t(), Activity.t()} | any()
defp accept_join(
%Participant{} = participant,
additional
) do
@spec accept_join(Participant.t(), map) :: {:ok, Participant.t(), Activity.t()} | any
defp accept_join(%Participant{} = participant, additional) do
with {:ok, %Participant{} = participant} <-
Events.update_participant(participant, %{role: :participant}),
Absinthe.Subscription.publish(MobilizonWeb.Endpoint, participant.actor,
@ -834,8 +818,7 @@ defmodule Mobilizon.Federation.ActivityPub do
end
end
@spec reject_join(Participant.t(), map()) ::
{:ok, Participant.t(), Activity.t()} | any()
@spec reject_join(Participant.t(), map()) :: {:ok, Participant.t(), Activity.t()} | any()
defp reject_join(%Participant{} = participant, additional) do
with {:ok, %Participant{} = participant} <-
Events.update_participant(participant, %{approved: false, role: :rejected}),
@ -866,8 +849,7 @@ defmodule Mobilizon.Federation.ActivityPub do
end
end
@spec reject_follow(Follower.t(), map()) ::
{:ok, Follower.t(), Activity.t()} | any()
@spec reject_follow(Follower.t(), map()) :: {:ok, Follower.t(), Activity.t()} | any()
defp reject_follow(%Follower{} = follower, additional) do
with {:ok, %Follower{} = follower} <- Actors.delete_follower(follower),
follower_as_data <- Convertible.model_to_as(follower),

View File

@ -3,10 +3,11 @@
# SPDX-License-Identifier: AGPL-3.0-only
# Upstream: https://git.pleroma.social/pleroma/pleroma/blob/develop/lib/pleroma/web/activity_pub/activity_pub_controller.ex
defmodule MobilizonWeb.ActivityPubController do
use MobilizonWeb, :controller
defmodule Mobilizon.Federation.ActivityPubController do
use Mobilizon.Federation, :controller
alias Mobilizon.{Actors, Actors.Actor, Config}
alias Mobilizon.{Actors, Config}
alias Mobilizon.Actors.Actor
alias Mobilizon.Federation.ActivityPub
alias Mobilizon.Federation.ActivityPub.Federator
@ -18,7 +19,7 @@ defmodule MobilizonWeb.ActivityPubController do
action_fallback(:errors)
plug(MobilizonWeb.Plugs.Federating when action in [:inbox, :relay])
plug(Mobilizon.Federation.Plugs.Federating when action in [:inbox, :relay])
plug(:relay_active? when action in [:relay])
def relay_active?(conn, _) do

View File

@ -3,10 +3,11 @@
# Copyright © 2017-2019 Pleroma Authors <https://pleroma.social/>
# SPDX-License-Identifier: AGPL-3.0-only
defmodule MobilizonWeb.Plugs.Federating do
defmodule Mobilizon.Federation.Plugs.Federating do
@moduledoc """
Restrict ActivityPub routes when not federating
"""
import Plug.Conn
def init(options) do

View File

@ -3,14 +3,13 @@
# SPDX-License-Identifier: AGPL-3.0-only
# Upstream: https://git.pleroma.social/pleroma/pleroma/blob/develop/lib/pleroma/plugs/http_signature.ex
defmodule MobilizonWeb.HTTPSignaturePlug do
defmodule Mobilizon.Federation.Plugs.HTTPSignatures do
@moduledoc """
# HTTPSignaturePlug
Plug to check HTTP Signatures on every incoming request
"""
import Plug.Conn
require Logger
def init(options) do

View File

@ -7,11 +7,12 @@ defmodule Mix.Tasks.Mobilizon.SetupSearch do
use Mix.Task
alias Mobilizon.Service.Workers.BuildSearchWorker
alias Mobilizon.Storage.Repo
alias Mobilizon.Events.Event
import Ecto.Query
alias Mobilizon.Events.Event
alias Mobilizon.Service.Workers
alias Mobilizon.Storage.Repo
require Logger
@shortdoc "Insert search data"
@ -30,7 +31,7 @@ defmodule Mix.Tasks.Mobilizon.SetupSearch do
end
defp insert_search_event([%Event{url: url} = event | events], nb_events) do
case BuildSearchWorker.insert_search_event(event) do
case Workers.BuildSearch.insert_search_event(event) do
{:ok, _} ->
Logger.debug("Added event #{url} to the search")

View File

@ -11,7 +11,7 @@ defmodule Mobilizon.Actors do
alias Mobilizon.Actors.{Actor, Bot, Follower, Member}
alias Mobilizon.{Crypto, Events}
alias Mobilizon.Media.File
alias Mobilizon.Service.Workers.BackgroundWorker
alias Mobilizon.Service.Workers
alias Mobilizon.Storage.{Page, Repo}
alias Mobilizon.Federation.ActivityPub
@ -229,7 +229,7 @@ defmodule Mobilizon.Actors do
end
def delete_actor(%Actor{} = actor) do
BackgroundWorker.enqueue("delete_actor", %{"actor_id" => actor.id})
Workers.Background.enqueue("delete_actor", %{"actor_id" => actor.id})
end
@doc """

View File

@ -13,7 +13,6 @@ defmodule Mobilizon.Events do
alias Mobilizon.Actors.Actor
alias Mobilizon.Addresses.Address
alias Mobilizon.Service.Workers.BuildSearchWorker
alias Mobilizon.Events.{
Comment,
@ -27,9 +26,12 @@ defmodule Mobilizon.Events do
Track
}
alias Mobilizon.Service.Workers
alias Mobilizon.Storage.{Page, Repo}
alias Mobilizon.Users.User
alias MobilizonWeb.Email
defenum(EventVisibility, :event_visibility, [
:public,
:unlisted,
@ -264,7 +266,7 @@ defmodule Mobilizon.Events do
with {:ok, %{insert: %Event{} = event}} <- do_create_event(attrs),
%Event{} = event <- Repo.preload(event, @event_preloads) do
unless event.draft,
do: BuildSearchWorker.enqueue(:insert_search_event, %{"event_id" => event.id})
do: Workers.BuildSearch.enqueue(:insert_search_event, %{"event_id" => event.id})
{:ok, event}
else
@ -308,10 +310,7 @@ defmodule Mobilizon.Events do
Event.update_changeset(Repo.preload(old_event, :tags), attrs),
{:ok, %{update: %Event{} = new_event}} <-
Multi.new()
|> Multi.update(
:update,
changeset
)
|> Multi.update(:update, changeset)
|> Multi.run(:write, fn _repo, %{update: %Event{draft: draft} = event} ->
with {:was_draft, true} <- {:was_draft, old_draft == true && draft == false},
{:ok, %Participant{} = participant} <-
@ -332,14 +331,14 @@ defmodule Mobilizon.Events do
|> Repo.transaction() do
Cachex.del(:ics, "event_#{new_event.uuid}")
Mobilizon.Service.Events.Tool.calculate_event_diff_and_send_notifications(
Email.Events.calculate_event_diff_and_send_notifications(
old_event,
new_event,
changes
)
unless new_event.draft,
do: BuildSearchWorker.enqueue(:update_search_event, %{"event_id" => new_event.id})
do: BuildSearch.enqueue(:update_search_event, %{"event_id" => new_event.id})
{:ok, Repo.preload(new_event, @event_preloads)}
end

View File

@ -0,0 +1,9 @@
defmodule Mobilizon.Users.Guards do
@moduledoc """
Guards for users
"""
defguard is_admin(role) when is_atom(role) and role == :administrator
defguard is_moderator(role) when is_atom(role) and role in [:administrator, :moderator]
end

View File

@ -10,9 +10,10 @@ defmodule Mobilizon.Users.User do
alias Mobilizon.Actors.Actor
alias Mobilizon.Crypto
alias Mobilizon.Events.FeedToken
alias Mobilizon.Service.EmailChecker
alias Mobilizon.Users.UserRole
alias MobilizonWeb.Email
@type t :: %__MODULE__{
email: String.t(),
password_hash: String.t(),
@ -176,7 +177,7 @@ defmodule Mobilizon.Users.User do
case changeset do
%Ecto.Changeset{valid?: true, changes: %{email: email}} ->
case EmailChecker.valid?(email) do
case Email.Checker.valid?(email) do
false ->
add_error(changeset, :email, "Email doesn't fit required format")

View File

@ -3,7 +3,7 @@ defmodule MobilizonWeb.API.Reports do
API for Reports.
"""
import Mobilizon.Service.Admin.ActionLogService
import Mobilizon.Service.Admin.ActionLog
alias Mobilizon.Actors.Actor
alias Mobilizon.Reports, as: ReportsAction

View File

@ -12,7 +12,7 @@ defmodule MobilizonWeb.WebFingerController do
alias Mobilizon.Federation.WebFinger
plug(MobilizonWeb.Plugs.Federating)
plug(Mobilizon.Federation.Plugs.Federating)
@doc """
Provides /.well-known/host-meta

View File

@ -1,4 +1,4 @@
defmodule Mobilizon.Service.EmailChecker do
defmodule MobilizonWeb.Email.Checker do
@moduledoc """
Provides a function to test emails against a "not so bad" regex.
"""

View File

@ -9,11 +9,16 @@ defmodule MobilizonWeb.Email.Event do
import MobilizonWeb.Gettext
alias Mobilizon.Events.Event
alias Mobilizon.Actors.Actor
alias Mobilizon.Events
alias Mobilizon.Events.Event
alias Mobilizon.Storage.Repo
alias Mobilizon.Users.User
alias MobilizonWeb.Email
@important_changes [:title, :begins_on, :ends_on, :status]
@spec event_updated(User.t(), Actor.t(), Event.t(), Event.t(), list(), String.t()) ::
Bamboo.Email.t()
def event_updated(
@ -40,4 +45,41 @@ defmodule MobilizonWeb.Email.Event do
|> assign(:subject, subject)
|> render(:event_updated)
end
def calculate_event_diff_and_send_notifications(
%Event{} = old_event,
%Event{id: event_id} = event,
changes
) do
important = MapSet.new(@important_changes)
diff =
changes
|> Map.keys()
|> MapSet.new()
|> MapSet.intersection(important)
if MapSet.size(diff) > 0 do
Repo.transaction(fn ->
event_id
|> Events.list_local_emails_user_participants_for_event_query()
|> Repo.stream()
|> Enum.to_list()
|> Enum.each(
&send_notification_for_event_update_to_participant(&1, old_event, event, diff)
)
end)
end
end
defp send_notification_for_event_update_to_participant(
{%Actor{} = actor, %User{locale: locale} = user},
%Event{} = old_event,
%Event{} = event,
diff
) do
user
|> Email.Event.event_updated(actor, old_event, event, diff, locale)
|> Email.Mailer.deliver_later()
end
end

View File

@ -9,11 +9,14 @@ defmodule MobilizonWeb.Email.User do
import MobilizonWeb.Gettext
alias Mobilizon.Config
alias Mobilizon.{Config, Crypto, Users}
alias Mobilizon.Storage.Repo
alias Mobilizon.Users.User
alias MobilizonWeb.Email
require Logger
@spec confirmation_email(User.t(), String.t()) :: Bamboo.Email.t()
def confirmation_email(
%User{email: email, confirmation_token: confirmation_token},
@ -53,4 +56,108 @@ defmodule MobilizonWeb.Email.User do
|> assign(:subject, subject)
|> render(:password_reset)
end
def check_confirmation_token(token) when is_binary(token) do
with %User{} = user <- Users.get_user_by_activation_token(token),
{:ok, %User{} = user} <-
Users.update_user(user, %{
"confirmed_at" => DateTime.utc_now() |> DateTime.truncate(:second),
"confirmation_sent_at" => nil,
"confirmation_token" => nil
}) do
Logger.info("User #{user.email} has been confirmed")
{:ok, user}
else
_err ->
{:error, :invalid_token}
end
end
def resend_confirmation_email(%User{} = user, locale \\ "en") do
with :ok <- we_can_send_email(user, :confirmation_sent_at),
{:ok, user} <-
Users.update_user(user, %{
"confirmation_sent_at" => DateTime.utc_now() |> DateTime.truncate(:second)
}) do
send_confirmation_email(user, locale)
Logger.info("Sent confirmation email again to #{user.email}")
{:ok, user.email}
end
end
def send_confirmation_email(%User{} = user, locale \\ "en") do
user
|> Email.User.confirmation_email(locale)
|> Email.Mailer.deliver_later()
end
@doc """
Check that the provided token is correct and update provided password
"""
@spec check_reset_password_token(String.t(), String.t()) :: tuple
def check_reset_password_token(password, token) do
with %User{} = user <- Users.get_user_by_reset_password_token(token),
{:ok, %User{} = user} <-
Repo.update(
User.password_reset_changeset(user, %{
"password" => password,
"reset_password_sent_at" => nil,
"reset_password_token" => nil
})
) do
{:ok, user}
else
{:error, %Ecto.Changeset{errors: [password: {"registration.error.password_too_short", _}]}} ->
{:error,
"The password you have choosen is too short. Please make sure your password contains at least 6 charaters."}
_err ->
{:error,
"The token you provided is invalid. Make sure that the URL is exactly the one provided inside the email you got."}
end
end
@doc """
Send the email reset password, if it's not too soon since the last send
"""
@spec send_password_reset_email(User.t(), String.t()) :: tuple
def send_password_reset_email(%User{} = user, locale \\ "en") do
with :ok <- we_can_send_email(user, :reset_password_sent_at),
{:ok, %User{} = user_updated} <-
Repo.update(
User.send_password_reset_changeset(user, %{
"reset_password_token" => Crypto.random_string(30),
"reset_password_sent_at" => DateTime.utc_now() |> DateTime.truncate(:second)
})
) do
mail =
user_updated
|> Email.User.reset_password_email(locale)
|> Email.Mailer.deliver_later()
{:ok, mail}
else
{:error, reason} -> {:error, reason}
end
end
@spec we_can_send_email(User.t(), atom) :: :ok | {:error, :email_too_soon}
defp we_can_send_email(%User{} = user, key) do
case Map.get(user, key) do
nil ->
:ok
_ ->
case Timex.before?(
Timex.shift(Map.get(user, key), hours: 1),
DateTime.utc_now() |> DateTime.truncate(:second)
) do
true ->
:ok
false ->
{:error, :email_too_soon}
end
end
end
end

View File

@ -35,8 +35,7 @@ defmodule MobilizonWeb.Plugs.UploadedMedia do
%{query_params: %{"name" => name}} = conn ->
name = String.replace(name, "\"", "\\\"")
conn
|> put_resp_header("content-disposition", "filename=\"#{name}\"")
put_resp_header(conn, "content-disposition", "filename=\"#{name}\"")
conn ->
conn
@ -77,11 +76,7 @@ defmodule MobilizonWeb.Plugs.UploadedMedia do
end
defp get_media(conn, {:url, url}, true, _) do
conn
|> MobilizonWeb.ReverseProxy.call(
url,
Config.get([Mobilizon.Upload, :proxy_opts], [])
)
MobilizonWeb.ReverseProxy.call(conn, url, Config.get([Mobilizon.Upload, :proxy_opts], []))
end
defp get_media(conn, {:url, url}, _, _) do

View File

@ -3,7 +3,7 @@ defmodule MobilizonWeb.Resolvers.Comment do
Handles the comment-related GraphQL calls.
"""
import Mobilizon.Service.Admin.ActionLogService
import Mobilizon.Service.Admin.ActionLog
alias Mobilizon.Actors
alias Mobilizon.Actors.Actor

View File

@ -3,7 +3,7 @@ defmodule MobilizonWeb.Resolvers.Event do
Handles the event-related GraphQL calls.
"""
import Mobilizon.Service.Admin.ActionLogService
import Mobilizon.Service.Admin.ActionLog
alias Mobilizon.Actors
alias Mobilizon.Actors.Actor

View File

@ -7,10 +7,11 @@ defmodule MobilizonWeb.Resolvers.User do
alias Mobilizon.{Actors, Config, Users, Events}
alias Mobilizon.Actors.Actor
alias Mobilizon.Service.Users.{Activation, ResetPassword}
alias Mobilizon.Storage.Repo
alias Mobilizon.Users.User
alias MobilizonWeb.Email
require Logger
@doc """
@ -118,7 +119,7 @@ defmodule MobilizonWeb.Resolvers.User do
def create_user(_parent, args, _resolution) do
with :registration_ok <- check_registration_config(args),
{:ok, %User{} = user} <- Users.register(args) do
Activation.send_confirmation_email(user, Map.get(args, :locale, "en"))
Email.User.send_confirmation_email(user, Map.get(args, :locale, "en"))
{:ok, user}
else
:registration_closed ->
@ -161,7 +162,7 @@ defmodule MobilizonWeb.Resolvers.User do
"""
def validate_user(_parent, %{token: token}, _resolution) do
with {:check_confirmation_token, {:ok, %User{} = user}} <-
{:check_confirmation_token, Activation.check_confirmation_token(token)},
{: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
@ -187,7 +188,7 @@ defmodule MobilizonWeb.Resolvers.User do
with {:ok, %User{locale: locale} = user} <-
Users.get_user_by_email(Map.get(args, :email), false),
{:ok, email} <-
Activation.resend_confirmation_email(user, Map.get(args, :locale, locale)) do
Email.User.resend_confirmation_email(user, Map.get(args, :locale, locale)) do
{:ok, email}
else
{:error, :user_not_found} ->
@ -205,7 +206,7 @@ defmodule MobilizonWeb.Resolvers.User do
with email <- Map.get(args, :email),
{:ok, %User{locale: locale} = user} <- Users.get_user_by_email(email, true),
{:ok, %Bamboo.Email{} = _email_html} <-
ResetPassword.send_password_reset_email(user, Map.get(args, :locale, locale)) do
Email.User.send_password_reset_email(user, Map.get(args, :locale, locale)) do
{:ok, email}
else
{:error, :user_not_found} ->
@ -222,7 +223,7 @@ defmodule MobilizonWeb.Resolvers.User do
"""
def reset_password(_parent, %{password: password, token: token}, _resolution) do
with {:ok, %User{} = user} <-
ResetPassword.check_reset_password_token(password, token),
Email.User.check_reset_password_token(password, token),
{: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}}
@ -233,11 +234,7 @@ defmodule MobilizonWeb.Resolvers.User do
def change_default_actor(
_parent,
%{preferred_username: username},
%{
context: %{
current_user: user
}
}
%{context: %{current_user: user}}
) do
with %Actor{id: actor_id} <- Actors.get_local_actor_by_name(username),
{:user_actor, true} <-

View File

@ -14,13 +14,13 @@ defmodule MobilizonWeb.Router do
end
pipeline :activity_pub_signature do
plug(MobilizonWeb.HTTPSignaturePlug)
plug(MobilizonWeb.Plugs.MappedSignatureToIdentity)
plug(Mobilizon.Federation.Plugs.HTTPSignatures)
plug(Mobilizon.Federation.Plugs.MappedSignatureToIdentity)
end
pipeline :relay do
plug(MobilizonWeb.HTTPSignaturePlug)
plug(MobilizonWeb.Plugs.MappedSignatureToIdentity)
plug(Mobilizon.Federation.Plugs.HTTPSignatures)
plug(Mobilizon.Federation.Plugs.MappedSignatureToIdentity)
plug(:accepts, ["activity-json", "json"])
end

View File

@ -1,12 +1,11 @@
defmodule Mobilizon.Service.Admin.ActionLogService do
defmodule Mobilizon.Service.Admin.ActionLog do
@moduledoc """
Module to handle action log creations.
"""
alias Mobilizon.Actors.Actor
alias Mobilizon.Admin
alias Mobilizon.{Admin, Users}
alias Mobilizon.Admin.ActionLog
alias Mobilizon.Users
alias Mobilizon.Users.User
@doc """

View File

@ -1,50 +0,0 @@
defmodule Mobilizon.Service.Events.Tool do
@moduledoc """
Event-related tools
"""
alias Mobilizon.Events
alias Mobilizon.Events.Event
alias Mobilizon.Actors.Actor
alias Mobilizon.Users.User
alias MobilizonWeb.Email
alias Mobilizon.Storage.Repo
@important_changes [:title, :begins_on, :ends_on, :status]
def calculate_event_diff_and_send_notifications(
%Event{} = old_event,
%Event{id: event_id} = event,
changes
) do
important = MapSet.new(@important_changes)
diff =
changes
|> Map.keys()
|> MapSet.new()
|> MapSet.intersection(important)
if MapSet.size(diff) > 0 do
Repo.transaction(fn ->
event_id
|> Events.list_local_emails_user_participants_for_event_query()
|> Repo.stream()
|> Enum.to_list()
|> Enum.each(
&send_notification_for_event_update_to_participant(&1, old_event, event, diff)
)
end)
end
end
defp send_notification_for_event_update_to_participant(
{%Actor{} = actor, %User{locale: locale} = user},
%Event{} = old_event,
%Event{} = event,
diff
) do
user
|> Email.Event.event_updated(actor, old_event, event, diff, locale)
|> Email.Mailer.deliver_later()
end
end

View File

@ -2,8 +2,8 @@ defmodule Mobilizon.Service.Statistics do
@moduledoc """
A module that provides cached statistics
"""
alias Mobilizon.Events
alias Mobilizon.Users
alias Mobilizon.{Events, Users}
def get_cached_value(key) do
case Cachex.fetch(:statistics, key, fn key ->

View File

@ -1,46 +0,0 @@
defmodule Mobilizon.Service.Users.Activation do
@moduledoc false
alias Mobilizon.Service.Users.Tools
alias Mobilizon.Users
alias Mobilizon.Users.User
alias MobilizonWeb.Email
require Logger
@doc false
def check_confirmation_token(token) when is_binary(token) do
with %User{} = user <- Users.get_user_by_activation_token(token),
{:ok, %User{} = user} <-
Users.update_user(user, %{
"confirmed_at" => DateTime.utc_now() |> DateTime.truncate(:second),
"confirmation_sent_at" => nil,
"confirmation_token" => nil
}) do
Logger.info("User #{user.email} has been confirmed")
{:ok, user}
else
_err ->
{:error, :invalid_token}
end
end
def resend_confirmation_email(%User{} = user, locale \\ "en") do
with :ok <- Tools.we_can_send_email(user, :confirmation_sent_at),
{:ok, user} <-
Users.update_user(user, %{
"confirmation_sent_at" => DateTime.utc_now() |> DateTime.truncate(:second)
}) do
send_confirmation_email(user, locale)
Logger.info("Sent confirmation email again to #{user.email}")
{:ok, user.email}
end
end
def send_confirmation_email(%User{} = user, locale \\ "en") do
user
|> Email.User.confirmation_email(locale)
|> Email.Mailer.deliver_later()
end
end

View File

@ -1,62 +0,0 @@
defmodule Mobilizon.Service.Users.ResetPassword do
@moduledoc false
alias Mobilizon.Service.Users.Tools
alias Mobilizon.Storage.Repo
alias Mobilizon.Users
alias Mobilizon.Users.User
alias MobilizonWeb.Email
require Logger
@doc """
Check that the provided token is correct and update provided password
"""
@spec check_reset_password_token(String.t(), String.t()) :: tuple
def check_reset_password_token(password, token) do
with %User{} = user <- Users.get_user_by_reset_password_token(token),
{:ok, %User{} = user} <-
Repo.update(
User.password_reset_changeset(user, %{
"password" => password,
"reset_password_sent_at" => nil,
"reset_password_token" => nil
})
) do
{:ok, user}
else
{:error, %Ecto.Changeset{errors: [password: {"registration.error.password_too_short", _}]}} ->
{:error,
"The password you have choosen is too short. Please make sure your password contains at least 6 charaters."}
_err ->
{:error,
"The token you provided is invalid. Make sure that the URL is exactly the one provided inside the email you got."}
end
end
@doc """
Send the email reset password, if it's not too soon since the last send
"""
@spec send_password_reset_email(User.t(), String.t()) :: tuple
def send_password_reset_email(%User{} = user, locale \\ "en") do
with :ok <- Tools.we_can_send_email(user, :reset_password_sent_at),
{:ok, %User{} = user_updated} <-
Repo.update(
User.send_password_reset_changeset(user, %{
"reset_password_token" => Tools.random_string(30),
"reset_password_sent_at" => DateTime.utc_now() |> DateTime.truncate(:second)
})
) do
mail =
user_updated
|> Email.User.reset_password_email(locale)
|> Email.Mailer.deliver_later()
{:ok, mail}
else
{:error, reason} -> {:error, reason}
end
end
end

View File

@ -1,43 +0,0 @@
defmodule Mobilizon.Service.Users.Tools do
@moduledoc """
Common functions for actors services
"""
alias Mobilizon.Users.User
@spec we_can_send_email(User.t(), atom()) :: :ok | {:error, :email_too_soon}
def we_can_send_email(%User{} = user, key \\ :reset_password_sent_at) do
case Map.get(user, key) do
nil ->
:ok
_ ->
case Timex.before?(
Timex.shift(Map.get(user, key), hours: 1),
DateTime.utc_now() |> DateTime.truncate(:second)
) do
true ->
:ok
false ->
{:error, :email_too_soon}
end
end
end
@spec random_string(integer) :: String.t()
def random_string(length) do
length
|> :crypto.strong_rand_bytes()
|> Base.url_encode64()
end
end
defmodule Mobilizon.Users.Guards do
@moduledoc """
Guards for users
"""
defguard is_admin(role) when is_atom(role) and role == :administrator
defguard is_moderator(role) when is_atom(role) and role in [:administrator, :moderator]
end

View File

@ -1,4 +1,4 @@
defmodule Mobilizon.Service.Workers.BackgroundWorker do
defmodule Mobilizon.Service.Workers.Background do
@moduledoc """
Worker to build search results
"""
@ -6,7 +6,7 @@ defmodule Mobilizon.Service.Workers.BackgroundWorker do
alias Mobilizon.Actors
alias Mobilizon.Actors.Actor
use Mobilizon.Service.Workers.WorkerHelper, queue: "background"
use Mobilizon.Service.Workers.Helper, queue: "background"
@impl Oban.Worker
def perform(%{"op" => "delete_actor", "actor_id" => actor_id}, _job) do

View File

@ -1,4 +1,4 @@
defmodule Mobilizon.Service.Workers.BuildSearchWorker do
defmodule Mobilizon.Service.Workers.BuildSearch do
@moduledoc """
Worker to build search results
"""
@ -8,7 +8,7 @@ defmodule Mobilizon.Service.Workers.BuildSearchWorker do
alias Mobilizon.Storage.Repo
alias Ecto.Adapters.SQL
use Mobilizon.Service.Workers.WorkerHelper, queue: "search"
use Mobilizon.Service.Workers.Helper, queue: "search"
@impl Oban.Worker
def perform(%{"op" => "insert_search_event", "event_id" => event_id}, _job) do

View File

@ -3,12 +3,13 @@
# SPDX-License-Identifier: AGPL-3.0-only
# Upstream: https://git.pleroma.social/pleroma/pleroma/blob/develop/lib/pleroma/workers/worker_helper.ex
defmodule Mobilizon.Service.Workers.WorkerHelper do
defmodule Mobilizon.Service.Workers.Helper do
@moduledoc """
Tools to ease dealing with workers
"""
alias Mobilizon.Config
alias Mobilizon.Service.Workers.WorkerHelper
alias Mobilizon.Storage.Repo
def worker_args(queue) do
case Config.get([:workers, :retries, queue]) do
@ -39,11 +40,11 @@ defmodule Mobilizon.Service.Workers.WorkerHelper do
def enqueue(operation, params, worker_args \\ []) do
params = Map.merge(%{"op" => operation}, params)
queue_atom = String.to_existing_atom(unquote(queue))
worker_args = worker_args ++ WorkerHelper.worker_args(queue_atom)
worker_args = worker_args ++ __MODULE__.worker_args(queue_atom)
unquote(caller_module)
|> apply(:new, [params, worker_args])
|> Mobilizon.Storage.Repo.insert()
|> Repo.insert()
end
end
end

View File

@ -283,10 +283,10 @@ defmodule Mobilizon.Mixfile do
Mobilizon.Federation.HTTPSignatures.Signature,
Mobilizon.Federation.WebFinger,
Mobilizon.Federation.WebFinger.XmlBuilder,
Mobilizon.Federation.Plugs.HTTPSignatures,
MobilizonWeb.ActivityPub.ActorView,
MobilizonWeb.ActivityPub.ObjectView,
MobilizonWeb.ActivityPubController,
MobilizonWeb.HTTPSignaturePlug,
MobilizonWeb.WebFingerController,
MobilizonWeb.NodeInfoController
],

View File

@ -3,15 +3,15 @@
# Copyright © 2017-2019 Pleroma Authors <https://pleroma.social/>
# SPDX-License-Identifier: AGPL-3.0-only
defmodule MobilizonWeb.Plug.FederatingTest do
defmodule Mobilizon.Federation.Plug.FederatingTest do
use MobilizonWeb.ConnCase
alias Mobilizon.Federation.Plugs.Federating
test "returns and halt the conn when federating is disabled" do
Mobilizon.Config.put([:instance, :federating], false)
conn =
build_conn()
|> MobilizonWeb.Plugs.Federating.call(%{})
conn = Federating.call(build_conn(), %{})
assert conn.status == 404
assert conn.halted
@ -20,9 +20,7 @@ defmodule MobilizonWeb.Plug.FederatingTest do
test "does nothing when federating is enabled" do
Mobilizon.Config.put([:instance, :federating], true)
conn =
build_conn()
|> MobilizonWeb.Plugs.Federating.call(%{})
conn = Federating.call(build_conn(), %{})
refute conn.status
refute conn.halted

View File

@ -3,9 +3,10 @@
# Copyright © 2017-2019 Pleroma Authors <https://pleroma.social/>
# SPDX-License-Identifier: AGPL-3.0-only
defmodule MobilizonWeb.Plugs.MappedSignatureToIdentityPlugTest do
defmodule Mobilizon.Federation.Plugs.MappedSignatureToIdentityTest do
use MobilizonWeb.ConnCase
use ExVCR.Mock, adapter: ExVCR.Adapter.Hackney
alias MobilizonWeb.Plugs.MappedSignatureToIdentity
defp set_signature(conn, key_id) do

View File

@ -9,6 +9,7 @@ defmodule Mobilizon.ActorsTest do
alias Mobilizon.Actors.{Actor, Bot, Follower, Member}
alias Mobilizon.Events.{Event, Comment}
alias Mobilizon.Media.File, as: FileModel
alias Mobilizon.Service.Workers
alias Mobilizon.Storage.Page
alias Mobilizon.Federation.ActivityPub
@ -311,7 +312,7 @@ defmodule Mobilizon.ActorsTest do
assert {:ok, %Oban.Job{}} = Actors.delete_actor(actor)
assert_enqueued(
worker: Mobilizon.Service.Workers.BackgroundWorker,
worker: Workers.Background,
args: %{"actor_id" => actor.id, "op" => "delete_actor"}
)

View File

@ -6,8 +6,8 @@ defmodule Mobilizon.EventsTest do
alias Mobilizon.Actors.Actor
alias Mobilizon.Events
alias Mobilizon.Events.{Comment, Event, Participant, Session, Tag, TagRelation, Track}
alias Mobilizon.Service.Workers
alias Mobilizon.Storage.Page
alias Mobilizon.Service.Workers.BuildSearchWorker
@event_valid_attrs %{
begins_on: "2010-04-17 14:00:00Z",
@ -23,7 +23,7 @@ defmodule Mobilizon.EventsTest do
setup do
actor = insert(:actor)
event = insert(:event, organizer_actor: actor, visibility: :public)
BuildSearchWorker.insert_search_event(event)
Workers.BuildSearch.insert_search_event(event)
{:ok, actor: actor, event: event}
end
@ -63,7 +63,7 @@ defmodule Mobilizon.EventsTest do
assert title == hd(Events.build_events_for_search(event.title).elements).title
%Event{} = event2 = insert(:event, title: "Special event")
BuildSearchWorker.insert_search_event(event2)
Workers.BuildSearch.insert_search_event(event2)
assert event2.title ==
Events.build_events_for_search("Special").elements |> hd() |> Map.get(:title)
@ -76,7 +76,7 @@ defmodule Mobilizon.EventsTest do
tag1 = insert(:tag, title: "coucou")
tag2 = insert(:tag, title: "hola")
%Event{} = event3 = insert(:event, title: "Nothing like it", tags: [tag1, tag2])
BuildSearchWorker.insert_search_event(event3)
Workers.BuildSearch.insert_search_event(event3)
assert event3.title ==
Events.build_events_for_search("hola").elements |> hd() |> Map.get(:title)

View File

@ -1,4 +1,4 @@
defmodule Mobilizon.Service.Users.ToolsTest do
defmodule Mobilizon.Users.GuardsTest do
use Mobilizon.DataCase
import Mobilizon.Factory

View File

@ -2,11 +2,14 @@ defmodule MobilizonWeb.Resolvers.EventResolverTest do
use MobilizonWeb.ConnCase
use Bamboo.Test
use Oban.Testing, repo: Mobilizon.Storage.Repo
alias Mobilizon.Events
alias MobilizonWeb.{AbsintheHelpers, Email}
alias Mobilizon.Service.Workers.BuildSearchWorker
import Mobilizon.Factory
alias Mobilizon.Events
alias Mobilizon.Service.Workers
alias MobilizonWeb.{AbsintheHelpers, Email}
@event %{
description: "some body",
title: "some title",
@ -155,7 +158,7 @@ defmodule MobilizonWeb.Resolvers.EventResolverTest do
assert json_response(res, 200)["data"]["createEvent"]["title"] == "come to my event"
{id, ""} = json_response(res, 200)["data"]["createEvent"]["id"] |> Integer.parse()
assert_enqueued(worker: BuildSearchWorker, args: %{event_id: id, op: :insert_search_event})
assert_enqueued(worker: Workers.BuildSearch, args: %{event_id: id, op: :insert_search_event})
end
test "create_event/3 creates an event and escapes title and description", %{
@ -201,7 +204,7 @@ defmodule MobilizonWeb.Resolvers.EventResolverTest do
"<b>My description</b> <img src=\"http://placekitten.com/g/200/300\" />"
{id, ""} = res["data"]["createEvent"]["id"] |> Integer.parse()
assert_enqueued(worker: BuildSearchWorker, args: %{event_id: id, op: :insert_search_event})
assert_enqueued(worker: Workers.BuildSearch, args: %{event_id: id, op: :insert_search_event})
end
test "create_event/3 creates an event as a draft", %{conn: conn, actor: actor, user: user} do
@ -238,7 +241,7 @@ defmodule MobilizonWeb.Resolvers.EventResolverTest do
{event_id_int, ""} = Integer.parse(event_id)
refute_enqueued(
worker: BuildSearchWorker,
worker: Workers.BuildSearch,
args: %{event_id: event_id_int, op: :insert_search_event}
)
@ -371,7 +374,7 @@ defmodule MobilizonWeb.Resolvers.EventResolverTest do
{event_id_int, ""} = Integer.parse(event["id"])
assert_enqueued(
worker: BuildSearchWorker,
worker: Workers.BuildSearch,
args: %{event_id: event_id_int, op: :insert_search_event}
)
end
@ -827,7 +830,7 @@ defmodule MobilizonWeb.Resolvers.EventResolverTest do
{event_id_int, ""} = Integer.parse(event_res["id"])
assert_enqueued(
worker: BuildSearchWorker,
worker: Workers.BuildSearch,
args: %{event_id: event_id_int, op: :update_search_event}
)

View File

@ -1,10 +1,14 @@
defmodule MobilizonWeb.Resolvers.PersonResolverTest do
use MobilizonWeb.ConnCase
alias MobilizonWeb.AbsintheHelpers
alias Mobilizon.Actors.Actor
import Mobilizon.Factory
use Oban.Testing, repo: Mobilizon.Storage.Repo
import Mobilizon.Factory
alias Mobilizon.Actors.Actor
alias Mobilizon.Service.Workers
alias MobilizonWeb.AbsintheHelpers
@non_existent_username "nonexistent"
describe "Person Resolver" do
@ -500,7 +504,7 @@ defmodule MobilizonWeb.Resolvers.PersonResolverTest do
assert json_response(res, 200)["errors"] == nil
assert_enqueued(
worker: Mobilizon.Service.Workers.BackgroundWorker,
worker: Workers.Background,
args: %{"actor_id" => person_id, "op" => "delete_actor"}
)

View File

@ -1,8 +1,10 @@
defmodule MobilizonWeb.Resolvers.SearchResolverTest do
use MobilizonWeb.ConnCase
alias MobilizonWeb.AbsintheHelpers
import Mobilizon.Factory
alias Mobilizon.Service.Workers.BuildSearchWorker
alias Mobilizon.Service.Workers
alias MobilizonWeb.AbsintheHelpers
setup %{conn: conn} do
user = insert(:user)
@ -17,7 +19,7 @@ defmodule MobilizonWeb.Resolvers.SearchResolverTest do
insert(:actor, user: user, preferred_username: "test_person")
insert(:actor, type: :Group, preferred_username: "test_group")
event = insert(:event, title: "test_event")
BuildSearchWorker.insert_search_event(event)
Workers.BuildSearch.insert_search_event(event)
query = """
{
@ -51,7 +53,7 @@ defmodule MobilizonWeb.Resolvers.SearchResolverTest do
actor = insert(:actor, user: user, preferred_username: "test_person")
insert(:actor, type: :Group, preferred_username: "test_group")
event = insert(:event, title: "test_event")
BuildSearchWorker.insert_search_event(event)
Workers.BuildSearch.insert_search_event(event)
query = """
{
@ -84,7 +86,7 @@ defmodule MobilizonWeb.Resolvers.SearchResolverTest do
insert(:actor, user: user, preferred_username: "test_person")
group = insert(:actor, type: :Group, preferred_username: "test_group")
event = insert(:event, title: "test_event")
BuildSearchWorker.insert_search_event(event)
Workers.BuildSearch.insert_search_event(event)
query = """
{
@ -118,9 +120,9 @@ defmodule MobilizonWeb.Resolvers.SearchResolverTest do
event1 = insert(:event, title: "Pineapple fashion week")
event2 = insert(:event, title: "I love pineAPPLE")
event3 = insert(:event, title: "Hello")
BuildSearchWorker.insert_search_event(event1)
BuildSearchWorker.insert_search_event(event2)
BuildSearchWorker.insert_search_event(event3)
Workers.BuildSearch.insert_search_event(event1)
Workers.BuildSearch.insert_search_event(event2)
Workers.BuildSearch.insert_search_event(event3)
query = """
{
@ -161,9 +163,9 @@ defmodule MobilizonWeb.Resolvers.SearchResolverTest do
event1 = insert(:event, title: "Pineapple fashion week")
event2 = insert(:event, title: "I love pineAPPLE")
event3 = insert(:event, title: "Hello")
BuildSearchWorker.insert_search_event(event1)
BuildSearchWorker.insert_search_event(event2)
BuildSearchWorker.insert_search_event(event3)
Workers.BuildSearch.insert_search_event(event1)
Workers.BuildSearch.insert_search_event(event2)
Workers.BuildSearch.insert_search_event(event3)
query = """
{
@ -198,7 +200,7 @@ defmodule MobilizonWeb.Resolvers.SearchResolverTest do
insert(:actor, user: user, preferred_username: "person", name: "Torréfaction du Kafé")
insert(:actor, type: :Group, preferred_username: "group", name: "Kafé group")
event = insert(:event, title: "Tour du monde des Kafés")
BuildSearchWorker.insert_search_event(event)
Workers.BuildSearch.insert_search_event(event)
# Elaborate query
query = """
@ -230,7 +232,7 @@ defmodule MobilizonWeb.Resolvers.SearchResolverTest do
insert(:actor, user: user, preferred_username: "person", name: "Torréfaction du Kafé")
group = insert(:actor, type: :Group, preferred_username: "group", name: "Kafé group")
event = insert(:event, title: "Tour du monde des Kafés")
BuildSearchWorker.insert_search_event(event)
Workers.BuildSearch.insert_search_event(event)
# Elaborate query
query = """

View File

@ -1,12 +1,12 @@
defmodule Mobilizon.Service.Admin.ActionLogServiceTest do
defmodule Mobilizon.Service.Admin.ActionLogTest do
@moduledoc """
Test the ActionLogService module.
Test the ActionLog module.
"""
use Mobilizon.DataCase
import Mobilizon.Factory
import Mobilizon.Service.Admin.ActionLogService
import Mobilizon.Service.Admin.ActionLog
alias Mobilizon.Admin.ActionLog
alias Mobilizon.Reports.{Note, Report}