Make register/1 only create an user

Signed-off-by: Thomas Citharel <tcit@tcit.fr>

Credo fix

Signed-off-by: Thomas Citharel <tcit@tcit.fr>

Fix rebase

Signed-off-by: Thomas Citharel <tcit@tcit.fr>
This commit is contained in:
Thomas Citharel 2019-01-25 13:59:58 +01:00
parent 812140d401
commit 0c2931c10b
No known key found for this signature in database
GPG key ID: A061B9DDE0CA0773
12 changed files with 184 additions and 161 deletions

View file

@ -11,7 +11,7 @@ defmodule Mobilizon.Actors do
alias Mobilizon.Actors.{Actor, Bot, Member, Follower, User}
alias Mobilizon.Service.ActivityPub
import Exgravatar
# import Exgravatar
@doc false
def data() do
@ -68,8 +68,14 @@ defmodule Mobilizon.Actors do
where: u.id == ^user.id
)
) do
nil -> user |> get_actors_for_user() |> hd
actor -> actor
nil ->
case user |> get_actors_for_user() do
[] -> nil
actors -> hd(actors)
end
actor ->
actor
end
end
@ -597,56 +603,71 @@ defmodule Mobilizon.Actors do
@doc """
Register user
"""
@spec register(map()) :: {:ok, Actor.t()} | {:error, String.t()}
def register(%{email: email, password: password, username: username}) do
with avatar <- gravatar(email),
user_changeset <-
User.registration_changeset(%User{}, %{
email: email,
password: password,
default_actor: %{
preferred_username: username,
domain: nil,
keys: create_keys(),
avatar_url: avatar
}
}),
{:ok, %User{default_actor: %Actor{} = actor, id: user_id} = user} <-
Mobilizon.Repo.insert(user_changeset),
{:ok, %Actor{} = _actor} <- update_actor(actor, %{user_id: user_id}) do
{:ok, Repo.preload(user, [:actors])}
else
{:error, %Ecto.Changeset{} = changeset} ->
handle_actor_user_changeset(changeset)
@spec register(map()) :: {:ok, User.t()} | {:error, String.t()}
def register(%{email: _email, password: _password} = args) do
with {:ok, %User{} = user} <-
%User{} |> User.registration_changeset(args) |> Mobilizon.Repo.insert() do
{:ok, user}
# else
# {:error, %Ecto.Changeset{} = changeset} ->
# {:error, Ecto.Changeset.traverse_errors(changeset, fn {msg, opts} ->
# Enum.reduce(opts, msg, fn {key, value}, acc ->
# String.replace(acc, "%{#{key}}", to_string(value))
# end)
# end)}
end
end
@spec gravatar(String.t()) :: String.t() | nil
defp gravatar(nil), do: nil
# @spec register(map()) :: {:ok, Actor.t()} | {:error, String.t()}
# def register(%{email: email, password: password, username: username}) do
# with avatar <- gravatar(email),
# user_changeset <-
# User.registration_changeset(%User{}, %{
# email: email,
# password: password,
# default_actor: %{
# preferred_username: username,
# domain: nil,
# keys: create_keys(),
# avatar_url: avatar
# }
# }),
# {:ok, %User{default_actor: %Actor{} = actor, id: user_id} = user} <-
# Mobilizon.Repo.insert(user_changeset),
# {:ok, %Actor{} = _actor} <- update_actor(actor, %{user_id: user_id}) do
# {:ok, Repo.preload(user, [:actors])}
# else
# {:error, %Ecto.Changeset{} = changeset} ->
# handle_actor_user_changeset(changeset)
# end
# end
defp gravatar(email) do
avatar_url = gravatar_url(email, default: "404")
# @spec handle_actor_user_changeset(Ecto.Changeset.t()) :: {:error, String.t()}
# defp handle_actor_user_changeset(changeset) do
# changeset =
# Ecto.Changeset.traverse_errors(changeset, fn
# {msg, _opts} -> msg
# msg -> msg
# end)
case HTTPoison.get(avatar_url) do
{:ok, %HTTPoison.Response{status_code: 200}} ->
avatar_url
# email_msg = Map.get(changeset, :email) || [:empty_email]
# {:error, hd(email_msg)}
# end
_ ->
nil
end
end
# @spec gravatar(String.t()) :: String.t() | nil
# defp gravatar(nil), do: nil
@spec handle_actor_user_changeset(Ecto.Changeset.t()) :: {:error, String.t()}
defp handle_actor_user_changeset(changeset) do
changeset =
Ecto.Changeset.traverse_errors(changeset, fn
{msg, _opts} -> msg
msg -> msg
end)
# defp gravatar(email) do
# avatar_url = gravatar_url(email, default: "404")
email_msg = Map.get(changeset, :email) || [:empty_email]
{:error, hd(email_msg)}
end
# case HTTPoison.get(avatar_url) do
# {:ok, %HTTPoison.Response{status_code: 200}} ->
# avatar_url
# _ ->
# nil
# end
# end
@doc """
Create a new person actor

View file

@ -43,12 +43,10 @@ defmodule MobilizonWeb.Resolvers.User do
@doc """
Register an user :
- create the user
- create the actor
- set the user's default_actor to the newly created actor
- send a validation email to the user
"""
@spec create_user_actor(any(), map(), any()) :: tuple()
def create_user_actor(_parent, args, _resolution) do
@spec create_user(any(), map(), any()) :: tuple()
def create_user(_parent, args, _resolution) do
with {:ok, %User{} = user} <- Actors.register(args) do
Mobilizon.Actors.Service.Activation.send_confirmation_email(user)
{:ok, user}
@ -62,7 +60,7 @@ defmodule MobilizonWeb.Resolvers.User do
with {:check_confirmation_token, {:ok, %User{} = user}} <-
{:check_confirmation_token,
Mobilizon.Actors.Service.Activation.check_confirmation_token(token)},
{:get_actor, %Actor{} = actor} <- {:get_actor, Actors.get_actor_for_user(user)},
{:get_actor, actor} <- {:get_actor, Actors.get_actor_for_user(user)},
{:guardian_encode_and_sign, {:ok, token, _}} <-
{:guardian_encode_and_sign, MobilizonWeb.Guardian.encode_and_sign(user)} do
{:ok, %{token: token, user: user, person: actor}}
@ -70,7 +68,7 @@ defmodule MobilizonWeb.Resolvers.User do
err ->
Logger.info("Unable to validate user with token #{token}")
Logger.debug(inspect(err))
{:error, :validation_failed}
{:error, "Unable to validate user"}
end
end

View file

@ -245,9 +245,8 @@ defmodule MobilizonWeb.Schema do
field :create_user, type: :user do
arg(:email, non_null(:string))
arg(:password, non_null(:string))
arg(:username, non_null(:string))
resolve(&Resolvers.User.create_user_actor/3)
resolve(handle_errors(&Resolvers.User.create_user/3))
end
@desc "Validate an user after registration"
@ -314,18 +313,30 @@ defmodule MobilizonWeb.Schema do
resolve(&Resolvers.Group.create_group/3)
end
@desc "Delete a group"
field :delete_group, :deleted_object do
arg(:group_id, non_null(:integer))
arg(:actor_id, non_null(:integer))
resolve(&Resolvers.Group.delete_group/3)
end
# @desc "Upload a picture"
# field :upload_picture, :picture do
# arg(:file, non_null(:upload))
# resolve(&Resolvers.Upload.upload_picture/3)
# end
end
def handle_errors(fun) do
fn source, args, info ->
case Absinthe.Resolution.call(fun, source, args, info) do
{:error, %Ecto.Changeset{} = changeset} -> format_changeset(changeset)
val -> val
end
end
end
def format_changeset(changeset) do
# {:error, [email: {"has already been taken", []}]}
errors =
changeset.errors
|> Enum.map(fn {_key, {value, context}} ->
[message: "#{value}", details: context]
end)
{:error, errors}
end
end

View file

@ -69,4 +69,42 @@ defmodule MobilizonWeb.Schema.Actors.GroupType do
value(:open, description: "The actor is open to followings")
end
object :group_queries do
@desc "Get all groups"
field :groups, list_of(:group) do
arg(:page, :integer, default_value: 1)
arg(:limit, :integer, default_value: 10)
resolve(&Resolvers.Group.list_groups/3)
end
@desc "Get a group by it's preferred username"
field :group, :group do
arg(:preferred_username, non_null(:string))
resolve(&Resolvers.Group.find_group/3)
end
end
object :group_mutations do
@desc "Create a group"
field :create_group, :group do
arg(:preferred_username, non_null(:string), description: "The name for the group")
arg(:name, :string, description: "The displayed name for the group")
arg(:description, :string, description: "The summary for the group", default_value: "")
arg(:admin_actor_username, :string,
description: "The actor's username which will be the admin (otherwise user's default one)"
)
resolve(&Resolvers.Group.create_group/3)
end
@desc "Delete a group"
field :delete_group, :deleted_object do
arg(:group_id, non_null(:integer))
arg(:actor_id, non_null(:integer))
resolve(&Resolvers.Group.delete_group/3)
end
end
end

View file

@ -13,7 +13,7 @@ defmodule MobilizonWeb.Schema.UserType do
description: "The user's list of profiles (identities)"
)
field(:default_actor, non_null(:person), description: "The user's default actor")
field(:default_actor, :person, description: "The user's default actor")
field(:confirmed_at, :datetime,
description: "The datetime when the user was confirmed/activated"

View file

@ -289,9 +289,9 @@ defmodule Mobilizon.ActorsTest do
describe "users" do
alias Mobilizon.Actors.{User, Actor}
@valid_attrs %{email: "foo@bar.tld", password: "some password", username: "foo"}
@valid_attrs %{email: "foo@bar.tld", password: "some password"}
@update_attrs %{email: "foo@fighters.tld", password: "some updated password"}
@invalid_attrs %{email: nil, password: nil, username: nil}
@invalid_attrs %{email: nil, password: nil}
test "list_users/0 returns all users" do
user = insert(:user)
@ -306,17 +306,20 @@ defmodule Mobilizon.ActorsTest do
# There's no create_user/1, just register/1
test "register/1 with valid data creates a user" do
assert {:ok,
%User{email: email, default_actor: %Actor{preferred_username: username} = actor} =
user} = Actors.register(@valid_attrs)
assert {:ok, %User{email: email} = user} = Actors.register(@valid_attrs)
assert email == @valid_attrs.email
assert username == @valid_attrs.username
assert [actor.id] == Actors.get_actors_for_user(user) |> Enum.map(& &1.id)
end
test "create_user/1 with invalid data returns error changeset" do
assert {:error, "can't be blank"} = Actors.register(@invalid_attrs)
assert {:error,
%Ecto.Changeset{
errors: [
password: {"can't be blank", [validation: :required]},
email: {"can't be blank", [validation: :required]}
],
valid?: false
}} = Actors.register(@invalid_attrs)
end
test "update_user/2 with valid data updates the user" do
@ -345,8 +348,7 @@ defmodule Mobilizon.ActorsTest do
@email "email@domain.tld"
@password "password"
test "authenticate/1 checks the user's password" do
{:ok, %User{} = user} =
Actors.register(%{email: @email, password: @password, username: "yolo"})
{:ok, %User{} = user} = Actors.register(%{email: @email, password: @password})
assert {:ok, _, _} = Actors.authenticate(%{user: user, password: @password})
@ -355,8 +357,7 @@ defmodule Mobilizon.ActorsTest do
end
test "get_user_by_email/1 finds an user by it's email" do
{:ok, %User{email: email} = user} =
Actors.register(%{email: @email, password: @password, username: "yolo"})
{:ok, %User{email: email} = user} = Actors.register(%{email: @email, password: @password})
assert email == @email
{:ok, %User{id: id}} = Actors.get_user_by_email(@email)
@ -365,8 +366,7 @@ defmodule Mobilizon.ActorsTest do
end
test "get_user_by_email/1 finds an activated user by it's email" do
{:ok, %User{} = user} =
Actors.register(%{email: @email, password: @password, username: "yolo"})
{:ok, %User{} = user} = Actors.register(%{email: @email, password: @password})
{:ok, %User{id: id}} = Actors.get_user_by_email(@email, false)
assert id == user.id

View file

@ -1,13 +1,11 @@
defmodule MobilizonWeb.Resolvers.CategoryResolverTest do
use MobilizonWeb.ConnCase
alias Mobilizon.Actors
alias Mobilizon.Actors.{Actor, User}
alias MobilizonWeb.AbsintheHelpers
import Mobilizon.Factory
setup %{conn: conn} do
{:ok, %User{default_actor: %Actor{} = actor} = user} =
Actors.register(%{email: "test@test.tld", password: "testest", username: "test"})
user = insert(:user)
actor = insert(:actor, user: user)
{:ok, conn: conn, actor: actor, user: user}
end

View file

@ -1,14 +1,13 @@
defmodule MobilizonWeb.Resolvers.CommentResolverTest do
use MobilizonWeb.ConnCase
alias Mobilizon.Actors
alias Mobilizon.Actors.{Actor, User}
alias MobilizonWeb.AbsintheHelpers
import Mobilizon.Factory
@comment %{text: "I love this event"}
setup %{conn: conn} do
{:ok, %User{default_actor: %Actor{} = actor} = user} =
Actors.register(%{email: "test@test.tld", password: "testest", username: "test"})
user = insert(:user)
actor = insert(:actor, user: user)
{:ok, conn: conn, actor: actor, user: user}
end

View file

@ -1,7 +1,6 @@
defmodule MobilizonWeb.Resolvers.EventResolverTest do
use MobilizonWeb.ConnCase
alias Mobilizon.{Events, Actors}
alias Mobilizon.Actors.{Actor, User}
alias Mobilizon.Events
alias MobilizonWeb.AbsintheHelpers
import Mobilizon.Factory
@ -14,8 +13,8 @@ defmodule MobilizonWeb.Resolvers.EventResolverTest do
}
setup %{conn: conn} do
{:ok, %User{default_actor: %Actor{} = actor} = user} =
Actors.register(%{email: "test@test.tld", password: "testest", username: "test"})
user = insert(:user)
actor = insert(:actor, user: user, preferred_username: "test")
{:ok, conn: conn, actor: actor, user: user}
end
@ -137,8 +136,6 @@ defmodule MobilizonWeb.Resolvers.EventResolverTest do
|> auth_conn(user)
|> post("/api", AbsintheHelpers.mutation_skeleton(mutation))
require Logger
Logger.error(inspect(json_response(res, 200)))
assert json_response(res, 200)["data"]["createEvent"]["title"] == "come to my event"
end

View file

@ -1,7 +1,5 @@
defmodule MobilizonWeb.Resolvers.GroupResolverTest do
use MobilizonWeb.ConnCase
alias Mobilizon.Actors
alias Mobilizon.Actors.{User, Actor}
alias MobilizonWeb.AbsintheHelpers
import Mobilizon.Factory
require Logger
@ -10,8 +8,8 @@ defmodule MobilizonWeb.Resolvers.GroupResolverTest do
@new_group_params %{groupname: "new group"}
setup %{conn: conn} do
{:ok, %User{default_actor: %Actor{} = actor} = user} =
Actors.register(%{email: "test2@test.tld", password: "testest", username: "test"})
user = insert(:user)
actor = insert(:actor, user: user)
{:ok, conn: conn, actor: actor, user: user}
end

View file

@ -1,15 +1,14 @@
defmodule MobilizonWeb.Resolvers.PersonResolverTest do
use MobilizonWeb.ConnCase
alias Mobilizon.Actors
alias Mobilizon.Actors.{User, Actor}
alias MobilizonWeb.AbsintheHelpers
import Mobilizon.Factory
@valid_actor_params %{email: "test@test.tld", password: "testest", username: "test"}
@non_existent_username "nonexistent"
describe "Person Resolver" do
test "find_person/3 returns a person by it's username", context do
{:ok, %User{default_actor: %Actor{} = actor} = _user} = Actors.register(@valid_actor_params)
user = insert(:user)
actor = insert(:actor, user: user)
query = """
{
@ -45,7 +44,8 @@ defmodule MobilizonWeb.Resolvers.PersonResolverTest do
end
test "get_current_person/3 returns the current logged-in actor", context do
{:ok, %User{default_actor: %Actor{} = actor} = user} = Actors.register(@valid_actor_params)
user = insert(:user)
actor = insert(:actor, user: user)
query = """
{

View file

@ -75,26 +75,21 @@ defmodule MobilizonWeb.Resolvers.UserResolverTest do
describe "Resolver: Create an user & actor" do
@account_creation %{
email: "test@demo.tld",
password: "long password",
username: "test_account"
password: "long password"
}
@account_creation_bad_email %{
email: "y@l@",
password: "long password",
username: "test_account"
password: "long password"
}
test "test create_user_actor/3 creates an user", context do
test "test create_user/3 creates an user", context do
mutation = """
mutation {
createUser(
email: "#{@account_creation.email}",
password: "#{@account_creation.password}",
username: "#{@account_creation.username}"
) {
default_actor {
preferred_username,
},
id,
email
}
}
@ -104,24 +99,18 @@ defmodule MobilizonWeb.Resolvers.UserResolverTest do
context.conn
|> post("/api", AbsintheHelpers.mutation_skeleton(mutation))
assert json_response(res, 200)["data"]["createUser"]["default_actor"]["preferred_username"] ==
@account_creation.username
assert json_response(res, 200)["data"]["createUser"]["email"] == @account_creation.email
end
test "test create_user_actor/3 doesn't create an user with bad email", context do
test "test create_user/3 doesn't create an user with bad email", context do
mutation = """
mutation {
createUser(
email: "#{@account_creation_bad_email.email}",
password: "#{@account_creation.password}",
username: "#{@account_creation.username}"
) {
default_actor {
preferred_username,
},
email,
id,
email
}
}
"""
@ -136,9 +125,9 @@ defmodule MobilizonWeb.Resolvers.UserResolverTest do
end
describe "Resolver: Validate an user" do
@valid_actor_params %{email: "test@test.tld", password: "testest", username: "test"}
@valid_actor_params %{email: "test@test.tld", password: "testest"}
test "test validate_user/3 validates an user", context do
{:ok, %User{default_actor: %Actor{} = _actor} = user} = Actors.register(@valid_actor_params)
{:ok, %User{} = user} = Actors.register(@valid_actor_params)
mutation = """
mutation {
@ -148,9 +137,6 @@ defmodule MobilizonWeb.Resolvers.UserResolverTest do
token,
user {
id,
default_actor {
preferredUsername
}
},
}
}
@ -160,16 +146,11 @@ defmodule MobilizonWeb.Resolvers.UserResolverTest do
context.conn
|> post("/api", AbsintheHelpers.mutation_skeleton(mutation))
assert json_response(res, 200)["data"]["validateUser"]["user"]["default_actor"][
"preferredUsername"
] == @valid_actor_params.username
assert json_response(res, 200)["data"]["validateUser"]["user"]["id"] == to_string(user.id)
end
test "test validate_user/3 with invalid token doesn't validate an user", context do
{:ok, %User{default_actor: %Actor{} = _actor} = _user} =
Actors.register(@valid_actor_params)
insert(:user, confirmation_token: "t0t0")
mutation = """
mutation {
@ -178,10 +159,7 @@ defmodule MobilizonWeb.Resolvers.UserResolverTest do
) {
token,
user {
id,
default_actor {
preferredUsername
}
id
},
}
}
@ -191,14 +169,14 @@ defmodule MobilizonWeb.Resolvers.UserResolverTest do
context.conn
|> post("/api", AbsintheHelpers.mutation_skeleton(mutation))
assert hd(json_response(res, 200)["errors"])["message"] == "validation_failed"
assert hd(json_response(res, 200)["errors"])["message"] == "Unable to validate user"
end
end
describe "Resolver: Resend confirmation emails" do
test "test resend_confirmation_email/3 with valid email resends an validation email",
context do
{:ok, %User{default_actor: %Actor{} = _actor} = user} = Actors.register(@valid_actor_params)
{:ok, %User{} = user} = Actors.register(%{email: "toto@tata.tld", password: "p4ssw0rd"})
mutation = """
mutation {
@ -230,9 +208,6 @@ defmodule MobilizonWeb.Resolvers.UserResolverTest do
test "test resend_confirmation_email/3 with invalid email resends an validation email",
context do
{:ok, %User{default_actor: %Actor{} = _actor} = _user} =
Actors.register(@valid_actor_params)
mutation = """
mutation {
resendConfirmationEmail(
@ -289,7 +264,7 @@ defmodule MobilizonWeb.Resolvers.UserResolverTest do
describe "Resolver: Reset user's password" do
test "test reset_password/3 with valid email", context do
%User{} = user = insert(:user)
{:ok, %User{} = user} = Actors.register(%{email: "toto@tata.tld", password: "p4ssw0rd"})
%Actor{} = insert(:actor, user: user)
{:ok, _email_sent} = Mobilizon.Actors.Service.ResetPassword.send_password_reset_email(user)
%User{reset_password_token: reset_password_token} = Mobilizon.Actors.get_user!(user.id)
@ -369,7 +344,7 @@ defmodule MobilizonWeb.Resolvers.UserResolverTest do
describe "Resolver: Login an user" do
test "test login_user/3 with valid credentials", context do
{:ok, %User{} = user} = Actors.register(@valid_actor_params)
{:ok, %User{} = user} = Actors.register(%{email: "toto@tata.tld", password: "p4ssw0rd"})
{:ok, %User{} = _user} =
Actors.update_user(user, %{
@ -381,14 +356,12 @@ defmodule MobilizonWeb.Resolvers.UserResolverTest do
mutation = """
mutation {
login(
email: "#{@valid_actor_params.email}",
password: "#{@valid_actor_params.password}",
email: "#{user.email}",
password: "#{user.password}",
) {
token,
user {
default_actor {
preferred_username,
}
id
}
}
}
@ -400,11 +373,10 @@ defmodule MobilizonWeb.Resolvers.UserResolverTest do
assert login = json_response(res, 200)["data"]["login"]
assert Map.has_key?(login, "token") && not is_nil(login["token"])
assert login["user"]["default_actor"]["preferred_username"] == @valid_actor_params.username
end
test "test login_user/3 with invalid password", context do
{:ok, %User{} = user} = Actors.register(@valid_actor_params)
{:ok, %User{} = user} = Actors.register(%{email: "toto@tata.tld", password: "p4ssw0rd"})
{:ok, %User{} = _user} =
Actors.update_user(user, %{
@ -416,7 +388,7 @@ defmodule MobilizonWeb.Resolvers.UserResolverTest do
mutation = """
mutation {
login(
email: "#{@valid_actor_params.email}",
email: "#{user.email}",
password: "bad password",
) {
token,
@ -438,15 +410,6 @@ defmodule MobilizonWeb.Resolvers.UserResolverTest do
end
test "test login_user/3 with invalid email", context do
{:ok, %User{} = user} = Actors.register(@valid_actor_params)
{:ok, %User{} = _user} =
Actors.update_user(user, %{
"confirmed_at" => DateTime.utc_now(),
"confirmation_sent_at" => nil,
"confirmation_token" => nil
})
mutation = """
mutation {
login(
@ -474,15 +437,15 @@ defmodule MobilizonWeb.Resolvers.UserResolverTest do
describe "Resolver: change default actor for user" do
test "test change_default_actor/3 with valid actor", context do
# Prepare user with two actors
assert {:ok, %User{id: user_id, default_actor: %Actor{} = actor} = user} =
Actors.register(@valid_actor_params)
user = insert(:user)
insert(:actor, user: user)
assert {:ok, %User{actors: actors}} = Actors.get_user_with_actors(user_id)
assert {:ok, %User{actors: actors}} = Actors.get_user_with_actors(user.id)
actor_params = @valid_single_actor_params |> Map.put(:user_id, user_id)
actor_params = @valid_single_actor_params |> Map.put(:user_id, user.id)
assert {:ok, %Actor{} = actor2} = Actors.create_actor(actor_params)
assert {:ok, %User{actors: actors}} = Actors.get_user_with_actors(user_id)
assert {:ok, %User{actors: actors}} = Actors.get_user_with_actors(user.id)
assert length(actors) == 2
mutation = """