Improve Federation boundaries

This commit is contained in:
rustra 2020-01-23 21:59:50 +01:00
parent 8ca5c0b320
commit 3577fe42e1
67 changed files with 314 additions and 227 deletions

View File

@ -44,7 +44,7 @@ config :mobilizon, MobilizonWeb.Endpoint,
# Upload configuration # Upload configuration
config :mobilizon, MobilizonWeb.Upload, config :mobilizon, MobilizonWeb.Upload,
uploader: MobilizonWeb.Uploaders.Local, uploader: MobilizonWeb.Upload.Uploader.Local,
filters: [ filters: [
MobilizonWeb.Upload.Filter.Dedupe, MobilizonWeb.Upload.Filter.Dedupe,
MobilizonWeb.Upload.Filter.Optimize MobilizonWeb.Upload.Filter.Optimize
@ -60,7 +60,7 @@ config :mobilizon, MobilizonWeb.Upload,
] ]
] ]
config :mobilizon, MobilizonWeb.Uploaders.Local, uploads: "uploads" config :mobilizon, MobilizonWeb.Upload.Uploader.Local, uploads: "uploads"
config :mobilizon, :media_proxy, config :mobilizon, :media_proxy,
enabled: true, enabled: true,
@ -78,7 +78,7 @@ config :logger, :console,
format: "$time $metadata[$level] $message\n", format: "$time $metadata[$level] $message\n",
metadata: [:request_id] metadata: [:request_id]
config :mobilizon, MobilizonWeb.Guardian, config :mobilizon, MobilizonWeb.Auth.Guardian,
issuer: "mobilizon", issuer: "mobilizon",
secret_key: "ty0WM7YBE3ojvxoUQxo8AERrNpfbXnIJ82ovkPdqbUFw31T5LcK8wGjaOiReVQjo" secret_key: "ty0WM7YBE3ojvxoUQxo8AERrNpfbXnIJ82ovkPdqbUFw31T5LcK8wGjaOiReVQjo"

View File

@ -66,8 +66,8 @@ config :mobilizon, MobilizonWeb.Email.Mailer, adapter: Bamboo.LocalAdapter
# Configure your database # Configure your database
config :mobilizon, Mobilizon.Storage.Repo, config :mobilizon, Mobilizon.Storage.Repo,
types: Mobilizon.Storage.PostgresTypes, types: Mobilizon.Storage.PostgresTypes,
username: System.get_env("MOBILIZON_DATABASE_USERNAME") || "postgres", username: System.get_env("MOBILIZON_DATABASE_USERNAME") || "mobilizon",
password: System.get_env("MOBILIZON_DATABASE_PASSWORD") || "postgres", password: System.get_env("MOBILIZON_DATABASE_PASSWORD") || "mobilizon",
database: System.get_env("MOBILIZON_DATABASE_DBNAME") || "mobilizon_dev", database: System.get_env("MOBILIZON_DATABASE_DBNAME") || "mobilizon_dev",
hostname: System.get_env("MOBILIZON_DATABASE_HOST") || "localhost", hostname: System.get_env("MOBILIZON_DATABASE_HOST") || "localhost",
port: System.get_env("MOBILIZON_DATABASE_PORT") || "5432", port: System.get_env("MOBILIZON_DATABASE_PORT") || "5432",

View File

@ -24,8 +24,8 @@ config :logger,
# Configure your database # Configure your database
config :mobilizon, Mobilizon.Storage.Repo, config :mobilizon, Mobilizon.Storage.Repo,
types: Mobilizon.Storage.PostgresTypes, types: Mobilizon.Storage.PostgresTypes,
username: System.get_env("MOBILIZON_DATABASE_USERNAME") || "postgres", username: System.get_env("MOBILIZON_DATABASE_USERNAME") || "mobilizon",
password: System.get_env("MOBILIZON_DATABASE_PASSWORD") || "postgres", password: System.get_env("MOBILIZON_DATABASE_PASSWORD") || "mobilizon",
database: System.get_env("MOBILIZON_DATABASE_DBNAME") || "mobilizon_test", database: System.get_env("MOBILIZON_DATABASE_DBNAME") || "mobilizon_test",
hostname: System.get_env("MOBILIZON_DATABASE_HOST") || "localhost", hostname: System.get_env("MOBILIZON_DATABASE_HOST") || "localhost",
pool: Ecto.Adapters.SQL.Sandbox pool: Ecto.Adapters.SQL.Sandbox
@ -34,7 +34,7 @@ config :mobilizon, MobilizonWeb.Email.Mailer, adapter: Bamboo.TestAdapter
config :mobilizon, MobilizonWeb.Upload, filters: [], link_name: false config :mobilizon, MobilizonWeb.Upload, filters: [], link_name: false
config :mobilizon, MobilizonWeb.Uploaders.Local, uploads: "test/uploads" config :mobilizon, MobilizonWeb.Upload.Uploader.Local, uploads: "test/uploads"
config :exvcr, config :exvcr,
vcr_cassette_library_dir: "test/fixtures/vcr_cassettes" vcr_cassette_library_dir: "test/fixtures/vcr_cassettes"

View File

@ -221,7 +221,7 @@ defmodule Mobilizon.Federation.ActivityPub.Transmogrifier do
%{"type" => "Update", "object" => %{"type" => "Event"} = object, "actor" => _actor} = %{"type" => "Update", "object" => %{"type" => "Event"} = object, "actor" => _actor} =
update_data update_data
) do ) do
with actor <- Utils.get_actor(update_data), with actor <- Utils.get_actor(update_data),
{:ok, %Actor{url: actor_url}} <- Actors.get_actor_by_url(actor), {:ok, %Actor{url: actor_url}} <- Actors.get_actor_by_url(actor),
{:ok, %Event{} = old_event} <- {:ok, %Event{} = old_event} <-
object |> Utils.get_url() |> ActivityPub.fetch_object_from_url(), object |> Utils.get_url() |> ActivityPub.fetch_object_from_url(),
@ -289,7 +289,8 @@ defmodule Mobilizon.Federation.ActivityPub.Transmogrifier do
with actor <- Utils.get_actor(data), with actor <- Utils.get_actor(data),
{:ok, %Actor{url: actor_url}} <- Actors.get_actor_by_url(actor), {:ok, %Actor{url: actor_url}} <- Actors.get_actor_by_url(actor),
object_id <- Utils.get_url(object), object_id <- Utils.get_url(object),
{:origin_check, true} <- {:origin_check, Utils.origin_check_from_id?(actor_url, object_id)}, {:origin_check, true} <-
{:origin_check, Utils.origin_check_from_id?(actor_url, object_id)},
{:ok, object} <- ActivityPub.fetch_object_from_url(object_id), {:ok, object} <- ActivityPub.fetch_object_from_url(object_id),
{:ok, activity, object} <- ActivityPub.delete(object, false) do {:ok, activity, object} <- ActivityPub.delete(object, false) do
{:ok, activity, object} {:ok, activity, object}

View File

@ -1,11 +1,3 @@
import EctoEnum
defenum(Mobilizon.Admin.ActionLogAction, [
"update",
"create",
"delete"
])
defmodule Mobilizon.Admin.ActionLog do defmodule Mobilizon.Admin.ActionLog do
@moduledoc """ @moduledoc """
Represents an action log entity. Represents an action log entity.

View File

@ -4,9 +4,19 @@ defmodule Mobilizon.Admin do
""" """
import Ecto.Query import Ecto.Query
import EctoEnum
alias Mobilizon.Actors.Actor
alias Mobilizon.{Admin, Users}
alias Mobilizon.Admin.ActionLog alias Mobilizon.Admin.ActionLog
alias Mobilizon.Storage.{Page, Repo} alias Mobilizon.Storage.{Page, Repo}
alias Mobilizon.Users.User
defenum(ActionLogAction, [
"update",
"create",
"delete"
])
@doc """ @doc """
Creates a action_log. Creates a action_log.
@ -28,8 +38,37 @@ defmodule Mobilizon.Admin do
|> Repo.all() |> Repo.all()
end end
@doc """
Log an admin action
"""
@spec log_action(Actor.t(), String.t(), String.t()) :: {:ok, ActionLog.t()}
def log_action(%Actor{user_id: user_id, id: actor_id}, action, target) do
with %User{role: role} <- Users.get_user!(user_id),
{:role, true} <- {:role, role in [:administrator, :moderator]},
{:ok, %ActionLog{} = create_action_log} <-
Admin.create_action_log(%{
"actor_id" => actor_id,
"target_type" => to_string(target.__struct__),
"target_id" => target.id,
"action" => action,
"changes" => stringify_struct(target)
}) do
{:ok, create_action_log}
end
end
@spec list_action_logs_query :: Ecto.Query.t() @spec list_action_logs_query :: Ecto.Query.t()
defp list_action_logs_query do defp list_action_logs_query do
from(r in ActionLog, preload: [:actor], order_by: [desc: :id]) from(r in ActionLog, preload: [:actor], order_by: [desc: :id])
end end
defp stringify_struct(%_{} = struct) do
association_fields = struct.__struct__.__schema__(:associations)
struct
|> Map.from_struct()
|> Map.drop(association_fields ++ [:__meta__])
end
defp stringify_struct(struct), do: struct
end end

