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
22 changed files with 927 additions and 157 deletions

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>