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 # Settings
MOBILIZON_INSTANCE_NAME="<%= instance_name %>" MOBILIZON_INSTANCE_NAME="<%= instance_name %>"
MOBILIZON_INSTANCE_HOST="<%= instance_domain %>" MOBILIZON_INSTANCE_HOST="<%= instance_domain %>"
MOBILIZON_INSTANCE_PORT=4002
MOBILIZON_INSTANCE_EMAIL="<%= instance_email %>" MOBILIZON_INSTANCE_EMAIL="<%= instance_email %>"
MOBILIZON_INSTANCE_REGISTRATIONS_OPEN=true MOBILIZON_INSTANCE_REGISTRATIONS_OPEN=true
@ -10,7 +11,6 @@ GRAPHQL_API_FULL_PATH=""
# APP # APP
MIX_ENV=prod MIX_ENV=prod
MOBILIZON_INSTANCE_PORT=4002
MOBILIZON_LOGLEVEL="info" MOBILIZON_LOGLEVEL="info"
MOBILIZON_SECRET="<%= instance_secret %>" MOBILIZON_SECRET="<%= instance_secret %>"

View File

@ -81,18 +81,20 @@ export default class App extends Vue {
@import "~bulma/sass/elements/other.sass"; @import "~bulma/sass/elements/other.sass";
@import "~bulma/sass/elements/tag.sass"; @import "~bulma/sass/elements/tag.sass";
@import "~bulma/sass/elements/title.sass"; @import "~bulma/sass/elements/title.sass";
@import "~bulma/sass/elements/notification";
@import "~bulma/sass/grid/_all.sass"; @import "~bulma/sass/grid/_all.sass";
@import "~bulma/sass/layout/_all.sass"; @import "~bulma/sass/layout/_all.sass";
@import "~bulma/sass/utilities/_all"; @import "~bulma/sass/utilities/_all";
/* Buefy imports */ /* Buefy imports */
@import "~buefy/src/scss/utils/_all";
@import "~buefy/src/scss/components/datepicker"; @import "~buefy/src/scss/components/datepicker";
@import "~buefy/src/scss/components/notices";
@import "~buefy/src/scss/components/dropdown"; @import "~buefy/src/scss/components/dropdown";
@import "~buefy/src/scss/components/form"; @import "~buefy/src/scss/components/form";
@import "~buefy/src/scss/components/modal"; @import "~buefy/src/scss/components/modal";
@import "~buefy/src/scss/components/tag"; @import "~buefy/src/scss/components/tag";
@import "~buefy/src/scss/components/upload"; @import "~buefy/src/scss/components/upload";
@import "~buefy/src/scss/utils/_all";
.router-enter-active, .router-enter-active,
.router-leave-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"> <ul class="identities">
<li v-for="identity in identities" :key="identity.id"> <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"> <div class="media-left">
<figure class="image is-48x48" v-if="identity.avatar"> <figure class="image is-48x48" v-if="identity.avatar">
<img class="is-rounded" :src="identity.avatar.url"> <img class="is-rounded" :src="identity.avatar.url">
@ -16,13 +19,13 @@
<div class="media-content"> <div class="media-content">
{{ identity.displayName() }} {{ identity.displayName() }}
</div> </div>
</div> </router-link>
</li> </li>
</ul> </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> <translate>Create a new identity</translate>
</a> </router-link>
</section> </section>
</template> </template>
@ -38,6 +41,7 @@
font-size: 1.3rem; font-size: 1.3rem;
padding-bottom: 0; padding-bottom: 0;
margin-bottom: 15px; margin-bottom: 15px;
color: #000;
&.is-current-identity { &.is-current-identity {
background-color: rgba(0, 0, 0, 0.1); background-color: rgba(0, 0, 0, 0.1);
@ -50,33 +54,29 @@
</style> </style>
<script lang="ts"> <script lang="ts">
import { Component, Vue } from 'vue-property-decorator'; import { Component, Prop, Vue } from 'vue-property-decorator';
import { IDENTITIES, LOGGED_PERSON } from '@/graphql/actor'; import { IDENTITIES, LOGGED_PERSON } from '@/graphql/actor';
import { IPerson, Person } from '@/types/actor'; import { IPerson, Person } from '@/types/actor';
@Component({ @Component({
apollo: { apollo: {
loggedPerson: { identities: {
query: LOGGED_PERSON, query: IDENTITIES,
update (result) {
return result.identities.map(i => new Person(i));
}, },
}, },
}) },
export default class Identities extends Vue { })
identities: Person[] = []; export default class Identities extends Vue {
loggedPerson!: IPerson; @Prop({ type: String }) currentIdentityName!: string;
errors: string[] = [];
async mounted() { identities: Person[] = [];
const result = await this.$apollo.query({ errors: string[] = [];
query: IDENTITIES,
});
this.identities = result.data.identities isCurrentIdentity(identity: IPerson) {
.map(i => new Person(i)); return identity.preferredUsername === this.currentIdentityName;
}
isCurrentIdentity(identity: IPerson) {
return identity.preferredUsername === this.loggedPerson.preferredUsername;
}
} }
}
</script> </script>

View File

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

View File

@ -1,29 +1,64 @@
<template> <template>
<b-field class="file"> <div class="root">
<b-upload v-model="pictureFile" @input="onFileChanged"> <figure class="image is-128x128">
<a class="button is-primary"> <img class="is-rounded" v-bind:src="imageSrc">
<b-icon icon="upload"></b-icon> <div class="image-placeholder" v-if="!imageSrc"></div>
<span>Click to upload</span> </figure>
</a>
</b-upload> <b-upload @input="onFileChanged">
<span class="file-name" v-if="pictureFile"> <a class="button is-primary">
{{ pictureFile.name }} <b-icon icon="upload"></b-icon>
</span> <span>Click to upload</span>
</b-field> </a>
</b-upload>
</div>
</template> </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"> <script lang="ts">
import { Component, Vue } from 'vue-property-decorator'; import { Component, Model, Vue, Watch } from 'vue-property-decorator';
import { IPictureUpload } from '@/types/picture.model';
@Component @Component
export default class PictureUpload extends Vue { export default class PictureUpload extends Vue {
picture!: IPictureUpload; @Model('change', { type: File }) readonly pictureFile!: File;
pictureFile: File|null = null;
imageSrc: string | null = null;
@Watch('pictureFile')
onPictureFileChanged (val: File) {
this.updatePreview(val);
}
onFileChanged(file: File) { onFileChanged(file: File) {
this.picture = { file, name: file.name, alt: '' }; this.$emit('change', file);
this.$emit('change', this.picture);
this.updatePreview(file);
}
private updatePreview(file?: File) {
if (file) {
this.imageSrc = URL.createObjectURL(file);
return;
}
this.imageSrc = null;
} }
} }
</script> </script>

View File

@ -11,6 +11,7 @@ query($name:String!) {
preferredUsername, preferredUsername,
suspended, suspended,
avatar { avatar {
name,
url url
}, },
banner { banner {
@ -64,6 +65,7 @@ query {
export const IDENTITIES = gql` export const IDENTITIES = gql`
query { query {
identities { identities {
id,
avatar { avatar {
url url
}, },
@ -73,22 +75,51 @@ query {
}`; }`;
export const CREATE_PERSON = gql` export const CREATE_PERSON = gql`
mutation CreatePerson($preferredUsername: String!) { mutation CreatePerson($preferredUsername: String!, $name: String!, $summary: String, $avatar: PictureInput) {
createPerson( createPerson(
preferredUsername: $preferredUsername, preferredUsername: $preferredUsername,
name: $name, name: $name,
summary: $summary summary: $summary,
avatar: $avatar
) { ) {
id,
preferredUsername, preferredUsername,
name, name,
summary, summary,
avatar { avatar {
url 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 * 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 App from '@/App.vue';
import router from '@/router'; import router from '@/router';
import { apolloProvider } from './vue-apollo'; import { apolloProvider } from './vue-apollo';
import { NotifierPlugin } from '@/plugins/notifier';
const translations = require('@/i18n/translations.json'); const translations = require('@/i18n/translations.json');
Vue.config.productionTip = false; Vue.config.productionTip = false;
Vue.use(Buefy, { Vue.use(Buefy);
defaultContainerElement: '#mobilizon', Vue.use(NotifierPlugin);
});
const language = (window.navigator as any).userLanguage || window.navigator.language; 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 Group from '@/views/Group/Group.vue';
import GroupList from '@/views/Group/GroupList.vue'; import GroupList from '@/views/Group/GroupList.vue';
import { RouteConfig } from 'vue-router'; import { RouteConfig } from 'vue-router';
import EditIdentity from '@/views/Account/children/EditIdentity.vue';
export enum ActorRouteName { export enum ActorRouteName {
GROUP_LIST = 'GroupList', GROUP_LIST = 'GroupList',
GROUP = 'Group', GROUP = 'Group',
CREATE_GROUP = 'CreateGroup', CREATE_GROUP = 'CreateGroup',
PROFILE = 'Profile', PROFILE = 'Profile',
MY_ACCOUNT = 'MyAccount', }
export enum MyAccountRouteName {
CREATE_IDENTITY = 'CreateIdentity',
UPDATE_IDENTITY = 'UpdateIdentity',
} }
export const actorRoutes: RouteConfig[] = [ export const actorRoutes: RouteConfig[] = [
@ -41,10 +46,23 @@ export const actorRoutes: RouteConfig[] = [
meta: { requiredAuth: false }, meta: { requiredAuth: false },
}, },
{ {
path: '/my-account', path: '/my-account/identity',
name: ActorRouteName.MY_ACCOUNT,
component: MyAccount, component: MyAccount,
props: true, props: true,
meta: { requiredAuth: 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 Home from '@/views/Home.vue';
import { UserRouteName, userRoutes } from './user'; import { UserRouteName, userRoutes } from './user';
import { EventRouteName, eventRoutes } from '@/router/event'; 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 { ErrorRouteName, errorRoutes } from '@/router/error';
import { authGuardIfNeeded } from '@/router/guards/auth-guard'; import { authGuardIfNeeded } from '@/router/guards/auth-guard';
import Search from '@/views/Search.vue'; import Search from '@/views/Search.vue';
@ -34,6 +34,7 @@ export const RouteName = {
...UserRouteName, ...UserRouteName,
...EventRouteName, ...EventRouteName,
...ActorRouteName, ...ActorRouteName,
...MyAccountRouteName,
...ErrorRouteName, ...ErrorRouteName,
}; };

View File

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

View File

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

View File

@ -1,15 +1,18 @@
<template> <template>
<section class="container"> <section class="container">
<div v-if="person"> <div v-if="loggedPerson">
<div class="header"> <div class="header">
<figure v-if="person.banner" class="image is-3by1"> <figure v-if="loggedPerson.banner" class="image is-3by1">
<img :src="person.banner.url" alt="banner"> <img :src="loggedPerson.banner.url" alt="banner">
</figure> </figure>
</div> </div>
<div class="columns"> <div class="columns">
<div class="identities column is-4"> <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> </div>
</div> </div>
@ -29,35 +32,46 @@
<script lang="ts"> <script lang="ts">
import { LOGGED_PERSON } from '@/graphql/actor'; 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 EventCard from '@/components/Event/EventCard.vue';
import { IPerson } from '@/types/actor'; import { IPerson } from '@/types/actor';
import { CURRENT_USER_CLIENT } from '@/graphql/user';
import Identities from '@/components/Account/Identities.vue'; import Identities from '@/components/Account/Identities.vue';
@Component({ @Component({
apollo: {
currentUser: {
query: CURRENT_USER_CLIENT,
},
loggedPerson: {
query: LOGGED_PERSON,
},
},
components: { components: {
EventCard, EventCard,
Identities, Identities,
}, },
}) })
export default class MyAccount extends Vue { 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({ const result = await this.$apollo.query({
query: LOGGED_PERSON, query: LOGGED_PERSON,
}); });
this.person = result.data.loggedPerson; return result.data.loggedPerson as IPerson;
} }
} }
</script> </script>

View File

@ -87,7 +87,6 @@ export default class Register extends Vue {
preferredUsername: '', preferredUsername: '',
name: '', name: '',
summary: '', summary: '',
id: '',
url: '', url: '',
suspended: false, suspended: false,
avatar: null, 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, "sourceMap": true,
"skipLibCheck": true, "skipLibCheck": true,
"baseUrl": ".", "baseUrl": ".",
"typeRoots": [ "node_modules/@types", "src/typings" ],
"types": [ "types": [
"webpack-env", "webpack-env",
"mocha", "mocha",

View File

@ -4,6 +4,7 @@
"max-line-length": [ true, 140 ], "max-line-length": [ true, 140 ],
"import-name": false, "import-name": false,
"ter-arrow-parens": 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 -> Enum.each([:avatar, :banner], fn key ->
if Map.has_key?(changes, key) do if Map.has_key?(changes, key) do
with %Ecto.Changeset{changes: %{url: new_url}} <- changes[key], 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 false <- new_url == old_url do
MobilizonWeb.Upload.remove(old_url) MobilizonWeb.Upload.remove(old_url)
end end
@ -155,13 +155,11 @@ defmodule Mobilizon.Actors do
def delete_actor(%Actor{domain: nil} = actor) do def delete_actor(%Actor{domain: nil} = actor) do
case Multi.new() case Multi.new()
|> Multi.delete(:actor, actor) |> Multi.delete(:actor, actor)
|> Multi.run(:remove_banner, fn _repo, |> Multi.run(:remove_banner, fn _repo, %{actor: %Actor{}} = _picture ->
%{actor: %Actor{banner: %File{url: url}}} = _picture -> remove_banner(actor)
MobilizonWeb.Upload.remove(url)
end) end)
|> Multi.run(:remove_avatar, fn _repo, |> Multi.run(:remove_avatar, fn _repo, %{actor: %Actor{}} = _picture ->
%{actor: %Actor{avatar: %File{url: url}}} = _picture -> remove_avatar(actor)
MobilizonWeb.Upload.remove(url)
end) end)
|> Repo.transaction() do |> Repo.transaction() do
{:ok, %{actor: %Actor{} = actor}} -> {:ok, %{actor: %Actor{} = actor}} ->
@ -989,4 +987,27 @@ defmodule Mobilizon.Actors do
def change_follower(%Follower{} = follower) do def change_follower(%Follower{} = follower) do
Follower.changeset(follower, %{}) Follower.changeset(follower, %{})
end 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 end

View File

@ -69,9 +69,80 @@ defmodule MobilizonWeb.Resolvers.Person do
{:error, "You need to be logged-in to create a new identity"} {:error, "You need to be logged-in to create a new identity"}
end 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 defp save_attached_pictures(args) do
Enum.reduce([:avatar, :banner], args, fn key, args -> 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] pic = args[key][:picture]
with {:ok, %{"name" => name, "url" => [%{"href" => url, "mediaType" => content_type}]}} <- 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)) resolve(handle_errors(&Person.create_person/3))
end 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" @desc "Register a first profile on registration"
field :register_person, :person do field :register_person, :person do
arg(:preferred_username, non_null(:string)) arg(:preferred_username, non_null(:string))

View File

@ -213,6 +213,235 @@ defmodule MobilizonWeb.Resolvers.PersonResolverTest do
MobilizonWeb.Endpoint.url() <> "/media/" MobilizonWeb.Endpoint.url() <> "/media/"
end 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 test "get_current_person/3 can return the events the person is going to", context do
user = insert(:user) user = insert(:user)
actor = insert(:actor, user: user) actor = insert(:actor, user: user)