View File

@ -7,10 +7,11 @@ defmodule Mobilizon.Events do
import Ecto.Query import Ecto.Query
import EctoEnum import EctoEnum
alias Ecto.{Multi, Changeset}
import Mobilizon.Storage.Ecto import Mobilizon.Storage.Ecto
alias Ecto.{Multi, Changeset}
alias Mobilizon.Actors.Actor alias Mobilizon.Actors.Actor
alias Mobilizon.Addresses.Address alias Mobilizon.Addresses.Address
@ -331,14 +332,14 @@ defmodule Mobilizon.Events do
|> Repo.transaction() do |> Repo.transaction() do
Cachex.del(:ics, "event_#{new_event.uuid}") Cachex.del(:ics, "event_#{new_event.uuid}")
Email.Events.calculate_event_diff_and_send_notifications( Email.Event.calculate_event_diff_and_send_notifications(
old_event, old_event,
new_event, new_event,
changes changes
) )
unless new_event.draft, unless new_event.draft,
do: BuildSearch.enqueue(:update_search_event, %{"event_id" => new_event.id}) do: Workers.BuildSearch.enqueue(:update_search_event, %{"event_id" => new_event.id})
{:ok, Repo.preload(new_event, @event_preloads)} {:ok, Repo.preload(new_event, @event_preloads)}
end end

View File

@ -13,6 +13,8 @@ defmodule Mobilizon.Users do
alias Mobilizon.Storage.{Page, Repo} alias Mobilizon.Storage.{Page, Repo}
alias Mobilizon.Users.User alias Mobilizon.Users.User
alias MobilizonWeb.Auth
@type tokens :: %{ @type tokens :: %{
required(:access_token) => String.t(), required(:access_token) => String.t(),
required(:refresh_token) => String.t() required(:refresh_token) => String.t()
@ -247,7 +249,7 @@ defmodule Mobilizon.Users do
@spec generate_access_token(User.t()) :: {:ok, String.t()} @spec generate_access_token(User.t()) :: {:ok, String.t()}
def generate_access_token(user) do def generate_access_token(user) do
with {:ok, access_token, _claims} <- with {:ok, access_token, _claims} <-
MobilizonWeb.Guardian.encode_and_sign(user, %{}, token_type: "access") do Auth.Guardian.encode_and_sign(user, %{}, token_type: "access") do
{:ok, access_token} {:ok, access_token}
end end
end end
@ -258,7 +260,7 @@ defmodule Mobilizon.Users do
@spec generate_refresh_token(User.t()) :: {:ok, String.t()} @spec generate_refresh_token(User.t()) :: {:ok, String.t()}
def generate_refresh_token(user) do def generate_refresh_token(user) do
with {:ok, refresh_token, _claims} <- with {:ok, refresh_token, _claims} <-
MobilizonWeb.Guardian.encode_and_sign(user, %{}, token_type: "refresh") do Auth.Guardian.encode_and_sign(user, %{}, token_type: "refresh") do
{:ok, refresh_token} {:ok, refresh_token}
end end
end end

View File

@ -3,12 +3,10 @@ defmodule MobilizonWeb.API.Reports do
API for Reports. API for Reports.
""" """
import Mobilizon.Service.Admin.ActionLog
alias Mobilizon.Actors.Actor alias Mobilizon.Actors.Actor
alias Mobilizon.{Admin, Users}
alias Mobilizon.Reports, as: ReportsAction alias Mobilizon.Reports, as: ReportsAction
alias Mobilizon.Reports.{Note, Report, ReportStatus} alias Mobilizon.Reports.{Note, Report, ReportStatus}
alias Mobilizon.Users
alias Mobilizon.Users.User alias Mobilizon.Users.User
alias Mobilizon.Federation.ActivityPub alias Mobilizon.Federation.ActivityPub
@ -34,7 +32,7 @@ defmodule MobilizonWeb.API.Reports do
with {:valid_state, true} <- with {:valid_state, true} <-
{:valid_state, ReportStatus.valid_value?(state)}, {:valid_state, ReportStatus.valid_value?(state)},
{:ok, report} <- ReportsAction.update_report(report, %{"status" => state}), {:ok, report} <- ReportsAction.update_report(report, %{"status" => state}),
{:ok, _} <- log_action(actor, "update", report) do {:ok, _} <- Admin.log_action(actor, "update", report) do
{:ok, report} {:ok, report}
else else
{:valid_state, false} -> {:error, "Unsupported state"} {:valid_state, false} -> {:error, "Unsupported state"}
@ -58,7 +56,7 @@ defmodule MobilizonWeb.API.Reports do
"moderator_id" => moderator_id, "moderator_id" => moderator_id,
"content" => content "content" => content
}), }),
{:ok, _} <- log_action(moderator, "create", note) do {:ok, _} <- Admin.log_action(moderator, "create", note) do
{:ok, note} {:ok, note}
else else
{:role, false} -> {:role, false} ->
@ -79,7 +77,7 @@ defmodule MobilizonWeb.API.Reports do
{:role, true} <- {:role, role in [:administrator, :moderator]}, {:role, true} <- {:role, role in [:administrator, :moderator]},
{:ok, %Note{} = note} <- {:ok, %Note{} = note} <-
Mobilizon.Reports.delete_note(note), Mobilizon.Reports.delete_note(note),
{:ok, _} <- log_action(moderator, "delete", note) do {:ok, _} <- Admin.log_action(moderator, "delete", note) do
{:ok, note} {:ok, note}
else else
{:role, false} -> {:role, false} ->

View File

@ -1,10 +1,11 @@
defmodule MobilizonWeb.Context do defmodule MobilizonWeb.Auth.Context do
@moduledoc """ @moduledoc """
Guardian context for MobilizonWeb Guardian context for MobilizonWeb
""" """
@behaviour Plug @behaviour Plug
import Plug.Conn import Plug.Conn
alias Mobilizon.Users.User alias Mobilizon.Users.User
def init(opts) do def init(opts) do
@ -17,8 +18,7 @@ defmodule MobilizonWeb.Context do
context = context =
case Guardian.Plug.current_resource(conn) do case Guardian.Plug.current_resource(conn) do
%User{} = user -> %User{} = user ->
context Map.put(context, :current_user, user)
|> Map.put(:current_user, user)
nil -> nil ->
context context

View File

@ -1,4 +1,4 @@
defmodule MobilizonWeb.AuthErrorHandler do defmodule MobilizonWeb.Auth.ErrorHandler do
@moduledoc """ @moduledoc """
In case we have an auth error In case we have an auth error
""" """

View File

