Merge branch 'change-registration-workflow' into 'master'

Change registration workflow

Closes #63

See merge request framasoft/mobilizon!52
This commit is contained in:
Thomas Citharel 2019-01-30 16:09:56 +01:00
commit 8cbcae1c86
29 changed files with 924 additions and 516 deletions

View file

@ -39,10 +39,34 @@ query {
export const CREATE_PERSON = gql` export const CREATE_PERSON = gql`
mutation CreatePerson($preferredUsername: String!) { mutation CreatePerson($preferredUsername: String!) {
createPerson(preferredUsername: $preferredUsername) { createPerson(
preferredUsername: $preferredUsername,
name: $name,
summary: $summary
) {
preferredUsername, preferredUsername,
name, name,
summary,
avatarUrl avatarUrl
} }
} }
` `;
/**
* This one is used only to register the first account. Prefer CREATE_PERSON when creating another identity
*/
export const REGISTER_PERSON = gql`
mutation ($preferredUsername: String!, $name: String!, $summary: String!, $email: String!) {
registerPerson(
preferredUsername: $preferredUsername,
name: $name,
summary: $summary,
email: $email
) {
preferredUsername,
name,
summary,
avatarUrl,
}
}
`;

View file

@ -1,8 +1,8 @@
import gql from 'graphql-tag'; import gql from 'graphql-tag';
export const CREATE_USER = gql` export const CREATE_USER = gql`
mutation CreateUser($email: String!, $username: String!, $password: String!) { mutation CreateUser($email: String!, $password: String!) {
createUser(email: $email, username: $username, password: $password) { createUser(email: $email, password: $password) {
email, email,
confirmationSentAt confirmationSentAt
} }
@ -15,6 +15,10 @@ mutation ValidateUser($token: String!) {
token, token,
user { user {
id, id,
email,
defaultActor {
id
}
} }
} }
} }
@ -33,4 +37,4 @@ export const UPDATE_CURRENT_USER_CLIENT = gql`
mutation UpdateCurrentUser($id: Int!, $email: String!) { mutation UpdateCurrentUser($id: Int!, $email: String!) {
updateCurrentUser(id: $id, email: $email) @client updateCurrentUser(id: $id, email: $email) @client
} }
` `;

View file

@ -8,17 +8,12 @@ import Location from '@/views/Location.vue';
import CreateEvent from '@/views/Event/Create.vue'; import CreateEvent from '@/views/Event/Create.vue';
import CategoryList from '@/views/Category/List.vue'; import CategoryList from '@/views/Category/List.vue';
import CreateCategory from '@/views/Category/Create.vue'; import CreateCategory from '@/views/Category/Create.vue';
import Register from '@/views/Account/Register.vue';
import Login from '@/views/User/Login.vue';
import Validate from '@/views/User/Validate.vue';
import ResendConfirmation from '@/views/User/ResendConfirmation.vue';
import SendPasswordReset from '@/views/User/SendPasswordReset.vue';
import PasswordReset from '@/views/User/PasswordReset.vue';
import Profile from '@/views/Account/Profile.vue'; import Profile from '@/views/Account/Profile.vue';
import CreateGroup from '@/views/Group/Create.vue'; import CreateGroup from '@/views/Group/Create.vue';
import Group from '@/views/Group/Group.vue'; import Group from '@/views/Group/Group.vue';
import GroupList from '@/views/Group/GroupList.vue'; import GroupList from '@/views/Group/GroupList.vue';
import Identities from '@/views/Account/Identities.vue'; import Identities from '@/views/Account/Identities.vue';
import userRoutes from './user';
Vue.use(Router); Vue.use(Router);
@ -26,6 +21,7 @@ const router = new Router({
mode: 'history', mode: 'history',
base: '/', base: '/',
routes: [ routes: [
...userRoutes,
{ {
path: '/', path: '/',
name: 'Home', name: 'Home',
@ -69,48 +65,6 @@ const router = new Router({
component: CreateCategory, component: CreateCategory,
meta: { requiredAuth: true }, meta: { requiredAuth: true },
}, },
{
path: '/register',
name: 'Register',
component: Register,
props: true,
meta: { requiredAuth: false },
},
{
path: '/resend-instructions',
name: 'ResendConfirmation',
component: ResendConfirmation,
props: true,
meta: { requiresAuth: false },
},
{
path: '/password-reset/send',
name: 'SendPasswordReset',
component: SendPasswordReset,
props: true,
meta: { requiresAuth: false },
},
{
path: '/password-reset/:token',
name: 'PasswordReset',
component: PasswordReset,
meta: { requiresAuth: false },
props: true,
},
{
path: '/validate/:token',
name: 'Validate',
component: Validate,
props: true,
meta: { requiresAuth: false },
},
{
path: '/login',
name: 'Login',
component: Login,
props: true,
meta: { requiredAuth: false },
},
{ {
path: '/identities', path: '/identities',
name: 'Identities', name: 'Identities',

60
js/src/router/user.ts Normal file
View file

@ -0,0 +1,60 @@
import RegisterUser from '@/views/User/Register.vue';
import RegisterProfile from '@/views/Account/Register.vue';
import Login from '@/views/User/Login.vue';
import Validate from '@/views/User/Validate.vue';
import ResendConfirmation from '@/views/User/ResendConfirmation.vue';
import SendPasswordReset from '@/views/User/SendPasswordReset.vue';
import PasswordReset from '@/views/User/PasswordReset.vue';
export default [
{
path: '/register/user',
name: 'Register',
component: RegisterUser,
props: true,
meta: { requiredAuth: false },
},
{
path: '/register/profile',
name: 'RegisterProfile',
component: RegisterProfile,
props: true,
meta: { requiredAuth: false },
},
{
path: '/resend-instructions',
name: 'ResendConfirmation',
component: ResendConfirmation,
props: true,
meta: { requiresAuth: false },
},
{
path: '/password-reset/send',
name: 'SendPasswordReset',
component: SendPasswordReset,
props: true,
meta: { requiresAuth: false },
},
{
path: '/password-reset/:token',
name: 'PasswordReset',
component: PasswordReset,
meta: { requiresAuth: false },
props: true,
},
{
path: '/validate/:token',
name: 'Validate',
component: Validate,
// We can only pass string values through params, therefore
props: (route) => ({ email: route.params.email, userAlreadyActivated: route.params.userAlreadyActivated === 'true'}),
meta: { requiresAuth: false },
},
{
path: '/login',
name: 'Login',
component: Login,
props: true,
meta: { requiredAuth: false },
},
];

View file

@ -2,7 +2,7 @@ export interface IActor {
id: string; id: string;
url: string; url: string;
name: string; name: string;
domain: string; domain: string|null;
summary: string; summary: string;
preferredUsername: string; preferredUsername: string;
suspended: boolean; suspended: boolean;

View file

@ -10,102 +10,63 @@
<section> <section>
<div class="container"> <div class="container">
<div class="columns is-mobile"> <div class="columns is-mobile">
<div class="column">
<div class="content">
<h2 class="subtitle" v-translate>Features</h2>
<ul>
<li v-translate>Create your communities and your events</li>
<li v-translate>Other stuff</li>
</ul>
</div>
<p v-translate>
Learn more on
<a target="_blank" href="https://joinmobilizon.org">joinmobilizon.org</a>
</p>
<hr>
<div class="content">
<h2 class="subtitle" v-translate>About this instance</h2>
<p>
<translate>Your local administrator resumed it's policy:</translate>
</p>
<ul>
<li v-translate>Please be nice to each other</li>
<li v-translate>meditate a bit</li>
</ul>
<p>
<translate>Please read the full rules</translate>
</p>
</div>
</div>
<div class="column"> <div class="column">
<form v-if="!validationSent"> <form v-if="!validationSent">
<div class="columns is-mobile is-centered"> <div class="columns is-mobile is-centered">
<div class="column is-narrow"> <div class="column is-narrow">
<figure class="image is-64x64"> <figure class="image is-64x64">
<transition name="avatar"> <transition name="avatar">
<v-gravatar v-bind="{email: credentials.email}" default-img="mp"></v-gravatar> <v-gravatar v-bind="{email: email}" default-img="mp"></v-gravatar>
</transition> </transition>
</figure> </figure>
</div> </div>
</div> </div>
<b-field label="Email"> <b-field
:label="$gettext('Username')"
:type="errors.preferred_username ? 'is-danger' : null"
:message="errors.preferred_username"
>
<b-field>
<b-input <b-input
aria-required="true" aria-required="true"
required required
type="email" expanded
v-model="credentials.email" v-model="person.preferredUsername"
@blur="showGravatar = true"
@focus="showGravatar = false"
/> />
<p class="control">
<span class="button is-static">@{{ host }}</span>
</p>
</b-field>
</b-field> </b-field>
<b-field label="Username"> <b-field :label="$gettext('Displayed name')">
<b-input aria-required="true" required v-model="credentials.username"/> <b-input v-model="person.name"/>
</b-field> </b-field>
<b-field label="Password"> <b-field :label="$gettext('Description')">
<b-input <b-input type="textarea" v-model="person.summary"/>
aria-required="true"
required
type="password"
password-reveal
minlength="6"
v-model="credentials.password"
/>
</b-field> </b-field>
<b-field grouped> <b-field grouped>
<div class="control"> <div class="control">
<button type="button" class="button is-primary" @click="submit()"> <button type="button" class="button is-primary" @click="submit()">
<translate>Register</translate> <translate>Create my profile</translate>
</button> </button>
</div> </div>
<div class="control">
<router-link
class="button is-text"
:to="{ name: 'ResendConfirmation', params: { email: credentials.email }}"
>
<translate>Didn't receive the instructions ?</translate>
</router-link>
</div>
<div class="control">
<router-link
class="button is-text"
:to="{ name: 'Login', params: { email: credentials.email, password: credentials.password }}"
:disabled="validationSent"
>
<translate>Login</translate>
</router-link>
</div>
</b-field> </b-field>
</form> </form>
<div v-if="validationSent"> <div v-if="validationSent && !userAlreadyActivated">
<b-message title="Success" type="is-success"> <b-message title="Success" type="is-success">
<h2> <h2 class="title">
<translate>A validation email was sent to %{email}</translate> <translate
:translate-params="{ username: person.preferredUsername }"
>Your account is nearly ready, %{username}</translate>
</h2> </h2>
<p>
<translate>A validation email was sent to %{email}</translate>
</p>
<p> <p>
<translate>Before you can login, you need to click on the link inside it to validate your account</translate> <translate>Before you can login, you need to click on the link inside it to validate your account</translate>
</p> </p>
@ -120,8 +81,9 @@
<script lang="ts"> <script lang="ts">
import Gravatar from "vue-gravatar"; import Gravatar from "vue-gravatar";
import { CREATE_USER } from "@/graphql/user";
import { Component, Prop, Vue } from "vue-property-decorator"; import { Component, Prop, Vue } from "vue-property-decorator";
import { IPerson } from "@/types/actor.model";
import { REGISTER_PERSON } from "@/graphql/actor";
import { MOBILIZON_INSTANCE_HOST } from "@/api/_entrypoint"; import { MOBILIZON_INSTANCE_HOST } from "@/api/_entrypoint";
@Component({ @Component({
@ -130,37 +92,47 @@ import { MOBILIZON_INSTANCE_HOST } from "@/api/_entrypoint";
} }
}) })
export default class Register extends Vue { export default class Register extends Vue {
@Prop({ type: String, required: false, default: "" }) email!: string; @Prop({ type: String, required: true }) email!: string;
@Prop({ type: String, required: false, default: "" }) password!: string; @Prop({ type: Boolean, required: false, default: false }) userAlreadyActivated!: boolean;
credentials = { host: string = MOBILIZON_INSTANCE_HOST;
username: "",
email: this.email, person: IPerson = {
password: this.password preferredUsername: "",
} as { username: string; email: string; password: string }; name: "",
errors: string[] = []; summary: "",
id: "",
url: "",
suspended: false,
avatarUrl: "", // TODO : Use Gravatar here
bannerUrl: "",
domain: null,
};
errors: object = {};
validationSent: boolean = false; validationSent: boolean = false;
sendingValidation: boolean = false;
showGravatar: boolean = false; showGravatar: boolean = false;
host() {
return MOBILIZON_INSTANCE_HOST;
}
validEmail() {
return this.credentials.email.includes("@") === true
? "v-gravatar"
: "avatar";
}
async submit() { async submit() {
try { try {
this.validationSent = true; this.sendingValidation = true;
this.errors = {};
await this.$apollo.mutate({ await this.$apollo.mutate({
mutation: CREATE_USER, mutation: REGISTER_PERSON,
variables: this.credentials variables: Object.assign({ email: this.email }, this.person)
}); });
this.validationSent = true;
if (this.userAlreadyActivated) {
this.$router.push({name: "Home"});
}
} catch (error) { } catch (error) {
this.errors = error.graphQLErrors.reduce((acc, error) => {
acc[error.details] = error.message;
return acc;
}, {});
console.error(error); console.error(error);
console.error(this.errors);
} }
} }
} }

View file

@ -0,0 +1,177 @@
<template>
<div>
<section class="hero">
<div class="hero-body">
<h1 class="title">
<translate>Register an account on Mobilizon!</translate>
</h1>
</div>
</section>
<section>
<div class="container">
<div class="columns is-mobile">
<div class="column">
<div class="content">
<h2 class="subtitle" v-translate>Features</h2>
<ul>
<li v-translate>Create your communities and your events</li>
<li v-translate>Other stuff</li>
</ul>
</div>
<p v-translate>
Learn more on
<a target="_blank" href="https://joinmobilizon.org">joinmobilizon.org</a>
</p>
<hr>
<div class="content">
<h2 class="subtitle" v-translate>About this instance</h2>
<p>
<translate>Your local administrator resumed it's policy:</translate>
</p>
<ul>
<li v-translate>Please be nice to each other</li>
<li v-translate>meditate a bit</li>
</ul>
<p>
<translate>Please read the full rules</translate>
</p>
</div>
</div>
<div class="column">
<form @submit="submit">
<b-field
label="Email"
:type="errors.email ? 'is-danger' : null"
:message="errors.email"
>
<b-input
aria-required="true"
required
type="email"
v-model="credentials.email"
@blur="showGravatar = true"
@focus="showGravatar = false"
/>
</b-field>
<b-field
label="Password"
:type="errors.password ? 'is-danger' : null"
:message="errors.password"
>
<b-input
aria-required="true"
required
type="password"
password-reveal
minlength="6"
v-model="credentials.password"
/>
</b-field>
<b-field grouped>
<div class="control">
<button type="button" class="button is-primary" @click="submit()">
<translate>Register</translate>
</button>
</div>
<div class="control">
<router-link
class="button is-text"
:to="{ name: 'ResendConfirmation', params: { email: credentials.email }}"
>
<translate>Didn't receive the instructions ?</translate>
</router-link>
</div>
<div class="control">
<router-link
class="button is-text"
:to="{ name: 'Login', params: { email: credentials.email, password: credentials.password }}"
:disabled="sendingValidation"
>
<translate>Login</translate>
</router-link>
</div>
</b-field>
</form>
<div v-if="errors.length > 0">
<b-message type="is-danger" v-for="error in errors" :key="error">
<translate>{{ error }}</translate>
</b-message>
</div>
</div>
</div>
</div>
</section>
</div>
</template>
<script lang="ts">
import Gravatar from "vue-gravatar";
import { CREATE_USER } from "@/graphql/user";
import { Component, Prop, Vue } from "vue-property-decorator";
@Component({
components: {
"v-gravatar": Gravatar
}
})
export default class Register extends Vue {
@Prop({ type: String, required: false, default: "" }) email!: string;
@Prop({ type: String, required: false, default: "" }) password!: string;
credentials = {
email: this.email,
password: this.password
} as { email: string; password: string };
errors: object = {};
sendingValidation: boolean = false;
validationSent: boolean = false;
showGravatar: boolean = false;
validEmail() {
return this.credentials.email.includes("@") === true
? "v-gravatar"
: "avatar";
}
async submit() {
try {
this.sendingValidation = true;
this.errors = {};
await this.$apollo.mutate({
mutation: CREATE_USER,
variables: this.credentials
});
this.validationSent = true;
this.$router.push({
name: "RegisterProfile",
params: { email: this.credentials.email }
});
} catch (error) {
console.error(error);
this.errors = error.graphQLErrors.reduce((acc, error) => {
acc[error.details] = error.message;
return acc;
}, {});
console.log(this.errors);
}
}
}
</script>
<style lang="scss">
.avatar-enter-active {
transition: opacity 1s ease;
}
.avatar-enter,
.avatar-leave-to {
opacity: 0;
}
.avatar-leave {
display: none;
}
</style>

View file

@ -5,8 +5,8 @@
</h1> </h1>
<div v-else> <div v-else>
<div v-if="failed"> <div v-if="failed">
<b-message title="Error" type="is-danger"> <b-message :title="$gettext('Error while validating account')" type="is-danger">
<translate>Error while validating account</translate> <translate>Either the account is already validated, either the validation token is incorrect.</translate>
</b-message> </b-message>
</div> </div>
<h1 class="title" v-else> <h1 class="title" v-else>
@ -28,21 +28,28 @@ export default class Validate extends Vue {
loading = true; loading = true;
failed = false; failed = false;
created() { async created() {
this.validateAction(); await this.validateAction();
} }
async validateAction() { async validateAction() {
try { try {
const data = await this.$apollo.mutate({ const { data } = await this.$apollo.mutate({
mutation: VALIDATE_USER, mutation: VALIDATE_USER,
variables: { variables: {
token: this.token token: this.token
} }
}); });
this.saveUserData(data.data); this.saveUserData(data);
const user = data.validateUser.user;
console.log(user);
if (user.defaultActor) {
this.$router.push({name: "Home"}); this.$router.push({name: "Home"});
} else { // If the user didn't register any profile yet, let's create one for them
this.$router.push({ name: 'RegisterProfile', params: {email: user.email, userAlreadyActivated: 'true'} });
}
} catch (err) { } catch (err) {
console.error(err); console.error(err);
this.failed = true; this.failed = true;

View file

@ -103,6 +103,8 @@ defmodule Mobilizon.Actors.Actor do
:user_id :user_id
]) ])
|> build_urls() |> build_urls()
# Needed because following constraint can't work for domain null values (local)
|> unique_username_validator()
|> unique_constraint(:preferred_username, name: :actors_preferred_username_domain_type_index) |> unique_constraint(:preferred_username, name: :actors_preferred_username_domain_type_index)
|> unique_constraint(:url, name: :actors_url_index) |> unique_constraint(:url, name: :actors_url_index)
|> validate_required([:preferred_username, :keys, :suspended, :url, :type]) |> validate_required([:preferred_username, :keys, :suspended, :url, :type])
@ -177,6 +179,16 @@ defmodule Mobilizon.Actors.Actor do
|> put_change(:local, true) |> put_change(:local, true)
end end
def unique_username_validator(
%Ecto.Changeset{changes: %{preferred_username: username}} = changeset
) do
if Actors.get_local_actor_by_name(username) do
changeset |> add_error(:preferred_username, "Username is already taken")
else
changeset
end
end
@spec build_urls(Ecto.Changeset.t(), atom()) :: Ecto.Changeset.t() @spec build_urls(Ecto.Changeset.t(), atom()) :: Ecto.Changeset.t()
defp build_urls(changeset, type \\ :Person) defp build_urls(changeset, type \\ :Person)

View file

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

View file

@ -30,6 +30,7 @@ defmodule Mobilizon.Actors.User do
|> cast(attrs, [ |> cast(attrs, [
:email, :email,
:role, :role,
:password,
:password_hash, :password_hash,
:confirmed_at, :confirmed_at,
:confirmation_sent_at, :confirmation_sent_at,
@ -38,13 +39,13 @@ defmodule Mobilizon.Actors.User do
:reset_password_token :reset_password_token
]) ])
|> validate_required([:email]) |> validate_required([:email])
|> unique_constraint(:email, message: "registration.error.email_already_used") |> unique_constraint(:email, message: "This email is already used.")
|> validate_format(:email, ~r/@/) |> validate_email()
|> validate_length( |> validate_length(
:password, :password,
min: 6, min: 6,
max: 100, max: 100,
message: "registration.error.password_too_short" message: "The choosen password is too short."
) )
if Map.has_key?(attrs, :default_actor) do if Map.has_key?(attrs, :default_actor) do
@ -57,21 +58,13 @@ defmodule Mobilizon.Actors.User do
def registration_changeset(struct, params) do def registration_changeset(struct, params) do
struct struct
|> changeset(params) |> changeset(params)
|> cast(params, ~w(password)a, [])
|> cast_assoc(:default_actor) |> cast_assoc(:default_actor)
|> validate_required([:email, :password]) |> validate_required([:email, :password])
|> validate_email()
|> validate_length(
:password,
min: 6,
max: 100,
message: "registration.error.password_too_short"
)
|> hash_password() |> hash_password()
|> save_confirmation_token() |> save_confirmation_token()
|> unique_constraint( |> unique_constraint(
:confirmation_token, :confirmation_token,
message: "regisration.error.confirmation_token_already_in_use" message: "The registration is already in use, this looks like an issue on our side."
) )
end end

View file

@ -3,7 +3,7 @@ defmodule MobilizonWeb.Resolvers.Person do
Handles the person-related GraphQL calls Handles the person-related GraphQL calls
""" """
alias Mobilizon.Actors alias Mobilizon.Actors
alias Mobilizon.Actors.Actor alias Mobilizon.Actors.{Actor, User}
alias Mobilizon.Service.ActivityPub alias Mobilizon.Service.ActivityPub
@deprecated "Use find_person/3 or find_group/3 instead" @deprecated "Use find_person/3 or find_group/3 instead"
@ -52,6 +52,9 @@ defmodule MobilizonWeb.Resolvers.Person do
{:error, "You need to be logged-in to view your list of identities"} {:error, "You need to be logged-in to view your list of identities"}
end end
@doc """
This function is used to create more identities from an existing user
"""
def create_person(_parent, %{preferred_username: _preferred_username} = args, %{ def create_person(_parent, %{preferred_username: _preferred_username} = args, %{
context: %{current_user: user} context: %{current_user: user}
}) do }) do
@ -59,9 +62,27 @@ defmodule MobilizonWeb.Resolvers.Person do
with {:ok, %Actor{} = new_person} <- Actors.new_person(args) do with {:ok, %Actor{} = new_person} <- Actors.new_person(args) do
{:ok, new_person} {:ok, new_person}
end
end
@doc """
This function is used to register a person afterwards the user has been created (but not activated)
"""
def register_person(_parent, args, _resolution) do
with {:ok, %User{} = user} <- Actors.get_user_by_email(args.email),
{:no_actor, nil} <- {:no_actor, Actors.get_actor_for_user(user)},
args <- Map.put(args, :user_id, user.id),
{:ok, %Actor{} = new_person} <- Actors.new_person(args) do
{:ok, new_person}
else else
{:error, %Ecto.Changeset{} = _e} -> {:error, :user_not_found} ->
{:error, "Unable to create a profile with this username"} {:error, "User with email not found"}
{:no_actor, _} ->
{:error, "You already have a profile for this user"}
{:error, %Ecto.Changeset{} = e} ->
{:error, e}
end end
end end
end end

View file

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

View file

@ -13,6 +13,7 @@ defmodule MobilizonWeb.Schema do
import_types(Absinthe.Type.Custom) import_types(Absinthe.Type.Custom)
import_types(Absinthe.Plug.Types) import_types(Absinthe.Plug.Types)
import_types(MobilizonWeb.Schema.UserType)
import_types(MobilizonWeb.Schema.ActorInterface) import_types(MobilizonWeb.Schema.ActorInterface)
import_types(MobilizonWeb.Schema.Actors.PersonType) import_types(MobilizonWeb.Schema.Actors.PersonType)
import_types(MobilizonWeb.Schema.Actors.GroupType) import_types(MobilizonWeb.Schema.Actors.GroupType)
@ -116,20 +117,6 @@ defmodule MobilizonWeb.Schema do
Root Query Root Query
""" """
query do query do
@desc "Get all events"
field :events, list_of(:event) do
arg(:page, :integer, default_value: 1)
arg(:limit, :integer, default_value: 10)
resolve(&Resolvers.Event.list_events/3)
end
@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 "Search through events, persons and groups" @desc "Search through events, persons and groups"
field :search, list_of(:search_result) do field :search, list_of(:search_result) do
arg(:search, non_null(:string)) arg(:search, non_null(:string))
@ -138,189 +125,24 @@ defmodule MobilizonWeb.Schema do
resolve(&Resolvers.Event.search_events_and_actors/3) resolve(&Resolvers.Event.search_events_and_actors/3)
end end
@desc "Get an event by uuid" import_fields(:user_queries)
field :event, :event do import_fields(:person_queries)
arg(:uuid, non_null(:uuid)) import_fields(:group_queries)
resolve(&Resolvers.Event.find_event/3) import_fields(:event_queries)
end import_fields(:participant_queries)
import_fields(:category_queries)
@desc "Get all participants for an event uuid"
field :participants, list_of(:participant) do
arg(:uuid, non_null(:uuid))
arg(:page, :integer, default_value: 1)
arg(:limit, :integer, default_value: 10)
resolve(&Resolvers.Event.list_participants_for_event/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
@desc "Get an user"
field :user, :user do
arg(:id, non_null(:id))
resolve(&Resolvers.User.find_user/3)
end
@desc "Get the current user"
field :logged_user, :user do
resolve(&Resolvers.User.get_current_user/3)
end
@desc "Get the current actor for the logged-in user"
field :logged_person, :person do
resolve(&Resolvers.Person.get_current_person/3)
end
@desc "Get a person by it's preferred username"
field :person, :person do
arg(:preferred_username, non_null(:string))
resolve(&Resolvers.Person.find_person/3)
end
@desc "Get the persons for an user"
field :identities, list_of(:person) do
resolve(&Resolvers.Person.identities/3)
end
@desc "Get the list of categories"
field :categories, non_null(list_of(:category)) do
arg(:page, :integer, default_value: 1)
arg(:limit, :integer, default_value: 10)
resolve(&Resolvers.Category.list_categories/3)
end
end end
@desc """ @desc """
Root Mutation Root Mutation
""" """
mutation do mutation do
@desc "Create an event" import_fields(:user_mutations)
field :create_event, type: :event do import_fields(:person_mutations)
arg(:title, non_null(:string)) import_fields(:group_mutations)
arg(:description, non_null(:string)) import_fields(:event_mutations)
arg(:begins_on, non_null(:datetime)) import_fields(:category_mutations)
arg(:ends_on, :datetime) import_fields(:comment_mutations)
arg(:state, :integer)
arg(:status, :integer)
arg(:public, :boolean)
arg(:thumbnail, :string)
arg(:large_image, :string)
arg(:publish_at, :datetime)
arg(:online_address, :string)
arg(:phone_address, :string)
arg(:organizer_actor_id, non_null(:id))
arg(:category, non_null(:string))
resolve(&Resolvers.Event.create_event/3)
end
@desc "Delete an event"
field :delete_event, :deleted_object do
arg(:event_id, non_null(:integer))
arg(:actor_id, non_null(:integer))
resolve(&Resolvers.Event.delete_event/3)
end
@desc "Create a comment"
field :create_comment, type: :comment do
arg(:text, non_null(:string))
arg(:actor_username, non_null(:string))
resolve(&Resolvers.Comment.create_comment/3)
end
@desc "Create a category with a title, description and picture"
field :create_category, type: :category do
arg(:title, non_null(:string))
arg(:description, non_null(:string))
arg(:picture, non_null(:upload))
resolve(&Resolvers.Category.create_category/3)
end
@desc "Create an user"
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)
end
@desc "Validate an user after registration"
field :validate_user, type: :login do
arg(:token, non_null(:string))
resolve(&Resolvers.User.validate_user/3)
end
@desc "Resend registration confirmation token"
field :resend_confirmation_email, type: :string do
arg(:email, non_null(:string))
arg(:locale, :string, default_value: "en")
resolve(&Resolvers.User.resend_confirmation_email/3)
end
@desc "Send a link through email to reset user password"
field :send_reset_password, type: :string do
arg(:email, non_null(:string))
arg(:locale, :string, default_value: "en")
resolve(&Resolvers.User.send_reset_password/3)
end
@desc "Reset user password"
field :reset_password, type: :login do
arg(:token, non_null(:string))
arg(:password, non_null(:string))
arg(:locale, :string, default_value: "en")
resolve(&Resolvers.User.reset_password/3)
end
@desc "Login an user"
field :login, :login do
arg(:email, non_null(:string))
arg(:password, non_null(:string))
resolve(&Resolvers.User.login_user/3)
end
@desc "Change default actor for user"
field :change_default_actor, :user do
arg(:preferred_username, non_null(:string))
resolve(&Resolvers.User.change_default_actor/3)
end
@desc "Create a new person for user"
field :create_person, :person do
arg(:preferred_username, non_null(:string))
arg(:name, :string, description: "The displayed name for the new profile")
arg(:description, :string, description: "The summary for the new profile", default_value: "")
resolve(&Resolvers.Person.create_person/3)
end
@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
# @desc "Upload a picture" # @desc "Upload a picture"
# field :upload_picture, :picture do # field :upload_picture, :picture do

View file

@ -5,6 +5,7 @@ defmodule MobilizonWeb.Schema.Actors.GroupType do
use Absinthe.Schema.Notation use Absinthe.Schema.Notation
import Absinthe.Resolution.Helpers, only: [dataloader: 1] import Absinthe.Resolution.Helpers, only: [dataloader: 1]
import_types(MobilizonWeb.Schema.Actors.MemberType) import_types(MobilizonWeb.Schema.Actors.MemberType)
alias MobilizonWeb.Resolvers
@desc """ @desc """
Represents a group of actors Represents a group of actors
@ -69,4 +70,42 @@ defmodule MobilizonWeb.Schema.Actors.GroupType do
value(:open, description: "The actor is open to followings") value(:open, description: "The actor is open to followings")
end 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 end

View file

@ -4,8 +4,9 @@ defmodule MobilizonWeb.Schema.Actors.PersonType do
""" """
use Absinthe.Schema.Notation use Absinthe.Schema.Notation
import Absinthe.Resolution.Helpers, only: [dataloader: 1] import Absinthe.Resolution.Helpers, only: [dataloader: 1]
import_types(MobilizonWeb.Schema.UserType)
alias Mobilizon.Events alias Mobilizon.Events
alias MobilizonWeb.Resolvers
import MobilizonWeb.Schema.Utils
@desc """ @desc """
Represents a person identity Represents a person identity
@ -46,4 +47,47 @@ defmodule MobilizonWeb.Schema.Actors.PersonType do
description: "A list of the events this actor has organized" description: "A list of the events this actor has organized"
) )
end end
object :person_queries do
@desc "Get the current actor for the logged-in user"
field :logged_person, :person do
resolve(&Resolvers.Person.get_current_person/3)
end
@desc "Get a person by it's preferred username"
field :person, :person do
arg(:preferred_username, non_null(:string))
resolve(&Resolvers.Person.find_person/3)
end
@desc "Get the persons for an user"
field :identities, list_of(:person) do
resolve(&Resolvers.Person.identities/3)
end
end
object :person_mutations do
@desc "Create a new person for user"
field :create_person, :person do
arg(:preferred_username, non_null(:string))
arg(:name, :string, description: "The displayed name for the new profile", default_value: "")
arg(:summary, :string, description: "The summary for the new profile", default_value: "")
resolve(handle_errors(&Resolvers.Person.create_person/3))
end
@desc "Register a first profile on registration"
field :register_person, :person do
arg(:preferred_username, non_null(:string))
arg(:name, :string, description: "The displayed name for the new profile", default_value: "")
arg(:summary, :string, description: "The summary for the new profile", default_value: "")
arg(:email, non_null(:string), description: "The email from the user previously created")
resolve(handle_errors(&Resolvers.Person.register_person/3))
end
end
end end

View file

@ -3,6 +3,7 @@ defmodule MobilizonWeb.Schema.CommentType do
Schema representation for Comment Schema representation for Comment
""" """
use Absinthe.Schema.Notation use Absinthe.Schema.Notation
alias MobilizonWeb.Resolvers.Comment
@desc "A comment" @desc "A comment"
object :comment do object :comment do
@ -29,4 +30,14 @@ defmodule MobilizonWeb.Schema.CommentType do
value(:moderated, description: "Visible only after a moderator accepted") value(:moderated, description: "Visible only after a moderator accepted")
value(:invite, description: "visible only to people invited") value(:invite, description: "visible only to people invited")
end end
object :comment_mutations do
@desc "Create a comment"
field :create_comment, type: :comment do
arg(:text, non_null(:string))
arg(:actor_username, non_null(:string))
resolve(&Comment.create_comment/3)
end
end
end end

View file

@ -8,6 +8,7 @@ defmodule MobilizonWeb.Schema.EventType do
import_types(MobilizonWeb.Schema.AddressType) import_types(MobilizonWeb.Schema.AddressType)
import_types(MobilizonWeb.Schema.Events.ParticipantType) import_types(MobilizonWeb.Schema.Events.ParticipantType)
import_types(MobilizonWeb.Schema.Events.CategoryType) import_types(MobilizonWeb.Schema.Events.CategoryType)
alias MobilizonWeb.Resolvers
@desc "An event" @desc "An event"
object :event do object :event do
@ -70,4 +71,49 @@ defmodule MobilizonWeb.Schema.EventType do
value(:confirmed, description: "The event is confirmed") value(:confirmed, description: "The event is confirmed")
value(:cancelled, description: "The event is cancelled") value(:cancelled, description: "The event is cancelled")
end end
object :event_queries do
@desc "Get all events"
field :events, list_of(:event) do
arg(:page, :integer, default_value: 1)
arg(:limit, :integer, default_value: 10)
resolve(&Resolvers.Event.list_events/3)
end
@desc "Get an event by uuid"
field :event, :event do
arg(:uuid, non_null(:uuid))
resolve(&Resolvers.Event.find_event/3)
end
end
object :event_mutations do
@desc "Create an event"
field :create_event, type: :event do
arg(:title, non_null(:string))
arg(:description, non_null(:string))
arg(:begins_on, non_null(:datetime))
arg(:ends_on, :datetime)
arg(:state, :integer)
arg(:status, :integer)
arg(:public, :boolean)
arg(:thumbnail, :string)
arg(:large_image, :string)
arg(:publish_at, :datetime)
arg(:online_address, :string)
arg(:phone_address, :string)
arg(:organizer_actor_id, non_null(:id))
arg(:category, non_null(:string))
resolve(&Resolvers.Event.create_event/3)
end
@desc "Delete an event"
field :delete_event, :deleted_object do
arg(:event_id, non_null(:integer))
arg(:actor_id, non_null(:integer))
resolve(&Resolvers.Event.delete_event/3)
end
end
end end

View file

@ -3,6 +3,7 @@ defmodule MobilizonWeb.Schema.Events.CategoryType do
Schema representation for Category Schema representation for Category
""" """
use Absinthe.Schema.Notation use Absinthe.Schema.Notation
alias MobilizonWeb.Resolvers
@desc "A category" @desc "A category"
object :category do object :category do
@ -11,4 +12,23 @@ defmodule MobilizonWeb.Schema.Events.CategoryType do
field(:picture, :picture, description: "The category's picture") field(:picture, :picture, description: "The category's picture")
field(:title, :string, description: "The category's title") field(:title, :string, description: "The category's title")
end end
object :category_queries do
@desc "Get the list of categories"
field :categories, non_null(list_of(:category)) do
arg(:page, :integer, default_value: 1)
arg(:limit, :integer, default_value: 10)
resolve(&Resolvers.Category.list_categories/3)
end
end
object :category_mutations do
@desc "Create a category with a title, description and picture"
field :create_category, type: :category do
arg(:title, non_null(:string))
arg(:description, non_null(:string))
arg(:picture, non_null(:upload))
resolve(&Resolvers.Category.create_category/3)
end
end
end end

View file

@ -4,6 +4,7 @@ defmodule MobilizonWeb.Schema.Events.ParticipantType do
""" """
use Absinthe.Schema.Notation use Absinthe.Schema.Notation
import Absinthe.Resolution.Helpers, only: [dataloader: 1] import Absinthe.Resolution.Helpers, only: [dataloader: 1]
alias MobilizonWeb.Resolvers
@desc "Represents a participant to an event" @desc "Represents a participant to an event"
object :participant do object :participant do
@ -15,4 +16,14 @@ defmodule MobilizonWeb.Schema.Events.ParticipantType do
field(:actor, :actor, description: "The actor that participates to the event") field(:actor, :actor, description: "The actor that participates to the event")
field(:role, :integer, description: "The role of this actor at this event") field(:role, :integer, description: "The role of this actor at this event")
end end
object :participant_queries do
@desc "Get all participants for an event uuid"
field :participants, list_of(:participant) do
arg(:uuid, non_null(:uuid))
arg(:page, :integer, default_value: 1)
arg(:limit, :integer, default_value: 10)
resolve(&Resolvers.Event.list_participants_for_event/3)
end
end
end end

View file

@ -3,6 +3,8 @@ defmodule MobilizonWeb.Schema.UserType do
Schema representation for User Schema representation for User
""" """
use Absinthe.Schema.Notation use Absinthe.Schema.Notation
alias MobilizonWeb.Resolvers.User
import MobilizonWeb.Schema.Utils
@desc "A local user of Mobilizon" @desc "A local user of Mobilizon"
object :user do object :user do
@ -13,7 +15,7 @@ defmodule MobilizonWeb.Schema.UserType do
description: "The user's list of profiles (identities)" 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, field(:confirmed_at, :datetime,
description: "The datetime when the user was confirmed/activated" description: "The datetime when the user was confirmed/activated"
@ -33,4 +35,68 @@ defmodule MobilizonWeb.Schema.UserType do
description: "The token sent when requesting password token" description: "The token sent when requesting password token"
) )
end end
object :user_queries do
@desc "Get an user"
field :user, :user do
arg(:id, non_null(:id))
resolve(&User.find_user/3)
end
@desc "Get the current user"
field :logged_user, :user do
resolve(&User.get_current_user/3)
end
end
object :user_mutations do
@desc "Create an user"
field :create_user, type: :user do
arg(:email, non_null(:string))
arg(:password, non_null(:string))
resolve(handle_errors(&User.create_user/3))
end
@desc "Validate an user after registration"
field :validate_user, type: :login do
arg(:token, non_null(:string))
resolve(&User.validate_user/3)
end
@desc "Resend registration confirmation token"
field :resend_confirmation_email, type: :string do
arg(:email, non_null(:string))
arg(:locale, :string, default_value: "en")
resolve(&User.resend_confirmation_email/3)
end
@desc "Send a link through email to reset user password"
field :send_reset_password, type: :string do
arg(:email, non_null(:string))
arg(:locale, :string, default_value: "en")
resolve(&User.send_reset_password/3)
end
@desc "Reset user password"
field :reset_password, type: :login do
arg(:token, non_null(:string))
arg(:password, non_null(:string))
arg(:locale, :string, default_value: "en")
resolve(&User.reset_password/3)
end
@desc "Login an user"
field :login, :login do
arg(:email, non_null(:string))
arg(:password, non_null(:string))
resolve(&User.login_user/3)
end
@desc "Change default actor for user"
field :change_default_actor, :user do
arg(:preferred_username, non_null(:string))
resolve(&User.change_default_actor/3)
end
end
end end

View file

@ -0,0 +1,21 @@
defmodule MobilizonWeb.Schema.Utils do
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: key]
end)
{:error, errors}
end
end

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -73,28 +73,27 @@ defmodule MobilizonWeb.Resolvers.UserResolverTest do
end end
describe "Resolver: Create an user & actor" do describe "Resolver: Create an user & actor" do
@account_creation %{ @user_creation %{
email: "test@demo.tld", email: "test@demo.tld",
password: "long password", password: "long password",
username: "test_account" username: "toto",
name: "Sir Toto",
summary: "Sir Toto, prince of the functional tests"
} }
@account_creation_bad_email %{ @user_creation_bad_email %{
email: "y@l@", email: "y@l@",
password: "long password", password: "long password"
username: "test_account"
} }
test "test create_user_actor/3 creates an user", context do test "test create_user/3 creates an user and register_person/3 registers a profile",
context do
mutation = """ mutation = """
mutation { mutation {
createUser( createUser(
email: "#{@account_creation.email}", email: "#{@user_creation.email}",
password: "#{@account_creation.password}", password: "#{@user_creation.password}",
username: "#{@account_creation.username}"
) { ) {
default_actor { id,
preferred_username,
},
email email
} }
} }
@ -104,24 +103,144 @@ defmodule MobilizonWeb.Resolvers.UserResolverTest do
context.conn context.conn
|> post("/api", AbsintheHelpers.mutation_skeleton(mutation)) |> post("/api", AbsintheHelpers.mutation_skeleton(mutation))
assert json_response(res, 200)["data"]["createUser"]["default_actor"]["preferred_username"] == assert json_response(res, 200)["data"]["createUser"]["email"] == @user_creation.email
@account_creation.username
assert json_response(res, 200)["data"]["createUser"]["email"] == @account_creation.email mutation = """
mutation {
registerPerson(
preferredUsername: "#{@user_creation.username}",
name: "#{@user_creation.name}",
summary: "#{@user_creation.summary}",
email: "#{@user_creation.email}",
) {
preferredUsername,
name,
summary,
avatarUrl,
}
}
"""
res =
context.conn
|> post("/api", AbsintheHelpers.mutation_skeleton(mutation))
assert json_response(res, 200)["data"]["registerPerson"]["preferredUsername"] ==
@user_creation.username
end end
test "test create_user_actor/3 doesn't create an user with bad email", context do test "register_person/3 doesn't register a profile from an unknown email", context do
mutation = """ mutation = """
mutation { mutation {
createUser( createUser(
email: "#{@account_creation_bad_email.email}", email: "#{@user_creation.email}",
password: "#{@account_creation.password}", password: "#{@user_creation.password}",
username: "#{@account_creation.username}"
) { ) {
default_actor { id,
preferred_username, email
}, }
email, }
"""
context.conn
|> post("/api", AbsintheHelpers.mutation_skeleton(mutation))
mutation = """
mutation {
registerPerson(
preferredUsername: "#{@user_creation.username}",
name: "#{@user_creation.name}",
summary: "#{@user_creation.summary}",
email: "random",
) {
preferredUsername,
name,
summary,
avatarUrl,
}
}
"""
res =
context.conn
|> post("/api", AbsintheHelpers.mutation_skeleton(mutation))
assert hd(json_response(res, 200)["errors"])["message"] ==
"User with email not found"
end
test "register_person/3 can't be called with an existing profile", context do
mutation = """
mutation {
createUser(
email: "#{@user_creation.email}",
password: "#{@user_creation.password}",
) {
id,
email
}
}
"""
context.conn
|> post("/api", AbsintheHelpers.mutation_skeleton(mutation))
mutation = """
mutation {
registerPerson(
preferredUsername: "#{@user_creation.username}",
name: "#{@user_creation.name}",
summary: "#{@user_creation.summary}",
email: "#{@user_creation.email}",
) {
preferredUsername,
name,
summary,
avatarUrl,
}
}
"""
res =
context.conn
|> post("/api", AbsintheHelpers.mutation_skeleton(mutation))
assert json_response(res, 200)["data"]["registerPerson"]["preferredUsername"] ==
@user_creation.username
mutation = """
mutation {
registerPerson(
preferredUsername: "#{@user_creation.username}",
name: "#{@user_creation.name}",
summary: "#{@user_creation.summary}",
email: "#{@user_creation.email}",
) {
preferredUsername,
name,
summary,
avatarUrl,
}
}
"""
res =
context.conn
|> post("/api", AbsintheHelpers.mutation_skeleton(mutation))
assert hd(json_response(res, 200)["errors"])["message"] ==
"You already have a profile for this user"
end
test "test create_user/3 doesn't create an user with bad email", context do
mutation = """
mutation {
createUser(
email: "#{@user_creation_bad_email.email}",
password: "#{@user_creation_bad_email.password}",
) {
id,
email
} }
} }
""" """
@ -136,9 +255,9 @@ defmodule MobilizonWeb.Resolvers.UserResolverTest do
end end
describe "Resolver: Validate an user" do 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 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 = """
mutation { mutation {
@ -148,9 +267,6 @@ defmodule MobilizonWeb.Resolvers.UserResolverTest do
token, token,
user { user {
id, id,
default_actor {
preferredUsername
}
}, },
} }
} }
@ -160,16 +276,11 @@ defmodule MobilizonWeb.Resolvers.UserResolverTest do
context.conn context.conn
|> post("/api", AbsintheHelpers.mutation_skeleton(mutation)) |> 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) assert json_response(res, 200)["data"]["validateUser"]["user"]["id"] == to_string(user.id)
end end
test "test validate_user/3 with invalid token doesn't validate an user", context do test "test validate_user/3 with invalid token doesn't validate an user", context do
{:ok, %User{default_actor: %Actor{} = _actor} = _user} = insert(:user, confirmation_token: "t0t0")
Actors.register(@valid_actor_params)
mutation = """ mutation = """
mutation { mutation {
@ -178,10 +289,7 @@ defmodule MobilizonWeb.Resolvers.UserResolverTest do
) { ) {
token, token,
user { user {
id, id
default_actor {
preferredUsername
}
}, },
} }
} }
@ -191,14 +299,14 @@ defmodule MobilizonWeb.Resolvers.UserResolverTest do
context.conn context.conn
|> post("/api", AbsintheHelpers.mutation_skeleton(mutation)) |> 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
end end
describe "Resolver: Resend confirmation emails" do describe "Resolver: Resend confirmation emails" do
test "test resend_confirmation_email/3 with valid email resends an validation email", test "test resend_confirmation_email/3 with valid email resends an validation email",
context do 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 = """
mutation { mutation {
@ -230,9 +338,6 @@ defmodule MobilizonWeb.Resolvers.UserResolverTest do
test "test resend_confirmation_email/3 with invalid email resends an validation email", test "test resend_confirmation_email/3 with invalid email resends an validation email",
context do context do
{:ok, %User{default_actor: %Actor{} = _actor} = _user} =
Actors.register(@valid_actor_params)
mutation = """ mutation = """
mutation { mutation {
resendConfirmationEmail( resendConfirmationEmail(
@ -289,7 +394,7 @@ defmodule MobilizonWeb.Resolvers.UserResolverTest do
describe "Resolver: Reset user's password" do describe "Resolver: Reset user's password" do
test "test reset_password/3 with valid email", context 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) %Actor{} = insert(:actor, user: user)
{:ok, _email_sent} = Mobilizon.Actors.Service.ResetPassword.send_password_reset_email(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) %User{reset_password_token: reset_password_token} = Mobilizon.Actors.get_user!(user.id)
@ -369,7 +474,7 @@ defmodule MobilizonWeb.Resolvers.UserResolverTest do
describe "Resolver: Login an user" do describe "Resolver: Login an user" do
test "test login_user/3 with valid credentials", context 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} = {:ok, %User{} = _user} =
Actors.update_user(user, %{ Actors.update_user(user, %{
@ -381,14 +486,12 @@ defmodule MobilizonWeb.Resolvers.UserResolverTest do
mutation = """ mutation = """
mutation { mutation {
login( login(
email: "#{@valid_actor_params.email}", email: "#{user.email}",
password: "#{@valid_actor_params.password}", password: "#{user.password}",
) { ) {
token, token,
user { user {
default_actor { id
preferred_username,
}
} }
} }
} }
@ -400,11 +503,10 @@ defmodule MobilizonWeb.Resolvers.UserResolverTest do
assert login = json_response(res, 200)["data"]["login"] assert login = json_response(res, 200)["data"]["login"]
assert Map.has_key?(login, "token") && not is_nil(login["token"]) assert Map.has_key?(login, "token") && not is_nil(login["token"])
assert login["user"]["default_actor"]["preferred_username"] == @valid_actor_params.username
end end
test "test login_user/3 with invalid password", context do 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} = {:ok, %User{} = _user} =
Actors.update_user(user, %{ Actors.update_user(user, %{
@ -416,7 +518,7 @@ defmodule MobilizonWeb.Resolvers.UserResolverTest do
mutation = """ mutation = """
mutation { mutation {
login( login(
email: "#{@valid_actor_params.email}", email: "#{user.email}",
password: "bad password", password: "bad password",
) { ) {
token, token,
@ -438,15 +540,6 @@ defmodule MobilizonWeb.Resolvers.UserResolverTest do
end end
test "test login_user/3 with invalid email", context do 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 = """
mutation { mutation {
login( login(
@ -474,15 +567,15 @@ defmodule MobilizonWeb.Resolvers.UserResolverTest do
describe "Resolver: change default actor for user" do describe "Resolver: change default actor for user" do
test "test change_default_actor/3 with valid actor", context do test "test change_default_actor/3 with valid actor", context do
# Prepare user with two actors # Prepare user with two actors
assert {:ok, %User{id: user_id, default_actor: %Actor{} = actor} = user} = user = insert(:user)
Actors.register(@valid_actor_params) 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, %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 assert length(actors) == 2
mutation = """ mutation = """