Remove credo and use mix format, and lint everything

Signed-off-by: Thomas Citharel <tcit@tcit.fr>
This commit is contained in:
Thomas Citharel 2018-07-27 10:45:35 +02:00
parent df3f08c528
commit 979aad5acb
104 changed files with 2278 additions and 1487 deletions

3
.formatter.exs Normal file
View File

@ -0,0 +1,3 @@
[
inputs: ["mix.exs", "{config,lib,test}/**/*.{ex,exs}"]
]

View File

@ -31,5 +31,5 @@ before_script:
mix:
script:
- mix credo
- mix format --check-formatted --dry-run
- mix coveralls

View File

@ -24,8 +24,7 @@ config :eventos, EventosWeb.Endpoint,
url: [host: "localhost"],
secret_key_base: "1yOazsoE0Wqu4kXk3uC5gu3jDbShOimTCzyFL3OjCdBmOXMyHX87Qmf3+Tu9s0iM",
render_errors: [view: EventosWeb.ErrorView, accepts: ~w(html json)],
pubsub: [name: Eventos.PubSub,
adapter: Phoenix.PubSub.PG2],
pubsub: [name: Eventos.PubSub, adapter: Phoenix.PubSub.PG2],
instance: "localhost",
email_from: "noreply@localhost",
email_to: "noreply@localhost"
@ -37,23 +36,26 @@ config :logger, :console,
# Import environment specific config. This must remain at the bottom
# of this file so it overrides the configuration defined above.
import_config "#{Mix.env}.exs"
import_config "#{Mix.env()}.exs"
config :eventos, EventosWeb.Guardian,
issuer: "eventos",
secret_key: "ty0WM7YBE3ojvxoUQxo8AERrNpfbXnIJ82ovkPdqbUFw31T5LcK8wGjaOiReVQjo"
issuer: "eventos",
secret_key: "ty0WM7YBE3ojvxoUQxo8AERrNpfbXnIJ82ovkPdqbUFw31T5LcK8wGjaOiReVQjo"
config :guardian, Guardian.DB,
repo: Eventos.Repo,
schema_name: "guardian_tokens", # default
token_types: ["refresh_token"], # store all token types if not set
sweep_interval: 60 # default: 60 minutes
repo: Eventos.Repo,
# default
schema_name: "guardian_tokens",
# store all token types if not set
token_types: ["refresh_token"],
# default: 60 minutes
sweep_interval: 60
config :geolix,
databases: [
%{
id: :city,
adapter: Geolix.Adapter.MMDB2,
source: System.get_env("GEOLITE_CITIES_PATH") || "priv/static/GeoLite2-City.mmdb"
}
]
databases: [
%{
id: :city,
adapter: Geolix.Adapter.MMDB2,
source: System.get_env("GEOLITE_CITIES_PATH") || "priv/static/GeoLite2-City.mmdb"
}
]

View File

@ -2,16 +2,15 @@ use Mix.Config
alias Dogma.Rule
config :dogma,
# Select a set of rules as a base
rule_set: Dogma.RuleSet.All,
# Select a set of rules as a base
rule_set: Dogma.RuleSet.All,
# Pick paths not to lint
exclude: [
~r(\Alib/vendor/)
],
# Pick paths not to lint
exclude: [
~r(\Alib/vendor/),
],
# Override an existing rule configuration
override: [
%Rule.LineLength{ enabled: false },
]
# Override an existing rule configuration
override: [
%Rule.LineLength{enabled: false}
]

View File

@ -23,13 +23,19 @@ config :eventos, Eventos.Mailer,
server: "localhost",
hostname: "localhost",
port: 25,
username: nil, # or {:system, "SMTP_USERNAME"}
password: nil, # or {:system, "SMTP_PASSWORD"}
tls: :if_available, # can be `:always` or `:never`
allowed_tls_versions: [:"tlsv1", :"tlsv1.1", :"tlsv1.2"], # or {":system", ALLOWED_TLS_VERSIONS"} w/ comma seprated values (e.g. "tlsv1.1,tlsv1.2")
ssl: false, # can be `true`
# or {:system, "SMTP_USERNAME"}
username: nil,
# or {:system, "SMTP_PASSWORD"}
password: nil,
# can be `:always` or `:never`
tls: :if_available,
# or {":system", ALLOWED_TLS_VERSIONS"} w/ comma seprated values (e.g. "tlsv1.1,tlsv1.2")
allowed_tls_versions: [:tlsv1, :"tlsv1.1", :"tlsv1.2"],
# can be `true`
ssl: false,
retries: 1,
no_mx_lookups: false # can be `true`
# can be `true`
no_mx_lookups: false
# Do not print debug messages in production
config :logger, level: :info

View File

@ -8,9 +8,9 @@ config :eventos, EventosWeb.Endpoint,
# Print only warnings and errors during test
config :logger,
backends: [:console],
compile_time_purge_level: :debug,
level: :info
backends: [:console],
compile_time_purge_level: :debug,
level: :info
# Configure your database
config :eventos, Eventos.Repo,
@ -22,5 +22,4 @@ config :eventos, Eventos.Repo,
pool: Ecto.Adapters.SQL.Sandbox,
types: Eventos.PostgresTypes
config :eventos, Eventos.Mailer,
adapter: Bamboo.TestAdapter
config :eventos, Eventos.Mailer, adapter: Bamboo.TestAdapter