@ -1,7 +1,8 @@
defmodule MobilizonWeb.Guardian do defmodule MobilizonWeb.Auth.Guardian do
@moduledoc """ @moduledoc """
Handles the JWT tokens encoding and decoding Handles the JWT tokens encoding and decoding
""" """
use Guardian, use Guardian,
otp_app: :mobilizon, otp_app: :mobilizon,
permissions: %{ permissions: %{
@ -11,6 +12,7 @@ defmodule MobilizonWeb.Guardian do
alias Mobilizon.Users alias Mobilizon.Users
alias Mobilizon.Users.User alias Mobilizon.Users.User
require Logger require Logger
def subject_for_token(%User{} = user, _claims) do def subject_for_token(%User{} = user, _claims) do

View File

@ -1,14 +1,14 @@
defmodule MobilizonWeb.AuthPipeline do defmodule MobilizonWeb.Auth.Pipeline do
@moduledoc """ @moduledoc """
Handles the app sessions Handles the app sessions
""" """
use Guardian.Plug.Pipeline, use Guardian.Plug.Pipeline,
otp_app: :mobilizon, otp_app: :mobilizon,
module: MobilizonWeb.Guardian, module: MobilizonWeb.Auth.Guardian,
error_handler: MobilizonWeb.AuthErrorHandler error_handler: MobilizonWeb.Auth.ErrorHandler
plug(Guardian.Plug.VerifyHeader, realm: "Bearer") plug(Guardian.Plug.VerifyHeader, realm: "Bearer")
plug(Guardian.Plug.LoadResource, allow_blank: true) plug(Guardian.Plug.LoadResource, allow_blank: true)
plug(MobilizonWeb.Context) plug(MobilizonWeb.Auth.Context)
end end

View File

@ -1,6 +1,6 @@
defmodule MobilizonWeb.Cache.ActivityPub do defmodule MobilizonWeb.Cache.ActivityPub do
@moduledoc """ @moduledoc """
The ActivityPub related functions. ActivityPub related cache.
""" """
alias Mobilizon.{Actors, Events, Tombstone} alias Mobilizon.{Actors, Events, Tombstone}
@ -9,8 +9,8 @@ defmodule MobilizonWeb.Cache.ActivityPub do
alias Mobilizon.Federation.ActivityPub.Relay alias Mobilizon.Federation.ActivityPub.Relay
alias MobilizonWeb.Router.Helpers, as: Routes
alias MobilizonWeb.Endpoint alias MobilizonWeb.Endpoint
alias MobilizonWeb.Router.Helpers, as: Routes
@cache :activity_pub @cache :activity_pub

View File

@ -8,7 +8,7 @@ defmodule MobilizonWeb.GraphQLSocket do
def connect(%{"token" => token}, socket) do def connect(%{"token" => token}, socket) do
with {:ok, authed_socket} <- with {:ok, authed_socket} <-
Guardian.Phoenix.Socket.authenticate(socket, MobilizonWeb.Guardian, token), Guardian.Phoenix.Socket.authenticate(socket, MobilizonWeb.Auth.Guardian, token),
%User{} = user <- Guardian.Phoenix.Socket.current_resource(authed_socket) do %User{} = user <- Guardian.Phoenix.Socket.current_resource(authed_socket) do
authed_socket = authed_socket =
Absinthe.Phoenix.Socket.put_options(socket, Absinthe.Phoenix.Socket.put_options(socket,

View File

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

View File

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

View File

@ -149,9 +149,9 @@ defmodule MobilizonWeb.Email.User do
_ -> _ ->
case Timex.before?( case Timex.before?(
Timex.shift(Map.get(user, key), hours: 1), Timex.shift(Map.get(user, key), hours: 1),
DateTime.utc_now() |> DateTime.truncate(:second) DateTime.utc_now() |> DateTime.truncate(:second)
) do ) do
true -> true ->
:ok :ok

View File

@ -3,7 +3,7 @@
# Copyright © 2017-2019 Pleroma Authors <https://pleroma.social/> # Copyright © 2017-2019 Pleroma Authors <https://pleroma.social/>
# SPDX-License-Identifier: AGPL-3.0-only # SPDX-License-Identifier: AGPL-3.0-only
defmodule Mobilizon.Federation.Plugs.Federating do defmodule MobilizonWeb.Plugs.Federating do
@moduledoc """ @moduledoc """
Restrict ActivityPub routes when not federating Restrict ActivityPub routes when not federating
""" """

View File

@ -3,7 +3,7 @@
# SPDX-License-Identifier: AGPL-3.0-only # SPDX-License-Identifier: AGPL-3.0-only
# Upstream: https://git.pleroma.social/pleroma/pleroma/blob/develop/lib/pleroma/plugs/http_signature.ex # Upstream: https://git.pleroma.social/pleroma/pleroma/blob/develop/lib/pleroma/plugs/http_signature.ex
defmodule Mobilizon.Federation.Plugs.HTTPSignatures do defmodule MobilizonWeb.Plugs.HTTPSignatures do
@moduledoc """ @moduledoc """
Plug to check HTTP Signatures on every incoming request Plug to check HTTP Signatures on every incoming request
""" """

View File

@ -3,9 +3,7 @@ defmodule MobilizonWeb.Resolvers.Comment do
Handles the comment-related GraphQL calls. Handles the comment-related GraphQL calls.
""" """
import Mobilizon.Service.Admin.ActionLog alias Mobilizon.{Actors, Admin, Events}
alias Mobilizon.Actors
alias Mobilizon.Actors.Actor alias Mobilizon.Actors.Actor
alias Mobilizon.Events alias Mobilizon.Events
alias Mobilizon.Events.Comment, as: CommentModel alias Mobilizon.Events.Comment, as: CommentModel
@ -49,7 +47,7 @@ defmodule MobilizonWeb.Resolvers.Comment do
role in [:moderator, :administrator] -> role in [:moderator, :administrator] ->
with {:ok, res} <- do_delete_comment(comment), with {:ok, res} <- do_delete_comment(comment),
%Actor{} = actor <- Actors.get_actor(actor_id) do %Actor{} = actor <- Actors.get_actor(actor_id) do
log_action(actor, "delete", comment) Admin.log_action(actor, "delete", comment)
{:ok, res} {:ok, res}
end end

View File

@ -3,11 +3,8 @@ defmodule MobilizonWeb.Resolvers.Event do
Handles the event-related GraphQL calls. Handles the event-related GraphQL calls.
""" """
import Mobilizon.Service.Admin.ActionLog alias Mobilizon.{Actors, Admin, Events}
alias Mobilizon.Actors
alias Mobilizon.Actors.Actor alias Mobilizon.Actors.Actor
alias Mobilizon.Events
alias Mobilizon.Events.{Event, Participant, EventParticipantStats} alias Mobilizon.Events.{Event, Participant, EventParticipantStats}
alias Mobilizon.Users.User alias Mobilizon.Users.User
@ -343,7 +340,7 @@ defmodule MobilizonWeb.Resolvers.Event do
role in [:moderator, :administrator] -> role in [:moderator, :administrator] ->
with {:ok, res} <- do_delete_event(event, !is_local), with {:ok, res} <- do_delete_event(event, !is_local),
%Actor{} = actor <- Actors.get_actor(actor_id) do %Actor{} = actor <- Actors.get_actor(actor_id) do
log_action(actor, "delete", event) Admin.log_action(actor, "delete", event)
{:ok, res} {:ok, res}
end end

View File

@ -10,7 +10,7 @@ defmodule MobilizonWeb.Resolvers.User do
alias Mobilizon.Storage.Repo alias Mobilizon.Storage.Repo
alias Mobilizon.Users.User alias Mobilizon.Users.User
alias MobilizonWeb.Email alias MobilizonWeb.{Auth, Email}
require Logger require Logger
@ -94,9 +94,9 @@ defmodule MobilizonWeb.Resolvers.User do
}, },
_context _context
) do ) do
with {:ok, user, _claims} <- MobilizonWeb.Guardian.resource_from_token(refresh_token), with {:ok, user, _claims} <- Auth.Guardian.resource_from_token(refresh_token),
{:ok, _old, {exchanged_token, _claims}} <- {:ok, _old, {exchanged_token, _claims}} <-
MobilizonWeb.Guardian.exchange(refresh_token, ["access", "refresh"], "access"), Auth.Guardian.exchange(refresh_token, ["access", "refresh"], "access"),
{:ok, refresh_token} <- Users.generate_refresh_token(user) do {:ok, refresh_token} <- Users.generate_refresh_token(user) do
{:ok, %{access_token: exchanged_token, refresh_token: refresh_token}} {:ok, %{access_token: exchanged_token, refresh_token: refresh_token}}
else else

View File

