Add ability to update/create/delete identities

This commit is contained in:
Chocobozzz 2019-06-17 17:15:27 +02:00 committed by Thomas Citharel
parent 69fb1ec828
commit 0e485b2388
No known key found for this signature in database
GPG key ID: A061B9DDE0CA0773
22 changed files with 927 additions and 157 deletions

View file

@ -1,6 +1,7 @@
# Settings
MOBILIZON_INSTANCE_NAME="<%= instance_name %>"
MOBILIZON_INSTANCE_HOST="<%= instance_domain %>"
MOBILIZON_INSTANCE_PORT=4002
MOBILIZON_INSTANCE_EMAIL="<%= instance_email %>"
MOBILIZON_INSTANCE_REGISTRATIONS_OPEN=true
@ -10,7 +11,6 @@ GRAPHQL_API_FULL_PATH=""
# APP
MIX_ENV=prod
MOBILIZON_INSTANCE_PORT=4002
MOBILIZON_LOGLEVEL="info"
MOBILIZON_SECRET="<%= instance_secret %>"
@ -19,4 +19,4 @@ MOBILIZON_DATABASE_USERNAME="<%= database_username %>"
MOBILIZON_DATABASE_PASSWORD="<%= database_password %>"
MOBILIZON_DATABASE_DBNAME="<%= database_name %>"
MOBILIZON_DATABASE_HOST="<%= database_host %>"
MOBILIZON_DATABASE_PORT=<%= database_port %>
MOBILIZON_DATABASE_PORT=<%= database_port %>

View file