View File

@ -13,11 +13,16 @@ defmodule Eventos.Actors.Actor.TitleSlug do
end
defp build_unique_slug(slug, changeset) do
query = from a in Actor,
where: a.slug == ^slug
query =
from(
a in Actor,
where: a.slug == ^slug
)
case Repo.one(query) do
nil -> slug
nil ->
slug
_story ->
slug
|> Eventos.Slug.increment_slug()
@ -27,8 +32,14 @@ defmodule Eventos.Actors.Actor.TitleSlug do
end
import EctoEnum
defenum Eventos.Actors.ActorTypeEnum, :actor_type, [:Person, :Application, :Group, :Organization, :Service]
defenum(Eventos.Actors.ActorTypeEnum, :actor_type, [
:Person,
:Application,
:Group,
:Organization,
:Service
])
defmodule Eventos.Actors.Actor do
@moduledoc """
@ -46,29 +57,29 @@ defmodule Eventos.Actors.Actor do
import Logger
# @type t :: %Actor{description: String.t, id: integer(), inserted_at: DateTime.t, updated_at: DateTime.t, display_name: String.t, domain: String.t, keys: String.t, suspended: boolean(), url: String.t, username: String.t, organized_events: list(), groups: list(), group_request: list(), user: User.t, field: ActorTypeEnum.t}
# @type t :: %Actor{description: String.t, id: integer(), inserted_at: DateTime.t, updated_at: DateTime.t, display_name: String.t, domain: String.t, keys: String.t, suspended: boolean(), url: String.t, username: String.t, organized_events: list(), groups: list(), group_request: list(), user: User.t, field: ActorTypeEnum.t}
schema "actors" do
field :url, :string
field :outbox_url, :string
field :inbox_url, :string
field :following_url, :string
field :followers_url, :string
field :shared_inbox_url, :string
field :type, Eventos.Actors.ActorTypeEnum, default: :Person
field :name, :string
field :domain, :string
field :summary, :string
field :preferred_username, :string
field :keys, :string
field :manually_approves_followers, :boolean, default: false
field :suspended, :boolean, default: false
field :avatar_url, :string
field :banner_url, :string
many_to_many :followers, Actor, join_through: Follower
has_many :organized_events, Event, [foreign_key: :organizer_actor_id]
many_to_many :memberships, Actor, join_through: Member
belongs_to :user, User
field(:url, :string)
field(:outbox_url, :string)
field(:inbox_url, :string)
field(:following_url, :string)
field(:followers_url, :string)
field(:shared_inbox_url, :string)
field(:type, Eventos.Actors.ActorTypeEnum, default: :Person)
field(:name, :string)
field(:domain, :string)
field(:summary, :string)
field(:preferred_username, :string)
field(:keys, :string)
field(:manually_approves_followers, :boolean, default: false)
field(:suspended, :boolean, default: false)
field(:avatar_url, :string)
field(:banner_url, :string)
many_to_many(:followers, Actor, join_through: Follower)
has_many(:organized_events, Event, foreign_key: :organizer_actor_id)
many_to_many(:memberships, Actor, join_through: Member)
belongs_to(:user, User)
timestamps()
end
@ -76,7 +87,25 @@ defmodule Eventos.Actors.Actor do
@doc false
def changeset(%Actor{} = actor, attrs) do
actor
|> Ecto.Changeset.cast(attrs, [:url, :outbox_url, :inbox_url, :shared_inbox_url, :following_url, :followers_url, :type, :name, :domain, :summary, :preferred_username, :keys, :manually_approves_followers, :suspended, :avatar_url, :banner_url, :user_id])
|> Ecto.Changeset.cast(attrs, [
:url,
:outbox_url,
:inbox_url,
:shared_inbox_url,
:following_url,
:followers_url,
:type,
:name,
:domain,
:summary,
:preferred_username,
:keys,
:manually_approves_followers,
:suspended,
:avatar_url,
:banner_url,
:user_id
])
|> put_change(:url, "#{EventosWeb.Endpoint.url()}/@#{attrs["prefered_username"]}")
|> validate_required([:preferred_username, :keys, :suspended, :url])
|> unique_constraint(:prefered_username, name: :actors_preferred_username_domain_index)
@ -84,7 +113,19 @@ defmodule Eventos.Actors.Actor do
def registration_changeset(%Actor{} = actor, attrs) do
actor
|> Ecto.Changeset.cast(attrs, [:preferred_username, :domain, :name, :summary, :keys, :keys, :suspended, :url, :type, :avatar_url, :user_id])
|> Ecto.Changeset.cast(attrs, [
:preferred_username,
:domain,
:name,
:summary,
:keys,
:keys,
:suspended,
:url,
:type,
:avatar_url,
:user_id
])
|> unique_constraint(:preferred_username, name: :actors_preferred_username_domain_index)
|> put_change(:url, "#{EventosWeb.Endpoint.url()}/@#{attrs["prefered_username"]}")
|> validate_required([:preferred_username, :keys, :suspended, :url, :type])
@ -94,27 +135,70 @@ defmodule Eventos.Actors.Actor do
def remote_actor_creation(params) do
changes =
%Actor{}
|> Ecto.Changeset.cast(params, [:url, :outbox_url, :inbox_url, :shared_inbox_url, :following_url, :followers_url, :type, :name, :domain, :summary, :preferred_username, :keys, :manually_approves_followers, :avatar_url, :banner_url])
|> validate_required([:url, :outbox_url, :inbox_url, :type, :name, :domain, :preferred_username, :keys])
|> Ecto.Changeset.cast(params, [
:url,
:outbox_url,
:inbox_url,
:shared_inbox_url,
:following_url,
:followers_url,
:type,
:name,
:domain,
:summary,
:preferred_username,
:keys,
:manually_approves_followers,
:avatar_url,
:banner_url
])
|> validate_required([
:url,
:outbox_url,
:inbox_url,
:type,
:name,
:domain,
:preferred_username,
:keys
])
|> unique_constraint(:preferred_username, name: :actors_preferred_username_domain_index)
|> validate_length(:summary, max: 5000)
|> validate_length(:preferred_username, max: 100)
|> put_change(:local, false)
Logger.debug("Remote actor creation")
Logger.debug(inspect changes)
Logger.debug(inspect(changes))
changes
end
def group_creation(%Actor{} = actor, params) do
actor
|> Ecto.Changeset.cast(params, [:url, :outbox_url, :inbox_url, :shared_inbox_url, :type, :name, :domain, :summary, :preferred_username, :avatar_url, :banner_url])
|> put_change(:outbox_url, "#{EventosWeb.Endpoint.url()}/@#{params["prefered_username"]}/outbox")
|> put_change(:inbox_url, "#{EventosWeb.Endpoint.url()}/@#{params["prefered_username"]}/inbox")
|> Ecto.Changeset.cast(params, [
:url,
:outbox_url,
:inbox_url,
:shared_inbox_url,
:type,
:name,
:domain,
:summary,
:preferred_username,
:avatar_url,
:banner_url
])
|> put_change(
:outbox_url,
"#{EventosWeb.Endpoint.url()}/@#{params["prefered_username"]}/outbox"
)
|> put_change(
:inbox_url,
"#{EventosWeb.Endpoint.url()}/@#{params["prefered_username"]}/inbox"
)
|> put_change(:shared_inbox_url, "#{EventosWeb.Endpoint.url()}/inbox")
|> put_change(:url, "#{EventosWeb.Endpoint.url()}/@#{params["prefered_username"]}")
|> put_change(:domain, nil)
|> put_change(:type, "Group")
|> put_change(:type, :Group)
|> validate_required([:url, :outbox_url, :inbox_url, :type, :name, :preferred_username])
|> validate_length(:summary, max: 5000)
|> validate_length(:preferred_username, max: 100)
@ -128,24 +212,26 @@ defmodule Eventos.Actors.Actor do
case ActivityPub.make_actor_from_url(url) do
{:ok, user} ->
user
_ -> {:error, "Could not fetch by AP id"}
_ ->
{:error, "Could not fetch by AP id"}
end
end
end
#@spec get_public_key_for_url(Actor.t) :: {:ok, String.t}
# @spec get_public_key_for_url(Actor.t) :: {:ok, String.t}
def get_public_key_for_url(url) do
with %Actor{} = actor <- get_or_fetch_by_url(url) do
actor
|> get_keys_for_actor
|> Eventos.Service.ActivityPub.Utils.pem_to_public_key
|> Eventos.Service.ActivityPub.Utils.pem_to_public_key()
else
_ -> :error
end
end
@deprecated "Use get_keys_for_actor/1 instead"
#@spec get_public_key_for_actor(Actor.t) :: {:ok, String.t}
# @spec get_public_key_for_actor(Actor.t) :: {:ok, String.t}
def get_public_key_for_actor(%Actor{} = actor) do
{:ok, actor.keys}
end
@ -158,24 +244,30 @@ defmodule Eventos.Actors.Actor do
end
@deprecated "Use get_keys_for_actor/1 instead"
#@spec get_private_key_for_actor(Actor.t) :: {:ok, String.t}
# @spec get_private_key_for_actor(Actor.t) :: {:ok, String.t}
def get_private_key_for_actor(%Actor{} = actor) do
actor.keys
end
def get_followers(%Actor{id: actor_id} = actor) do
Repo.all(
from a in Actor,
join: f in Follower, on: a.id == f.actor_id,
where: f.target_actor_id == ^actor_id
from(
a in Actor,
join: f in Follower,
on: a.id == f.actor_id,
where: f.target_actor_id == ^actor_id
)
)
end
def get_followings(%Actor{id: actor_id} = actor) do
Repo.all(
from a in Actor,
join: f in Follower, on: a.id == f.target_actor_id,
where: f.actor_id == ^actor_id
from(
a in Actor,
join: f in Follower,
on: a.id == f.target_actor_id,
where: f.actor_id == ^actor_id
)
)
end
end

View File

@ -130,16 +130,18 @@ defmodule Eventos.Actors do
List the groups
"""
def list_groups do
Repo.all(from a in Actor, where: a.type == "Group")
Repo.all(from(a in Actor, where: a.type == "Group"))
end
def get_group_by_name(name) do
actor = case String.split(name, "@") do
[name] ->
Repo.get_by(Actor, preferred_username: name, type: :Group)
[name, domain] ->
Repo.get_by(Actor, preferred_username: name, domain: domain, type: :Group)
end
actor =
case String.split(name, "@") do
[name] ->
Repo.get_by(Actor, preferred_username: name, type: :Group)
[name, domain] ->
Repo.get_by(Actor, preferred_username: name, domain: domain, type: :Group)
end
end
@doc """
@ -185,22 +187,36 @@ defmodule Eventos.Actors do
def insert_or_update_actor(data) do
cs = Actor.remote_actor_creation(data)
Repo.insert(cs, on_conflict: [set: [keys: data.keys, avatar_url: data.avatar_url, banner_url: data.banner_url, name: data.name]], conflict_target: [:preferred_username, :domain])
Repo.insert(
cs,
on_conflict: [
set: [
keys: data.keys,
avatar_url: data.avatar_url,
banner_url: data.banner_url,
name: data.name
]
],
conflict_target: [:preferred_username, :domain]
)
end
# def increase_event_count(%Actor{} = actor) do
# event_count = (actor.info["event_count"] || 0) + 1
# new_info = Map.put(actor.info, "note_count", note_count)
#
# cs = info_changeset(actor, %{info: new_info})
#
# update_and_set_cache(cs)
# end
# def increase_event_count(%Actor{} = actor) do
# event_count = (actor.info["event_count"] || 0) + 1
# new_info = Map.put(actor.info, "note_count", note_count)
#
# cs = info_changeset(actor, %{info: new_info})
#
# update_and_set_cache(cs)
# end
def count_users() do
Repo.one(
from u in User,
select: count(u.id)
from(
u in User,
select: count(u.id)
)
)
end
@ -230,28 +246,35 @@ defmodule Eventos.Actors do
end
def get_actor_by_name(name) do
actor = case String.split(name, "@") do
[name] ->
Repo.get_by(Actor, preferred_username: name)
[name, domain] ->
Repo.get_by(Actor, preferred_username: name, domain: domain)
end
actor =
case String.split(name, "@") do
[name] ->
Repo.get_by(Actor, preferred_username: name)
[name, domain] ->
Repo.get_by(Actor, preferred_username: name, domain: domain)
end
end
def get_local_actor_by_name(name) do
Repo.one from a in Actor, where: a.preferred_username == ^name and is_nil(a.domain)
Repo.one(from(a in Actor, where: a.preferred_username == ^name and is_nil(a.domain)))
end
def get_local_actor_by_name_with_everything(name) do
actor = Repo.one from a in Actor, where: a.preferred_username == ^name and is_nil(a.domain)
actor = Repo.one(from(a in Actor, where: a.preferred_username == ^name and is_nil(a.domain)))
Repo.preload(actor, :organized_events)
end
def get_actor_by_name_with_everything(name) do
actor = case String.split(name, "@") do
[name] -> Repo.one from a in Actor, where: a.preferred_username == ^name and is_nil(a.domain)
[name, domain] -> Repo.one from a in Actor, where: a.preferred_username == ^name and a.domain == ^domain
end
actor =
case String.split(name, "@") do
[name] ->
Repo.one(from(a in Actor, where: a.preferred_username == ^name and is_nil(a.domain)))
[name, domain] ->
Repo.one(from(a in Actor, where: a.preferred_username == ^name and a.domain == ^domain))
end
Repo.preload(actor, :organized_events)
end
@ -265,7 +288,8 @@ defmodule Eventos.Actors do
{:ok, actor} ->
actor
_ -> {:error, "Could not fetch by AP id"}
_ ->
{:error, "Could not fetch by AP id"}
end
end
end
@ -274,7 +298,16 @@ defmodule Eventos.Actors do
Find local users by it's username
"""
def find_local_by_username(username) do
actors = Repo.all from a in Actor, where: (ilike(a.preferred_username, ^like_sanitize(username)) or ilike(a.name, ^like_sanitize(username))) and is_nil(a.domain)
actors =
Repo.all(
from(
a in Actor,
where:
(ilike(a.preferred_username, ^like_sanitize(username)) or
ilike(a.name, ^like_sanitize(username))) and is_nil(a.domain)
)
)
Repo.preload(actors, :organized_events)
end
@ -282,7 +315,14 @@ defmodule Eventos.Actors do
Find actors by their name or displayed name
"""
def find_actors_by_username(username) do
Repo.all from a in Actor, where: ilike(a.preferred_username, ^like_sanitize(username)) or ilike(a.name, ^like_sanitize(username))
Repo.all(
from(
a in Actor,
where:
ilike(a.preferred_username, ^like_sanitize(username)) or
ilike(a.name, ^like_sanitize(username))
)
)
end
@doc """
@ -294,17 +334,26 @@ defmodule Eventos.Actors do
@email_regex ~r/^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/
def search(name) do
case find_actors_by_username(name) do # find already saved accounts
# find already saved accounts
case find_actors_by_username(name) do
[] ->
with true <- Regex.match?(@email_regex, name), # no accounts found, let's test if it's an username@domain.tld
{:ok, actor} <- ActivityPub.find_or_make_actor_from_nickname(name) do # creating the actor in that case
# no accounts found, let's test if it's an username@domain.tld
with true <- Regex.match?(@email_regex, name),
# creating the actor in that case
{:ok, actor} <- ActivityPub.find_or_make_actor_from_nickname(name) do
{:ok, [actor]}
else
false -> {:ok, []}
{:error, err} -> {:error, err} # error fingering the actor
false ->
{:ok, []}
# error fingering the actor
{:error, err} ->
{:error, err}
end
actors = [_|_] ->
{:ok, actors} # actors already saved found !
actors = [_ | _] ->
# actors already saved found !
{:ok, actors}
end
end
@ -315,6 +364,7 @@ defmodule Eventos.Actors do
case Repo.preload(Repo.get_by(User, email: email), :actors) do
nil ->
{:error, nil}
user ->
{:ok, user}
end
@ -329,6 +379,7 @@ defmodule Eventos.Actors do
true ->
# Yes, create and return the token
EventosWeb.Guardian.encode_and_sign(user)
_ ->
# No, return an error
{:error, :unauthorized}
@ -346,25 +397,29 @@ defmodule Eventos.Actors do
import Exgravatar
avatar_url = gravatar_url(email, default: "404")
avatar = case HTTPoison.get(avatar_url) do
{:ok, %HTTPoison.Response{status_code: 200}} ->
avatar_url
_ ->
nil
end
actor = Eventos.Actors.Actor.registration_changeset(%Eventos.Actors.Actor{}, %{
preferred_username: username,
domain: nil,
keys: pem,
avatar_url: avatar,
})
avatar =
case HTTPoison.get(avatar_url) do
{:ok, %HTTPoison.Response{status_code: 200}} ->
avatar_url
user = Eventos.Actors.User.registration_changeset(%Eventos.Actors.User{}, %{
email: email,
password: password
})
_ ->
nil
end
actor =
Eventos.Actors.Actor.registration_changeset(%Eventos.Actors.Actor{}, %{
preferred_username: username,
domain: nil,
keys: pem,
avatar_url: avatar
})
user =
Eventos.Actors.User.registration_changeset(%Eventos.Actors.User{}, %{
email: email,
password: password
})
actor_with_user = Ecto.Changeset.put_assoc(actor, :user, user)
@ -372,8 +427,8 @@ defmodule Eventos.Actors do
Eventos.Repo.insert!(actor_with_user)
find_by_email(email)
rescue
e in Ecto.InvalidChangesetError ->
{:error, e.changeset}
e in Ecto.InvalidChangesetError ->
{:error, e.changeset}
end
end
@ -382,13 +437,14 @@ defmodule Eventos.Actors do
entry = :public_key.pem_entry_encode(:RSAPrivateKey, key)
pem = [entry] |> :public_key.pem_encode() |> String.trim_trailing()
actor = Eventos.Actors.Actor.registration_changeset(%Eventos.Actors.Actor{}, %{
preferred_username: name,
domain: nil,
keys: pem,
summary: summary,
type: :Service
})
actor =
Eventos.Actors.Actor.registration_changeset(%Eventos.Actors.Actor{}, %{
preferred_username: name,
domain: nil,
keys: pem,
summary: summary,
type: :Service
})
try do
Eventos.Repo.insert!(actor)
@ -398,7 +454,6 @@ defmodule Eventos.Actors do
end
end
@doc """
Creates a user.
@ -563,21 +618,24 @@ defmodule Eventos.Actors do
def groups_for_actor(%Actor{id: id} = _actor) do
Repo.all(
from m in Member,
where: m.actor_id == ^id,
preload: [:parent]
from(
m in Member,
where: m.actor_id == ^id,
preload: [:parent]
)
)
end
def members_for_group(%Actor{type: :Group, id: id} = _group) do
Repo.all(
from m in Member,
where: m.parent_id == ^id,
preload: [:parent, :actor]
from(
m in Member,
where: m.parent_id == ^id,
preload: [:parent, :actor]
)
)
end
alias Eventos.Actors.Bot
@doc """
@ -609,7 +667,7 @@ defmodule Eventos.Actors do
"""
def get_bot!(id), do: Repo.get!(Bot, id)
@spec get_bot_by_actor(Actor.t) :: Bot.t
@spec get_bot_by_actor(Actor.t()) :: Bot.t()
def get_bot_by_actor(%Actor{} = actor) do
Repo.get_by!(Bot, actor_id: actor.id)
end

View File

@ -6,12 +6,11 @@ defmodule Eventos.Actors.Bot do
import Ecto.Changeset
alias Eventos.Actors.{Actor, User, Bot}
schema "bots" do
field :source, :string
field :type, :string, default: :ics
belongs_to :actor, Actor
belongs_to :user, User
field(:source, :string)
field(:type, :string, default: :ics)
belongs_to(:actor, Actor)
belongs_to(:user, User)
timestamps()
end

View File

@ -7,12 +7,11 @@ defmodule Eventos.Actors.Follower do
alias Eventos.Actors.Follower
alias Eventos.Actors.Actor
schema "followers" do
field :approved, :boolean, default: false
field :score, :integer, default: 1000
belongs_to :target_actor, Actor
belongs_to :actor, Actor
field(:approved, :boolean, default: false)
field(:score, :integer, default: 1000)
belongs_to(:target_actor, Actor)
belongs_to(:actor, Actor)
timestamps()
end

View File

@ -9,10 +9,11 @@ defmodule Eventos.Actors.Member do
@primary_key false
schema "members" do
field :approved, :boolean, default: true
field :role, :integer, default: 0 # 0 : Member, 1 : Moderator, 2 : Admin
belongs_to :parent, Actor
belongs_to :actor, Actor
field(:approved, :boolean, default: true)
# 0 : Member, 1 : Moderator, 2 : Admin
field(:role, :integer, default: 0)
belongs_to(:parent, Actor)
belongs_to(:actor, Actor)
timestamps()
end

View File

@ -9,7 +9,12 @@ defmodule Eventos.Actors.Service.Activation do
@doc false
def check_confirmation_token(token) when is_binary(token) do
with %User{} = user <- Repo.get_by(User, confirmation_token: token),
{:ok, %User{} = user} <- Actors.update_user(user, %{"confirmed_at" => DateTime.utc_now(), "confirmation_sent_at" => nil, "confirmation_token" => nil}) do
{:ok, %User{} = user} <-
Actors.update_user(user, %{
"confirmed_at" => DateTime.utc_now(),
"confirmation_sent_at" => nil,
"confirmation_token" => nil
}) do
{:ok, Repo.preload(user, :actors)}
else
_err ->

View File

@ -9,10 +9,16 @@ defmodule Eventos.Actors.Service.ResetPassword do
@doc """
Check that the provided token is correct and update provided password
"""
@spec check_reset_password_token(String.t, String.t) :: tuple
@spec check_reset_password_token(String.t(), String.t()) :: tuple
def check_reset_password_token(password, token) do
with %User{} = user <- Repo.get_by(User, reset_password_token: token) do
Repo.update(User.password_reset_changeset(user, %{"password" => password, "reset_password_sent_at" => nil, "reset_password_token" => nil}))
Repo.update(
User.password_reset_changeset(user, %{
"password" => password,
"reset_password_sent_at" => nil,
"reset_password_token" => nil
})
)
else
_err ->
{:error, :invalid_token}
@ -22,38 +28,48 @@ defmodule Eventos.Actors.Service.ResetPassword do
@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
@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),
{:ok, %User{} = user_updated} <- Repo.update(User.send_password_reset_changeset(user, %{"reset_password_token" => random_string(30), "reset_password_sent_at" => DateTime.utc_now()})) do
mail = user_updated
|> UserEmail.reset_password_email(locale)
|> Mailer.deliver_later()
{:ok, %User{} = user_updated} <-
Repo.update(
User.send_password_reset_changeset(user, %{
"reset_password_token" => random_string(30),
"reset_password_sent_at" => DateTime.utc_now()
})
) do
mail =
user_updated
|> UserEmail.reset_password_email(locale)
|> Mailer.deliver_later()
{:ok, mail}
else
{:error, reason} -> {:error, reason}
end
end
@spec random_string(integer) :: String.t
@spec random_string(integer) :: String.t()
defp random_string(length) do
length
|> :crypto.strong_rand_bytes()
|> Base.url_encode64
|> Base.url_encode64()
end
@spec we_can_send_email(User.t) :: boolean
@spec we_can_send_email(User.t()) :: boolean
defp we_can_send_email(%User{} = user) do
case user.reset_password_sent_at do
nil ->
:ok
_ ->
case Timex.before?(Timex.shift(user.reset_password_sent_at, hours: 1), DateTime.utc_now()) do
true ->
:ok
false ->
{:error, :email_too_soon}
end
end
end
end
end

View File

@ -7,16 +7,16 @@ defmodule Eventos.Actors.User do
alias Eventos.Actors.{Actor, User}
schema "users" do
field :email, :string
field :password_hash, :string
field :password, :string, virtual: true
field :role, :integer, default: 0
has_many :actors, Actor
field :confirmed_at, :utc_datetime
field :confirmation_sent_at, :utc_datetime
field :confirmation_token, :string
field :reset_password_sent_at, :utc_datetime
field :reset_password_token, :string
field(:email, :string)
field(:password_hash, :string)
field(:password, :string, virtual: true)
field(:role, :integer, default: 0)
has_many(:actors, Actor)
field(:confirmed_at, :utc_datetime)
field(:confirmation_sent_at, :utc_datetime)
field(:confirmation_token, :string)
field(:reset_password_sent_at, :utc_datetime)
field(:reset_password_token, :string)
timestamps()
end
@ -24,11 +24,25 @@ defmodule Eventos.Actors.User do
@doc false
def changeset(%User{} = user, attrs) do
user
|> cast(attrs, [:email, :role, :password_hash, :confirmed_at, :confirmation_sent_at, :confirmation_token, :reset_password_sent_at, :reset_password_token])
|> cast(attrs, [
:email,
:role,
:password_hash,
:confirmed_at,
:confirmation_sent_at,
:confirmation_token,
:reset_password_sent_at,
:reset_password_token
])
|> validate_required([:email])
|> unique_constraint(:email, [message: "registration.error.email_already_used"])
|> unique_constraint(:email, message: "registration.error.email_already_used")
|> validate_format(:email, ~r/@/)
|> validate_length(:password, min: 6, max: 100, message: "registration.error.password_too_short")
|> validate_length(
:password,
min: 6,
max: 100,
message: "registration.error.password_too_short"
)
end
def registration_changeset(struct, params) do
@ -36,10 +50,18 @@ defmodule Eventos.Actors.User do
|> changeset(params)
|> cast(params, ~w(password)a, [])
|> validate_required([:email, :password])
|> validate_length(:password, min: 6, max: 100, message: "registration.error.password_too_short")
|> validate_length(
:password,
min: 6,
max: 100,
message: "registration.error.password_too_short"
)
|> hash_password()
|> save_confirmation_token()
|> unique_constraint(:confirmation_token, [message: "regisration.error.confirmation_token_already_in_use"])
|> unique_constraint(
:confirmation_token,
message: "regisration.error.confirmation_token_already_in_use"
)
end
def send_password_reset_changeset(%User{} = user, attrs) do
@ -50,16 +72,21 @@ defmodule Eventos.Actors.User do
def password_reset_changeset(%User{} = user, attrs) do
user
|> cast(attrs, [:password, :reset_password_token, :reset_password_sent_at])
|> validate_length(:password, min: 6, max: 100, message: "registration.error.password_too_short")
|> validate_length(
:password,
min: 6,
max: 100,
message: "registration.error.password_too_short"
)
|> hash_password()
end
defp save_confirmation_token(changeset) do
case changeset do
%Ecto.Changeset{valid?: true,
changes: %{email: _email}} ->
changeset = put_change(changeset, :confirmation_token, random_string(30))
put_change(changeset, :confirmation_sent_at, DateTime.utc_now())
%Ecto.Changeset{valid?: true, changes: %{email: _email}} ->
changeset = put_change(changeset, :confirmation_token, random_string(30))
put_change(changeset, :confirmation_sent_at, DateTime.utc_now())
_ ->
changeset
end
@ -68,7 +95,7 @@ defmodule Eventos.Actors.User do
defp random_string(length) do
length
|> :crypto.strong_rand_bytes()
|> Base.url_encode64
|> Base.url_encode64()
end
@doc """
@ -76,11 +103,13 @@ defmodule Eventos.Actors.User do
"""
defp hash_password(changeset) do
case changeset do
%Ecto.Changeset{valid?: true,
changes: %{password: password}} ->
put_change(changeset,
%Ecto.Changeset{valid?: true, changes: %{password: password}} ->
put_change(
changeset,
:password_hash,
Comeonin.Argon2.hashpwsalt(password))
Comeonin.Argon2.hashpwsalt(password)
)
_ ->
changeset
end

View File

@ -8,16 +8,16 @@ defmodule Eventos.Addresses.Address do
alias Eventos.Groups.Group
schema "addresses" do
field :addressCountry, :string
field :addressLocality, :string
field :addressRegion, :string
field :description, :string
field :floor, :string
field :geom, Geo.Geometry
field :postalCode, :string
field :streetAddress, :string
has_one :event, Event
has_one :group, Group
field(:addressCountry, :string)
field(:addressLocality, :string)
field(:addressRegion, :string)
field(:description, :string)
field(:floor, :string)
field(:geom, Geo.Geometry)
field(:postalCode, :string)
field(:streetAddress, :string)
has_one(:event, Event)
has_one(:group, Group)
timestamps()
end
@ -25,6 +25,15 @@ defmodule Eventos.Addresses.Address do
@doc false
def changeset(%Address{} = address, attrs) do
address
|> cast(attrs, [:description, :floor, :geom, :addressCountry, :addressLocality, :addressRegion, :postalCode, :streetAddress])
|> cast(attrs, [
:description,
:floor,
:geom,
:addressCountry,
:addressLocality,
:addressRegion,
:postalCode,
:streetAddress
])
end
end

View File

@ -116,7 +116,7 @@ defmodule Eventos.Addresses do
String.to_existing_atom(type_input)
rescue
e in ArgumentError ->
Logger.error("#{type_input} is not an existing atom : #{inspect e}")
Logger.error("#{type_input} is not an existing atom : #{inspect(e)}")
nil
end
else

View File

@ -18,7 +18,7 @@ defmodule Eventos.Application do
# Start your own worker by calling: Eventos.Worker.start_link(arg1, arg2, arg3)
# worker(Eventos.Worker, [arg1, arg2, arg3]),
worker(Guardian.DB.Token.SweeperServer, []),
worker(Eventos.Service.Federator, []),
worker(Eventos.Service.Federator, [])
]
# See https://hexdocs.pm/elixir/Supervisor.html

View File

@ -12,9 +12,12 @@ defmodule Eventos.Email.User do
def confirmation_email(%User{} = user, locale \\ "en") do
Gettext.put_locale(locale)
instance_url = get_config(:instance)
base_email()
|> to(user.email)
|> subject(gettext "Peakweaver: Confirmation instructions for %{instance}", instance: instance_url)
|> subject(
gettext("Peakweaver: Confirmation instructions for %{instance}", instance: instance_url)
)
|> put_header("Reply-To", get_config(:reply_to))
|> assign(:token, user.confirmation_token)
|> assign(:instance, instance_url)
@ -24,9 +27,15 @@ defmodule Eventos.Email.User do
def reset_password_email(%User{} = user, locale \\ "en") do
Gettext.put_locale(locale)
instance_url = get_config(:instance)
base_email()
|> to(user.email)
|> subject(gettext "Peakweaver: Reset your password on %{instance} instructions", instance: instance_url)
|> subject(
gettext(
"Peakweaver: Reset your password on %{instance} instructions",
instance: instance_url
)
)
|> put_header("Reply-To", get_config(:reply_to))
|> assign(:token, user.reset_password_token)
|> assign(:instance, instance_url)

View File

@ -6,11 +6,10 @@ defmodule Eventos.Events.Category do
import Ecto.Changeset
alias Eventos.Events.Category
schema "categories" do
field :description, :string
field :picture, :string
field :title, :string, null: false
field(:description, :string)
field(:picture, :string)
field(:title, :string, null: false)
timestamps()
end

View File

@ -11,15 +11,15 @@ defmodule Eventos.Events.Comment do
alias Eventos.Actors.Comment
schema "comments" do
field :text, :string
field :url, :string
field :local, :boolean, default: true
field :uuid, Ecto.UUID
belongs_to :actor, Actor, [foreign_key: :actor_id]
belongs_to :attributed_to, Actor, [foreign_key: :attributed_to_id]
belongs_to :event, Event, [foreign_key: :event_id]
belongs_to :in_reply_to_comment, Comment, [foreign_key: :in_reply_to_comment_id]
belongs_to :origin_comment, Comment, [foreign_key: :origin_comment_id]
field(:text, :string)
field(:url, :string)
field(:local, :boolean, default: true)
field(:uuid, Ecto.UUID)
belongs_to(:actor, Actor, foreign_key: :actor_id)
belongs_to(:attributed_to, Actor, foreign_key: :attributed_to_id)
belongs_to(:event, Event, foreign_key: :event_id)
belongs_to(:in_reply_to_comment, Comment, foreign_key: :in_reply_to_comment_id)
belongs_to(:origin_comment, Comment, foreign_key: :origin_comment_id)
timestamps()
end
@ -27,6 +27,7 @@ defmodule Eventos.Events.Comment do
@doc false
def changeset(comment, attrs) do
uuid = Ecto.UUID.generate()
comment
|> cast(attrs, [:url, :text, :actor_id, :event_id, :in_reply_to_comment_id, :attributed_to_id])
|> validate_required([:text, :actor_id])

View File

@ -1,5 +1,5 @@
import EctoEnum
defenum AddressTypeEnum, :address_type, [:physical, :url, :phone, :other]
defenum(AddressTypeEnum, :address_type, [:physical, :url, :phone, :other])
defmodule Eventos.Events.Event do
@moduledoc """
@ -12,30 +12,30 @@ defmodule Eventos.Events.Event do
alias Eventos.Addresses.Address
schema "events" do
field :url, :string
field :local, :boolean, default: true
field :begins_on, Timex.Ecto.DateTimeWithTimezone
field :description, :string
field :ends_on, Timex.Ecto.DateTimeWithTimezone
field :title, :string
field :state, :integer, default: 0
field :status, :integer, default: 0
field :public, :boolean, default: true
field :thumbnail, :string
field :large_image, :string
field :publish_at, Timex.Ecto.DateTimeWithTimezone
field :uuid, Ecto.UUID, default: Ecto.UUID.generate()
field :address_type, AddressTypeEnum, default: :physical
field :online_address, :string
field :phone, :string
belongs_to :organizer_actor, Actor, [foreign_key: :organizer_actor_id]
belongs_to :attributed_to, Actor, [foreign_key: :attributed_to_id]
many_to_many :tags, Tag, join_through: "events_tags"
belongs_to :category, Category
many_to_many :participants, Actor, join_through: Participant
has_many :tracks, Track
has_many :sessions, Session
belongs_to :physical_address, Address
field(:url, :string)
field(:local, :boolean, default: true)
field(:begins_on, Timex.Ecto.DateTimeWithTimezone)
field(:description, :string)
field(:ends_on, Timex.Ecto.DateTimeWithTimezone)
field(:title, :string)
field(:state, :integer, default: 0)
field(:status, :integer, default: 0)
field(:public, :boolean, default: true)
field(:thumbnail, :string)
field(:large_image, :string)
field(:publish_at, Timex.Ecto.DateTimeWithTimezone)
field(:uuid, Ecto.UUID, default: Ecto.UUID.generate())
field(:address_type, AddressTypeEnum, default: :physical)
field(:online_address, :string)
field(:phone, :string)
belongs_to(:organizer_actor, Actor, foreign_key: :organizer_actor_id)
belongs_to(:attributed_to, Actor, foreign_key: :attributed_to_id)
many_to_many(:tags, Tag, join_through: "events_tags")
belongs_to(:category, Category)
many_to_many(:participants, Actor, join_through: Participant)
has_many(:tracks, Track)
has_many(:sessions, Session)
belongs_to(:physical_address, Address)
timestamps(type: :utc_datetime)
end
@ -45,11 +45,13 @@ defmodule Eventos.Events.Event do
uuid = Ecto.UUID.generate()
# TODO : check what's the use here. Tests ?
actor_url = if Map.has_key?(attrs, :organizer_actor) do
attrs.organizer_actor.preferred_username
else
""
end
actor_url =
if Map.has_key?(attrs, :organizer_actor) do
attrs.organizer_actor.preferred_username
else
""
end