@ -6,7 +6,7 @@ defmodule MobilizonWeb.Router do
pipeline :graphql do pipeline :graphql do
# plug(:accepts, ["json"]) # plug(:accepts, ["json"])
plug(MobilizonWeb.AuthPipeline) plug(MobilizonWeb.Auth.Pipeline)
end end
pipeline :well_known do pipeline :well_known do
@ -14,13 +14,13 @@ defmodule MobilizonWeb.Router do
end end
pipeline :activity_pub_signature do pipeline :activity_pub_signature do
plug(Mobilizon.Federation.Plugs.HTTPSignatures) plug(MobilizonWeb.Plugs.HTTPSignatures)
plug(Mobilizon.Federation.Plugs.MappedSignatureToIdentity) plug(MobilizonWeb.Plugs.MappedSignatureToIdentity)
end end
pipeline :relay do pipeline :relay do
plug(Mobilizon.Federation.Plugs.HTTPSignatures) plug(MobilizonWeb.Plugs.HTTPSignatures)
plug(Mobilizon.Federation.Plugs.MappedSignatureToIdentity) plug(MobilizonWeb.Plugs.MappedSignatureToIdentity)
plug(:accepts, ["activity-json", "json"]) plug(:accepts, ["activity-json", "json"])
end end
@ -58,7 +58,7 @@ defmodule MobilizonWeb.Router do
) )
end end
forward("/graphiql", Absinthe.Plug.GraphiQL, schema: MobilizonWeb.Schema) ## FEDERATION
scope "/.well-known", MobilizonWeb do scope "/.well-known", MobilizonWeb do
pipe_through(:well_known) pipe_through(:well_known)
@ -69,28 +69,6 @@ defmodule MobilizonWeb.Router do
get("/nodeinfo/:version", NodeInfoController, :nodeinfo) get("/nodeinfo/:version", NodeInfoController, :nodeinfo)
end end
scope "/", MobilizonWeb do
pipe_through(:atom_and_ical)
get("/@:name/feed/:format", FeedController, :actor)
get("/events/:uuid/export/:format", FeedController, :event)
get("/events/going/:token/:format", FeedController, :going)
end
scope "/", MobilizonWeb do
pipe_through(:browser)
# Because the "/events/:uuid" route caches all these, we need to force them
get("/events/create", PageController, :index)
get("/events/list", PageController, :index)
get("/events/me", PageController, :index)
get("/events/explore", PageController, :index)
get("/events/:uuid/edit", PageController, :index)
# This is a hack to ease link generation into emails
get("/moderation/reports/:id", PageController, :index, as: "moderation_report")
end
scope "/", MobilizonWeb do scope "/", MobilizonWeb do
pipe_through(:activity_pub_and_html) pipe_through(:activity_pub_and_html)
pipe_through(:activity_pub_signature) pipe_through(:activity_pub_signature)
@ -121,6 +99,34 @@ defmodule MobilizonWeb.Router do
post("/inbox", ActivityPubController, :inbox) post("/inbox", ActivityPubController, :inbox)
end end
## FEED
scope "/", MobilizonWeb do
pipe_through(:atom_and_ical)
get("/@:name/feed/:format", FeedController, :actor)
get("/events/:uuid/export/:format", FeedController, :event)
get("/events/going/:token/:format", FeedController, :going)
end
## MOBILIZON
forward("/graphiql", Absinthe.Plug.GraphiQL, schema: MobilizonWeb.Schema)
scope "/", MobilizonWeb do
pipe_through(:browser)
# Because the "/events/:uuid" route caches all these, we need to force them
get("/events/create", PageController, :index)
get("/events/list", PageController, :index)
get("/events/me", PageController, :index)
get("/events/explore", PageController, :index)
get("/events/:uuid/edit", PageController, :index)
# This is a hack to ease link generation into emails
get("/moderation/reports/:id", PageController, :index, as: "moderation_report")
end
scope "/proxy/", MobilizonWeb do scope "/proxy/", MobilizonWeb do
pipe_through(:remote_media) pipe_through(:remote_media)

View File

@ -3,7 +3,7 @@
# SPDX-License-Identifier: AGPL-3.0-only # SPDX-License-Identifier: AGPL-3.0-only
# Upstream: https://git.pleroma.social/pleroma/pleroma/blob/develop/lib/pleroma/mime.ex # Upstream: https://git.pleroma.social/pleroma/pleroma/blob/develop/lib/pleroma/mime.ex
defmodule MobilizonWeb.MIME do defmodule MobilizonWeb.Upload.MIME do
@moduledoc """ @moduledoc """
Returns the mime-type of a binary and optionally a normalized file-name. Returns the mime-type of a binary and optionally a normalized file-name.
""" """

View File