@ -81,18 +81,20 @@ export default class App extends Vue {
@import "~bulma/sass/elements/other.sass";
@import "~bulma/sass/elements/tag.sass";
@import "~bulma/sass/elements/title.sass";
@import "~bulma/sass/elements/notification";
@import "~bulma/sass/grid/_all.sass";
@import "~bulma/sass/layout/_all.sass";
@import "~bulma/sass/utilities/_all";
/* Buefy imports */
@import "~buefy/src/scss/utils/_all";
@import "~buefy/src/scss/components/datepicker";
@import "~buefy/src/scss/components/notices";
@import "~buefy/src/scss/components/dropdown";
@import "~buefy/src/scss/components/form";
@import "~buefy/src/scss/components/modal";
@import "~buefy/src/scss/components/tag";
@import "~buefy/src/scss/components/upload";
@import "~buefy/src/scss/utils/_all";
.router-enter-active,
.router-leave-active {

View file

@ -1,44 +0,0 @@
<template>
<!-- TODO -->
</template>
<script lang="ts">
import { Component, Vue } from 'vue-property-decorator';
import { CREATE_PERSON, LOGGED_PERSON } from '../../graphql/actor';
import { IPerson } from '@/types/actor';
@Component({
apollo: {
loggedPerson: {
query: LOGGED_PERSON,
},
},
})
export default class Identities extends Vue {
loggedPerson!: IPerson;
errors: string[] = [];
newPerson!: IPerson;
async createProfile(e) {
e.preventDefault();
try {
await this.$apollo.mutate({
mutation: CREATE_PERSON,
variables: this.newPerson,
});
this.$apollo.queries.identities.refresh();
} catch (err) {
console.error(err);
err.graphQLErrors.forEach(({ message }) => {
this.errors.push(message);
});
}
}
host() {
return `@${window.location.host}`;
}
}
</script>

View file

@ -6,7 +6,10 @@
<ul class="identities">
<li v-for="identity in identities" :key="identity.id">
<div class="media identity" v-bind:class="{ 'is-current-identity': isCurrentIdentity(identity) }">
<router-link
:to="{ name: 'UpdateIdentity', params: { identityName: identity.preferredUsername } }"
class="media identity" v-bind:class="{ 'is-current-identity': isCurrentIdentity(identity) }"
>
<div class="media-left">
<figure class="image is-48x48" v-if="identity.avatar">
<img class="is-rounded" :src="identity.avatar.url">
@ -16,13 +19,13 @@
<div class="media-content">
{{ identity.displayName() }}
</div>
</div>
</router-link>
</li>
</ul>
<a class="button create-identity is-primary">
<router-link :to="{ name: 'CreateIdentity' }" class="button create-identity is-primary" >
<translate>Create a new identity</translate>
</a>
</router-link>
</section>
</template>
@ -38,6 +41,7 @@
font-size: 1.3rem;
padding-bottom: 0;
margin-bottom: 15px;
color: #000;
&.is-current-identity {
background-color: rgba(0, 0, 0, 0.1);
@ -50,33 +54,29 @@
</style>
<script lang="ts">
import { Component, Vue } from 'vue-property-decorator';
import { IDENTITIES, LOGGED_PERSON } from '@/graphql/actor';
import { IPerson, Person } from '@/types/actor';
import { Component, Prop, Vue } from 'vue-property-decorator';
import { IDENTITIES, LOGGED_PERSON } from '@/graphql/actor';
import { IPerson, Person } from '@/types/actor';
@Component({
apollo: {
loggedPerson: {
query: LOGGED_PERSON,
@Component({
apollo: {
identities: {
query: IDENTITIES,
update (result) {
return result.identities.map(i => new Person(i));
},
},
})
export default class Identities extends Vue {
identities: Person[] = [];
loggedPerson!: IPerson;
errors: string[] = [];
},
})
export default class Identities extends Vue {
@Prop({ type: String }) currentIdentityName!: string;
async mounted() {
const result = await this.$apollo.query({
query: IDENTITIES,
});
identities: Person[] = [];
errors: string[] = [];
this.identities = result.data.identities
.map(i => new Person(i));
}
isCurrentIdentity(identity: IPerson) {
return identity.preferredUsername === this.loggedPerson.preferredUsername;
}
isCurrentIdentity(identity: IPerson) {
return identity.preferredUsername === this.currentIdentityName;
}
}
</script>

View file

@ -17,43 +17,40 @@
<span aria-hidden="true"></span>
</a>
</div>
<div class="navbar-menu" :class="{ 'is-active': showNavbar }">
<div class="navbar-end">
<div class="navbar-item">
<search-field />
</div>
<div class="navbar-item" v-if="!currentUser.isLoggedIn">
<div class="buttons">
<router-link class="button is-primary" v-if="config && config.registrationsOpen" :to="{ name: 'Register' }">
<strong>
<translate>Sign up</translate>
</strong>
</router-link>
<router-link class="button is-primary" :to="{ name: 'Login' }">
<translate>Log in</translate>
</router-link>
</div>
</div>
<div class="navbar-item has-dropdown is-hoverable" v-else>
<router-link
class="navbar-link"
v-if="currentUser.isLoggedIn && loggedPerson"
:to="{ name: 'MyAccount' }"
>
<figure class="image is-24x24" v-if="loggedPerson.avatar">
<img :src="loggedPerson.avatar.url">
</figure>
<span>{{ loggedPerson.preferredUsername }}</span>
</router-link>
<div class="navbar-item has-dropdown is-hoverable" v-if="currentUser.isLoggedIn">
<a
class="navbar-link"
v-if="loggedPerson"
>
<figure class="image is-24x24" v-if="loggedPerson.avatar">
<img alt="avatarUrl" :src="loggedPerson.avatar.url">
</figure>
<span>{{ loggedPerson.preferredUsername }}</span>
</a>
<div class="navbar-dropdown">
<router-link :to="{ name: 'MyAccount' }" class="navbar-item">
<translate>My account</translate>
<span class="navbar-item">
<router-link :to="{ name: 'UpdateIdentity' }" v-translate>My account</router-link>
</span>
<a v-translate class="navbar-item" v-on:click="logout()">Log out</a>
</div>
</div>
<div class="navbar-item" v-else>
<div class="buttons">
<router-link class="button is-primary" v-if="config && config.registrationsOpen" :to="{ name: 'Register' }">
<strong v-translate>Sign up</strong>
</router-link>
<a class="navbar-item" v-on:click="logout()">
<translate>Log out</translate>
</a>
<router-link class="button is-primary" :to="{ name: 'Login' }" v-translate>Log in</router-link>
</div>
</div>
</div>

View file

@ -1,29 +1,64 @@
<template>
<b-field class="file">
<b-upload v-model="pictureFile" @input="onFileChanged">
<a class="button is-primary">
<b-icon icon="upload"></b-icon>
<span>Click to upload</span>
</a>
</b-upload>
<span class="file-name" v-if="pictureFile">
{{ pictureFile.name }}
</span>
</b-field>
<div class="root">
<figure class="image is-128x128">
<img class="is-rounded" v-bind:src="imageSrc">
<div class="image-placeholder" v-if="!imageSrc"></div>
</figure>
<b-upload @input="onFileChanged">
<a class="button is-primary">
<b-icon icon="upload"></b-icon>
<span>Click to upload</span>
</a>
</b-upload>
</div>
</template>
<style scoped type="scss">
.root {
display: flex;
align-items: center;
}
.image {
margin-right: 30px;
}
.image-placeholder {
background-color: grey;
width: 100%;
height: 100%;
border-radius: 100%;
}
</style>
<script lang="ts">
import { Component, Vue } from 'vue-property-decorator';
import { IPictureUpload } from '@/types/picture.model';
import { Component, Model, Vue, Watch } from 'vue-property-decorator';
@Component
export default class PictureUpload extends Vue {
picture!: IPictureUpload;
pictureFile: File|null = null;
@Model('change', { type: File }) readonly pictureFile!: File;
imageSrc: string | null = null;
@Watch('pictureFile')
onPictureFileChanged (val: File) {
this.updatePreview(val);
}
onFileChanged(file: File) {
this.picture = { file, name: file.name, alt: '' };
this.$emit('change', this.picture);
this.$emit('change', file);
this.updatePreview(file);
}
private updatePreview(file?: File) {
if (file) {
this.imageSrc = URL.createObjectURL(file);
return;
}
this.imageSrc = null;
}
}
</script>

View file

@ -11,6 +11,7 @@ query($name:String!) {
preferredUsername,
suspended,
avatar {
name,
url
},
banner {
@ -64,6 +65,7 @@ query {
export const IDENTITIES = gql`
query {
identities {
id,
avatar {
url
},
@ -73,22 +75,51 @@ query {
}`;
export const CREATE_PERSON = gql`
mutation CreatePerson($preferredUsername: String!) {
mutation CreatePerson($preferredUsername: String!, $name: String!, $summary: String, $avatar: PictureInput) {
createPerson(
preferredUsername: $preferredUsername,
name: $name,
summary: $summary
summary: $summary,
avatar: $avatar
) {
id,
preferredUsername,
name,
summary,
avatar {
url
},
}
}
}
`;
export const UPDATE_PERSON = gql`
mutation UpdatePerson($preferredUsername: String!, $name: String, $summary: String, $avatar: PictureInput) {
updatePerson(
preferredUsername: $preferredUsername,
name: $name,
summary: $summary,
avatar: $avatar
) {
id,
preferredUsername,
name,
summary,
avatar {
url
},
}
}
`;
export const DELETE_PERSON = gql`
mutation DeletePerson($preferredUsername: String!) {
deletePerson(preferredUsername: $preferredUsername) {
preferredUsername,
}
}
`;
/**
* This one is used only to register the first account. Prefer CREATE_PERSON when creating another identity
*/

View file

@ -6,14 +6,14 @@ import GetTextPlugin from 'vue-gettext';
import App from '@/App.vue';
import router from '@/router';
import { apolloProvider } from './vue-apollo';
import { NotifierPlugin } from '@/plugins/notifier';
const translations = require('@/i18n/translations.json');
Vue.config.productionTip = false;
Vue.use(Buefy, {
defaultContainerElement: '#mobilizon',
});
Vue.use(Buefy);
Vue.use(NotifierPlugin);
const language = (window.navigator as any).userLanguage || window.navigator.language;

View file

@ -0,0 +1,32 @@
import Vue from 'vue';
declare module 'vue/types/vue' {
interface Vue {
$notifier: {
success: (message: string) => void;
};
}
}
export class Notifier {
private readonly vue: typeof Vue;
constructor(vue: typeof Vue) {
this.vue = vue;
}
success(message: string) {
this.vue.prototype.$notification.open({
message,
duration: 5000,
position: 'is-bottom-right',
type: 'is-success',
hasIcon: true,
});
}
}
// tslint:disable
export function NotifierPlugin(vue: typeof Vue, options?: any): void {
vue.prototype.$notifier = new Notifier(vue);
}

View file

@ -4,13 +4,18 @@ import CreateGroup from '@/views/Group/Create.vue';
import Group from '@/views/Group/Group.vue';
import GroupList from '@/views/Group/GroupList.vue';
import { RouteConfig } from 'vue-router';
import EditIdentity from '@/views/Account/children/EditIdentity.vue';
export enum ActorRouteName {
GROUP_LIST = 'GroupList',
GROUP = 'Group',
CREATE_GROUP = 'CreateGroup',
PROFILE = 'Profile',
MY_ACCOUNT = 'MyAccount',
}
export enum MyAccountRouteName {
CREATE_IDENTITY = 'CreateIdentity',
UPDATE_IDENTITY = 'UpdateIdentity',
}
export const actorRoutes: RouteConfig[] = [
@ -41,10 +46,23 @@ export const actorRoutes: RouteConfig[] = [
meta: { requiredAuth: false },
},
{
path: '/my-account',
name: ActorRouteName.MY_ACCOUNT,
path: '/my-account/identity',
component: MyAccount,
props: true,
meta: { requiredAuth: true },
children: [
{
path: 'create',
name: MyAccountRouteName.CREATE_IDENTITY,
component: EditIdentity,
props: { isUpdate: false },
},
{
path: 'update/:identityName?',
name: MyAccountRouteName.UPDATE_IDENTITY,
component: EditIdentity,
props: { isUpdate: true },
},
],
},
];

View file

@ -4,7 +4,7 @@ import PageNotFound from '@/views/PageNotFound.vue';
import Home from '@/views/Home.vue';
import { UserRouteName, userRoutes } from './user';
import { EventRouteName, eventRoutes } from '@/router/event';
import { ActorRouteName, actorRoutes } from '@/router/actor';
import { ActorRouteName, actorRoutes, MyAccountRouteName } from '@/router/actor';
import { ErrorRouteName, errorRoutes } from '@/router/error';
import { authGuardIfNeeded } from '@/router/guards/auth-guard';
import Search from '@/views/Search.vue';
@ -34,6 +34,7 @@ export const RouteName = {
...UserRouteName,
...EventRouteName,
...ActorRouteName,
...MyAccountRouteName,
...ErrorRouteName,
};

View file

@ -1,7 +1,7 @@
import { IPicture } from '@/types/picture.model';
export interface IActor {
id?: string;
id?: number;
url: string;
name: string;
domain: string|null;
@ -13,6 +13,7 @@ export interface IActor {
}
export class Actor implements IActor {
id?: number;
avatar: IPicture | null = null;
banner: IPicture | null = null;
domain: string | null = null;

View file

@ -20,6 +20,10 @@ export class Person extends Actor implements IPerson {
constructor(hash: IPerson | {} = {}) {
super(hash);
this.patch(hash);
}
patch (hash: any) {
Object.assign(this, hash);
}
}

View file

@ -1,15 +1,18 @@
<template>
<section class="container">
<div v-if="person">
<div v-if="loggedPerson">
<div class="header">
<figure v-if="person.banner" class="image is-3by1">
<img :src="person.banner.url" alt="banner">
<figure v-if="loggedPerson.banner" class="image is-3by1">
<img :src="loggedPerson.banner.url" alt="banner">
</figure>
</div>
<div class="columns">
<div class="identities column is-4">
<identities></identities>
<identities v-bind:currentIdentityName="currentIdentityName"></identities>
</div>
<div class="column is-8">
<router-view></router-view>
</div>
</div>
</div>
@ -29,35 +32,46 @@
<script lang="ts">
import { LOGGED_PERSON } from '@/graphql/actor';
import { Component, Vue } from 'vue-property-decorator';
import { Component, Vue, Watch } from 'vue-property-decorator';
import EventCard from '@/components/Event/EventCard.vue';
import { IPerson } from '@/types/actor';
import { CURRENT_USER_CLIENT } from '@/graphql/user';
import Identities from '@/components/Account/Identities.vue';
@Component({
apollo: {
currentUser: {
query: CURRENT_USER_CLIENT,
},
loggedPerson: {
query: LOGGED_PERSON,
},
},
components: {
EventCard,
Identities,
},
})
export default class MyAccount extends Vue {
person: IPerson | null = null;
loggedPerson: IPerson | null = null;
currentIdentityName: string | null = null;
async mounted () {
@Watch('$route.params.identityName', { immediate: true })
async onIdentityParamChanged (val: string) {
if (!this.loggedPerson) {
this.loggedPerson = await this.loadLoggedPerson();
}
await this.redirectIfNoIdentitySelected(val);
this.currentIdentityName = val;
}
private async redirectIfNoIdentitySelected (identityParam?: string) {
if (!!identityParam) return;
if (!!this.loggedPerson) {
this.$router.push({ params: { identityName: this.loggedPerson.preferredUsername } });
}
}
private async loadLoggedPerson () {
const result = await this.$apollo.query({
query: LOGGED_PERSON,
});
this.person = result.data.loggedPerson;
return result.data.loggedPerson as IPerson;
}
}
</script>

View file

@ -87,7 +87,6 @@ export default class Register extends Vue {
preferredUsername: '',
name: '',
summary: '',
id: '',
url: '',
suspended: false,
avatar: null,

View file

@ -0,0 +1,329 @@
<template>
<div class="root">
<h1 class="title">
<span v-if="isUpdate">{{ identity.displayName() }}</span>
<translate v-else>I create an identity</translate>
</h1>
<picture-upload v-model="avatarFile" class="picture-upload"></picture-upload>
<b-field :label="$gettext('Display name')">
<b-input aria-required="true" required v-model="identity.name" @input="autoUpdateUsername($event)"/>
</b-field>
<b-field :label="$gettext('Username')">
<b-field>
<b-input aria-required="true" required v-model="identity.preferredUsername" :disabled="isUpdate"/>
<p class="control">
<span class="button is-static">@{{ getInstanceHost() }}</span>
</p>
</b-field>
</b-field>
<b-field :label="$gettext('Description')">
<b-input type="textarea" aria-required="false" v-model="identity.summary"/>
</b-field>
<b-field class="submit">
<div class="control">
<button v-translate type="button" class="button is-primary" @click="submit()">
Save
</button>
</div>
</b-field>
<div class="delete-identity" v-if="isUpdate">
<span v-translate @click="openDeleteIdentityConfirmation()">
Delete this identity
</span>
</div>
</div>
</template>
<style scoped type="scss">
h1 {
display: flex;
justify-content: center;
}
.picture-upload {
margin: 30px 0;
}
.submit,
.delete-identity {
display: flex;
justify-content: center;
}
.submit {
margin: 30px 0;
}
.delete-identity {
text-decoration: underline;
cursor: pointer;
margin-top: 15px;
}
</style>
<script lang="ts">
import { Component, Prop, Vue, Watch } from 'vue-property-decorator';
import { CREATE_PERSON, DELETE_PERSON, FETCH_PERSON, IDENTITIES, LOGGED_PERSON, UPDATE_PERSON } from '../../../graphql/actor';
import { IPerson, Person } from '@/types/actor';
import PictureUpload from '@/components/PictureUpload.vue';
import { MOBILIZON_INSTANCE_HOST } from '@/api/_entrypoint';
import { Dialog } from 'buefy/dist/components/dialog';
import { RouteName } from '@/router';
@Component({
components: {
PictureUpload,
Dialog,
},
})
export default class EditIdentity extends Vue {
@Prop({ type: Boolean }) isUpdate!: boolean;
errors: string[] = [];
identityName!: string | undefined;
avatarFile: File | null = null;
identity = new Person();
private oldDisplayName: string | null = null;
private loggedPerson: IPerson | null = null;
@Watch('isUpdate')
async isUpdateChanged () {
this.resetFields();
}
@Watch('$route.params.identityName', { immediate: true })
async onIdentityParamChanged (val: string) {
// Only used when we update the identity
if (this.isUpdate !== true) return;
await this.redirectIfNoIdentitySelected(val);
this.resetFields();
this.identityName = val;
if (this.identityName) {
this.identity = await this.getIdentity();
this.avatarFile = await this.getAvatarFileFromIdentity(this.identity);
}
}
submit() {
if (this.isUpdate) return this.updateIdentity();
return this.createIdentity();
}
autoUpdateUsername(newDisplayName: string | null) {
const oldUsername = this.convertToUsername(this.oldDisplayName);
if (this.identity.preferredUsername === oldUsername) {
this.identity.preferredUsername = this.convertToUsername(newDisplayName);
}
this.oldDisplayName = newDisplayName;
}
async deleteIdentity() {
try {
await this.$apollo.mutate({
mutation: DELETE_PERSON,
variables: this.identity,
update: (store) => {
const data = store.readQuery<{ identities: IPerson[] }>({ query: IDENTITIES });
if (data) {
data.identities = data.identities.filter(i => i.id !== this.identity.id);
store.writeQuery({ query: IDENTITIES, data });
}
},
});
this.$notifier.success(
this.$gettextInterpolate('Identity %{displayName} deleted', { displayName: this.identity.displayName() }),
);
await this.loadLoggedPersonIfNeeded();
// Refresh the loaded person if we deleted the default identity
if (this.loggedPerson && this.identity.id === this.loggedPerson.id) {
this.loggedPerson = null;
await this.loadLoggedPersonIfNeeded(true);
}
await this.redirectIfNoIdentitySelected();
} catch (err) {
this.handleError(err);
}
}
async updateIdentity() {
try {
await this.$apollo.mutate({
mutation: UPDATE_PERSON,
variables: this.buildVariables(),
update: (store, { data: { updatePerson } }) => {
const data = store.readQuery<{ identities: IPerson[] }>({ query: IDENTITIES });
if (data) {
const index = data.identities.findIndex(i => i.id === this.identity.id);
this.$set(data.identities, index, updatePerson);
store.writeQuery({ query: IDENTITIES, data });
}
},
});
this.$notifier.success(
this.$gettextInterpolate('Identity %{displayName} updated', { displayName: this.identity.displayName() }),
);
} catch (err) {
this.handleError(err);
}
}
async createIdentity() {
try {
await this.$apollo.mutate({
mutation: CREATE_PERSON,
variables: this.buildVariables(),
update: (store, { data: { createPerson } }) => {
const data = store.readQuery<{ identities: IPerson[] }>({ query: IDENTITIES });
if (data) {
data.identities.push(createPerson);
store.writeQuery({ query: IDENTITIES, data });
}
},
});
this.$router.push({ name: RouteName.UPDATE_IDENTITY, params: { identityName: this.identity.preferredUsername } });
this.$notifier.success(
this.$gettextInterpolate('Identity %{displayName} created', { displayName: this.identity.displayName() }),
);
} catch (err) {
this.handleError(err);
}
}
getInstanceHost() {
return MOBILIZON_INSTANCE_HOST;
}
openDeleteIdentityConfirmation() {
this.$dialog.prompt({
type: 'is-danger',
title: this.$gettext('Delete your identity'),
message: this.$gettextInterpolate(
'To confirm, type your identity username "%{preferredUsername}"',
{ preferredUsername: this.identity.preferredUsername },
),
confirmText: this.$gettextInterpolate(
'Delete %{preferredUsername}',
{ preferredUsername: this.identity.preferredUsername },
),
inputAttrs: {
placeholder: this.identity.preferredUsername,
pattern: this.identity.preferredUsername,
},
onConfirm: () => this.deleteIdentity(),
});
}
private async getIdentity() {
const result = await this.$apollo.query({
query: FETCH_PERSON,
variables: {
name: this.identityName,
},
});
return new Person(result.data.person);
}
private async getAvatarFileFromIdentity(identity: IPerson) {
if (!identity.avatar) return null;
const response = await fetch(identity.avatar.url);
const blob = await response.blob();
return new File([blob], identity.avatar.name);
}
private handleError(err: any) {
console.error(err);
err.graphQLErrors.forEach(({ message }) => {
this.errors.push(message);
});
}
private convertToUsername(value: string | null) {
if (!value) return '';
return value.toLowerCase()
.replace(/ /g, '_')
.replace(/[^a-z0-9._]/g, '');
}
private buildVariables() {
let avatarObj = {};
if (this.avatarFile) {
avatarObj = {
avatar: {
picture: {
name: this.avatarFile.name,
alt: `${this.identity.preferredUsername}'s avatar`,
file: this.avatarFile,
},
},
};
}
return Object.assign({}, this.identity, avatarObj);
}
private async redirectIfNoIdentitySelected (identityParam?: string) {
if (!!identityParam) return;
await this.loadLoggedPersonIfNeeded();
if (!!this.loggedPerson) {
this.$router.push({ params: { identityName: this.loggedPerson.preferredUsername } });
}
}
private async loadLoggedPersonIfNeeded (bypassCache = false) {
if (this.loggedPerson) return;
const result = await this.$apollo.query({
query: LOGGED_PERSON,
fetchPolicy: bypassCache ? 'network-only' : undefined,
});
this.loggedPerson = result.data.loggedPerson;
}
private resetFields () {
this.identityName = undefined;
this.identity = new Person();
this.oldDisplayName = null;
this.avatarFile = null;
}
}
</script>

View file

@ -13,6 +13,7 @@
"sourceMap": true,
"skipLibCheck": true,
"baseUrl": ".",
"typeRoots": [ "node_modules/@types", "src/typings" ],
"types": [
"webpack-env",
"mocha",

View file

@ -4,6 +4,7 @@
"max-line-length": [ true, 140 ],
"import-name": false,
"ter-arrow-parens": false,
"no-boolean-literal-compare": false
"no-boolean-literal-compare": false,
"object-shorthand-properties-first": false
}
}

View file

@ -129,7 +129,7 @@ defmodule Mobilizon.Actors do
Enum.each([:avatar, :banner], fn key ->
if Map.has_key?(changes, key) do
with %Ecto.Changeset{changes: %{url: new_url}} <- changes[key],
old_url <- Map.from_struct(changeset.data) |> Map.get(key) |> Map.get(:url),
%{url: old_url} = _old_key <- Map.from_struct(changeset.data) |> Map.get(key),
false <- new_url == old_url do
MobilizonWeb.Upload.remove(old_url)
end
@ -155,13 +155,11 @@ defmodule Mobilizon.Actors do
def delete_actor(%Actor{domain: nil} = actor) do
case Multi.new()
|> Multi.delete(:actor, actor)
|> Multi.run(:remove_banner, fn _repo,
%{actor: %Actor{banner: %File{url: url}}} = _picture ->
MobilizonWeb.Upload.remove(url)
|> Multi.run(:remove_banner, fn _repo, %{actor: %Actor{}} = _picture ->
remove_banner(actor)
end)
|> Multi.run(:remove_avatar, fn _repo,
%{actor: %Actor{avatar: %File{url: url}}} = _picture ->
MobilizonWeb.Upload.remove(url)
|> Multi.run(:remove_avatar, fn _repo, %{actor: %Actor{}} = _picture ->
remove_avatar(actor)
end)
|> Repo.transaction() do
{:ok, %{actor: %Actor{} = actor}} ->
@ -989,4 +987,27 @@ defmodule Mobilizon.Actors do
def change_follower(%Follower{} = follower) do
Follower.changeset(follower, %{})
end
defp remove_banner(%Actor{banner: nil} = actor), do: {:ok, actor}
defp remove_banner(%Actor{banner: %File{url: url}} = actor) do
safe_remove_file(url, actor)
end
defp remove_avatar(%Actor{avatar: nil} = actor), do: {:ok, actor}
defp remove_avatar(%Actor{avatar: %File{url: url}} = actor) do
safe_remove_file(url, actor)
end
defp safe_remove_file(url, %Actor{} = actor) do
with {:ok, _value} <- MobilizonWeb.Upload.remove(url) do
{:ok, actor}
else
{:error, error} ->
Logger.error("Error while removing an upload file")
Logger.error(inspect(error))
{:ok, actor}
end
end
end

View file

@ -69,9 +69,80 @@ defmodule MobilizonWeb.Resolvers.Person do
{:error, "You need to be logged-in to create a new identity"}
end
@doc """
This function is used to update an existing identity
"""
def update_person(
_parent,
%{preferred_username: preferred_username} = args,
%{
context: %{
current_user: user
}
} = _resolution
) do
args = Map.put(args, :user_id, user.id)
with {:find_actor, %Actor{} = actor} <-
{:find_actor, Actors.get_actor_by_name(preferred_username)},
{:is_owned, true, _} <- User.owns_actor(user, actor.id),
args <- save_attached_pictures(args),
{:ok, actor} <- Actors.update_actor(actor, args) do
{:ok, actor}
else
{:find_actor, nil} ->
{:error, "Actor not found"}
{:is_owned, false} ->
{:error, "Actor is not owned by authenticated user"}
end
end
def update_person(_parent, _args, _resolution) do
{:error, "You need to be logged-in to update an identity"}
end
@doc """
This function is used to delete an existing identity
"""
def delete_person(
_parent,
%{preferred_username: preferred_username} = _args,
%{
context: %{
current_user: user
}
} = _resolution
) do
with {:find_actor, %Actor{} = actor} <-
{:find_actor, Actors.get_actor_by_name(preferred_username)},
{:is_owned, true, _} <- User.owns_actor(user, actor.id),
{:last_identity, false} <- {:last_identity, last_identity?(user)},
{:ok, actor} <- Actors.delete_actor(actor) do
{:ok, actor}
else
{:find_actor, nil} ->
{:error, "Actor not found"}
{:last_identity, true} ->
{:error, "Cannot remove the last identity of a user"}
{:is_owned, false} ->
{:error, "Actor is not owned by authenticated user"}
end
end
def delete_person(_parent, _args, _resolution) do
{:error, "You need to be logged-in to delete an identity"}
end
defp last_identity?(user) do
length(Users.get_actors_for_user(user)) <= 1
end
defp save_attached_pictures(args) do
Enum.reduce([:avatar, :banner], args, fn key, args ->
if Map.has_key?(args, key) do
if Map.has_key?(args, key) && !is_nil(args[key][:picture]) do
pic = args[key][:picture]
with {:ok, %{"name" => name, "url" => [%{"href" => url, "mediaType" => content_type}]}} <-

View file

@ -101,6 +101,34 @@ defmodule MobilizonWeb.Schema.Actors.PersonType do
resolve(handle_errors(&Person.create_person/3))
end
@desc "Update an identity"
field :update_person, :person do
arg(:preferred_username, non_null(:string))
arg(:name, :string, description: "The displayed name for this profile")
arg(:summary, :string, description: "The summary for this profile")
arg(:avatar, :picture_input,
description:
"The avatar for the profile, either as an object or directly the ID of an existing Picture"
)
arg(:banner, :picture_input,
description:
"The banner for the profile, either as an object or directly the ID of an existing Picture"
)
resolve(handle_errors(&Person.update_person/3))
end
@desc "Delete an identity"
field :delete_person, :person do
arg(:preferred_username, non_null(:string))
resolve(handle_errors(&Person.delete_person/3))
end
@desc "Register a first profile on registration"
field :register_person, :person do
arg(:preferred_username, non_null(:string))

View file

@ -213,6 +213,235 @@ defmodule MobilizonWeb.Resolvers.PersonResolverTest do
MobilizonWeb.Endpoint.url() <> "/media/"
end
test "update_person/3 updates an existing identity", context do
user = insert(:user)
insert(:actor, user: user, preferred_username: "riri")
mutation = """
mutation {
updatePerson(
preferredUsername: "riri",
name: "riri updated",
summary: "summary updated",
banner: {
picture: {
file: "landscape.jpg",
name: "irish landscape",
alt: "The beautiful atlantic way"
}
}
) {
id,
preferredUsername,
name,
summary,
avatar {
id,
url
},
banner {
id,
name,
url
}
}
}
"""
map = %{
"query" => mutation,
"landscape.jpg" => %Plug.Upload{
path: "test/fixtures/picture.png",
filename: "landscape.jpg"
}
}
res =
context.conn
|> put_req_header("content-type", "multipart/form-data")
|> post("/api", map)
assert json_response(res, 200)["data"]["updatePerson"] == nil
assert hd(json_response(res, 200)["errors"])["message"] ==
"You need to be logged-in to update an identity"
res =
context.conn
|> auth_conn(user)
|> put_req_header("content-type", "multipart/form-data")
|> post("/api", map)
res_person = json_response(res, 200)["data"]["updatePerson"]
assert res_person["preferredUsername"] == "riri"
assert res_person["name"] == "riri updated"
assert res_person["summary"] == "summary updated"
assert res_person["banner"]["id"]
assert res_person["banner"]["name"] == "The beautiful atlantic way"
assert res_person["banner"]["url"] =~ MobilizonWeb.Endpoint.url() <> "/media/"
end
test "update_person/3 should fail to update a not owned identity", context do
user1 = insert(:user)
user2 = insert(:user)
insert(:actor, user: user2, preferred_username: "riri")
mutation = """
mutation {
updatePerson(
preferredUsername: "riri",
name: "riri updated",
) {
id,
}
}
"""
res =
context.conn
|> auth_conn(user1)
|> post("/api", AbsintheHelpers.mutation_skeleton(mutation))
assert json_response(res, 200)["data"]["updatePerson"] == nil
assert hd(json_response(res, 200)["errors"])["message"] ==
"Actor is not owned by authenticated user"
end
test "update_person/3 should fail to update a not existing identity", context do
user = insert(:user)
insert(:actor, user: user, preferred_username: "riri")
mutation = """
mutation {
updatePerson(
preferredUsername: "not_existing",
name: "riri updated",
) {
id,
}
}
"""
res =
context.conn
|> auth_conn(user)
|> post("/api", AbsintheHelpers.mutation_skeleton(mutation))
assert json_response(res, 200)["data"]["updatePerson"] == nil
assert hd(json_response(res, 200)["errors"])["message"] ==
"Actor not found"
end
test "delete_person/3 should fail to update a not owned identity", context do
user1 = insert(:user)
user2 = insert(:user)
insert(:actor, user: user2, preferred_username: "riri")
mutation = """
mutation {
deletePerson(preferredUsername: "riri") {
id,
}
}
"""
res =
context.conn
|> auth_conn(user1)
|> post("/api", AbsintheHelpers.mutation_skeleton(mutation))
assert json_response(res, 200)["data"]["updatePerson"] == nil
assert hd(json_response(res, 200)["errors"])["message"] ==
"Actor is not owned by authenticated user"
end
test "delete_person/3 should fail to delete a not existing identity", context do
user = insert(:user)
insert(:actor, user: user, preferred_username: "riri")
mutation = """
mutation {
deletePerson(preferredUsername: "fifi") {
id,
}
}
"""
res =
context.conn
|> auth_conn(user)
|> post("/api", AbsintheHelpers.mutation_skeleton(mutation))
assert json_response(res, 200)["data"]["updatePerson"] == nil
assert hd(json_response(res, 200)["errors"])["message"] ==
"Actor not found"
end
test "delete_person/3 should fail to delete the last user identity", context do
user = insert(:user)
insert(:actor, user: user, preferred_username: "riri")
mutation = """
mutation {
deletePerson(preferredUsername: "riri") {
id,
}
}
"""
res =
context.conn
|> auth_conn(user)
|> post("/api", AbsintheHelpers.mutation_skeleton(mutation))
assert json_response(res, 200)["data"]["updatePerson"] == nil
assert hd(json_response(res, 200)["errors"])["message"] ==
"Cannot remove the last identity of a user"
end
test "delete_person/3 should delete a user identity", context do
user = insert(:user)
insert(:actor, user: user, preferred_username: "riri")
insert(:actor, user: user, preferred_username: "fifi")
mutation = """
mutation {
deletePerson(preferredUsername: "riri") {
id,
}
}
"""
res =
context.conn
|> auth_conn(user)
|> post("/api", AbsintheHelpers.mutation_skeleton(mutation))
assert json_response(res, 200)["errors"] == nil
query = """
{
person(preferredUsername: "riri") {
id,
}
}
"""
res =
context.conn
|> auth_conn(user)
|> get("/api", AbsintheHelpers.query_skeleton(query, "person"))
assert hd(json_response(res, 200)["errors"])["message"] == "Person with name riri not found"
end
test "get_current_person/3 can return the events the person is going to", context do
user = insert(:user)
actor = insert(:actor, user: user)