@ -27,7 +27,7 @@ defmodule MobilizonWeb.Upload do
Related behaviors: Related behaviors:
* `MobilizonWeb.Uploaders.Uploader` * `MobilizonWeb.Upload.Uploader`
* `MobilizonWeb.Upload.Filter` * `MobilizonWeb.Upload.Filter`
""" """
@ -36,7 +36,7 @@ defmodule MobilizonWeb.Upload do
alias Mobilizon.Config alias Mobilizon.Config
alias MobilizonWeb.{MIME, Upload, Uploaders} alias MobilizonWeb.Upload.{Filter, MIME, Uploader}
require Logger require Logger
@ -69,8 +69,8 @@ defmodule MobilizonWeb.Upload do
with {:ok, upload} <- prepare_upload(upload, opts), with {:ok, upload} <- prepare_upload(upload, opts),
upload = %__MODULE__{upload | path: upload.path || "#{upload.id}/#{upload.name}"}, upload = %__MODULE__{upload | path: upload.path || "#{upload.id}/#{upload.name}"},
{:ok, upload} <- Upload.Filter.filter(opts.filters, upload), {:ok, upload} <- Filter.filter(opts.filters, upload),
{:ok, url_spec} <- Uploaders.Uploader.put_file(opts.uploader, upload) do {:ok, url_spec} <- Uploader.put_file(opts.uploader, upload) do
{:ok, {:ok,
%{ %{
name: Map.get(opts, :description) || upload.name, name: Map.get(opts, :description) || upload.name,
@ -92,7 +92,7 @@ defmodule MobilizonWeb.Upload do
with opts <- get_opts(opts), with opts <- get_opts(opts),
%URI{path: "/media/" <> path, host: host} <- URI.parse(url), %URI{path: "/media/" <> path, host: host} <- URI.parse(url),
{:same_host, true} <- {:same_host, host == MobilizonWeb.Endpoint.host()} do {:same_host, true} <- {:same_host, host == MobilizonWeb.Endpoint.host()} do
Uploaders.Uploader.remove_file(opts.uploader, path) Uploader.remove_file(opts.uploader, path)
else else
%URI{} = _uri -> %URI{} = _uri ->
{:error, "URL doesn't match pattern"} {:error, "URL doesn't match pattern"}

View File

@ -3,12 +3,12 @@
# SPDX-License-Identifier: AGPL-3.0-only # SPDX-License-Identifier: AGPL-3.0-only
# Upstream: https://git.pleroma.social/pleroma/pleroma/blob/develop/lib/pleroma/uploaders/local.ex # Upstream: https://git.pleroma.social/pleroma/pleroma/blob/develop/lib/pleroma/uploaders/local.ex
defmodule MobilizonWeb.Uploaders.Local do defmodule MobilizonWeb.Upload.Uploader.Local do
@moduledoc """ @moduledoc """
Local uploader for files Local uploader for files
""" """
@behaviour MobilizonWeb.Uploaders.Uploader @behaviour MobilizonWeb.Upload.Uploader
alias Mobilizon.Config alias Mobilizon.Config

View File

@ -3,7 +3,7 @@
# SPDX-License-Identifier: AGPL-3.0-only # SPDX-License-Identifier: AGPL-3.0-only
# Upstream: https://git.pleroma.social/pleroma/pleroma/blob/develop/lib/pleroma/uploaders/uploader.ex # Upstream: https://git.pleroma.social/pleroma/pleroma/blob/develop/lib/pleroma/uploaders/uploader.ex
defmodule MobilizonWeb.Uploaders.Uploader do defmodule MobilizonWeb.Upload.Uploader do
@moduledoc """ @moduledoc """
Defines the contract to put and get an uploaded file to any backend. Defines the contract to put and get an uploaded file to any backend.
""" """

View File

@ -1,39 +0,0 @@
defmodule Mobilizon.Service.Admin.ActionLog do
@moduledoc """
Module to handle action log creations.
"""
alias Mobilizon.Actors.Actor
alias Mobilizon.{Admin, Users}
alias Mobilizon.Admin.ActionLog
alias Mobilizon.Users.User
@doc """
Log an admin action
"""
@spec log_action(Actor.t(), String.t(), String.t()) :: {:ok, ActionLog.t()}
def log_action(%Actor{user_id: user_id, id: actor_id}, action, target) do
with %User{role: role} <- Users.get_user!(user_id),
{:role, true} <- {:role, role in [:administrator, :moderator]},
{:ok, %ActionLog{} = create_action_log} <-
Admin.create_action_log(%{
"actor_id" => actor_id,
"target_type" => to_string(target.__struct__),
"target_id" => target.id,
"action" => action,
"changes" => stringify_struct(target)
}) do
{:ok, create_action_log}
end
end
defp stringify_struct(%_{} = struct) do
association_fields = struct.__struct__.__schema__(:associations)
struct
|> Map.from_struct()
|> Map.drop(association_fields ++ [:__meta__])
end
defp stringify_struct(struct), do: struct
end

View File

@ -14,4 +14,3 @@ defmodule Mobilizon.Service.Formatter.HTML do
def filter_tags(html), do: Scrubber.scrub(html, DefaultScrubbler) def filter_tags(html), do: Scrubber.scrub(html, DefaultScrubbler)
end end

View File

@ -9,6 +9,7 @@ defmodule Mobilizon.Service.Workers.Helper do
""" """
alias Mobilizon.Config alias Mobilizon.Config
alias Mobilizon.Service.Workers.Helper
alias Mobilizon.Storage.Repo alias Mobilizon.Storage.Repo
def worker_args(queue) do def worker_args(queue) do
@ -40,7 +41,7 @@ defmodule Mobilizon.Service.Workers.Helper do
def enqueue(operation, params, worker_args \\ []) do def enqueue(operation, params, worker_args \\ []) do
params = Map.merge(%{"op" => operation}, params) params = Map.merge(%{"op" => operation}, params)
queue_atom = String.to_existing_atom(unquote(queue)) queue_atom = String.to_existing_atom(unquote(queue))
worker_args = worker_args ++ __MODULE__.worker_args(queue_atom) worker_args = worker_args ++ Helper.worker_args(queue_atom)
unquote(caller_module) unquote(caller_module)
|> apply(:new, [params, worker_args]) |> apply(:new, [params, worker_args])

141
mix.exs
View File

@ -181,6 +181,8 @@ defmodule Mobilizon.Mixfile do
Mobilizon.Actors.Member, Mobilizon.Actors.Member,
Mobilizon.Addresses, Mobilizon.Addresses,
Mobilizon.Addresses.Address, Mobilizon.Addresses.Address,
Mobilizon.Admin,
Mobilizon.Admin.ActionLog,
Mobilizon.Events, Mobilizon.Events,
Mobilizon.Events.Event, Mobilizon.Events.Event,
Mobilizon.Events.Comment, Mobilizon.Events.Comment,
@ -190,7 +192,7 @@ defmodule Mobilizon.Mixfile do
Mobilizon.Events.Tag, Mobilizon.Events.Tag,
Mobilizon.Events.TagRelations, Mobilizon.Events.TagRelations,
Mobilizon.Events.Track, Mobilizon.Events.Track,
Mobilizon.Event.EventCategory, Mobilizon.Events.EventCategory,
Mobilizon.Events.CommentVisibility, Mobilizon.Events.CommentVisibility,
Mobilizon.Events.EventStatus, Mobilizon.Events.EventStatus,
Mobilizon.Events.EventVisibility, Mobilizon.Events.EventVisibility,
@ -199,111 +201,184 @@ defmodule Mobilizon.Mixfile do
Mobilizon.Events.Tag.TitleSlug, Mobilizon.Events.Tag.TitleSlug,
Mobilizon.Events.Tag.TitleSlug.Type, Mobilizon.Events.Tag.TitleSlug.Type,
Mobilizon.Events.TagRelation, Mobilizon.Events.TagRelation,
Mobilizon.Media,
Mobilizon.Media.File,
Mobilizon.Media.Picture,
Mobilizon.Mention,
Mobilizon.Reports,
Mobilizon.Reports.Note,
Mobilizon.Reports.Report,
Mobilizon.Share,
Mobilizon.Tombstone,
Mobilizon.Users, Mobilizon.Users,
Mobilizon.Users.User, Mobilizon.Users.User,
Mobilizon.Users.UserRole, Mobilizon.Users.UserRole,
Mobilizon.Users.Guards,
Mobilizon.Storage.Ecto,
Mobilizon.Storage.Repo,
Mobilizon.Federation.ActivityPub.Activity Mobilizon.Federation.ActivityPub.Activity
], ],
APIs: [ APIs: [
MobilizonWeb.API.Comments, MobilizonWeb.API.Comments,
MobilizonWeb.API.Events, MobilizonWeb.API.Events,
MobilizonWeb.API.Follows,
MobilizonWeb.API.Groups, MobilizonWeb.API.Groups,
MobilizonWeb.API.Participations,
MobilizonWeb.API.Reports,
MobilizonWeb.API.Search, MobilizonWeb.API.Search,
MobilizonWeb.API.Utils MobilizonWeb.API.Utils
], ],
Web: [ Web: [
MobilizonWeb, MobilizonWeb,
MobilizonWeb.PageView, MobilizonWeb.Endpoint,
MobilizonWeb.Router, MobilizonWeb.Router,
MobilizonWeb.Router.Helpers, MobilizonWeb.Router.Helpers,
MobilizonWeb.AuthErrorHandler, MobilizonWeb.Plugs.UploadedMedia,
MobilizonWeb.AuthPipeline,
MobilizonWeb.Cache,
MobilizonWeb.ChangesetView,
MobilizonWeb.Context,
MobilizonWeb.Endpoint,
MobilizonWeb.ErrorHelpers,
MobilizonWeb.ErrorView,
MobilizonWeb.FallbackController, MobilizonWeb.FallbackController,
MobilizonWeb.FeedController, MobilizonWeb.FeedController,
MobilizonWeb.Gettext, MobilizonWeb.MediaProxyController,
MobilizonWeb.Guardian,
MobilizonWeb.Guardian.Plug,
MobilizonWeb.JsonLD.ObjectView,
MobilizonWeb.PageController, MobilizonWeb.PageController,
MobilizonWeb.Uploaders.Avatar, MobilizonWeb.ChangesetView,
MobilizonWeb.Uploaders.Category, MobilizonWeb.JsonLD.ObjectView,
MobilizonWeb.Uploaders.Category.Type MobilizonWeb.EmailView,
MobilizonWeb.ErrorHelpers,
MobilizonWeb.ErrorView,
MobilizonWeb.LayoutView,
MobilizonWeb.PageView,
MobilizonWeb.Auth.Context,
MobilizonWeb.Auth.ErrorHandler,
MobilizonWeb.Auth.Guardian,
MobilizonWeb.Auth.Pipeline,
MobilizonWeb.Cache,
MobilizonWeb.Cache.ActivityPub,
MobilizonWeb.Email,
MobilizonWeb.Email.Admin,
MobilizonWeb.Email.Checker,
MobilizonWeb.Email.Event,
MobilizonWeb.Email.Mailer,
MobilizonWeb.Email.Participation,
MobilizonWeb.Email.User,
MobilizonWeb.Upload,
MobilizonWeb.Upload.Filter,
MobilizonWeb.Upload.Filter.AnonymizeFilename,
MobilizonWeb.Upload.Filter.Dedupe,
MobilizonWeb.Upload.Filter.Mogrify,
MobilizonWeb.Upload.Filter.Optimize,
MobilizonWeb.Upload.MIME,
MobilizonWeb.Upload.Uploader,
MobilizonWeb.Upload.Uploader.Local,
MobilizonWeb.MediaProxy,
MobilizonWeb.ReverseProxy
], ],
Geospatial: [ Geospatial: [
Mobilizon.Service.Geospatial, Mobilizon.Service.Geospatial,
Mobilizon.Service.Geospatial.Addok, Mobilizon.Service.Geospatial.Addok,
Mobilizon.Service.Geospatial.GoogleMaps, Mobilizon.Service.Geospatial.GoogleMaps,
Mobilizon.Service.Geospatial.MapQuest, Mobilizon.Service.Geospatial.MapQuest,
Mobilizon.Service.Geospatial.Mimirsbrunn,
Mobilizon.Service.Geospatial.Nominatim, Mobilizon.Service.Geospatial.Nominatim,
Mobilizon.Service.Geospatial.Pelias,
Mobilizon.Service.Geospatial.Photon, Mobilizon.Service.Geospatial.Photon,
Mobilizon.Service.Geospatial.Provider Mobilizon.Service.Geospatial.Provider
], ],
Localization: [
Mobilizon.Cldr,
MobilizonWeb.Gettext
],
GraphQL: [ GraphQL: [
MobilizonWeb.GraphQLSocket,
MobilizonWeb.Resolvers.Address, MobilizonWeb.Resolvers.Address,
MobilizonWeb.Resolvers.Admin,
MobilizonWeb.Resolvers.Comment, MobilizonWeb.Resolvers.Comment,
MobilizonWeb.Resolvers.Config,
MobilizonWeb.Resolvers.Event, MobilizonWeb.Resolvers.Event,
MobilizonWeb.Resolvers.FeedToken, MobilizonWeb.Resolvers.FeedToken,
MobilizonWeb.Resolvers.Group, MobilizonWeb.Resolvers.Group,
MobilizonWeb.Resolvers.Member,
MobilizonWeb.Resolvers.Person, MobilizonWeb.Resolvers.Person,
MobilizonWeb.Resolvers.Picture,
MobilizonWeb.Resolvers.Report,
MobilizonWeb.Resolvers.Search, MobilizonWeb.Resolvers.Search,
MobilizonWeb.Resolvers.Tag, MobilizonWeb.Resolvers.Tag,
MobilizonWeb.Resolvers.User, MobilizonWeb.Resolvers.User,
MobilizonWeb.Schema, MobilizonWeb.Schema,
MobilizonWeb.Schema.ActorInterface, MobilizonWeb.Schema.ActorInterface,
MobilizonWeb.Schema.Actors.ApplicationType,
MobilizonWeb.Schema.Actors.FollowerType, MobilizonWeb.Schema.Actors.FollowerType,
MobilizonWeb.Schema.Actors.GroupType, MobilizonWeb.Schema.Actors.GroupType,
MobilizonWeb.Schema.Actors.MemberType, MobilizonWeb.Schema.Actors.MemberType,
MobilizonWeb.Schema.Actors.PersonType, MobilizonWeb.Schema.Actors.PersonType,
MobilizonWeb.Schema.AddressType, MobilizonWeb.Schema.AddressType,
MobilizonWeb.Schema.AdminType,
MobilizonWeb.Schema.CommentType, MobilizonWeb.Schema.CommentType,
MobilizonWeb.Schema.Custom.Point, MobilizonWeb.Schema.ConfigType,
MobilizonWeb.Schema.Custom.UUID,
MobilizonWeb.Schema.EventType, MobilizonWeb.Schema.EventType,
MobilizonWeb.Schema.Events.FeedTokenType, MobilizonWeb.Schema.Events.FeedTokenType,
MobilizonWeb.Schema.Events.ParticipantType, MobilizonWeb.Schema.Events.ParticipantType,
MobilizonWeb.Schema.PictureType,
MobilizonWeb.Schema.ReportType,
MobilizonWeb.Schema.SearchType,
MobilizonWeb.Schema.SortType, MobilizonWeb.Schema.SortType,
MobilizonWeb.Schema.TagType, MobilizonWeb.Schema.TagType,
MobilizonWeb.Schema.UserType, MobilizonWeb.Schema.UserType,
MobilizonWeb.Schema.Utils MobilizonWeb.Schema.Utils,
MobilizonWeb.Schema.Custom.Point,
MobilizonWeb.Schema.Custom.UUID
], ],
ActivityPub: [ ActivityPub: [
Mobilizon.Federation.ActivityPub, Mobilizon.Federation.ActivityPub,
Mobilizon.Federation.ActivityPub.Audience,
Mobilizon.Federation.ActivityPub.Federator, Mobilizon.Federation.ActivityPub.Federator,
Mobilizon.Federation.ActivityPub.Relay,
Mobilizon.Federation.ActivityPub.Transmogrifier, Mobilizon.Federation.ActivityPub.Transmogrifier,
Mobilizon.Federation.ActivityPub.Visibility,
Mobilizon.Federation.ActivityPub.Utils, Mobilizon.Federation.ActivityPub.Utils,
Mobilizon.Federation.ActivityStream.Convertible,
Mobilizon.Federation.ActivityStream.Converter,
Mobilizon.Federation.ActivityStream.Converter.Actor,
Mobilizon.Federation.ActivityStream.Converter.Address,
Mobilizon.Federation.ActivityStream.Converter.Comment,
Mobilizon.Federation.ActivityStream.Converter.Event,
Mobilizon.Federation.ActivityStream.Converter.Flag,
Mobilizon.Federation.ActivityStream.Converter.Follower,
Mobilizon.Federation.ActivityStream.Converter.Participant,
Mobilizon.Federation.ActivityStream.Converter.Picture,
Mobilizon.Federation.ActivityStream.Converter.Tombstone,
Mobilizon.Federation.ActivityStream.Converter.Utils,
Mobilizon.Federation.HTTPSignatures.Signature, Mobilizon.Federation.HTTPSignatures.Signature,
Mobilizon.Federation.WebFinger, Mobilizon.Federation.WebFinger,
Mobilizon.Federation.WebFinger.XmlBuilder, Mobilizon.Federation.WebFinger.XmlBuilder,
Mobilizon.Federation.Plugs.HTTPSignatures, MobilizonWeb.Plugs.Federating,
MobilizonWeb.ActivityPub.ActorView, MobilizonWeb.Plugs.HTTPSignatures,
MobilizonWeb.ActivityPub.ObjectView, MobilizonWeb.Plugs.MappedSignatureToIdentity,
MobilizonWeb.ActivityPubController, MobilizonWeb.ActivityPubController,
MobilizonWeb.NodeInfoController,
MobilizonWeb.WebFingerController, MobilizonWeb.WebFingerController,
MobilizonWeb.NodeInfoController MobilizonWeb.ActivityPub.ActorView,
MobilizonWeb.ActivityPub.ObjectView
], ],
Services: [ Services: [
Mobilizon.Service.EmailChecker,
Mobilizon.Service.Export.Feed, Mobilizon.Service.Export.Feed,
Mobilizon.Service.Export.ICalendar, Mobilizon.Service.Export.ICalendar,
Mobilizon.Service.Metadata,
Mobilizon.Service.Formatter, Mobilizon.Service.Formatter,
Mobilizon.Service.Users.Tools Mobilizon.Service.Formatter.HTML,
Mobilizon.Service.Formatter.DefaultScrubbler,
Mobilizon.Service.Metadata,
Mobilizon.Service.Metadata.Actor,
Mobilizon.Service.Metadata.Comment,
Mobilizon.Service.Metadata.Event,
Mobilizon.Service.Metadata.Instance,
Mobilizon.Service.Metadata.Utils,
Mobilizon.Service.Statistics,
Mobilizon.Service.Workers.Background,
Mobilizon.Service.Workers.BuildSearch,
Mobilizon.Service.Workers.Helper
], ],
Tools: [ Tools: [
Mobilizon.Application, Mobilizon.Application,
Mobilizon.Config,
Mobilizon.Crypto,
Mobilizon.Factory, Mobilizon.Factory,
MobilizonWeb.Email.Mailer, Mobilizon.Storage.Ecto,
MobilizonWeb.Email.User, Mobilizon.Storage.Page,
MobilizonWeb.EmailView Mobilizon.Storage.Repo
] ]
] ]
end end

View File

@ -14,6 +14,8 @@ defmodule Mobilizon.ActorsTest do
alias Mobilizon.Federation.ActivityPub alias Mobilizon.Federation.ActivityPub
alias MobilizonWeb.Upload.Uploader
describe "actors" do describe "actors" do
@valid_attrs %{ @valid_attrs %{
summary: "some description", summary: "some description",
@ -241,12 +243,12 @@ defmodule Mobilizon.ActorsTest do
%URI{path: "/media/" <> banner_path} = URI.parse(banner_url) %URI{path: "/media/" <> banner_path} = URI.parse(banner_url)
assert File.exists?( assert File.exists?(
Config.get!([MobilizonWeb.Uploaders.Local, :uploads]) <> Config.get!([Uploader.Local, :uploads]) <>
"/" <> avatar_path "/" <> avatar_path
) )
assert File.exists?( assert File.exists?(
Config.get!([MobilizonWeb.Uploaders.Local, :uploads]) <> Config.get!([Uploader.Local, :uploads]) <>
"/" <> banner_path "/" <> banner_path
) )
@ -271,12 +273,12 @@ defmodule Mobilizon.ActorsTest do
refute actor.suspended refute actor.suspended
refute File.exists?( refute File.exists?(
Config.get!([MobilizonWeb.Uploaders.Local, :uploads]) <> Config.get!([Uploader.Local, :uploads]) <>
"/" <> avatar_path "/" <> avatar_path
) )
assert File.exists?( assert File.exists?(
Config.get!([MobilizonWeb.Uploaders.Local, :uploads]) <> Config.get!([Uploader.Local, :uploads]) <>
"/" <> banner_path "/" <> banner_path
) )
end end
@ -300,12 +302,12 @@ defmodule Mobilizon.ActorsTest do
%URI{path: "/media/" <> banner_path} = URI.parse(banner_url) %URI{path: "/media/" <> banner_path} = URI.parse(banner_url)
assert File.exists?( assert File.exists?(
Config.get!([MobilizonWeb.Uploaders.Local, :uploads]) <> Config.get!([Uploader.Local, :uploads]) <>
"/" <> avatar_path "/" <> avatar_path
) )
assert File.exists?( assert File.exists?(
Config.get!([MobilizonWeb.Uploaders.Local, :uploads]) <> Config.get!([Uploader.Local, :uploads]) <>
"/" <> banner_path "/" <> banner_path
) )
@ -334,12 +336,12 @@ defmodule Mobilizon.ActorsTest do
assert %Tombstone{} = Tombstone.find_tombstone(comment1_url) assert %Tombstone{} = Tombstone.find_tombstone(comment1_url)
refute File.exists?( refute File.exists?(
Config.get!([MobilizonWeb.Uploaders.Local, :uploads]) <> Config.get!([Uploader.Local, :uploads]) <>
"/" <> avatar_path "/" <> avatar_path
) )
refute File.exists?( refute File.exists?(
Config.get!([MobilizonWeb.Uploaders.Local, :uploads]) <> Config.get!([Uploader.Local, :uploads]) <>
"/" <> banner_path "/" <> banner_path
) )
end end

View File

@ -6,8 +6,8 @@ defmodule Mobilizon.Service.Admin.ActionLogTest do
use Mobilizon.DataCase use Mobilizon.DataCase
import Mobilizon.Factory import Mobilizon.Factory
import Mobilizon.Service.Admin.ActionLog
alias Mobilizon.Admin
alias Mobilizon.Admin.ActionLog alias Mobilizon.Admin.ActionLog
alias Mobilizon.Reports.{Note, Report} alias Mobilizon.Reports.{Note, Report}
@ -27,7 +27,7 @@ defmodule Mobilizon.Service.Admin.ActionLogTest do
target_id: report_id, target_id: report_id,
action: :update, action: :update,
actor: moderator actor: moderator
}} = log_action(moderator, "update", report) }} = Admin.log_action(moderator, "update", report)
end end
test "log the creation of a report note", %{moderator: moderator} do test "log the creation of a report note", %{moderator: moderator} do
@ -40,7 +40,7 @@ defmodule Mobilizon.Service.Admin.ActionLogTest do
target_id: note_id, target_id: note_id,
action: :create, action: :create,
actor: moderator actor: moderator
}} = log_action(moderator, "create", report) }} = Admin.log_action(moderator, "create", report)
end end
end end
end end

View File

@ -5,6 +5,8 @@ defmodule Mobilizon.MediaTest do
alias Mobilizon.{Config, Media} alias Mobilizon.{Config, Media}
alias MobilizonWeb.Upload.Uploader
describe "media" do describe "media" do
setup [:ensure_local_uploader] setup [:ensure_local_uploader]
alias Mobilizon.Media.Picture alias Mobilizon.Media.Picture
@ -49,7 +51,7 @@ defmodule Mobilizon.MediaTest do
%URI{path: "/media/" <> path} = URI.parse(picture.file.url) %URI{path: "/media/" <> path} = URI.parse(picture.file.url)
assert File.exists?( assert File.exists?(
Config.get!([MobilizonWeb.Uploaders.Local, :uploads]) <> Config.get!([Uploader.Local, :uploads]) <>
"/" <> path "/" <> path
) )
@ -57,7 +59,7 @@ defmodule Mobilizon.MediaTest do
assert_raise Ecto.NoResultsError, fn -> Media.get_picture!(picture.id) end assert_raise Ecto.NoResultsError, fn -> Media.get_picture!(picture.id) end
refute File.exists?( refute File.exists?(
Config.get!([MobilizonWeb.Uploaders.Local, :uploads]) <> Config.get!([Uploader.Local, :uploads]) <>
"/" <> path "/" <> path
) )
end end

View File

@ -3,10 +3,10 @@
# Copyright © 2017-2019 Pleroma Authors <https://pleroma.social/> # Copyright © 2017-2019 Pleroma Authors <https://pleroma.social/>
# SPDX-License-Identifier: AGPL-3.0-only # SPDX-License-Identifier: AGPL-3.0-only
defmodule Mobilizon.Federation.Plug.FederatingTest do defmodule MobilizonWeb.Plug.FederatingTest do
use MobilizonWeb.ConnCase use MobilizonWeb.ConnCase
alias Mobilizon.Federation.Plugs.Federating alias MobilizonWeb.Plugs.Federating
test "returns and halt the conn when federating is disabled" do test "returns and halt the conn when federating is disabled" do
Mobilizon.Config.put([:instance, :federating], false) Mobilizon.Config.put([:instance, :federating], false)

View File

@ -3,7 +3,7 @@
# Copyright © 2017-2019 Pleroma Authors <https://pleroma.social/> # Copyright © 2017-2019 Pleroma Authors <https://pleroma.social/>
# SPDX-License-Identifier: AGPL-3.0-only # SPDX-License-Identifier: AGPL-3.0-only
defmodule Mobilizon.Federation.Plugs.MappedSignatureToIdentityTest do defmodule MobilizonWeb.Plugs.MappedSignatureToIdentityTest do
use MobilizonWeb.ConnCase use MobilizonWeb.ConnCase
use ExVCR.Mock, adapter: ExVCR.Adapter.Hackney use ExVCR.Mock, adapter: ExVCR.Adapter.Hackney

View File

@ -158,7 +158,11 @@ defmodule MobilizonWeb.Resolvers.EventResolverTest do
assert json_response(res, 200)["data"]["createEvent"]["title"] == "come to my event" assert json_response(res, 200)["data"]["createEvent"]["title"] == "come to my event"
{id, ""} = json_response(res, 200)["data"]["createEvent"]["id"] |> Integer.parse() {id, ""} = json_response(res, 200)["data"]["createEvent"]["id"] |> Integer.parse()
assert_enqueued(worker: Workers.BuildSearch, args: %{event_id: id, op: :insert_search_event})
assert_enqueued(
worker: Workers.BuildSearch,
args: %{event_id: id, op: :insert_search_event}
)
end end
test "create_event/3 creates an event and escapes title and description", %{ test "create_event/3 creates an event and escapes title and description", %{
@ -204,7 +208,11 @@ defmodule MobilizonWeb.Resolvers.EventResolverTest do
"<b>My description</b> <img src=\"http://placekitten.com/g/200/300\" />" "<b>My description</b> <img src=\"http://placekitten.com/g/200/300\" />"
{id, ""} = res["data"]["createEvent"]["id"] |> Integer.parse() {id, ""} = res["data"]["createEvent"]["id"] |> Integer.parse()
assert_enqueued(worker: Workers.BuildSearch, args: %{event_id: id, op: :insert_search_event})
assert_enqueued(
worker: Workers.BuildSearch,
args: %{event_id: id, op: :insert_search_event}
)
end end
test "create_event/3 creates an event as a draft", %{conn: conn, actor: actor, user: user} do test "create_event/3 creates an event as a draft", %{conn: conn, actor: actor, user: user} do

View File

@ -5,10 +5,8 @@ defmodule MobilizonWeb.Resolvers.UserResolverTest do
use Bamboo.Test use Bamboo.Test
alias Mobilizon.{Actors, Users} alias Mobilizon.{Actors, Config, Users}
alias Mobilizon.Actors.Actor alias Mobilizon.Actors.Actor
alias Mobilizon.Service.Users.ResetPassword
alias Mobilizon.Users
alias Mobilizon.Users.User alias Mobilizon.Users.User
alias MobilizonWeb.{AbsintheHelpers, Email} alias MobilizonWeb.{AbsintheHelpers, Email}
@ -321,8 +319,8 @@ defmodule MobilizonWeb.Resolvers.UserResolverTest do
end end
test "create_user/3 doesn't allow registration when registration is closed", %{conn: conn} do test "create_user/3 doesn't allow registration when registration is closed", %{conn: conn} do
Mobilizon.Config.put([:instance, :registrations_open], false) Config.put([:instance, :registrations_open], false)
Mobilizon.Config.put([:instance, :registration_email_whitelist], []) Config.put([:instance, :registration_email_whitelist], [])
mutation = """ mutation = """
mutation createUser($email: String!, $password: String!) { mutation createUser($email: String!, $password: String!) {
@ -344,14 +342,14 @@ defmodule MobilizonWeb.Resolvers.UserResolverTest do
) )
assert hd(res["errors"])["message"] == "Registrations are not enabled" assert hd(res["errors"])["message"] == "Registrations are not enabled"
Mobilizon.Config.put([:instance, :registrations_open], true) Config.put([:instance, :registrations_open], true)
end end
test "create_user/3 doesn't allow registration when user email is not on the whitelist", %{ test "create_user/3 doesn't allow registration when user email is not on the whitelist", %{
conn: conn conn: conn
} do } do
Mobilizon.Config.put([:instance, :registrations_open], false) Config.put([:instance, :registrations_open], false)
Mobilizon.Config.put([:instance, :registration_email_whitelist], ["random.org"]) Config.put([:instance, :registration_email_whitelist], ["random.org"])
mutation = """ mutation = """
mutation createUser($email: String!, $password: String!) { mutation createUser($email: String!, $password: String!) {
@ -373,15 +371,15 @@ defmodule MobilizonWeb.Resolvers.UserResolverTest do
) )
assert hd(res["errors"])["message"] == "Your email is not on the whitelist" assert hd(res["errors"])["message"] == "Your email is not on the whitelist"
Mobilizon.Config.put([:instance, :registrations_open], true) Config.put([:instance, :registrations_open], true)
Mobilizon.Config.put([:instance, :registration_email_whitelist], []) Config.put([:instance, :registration_email_whitelist], [])
end end
test "create_user/3 allows registration when user email domain is on the whitelist", %{ test "create_user/3 allows registration when user email domain is on the whitelist", %{
conn: conn conn: conn
} do } do
Mobilizon.Config.put([:instance, :registrations_open], false) Config.put([:instance, :registrations_open], false)
Mobilizon.Config.put([:instance, :registration_email_whitelist], ["demo.tld"]) Config.put([:instance, :registration_email_whitelist], ["demo.tld"])
mutation = """ mutation = """
mutation createUser($email: String!, $password: String!) { mutation createUser($email: String!, $password: String!) {
@ -404,13 +402,13 @@ defmodule MobilizonWeb.Resolvers.UserResolverTest do
refute res["errors"] refute res["errors"]
assert res["data"]["createUser"]["email"] == @user_creation.email assert res["data"]["createUser"]["email"] == @user_creation.email
Mobilizon.Config.put([:instance, :registrations_open], true) Config.put([:instance, :registrations_open], true)
Mobilizon.Config.put([:instance, :registration_email_whitelist], []) Config.put([:instance, :registration_email_whitelist], [])
end end
test "create_user/3 allows registration when user email is on the whitelist", %{conn: conn} do test "create_user/3 allows registration when user email is on the whitelist", %{conn: conn} do
Mobilizon.Config.put([:instance, :registrations_open], false) Config.put([:instance, :registrations_open], false)
Mobilizon.Config.put([:instance, :registration_email_whitelist], [@user_creation.email]) Config.put([:instance, :registration_email_whitelist], [@user_creation.email])
mutation = """ mutation = """
mutation createUser($email: String!, $password: String!) { mutation createUser($email: String!, $password: String!) {
@ -433,8 +431,8 @@ defmodule MobilizonWeb.Resolvers.UserResolverTest do
refute res["errors"] refute res["errors"]
assert res["data"]["createUser"]["email"] == @user_creation.email assert res["data"]["createUser"]["email"] == @user_creation.email
Mobilizon.Config.put([:instance, :registrations_open], true) Config.put([:instance, :registrations_open], true)
Mobilizon.Config.put([:instance, :registration_email_whitelist], []) Config.put([:instance, :registration_email_whitelist], [])
end end
test "register_person/3 doesn't register a profile from an unknown email", context do test "register_person/3 doesn't register a profile from an unknown email", context do
@ -637,7 +635,7 @@ defmodule MobilizonWeb.Resolvers.UserResolverTest do
"You requested again a confirmation email too soon" "You requested again a confirmation email too soon"
# Hammer time ! # Hammer time !
Mobilizon.Users.update_user(user, %{ Users.update_user(user, %{
confirmation_sent_at: Timex.shift(user.confirmation_sent_at, hours: -3) confirmation_sent_at: Timex.shift(user.confirmation_sent_at, hours: -3)
}) })
@ -709,8 +707,8 @@ defmodule MobilizonWeb.Resolvers.UserResolverTest do
test "test reset_password/3 with valid email", context do test "test reset_password/3 with valid email", context do
{:ok, %User{} = user} = Users.register(%{email: "toto@tata.tld", password: "p4ssw0rd"}) {:ok, %User{} = user} = Users.register(%{email: "toto@tata.tld", password: "p4ssw0rd"})
%Actor{} = insert(:actor, user: user) %Actor{} = insert(:actor, user: user)
{:ok, _email_sent} = ResetPassword.send_password_reset_email(user) {:ok, _email_sent} = Email.User.send_password_reset_email(user)
%User{reset_password_token: reset_password_token} = Mobilizon.Users.get_user!(user.id) %User{reset_password_token: reset_password_token} = Users.get_user!(user.id)
mutation = """ mutation = """
mutation { mutation {
@ -734,8 +732,8 @@ defmodule MobilizonWeb.Resolvers.UserResolverTest do
test "test reset_password/3 with a password too short", context do test "test reset_password/3 with a password too short", context do
%User{} = user = insert(:user) %User{} = user = insert(:user)
{:ok, _email_sent} = ResetPassword.send_password_reset_email(user) {:ok, _email_sent} = Email.User.send_password_reset_email(user)
%User{reset_password_token: reset_password_token} = Mobilizon.Users.get_user!(user.id) %User{reset_password_token: reset_password_token} = Users.get_user!(user.id)
mutation = """ mutation = """
mutation { mutation {
@ -760,8 +758,8 @@ defmodule MobilizonWeb.Resolvers.UserResolverTest do
test "test reset_password/3 with an invalid token", context do test "test reset_password/3 with an invalid token", context do
%User{} = user = insert(:user) %User{} = user = insert(:user)
{:ok, _email_sent} = ResetPassword.send_password_reset_email(user) {:ok, _email_sent} = Email.User.send_password_reset_email(user)
%User{} = Mobilizon.Users.get_user!(user.id) %User{} = Users.get_user!(user.id)
mutation = """ mutation = """
mutation { mutation {

View File

@ -9,6 +9,7 @@ defmodule Mobilizon.UploadTest do
alias Mobilizon.Config alias Mobilizon.Config
alias MobilizonWeb.Upload alias MobilizonWeb.Upload
alias MobilizonWeb.Upload.Uploader
describe "Storing a file with the Local uploader" do describe "Storing a file with the Local uploader" do
setup [:ensure_local_uploader] setup [:ensure_local_uploader]
@ -184,7 +185,7 @@ defmodule Mobilizon.UploadTest do
test "delete a not existing file" do test "delete a not existing file" do
file = file =
Config.get!([MobilizonWeb.Uploaders.Local, :uploads]) <> Config.get!([Uploader.Local, :uploads]) <>
"/not_existing/definitely.jpg" "/not_existing/definitely.jpg"
refute File.exists?(file) refute File.exists?(file)
@ -214,6 +215,6 @@ defmodule Mobilizon.UploadTest do
assert String.starts_with?(url, MobilizonWeb.Endpoint.url() <> "/media/") assert String.starts_with?(url, MobilizonWeb.Endpoint.url() <> "/media/")
%URI{path: "/media/" <> path} = URI.parse(url) %URI{path: "/media/" <> path} = URI.parse(url)
{Config.get!([MobilizonWeb.Uploaders.Local, :uploads]) <> "/" <> path, url} {Config.get!([Uploader.Local, :uploads]) <> "/" <> path, url}
end end
end end

View File

@ -30,7 +30,7 @@ defmodule MobilizonWeb.ConnCase do
@endpoint MobilizonWeb.Endpoint @endpoint MobilizonWeb.Endpoint
def auth_conn(%Plug.Conn{} = conn, %User{} = user) do def auth_conn(%Plug.Conn{} = conn, %User{} = user) do
{:ok, token, _claims} = MobilizonWeb.Guardian.encode_and_sign(user) {:ok, token, _claims} = MobilizonWeb.Auth.Guardian.encode_and_sign(user)
conn conn
|> Plug.Conn.put_req_header("authorization", "Bearer #{token}") |> Plug.Conn.put_req_header("authorization", "Bearer #{token}")

View File

@ -19,6 +19,9 @@ defmodule Mobilizon.DataCase do
alias Mobilizon.Config alias Mobilizon.Config
alias Mobilizon.Storage.Repo alias Mobilizon.Storage.Repo
alias MobilizonWeb.Upload
alias MobilizonWeb.Upload.Uploader
using do using do
quote do quote do
alias Mobilizon.Storage.Repo alias Mobilizon.Storage.Repo
@ -55,16 +58,16 @@ defmodule Mobilizon.DataCase do
end end
def ensure_local_uploader(_context) do def ensure_local_uploader(_context) do
uploader = Config.get([MobilizonWeb.Upload, :uploader]) uploader = Config.get([Upload, :uploader])
filters = Config.get([MobilizonWeb.Upload, :filters]) filters = Config.get([Upload, :filters])
unless uploader == MobilizonWeb.Uploaders.Local || filters != [] do unless uploader == Uploader.Local || filters != [] do
Config.put([MobilizonWeb.Upload, :uploader], MobilizonWeb.Uploaders.Local) Config.put([Upload, :uploader], Uploader.Local)
Config.put([MobilizonWeb.Upload, :filters], []) Config.put([Upload, :filters], [])
on_exit(fn -> on_exit(fn ->
Config.put([MobilizonWeb.Upload, :uploader], uploader) Config.put([Upload, :uploader], uploader)
Config.put([MobilizonWeb.Upload, :filters], filters) Config.put([Upload, :filters], filters)
end) end)
end end

View File

@ -1,10 +1,11 @@
defmodule Mix.Tasks.Mobilizon.UsersTest do defmodule Mix.Tasks.Mobilizon.UsersTest do
use Mobilizon.DataCase use Mobilizon.DataCase
import Mobilizon.Factory
alias Mobilizon.Users alias Mobilizon.Users
alias Mobilizon.Users.User alias Mobilizon.Users.User
alias Mix.Tasks.Mobilizon.Users.{New, Delete, Show, Modify} alias Mix.Tasks.Mobilizon.Users.{New, Delete, Show, Modify}
import Mobilizon.Factory
Mix.shell(Mix.Shell.Process) Mix.shell(Mix.Shell.Process)