diff --git a/components/Account.vue b/components/Account.vue index 8479d351..85a83b31 100644 --- a/components/Account.vue +++ b/components/Account.vue @@ -70,7 +70,7 @@

- {{message}} + {{message}}

@@ -192,6 +192,7 @@ email: this.$user().email, message: '', + messageParams: {}, messageIcon: null, error: '', changeEmailAuthId: null, @@ -254,6 +255,7 @@ this.username = this.$user().username; this.$cookies.set('token', this.$store.state.token, cookieSettings); this.message = 'crud.saved'; + this.messageParams = {}; this.messageIcon = 'check-circle'; setTimeout(() => this.message = '', 3000); } finally { @@ -281,6 +283,7 @@ if (!this.changeEmailAuthId) { this.changeEmailAuthId = response.authId; this.message = 'user.login.emailSent'; + this.messageParams = {'email': this.addBrackets(this.email)}; this.messageIcon = 'envelope-open-text'; this.$nextTick(_ => { this.$refs.code.focus(); @@ -288,11 +291,13 @@ } else { this.changeEmailAuthId = null; this.message = ''; + this.messageParams = {}; this.code = null; this.$store.commit('setToken', response.token); this.$cookies.set('token', this.$store.state.token, cookieSettings); this.message = 'crud.saved'; + this.messageParams = {}; this.messageIcon = 'check-circle'; setTimeout(() => this.message = '', 3000); } @@ -336,6 +341,9 @@ this.$cookies.set('termsUpdateDismissed', true); this.showTermsUpdate = false; }, + addBrackets(str) { + return str ? `(${str})` : ''; + }, }, computed: { ...mapState([ diff --git a/components/Login.vue b/components/Login.vue index 1c32e907..ef3f9b17 100644 --- a/components/Login.vue +++ b/components/Login.vue @@ -41,7 +41,7 @@

- user.login.emailSent + user.login.emailSent

@@ -171,6 +171,12 @@ } }) }, + getEmail(payload) { + return payload.email || payload.emailObfuscated || ''; + }, + addBrackets(str) { + return str ? `(${str})` : ''; + }, }, } diff --git a/locale/_base/translations.suml b/locale/_base/translations.suml index 363985dc..ee61b826 100644 --- a/locale/_base/translations.suml +++ b/locale/_base/translations.suml @@ -487,7 +487,7 @@ user: help: 'To log in or create an account you can either use the social media buttons or enter your email in the field below and then confirm the code you will have received in your mailbox.' placeholder: 'Email (or username, if you''re already registered)' action: 'Log in / register' - emailSent: 'We''ve sent you an email with a 6-digit code. Enter it here. The code is single-use and stays valid for 15 minutes.' + emailSent: 'We''ve sent you %email% an email with a 6-digit code. Enter it here. The code is single-use and stays valid for 15 minutes.' userNotFound: 'User not found.' email: subject: 'Your login code is {{code}}' diff --git a/locale/de/translations.suml b/locale/de/translations.suml index a181f6b6..e1e2b97a 100644 --- a/locale/de/translations.suml +++ b/locale/de/translations.suml @@ -411,7 +411,7 @@ user: help: 'Um sich anzumelden oder ein Konto zu erstellen, kannst du entweder die Schaltflächen in den sozialen Medien verwenden oder deine E-Mail-Adresse in das unten stehende Feld eingeben und dann den Code bestätigen, den du in deiner Mailbox erhalten hast.' placeholder: 'E-Mail (oder Username, falls du schon registriert bist)' action: 'Anmelden / Registrieren' - emailSent: 'Wir haben dir eine E-Mail mit einem 6-stelligen Code geschickt. Gib ihn hier ein. Der Code ist einmalig verwendbar und bleibt 15 Minuten lang gültig.' + emailSent: 'Wir haben dir %email% eine E-Mail mit einem 6-stelligen Code geschickt. Gib ihn hier ein. Der Code ist einmalig verwendbar und bleibt 15 Minuten lang gültig.' userNotFound: 'Nutzer*in nicht gefunden.' email: subject: 'Dein Logincode ist {{code}}' diff --git a/locale/en/translations.suml b/locale/en/translations.suml index 04438dd9..888d4adb 100644 --- a/locale/en/translations.suml +++ b/locale/en/translations.suml @@ -511,7 +511,7 @@ user: help: 'To log in or create an account you can either use the social media buttons or enter your email in the field below and then confirm the code you will have received in your mailbox.' placeholder: 'Email (or username, if you''re already registered)' action: 'Log in / register' - emailSent: 'We''ve sent you an email with a 6-digit code. Enter it here. The code is single-use and stays valid for 15 minutes.' + emailSent: 'We''ve sent you %email% an email with a 6-digit code. Enter it here. The code is single-use and stays valid for 15 minutes.' userNotFound: 'User not found.' email: subject: 'Your login code is {{code}}' diff --git a/locale/eo/translations.suml b/locale/eo/translations.suml index 73a7a34b..072ec40a 100644 --- a/locale/eo/translations.suml +++ b/locale/eo/translations.suml @@ -472,7 +472,7 @@ user: help: 'To log in or create an account you can either use the social media buttons or enter your email in the field below and then confirm the code you will have received in your mailbox.' placeholder: 'Email (or username, if you''re already registered)' action: 'Ensaluti' - emailSent: 'We''ve sent you an email with a 6-digit code. Enter it here. The code is single-use and stays valid for 15 minutes.' + emailSent: 'We''ve sent you %email% an email with a 6-digit code. Enter it here. The code is single-use and stays valid for 15 minutes.' userNotFound: 'Konto ne trovita.' email: subject: 'Your login code is {{code}}' diff --git a/locale/es/translations.suml b/locale/es/translations.suml index a617b641..2f8760cd 100644 --- a/locale/es/translations.suml +++ b/locale/es/translations.suml @@ -496,7 +496,7 @@ user: help: 'Para iniciar sesión o crear una cuenta puedes usar los botones de medios sociales o ingresar tu dirección de correo electronico en el campo de abajo y luego confirmar el código que vas a recibir en tu buzón.' placeholder: 'Correo electrónico (o nombre de usuarie, si ya estás registrade)' action: 'Iniciar sesión / registrarte' - emailSent: 'Te hemos enviado un correo electrónico con un código de 6 dígitos. Introdúcelo aquí. El código es de un solo uso y es válido por 15 minutos.' + emailSent: 'Te hemos enviado un correo electrónico %email% con un código de 6 dígitos. Introdúcelo aquí. El código es de un solo uso y es válido por 15 minutos.' userNotFound: 'Usuarie no encontrade.' email: subject: 'Tu código de inicio de sesión es {{code}}' diff --git a/locale/fr/translations.suml b/locale/fr/translations.suml index 806b7067..2802b53d 100644 --- a/locale/fr/translations.suml +++ b/locale/fr/translations.suml @@ -414,7 +414,7 @@ user: help: 'Pour vous connecter ou créer un compte vous pouvez soit utiliser les options de connexion de réseaux sociaux, soit utiliser votre adresse mail dans le formulaire ci-dessous, puis confirmer avec le code que vous recevrez dans votre boîte mail.' placeholder: 'Adresse mail(ou nom d’utilisateur si vous êtes déjà inscrit)' action: 'Se connecter / S''inscrire' - emailSent: 'Nous vous avons envoyé un mail avec un code à 6 chiffres. Entrez-le ici. Ce code est à usage unique et reste utilisable pendant 15 minutes.' + emailSent: 'Nous vous %email% avons envoyé un mail avec un code à 6 chiffres. Entrez-le ici. Ce code est à usage unique et reste utilisable pendant 15 minutes.' userNotFound: 'Cet utilisateur n’existe pas.' email: subject: 'Votre code de connexion est {{code}}' diff --git a/locale/gl/translations.suml b/locale/gl/translations.suml index 49b0db79..e7a53711 100644 --- a/locale/gl/translations.suml +++ b/locale/gl/translations.suml @@ -395,7 +395,7 @@ user: # help: 'To log in or create an account you can either use the social media buttons or enter your email in the field below and then confirm the code you will have received in your mailbox.' placeholder: 'E-mail (ou nome de usuarie, se já está registrade)' action: 'Iniciar sessão' # TODO 'Log in / register' - emailSent: 'Te enviamos um email com um código de 6 dígitos. Digite aqui. O código é pode ser usado apenas uma vez e é válido por 15 minutos.' + emailSent: 'Te enviamos um email %email% com um código de 6 dígitos. Digite aqui. O código é pode ser usado apenas uma vez e é válido por 15 minutos.' userNotFound: 'Usuarie não encontrade.' email: subject: 'O código de início da sessão é {{code}}' diff --git a/locale/it/translations.suml b/locale/it/translations.suml index 110b7987..22f07175 100644 --- a/locale/it/translations.suml +++ b/locale/it/translations.suml @@ -488,7 +488,7 @@ user: help: 'To log in or create an account you can either use the social media buttons or enter your email in the field below and then confirm the code you will have received in your mailbox.' placeholder: 'Email (or username, if you''re already registered)' action: 'Log in / register' - emailSent: 'We''ve sent you an email with a 6-digit code. Enter it here. The code is single-use and stays valid for 15 minutes.' + emailSent: 'We''ve sent you %email% an email with a 6-digit code. Enter it here. The code is single-use and stays valid for 15 minutes.' userNotFound: 'User not found.' email: subject: 'Your login code is {{code}}' diff --git a/locale/lad/translations.suml b/locale/lad/translations.suml index 213f48a1..3fca1c47 100644 --- a/locale/lad/translations.suml +++ b/locale/lad/translations.suml @@ -390,7 +390,7 @@ user: help: 'Para konektarte o krear un kuento puedes uzar los botones de redes sosyalas o eskrivir tu adreso de posta elektronika en el kampo abasho i entonses konfirmar el kodiche ke vas resibir en tu posta.' placeholder: 'Posta elektronika (o nombre de uzadore, si ya estas rejistrade)' action: 'Konektarte / rejistrarte' - emailSent: 'Te tenemos embiado una posta elektronika kon un kodiche de 6 dijitos. Introduzelo aki. El kodiche es de un solo uzo i es balido por 15 minutos.' + emailSent: 'Te tenemos embiado una posta elektronika %email% kon un kodiche de 6 dijitos. Introduzelo aki. El kodiche es de un solo uzo i es balido por 15 minutos.' userNotFound: 'Uzadore no topade.' email: subject: 'Tu kodiche de koneksion kon tu kuento es %code%' diff --git a/locale/nl/translations.suml b/locale/nl/translations.suml index 2c7a5538..96e4be17 100644 --- a/locale/nl/translations.suml +++ b/locale/nl/translations.suml @@ -386,7 +386,7 @@ user: help: 'Om in te loggen of te registreren kun je de social media buttons gebruiken, of jouw emailadres in het onderstaande veld invoeren, en vervolgens de code bevestigen die naar jouw mailbox wordt verstuurd.' placeholder: 'Email (of gebruikersnaam, als je al bent geregistreerd)' action: 'Inloggen / registreren' - emailSent: 'We hebben een email verstuurd met een code bestaande uit 6 getallen. Voer deze code hier in. De code is voor eenmalig gebruik en vervalt na 15 minuten.' + emailSent: 'We hebben een email verstuurd %email% met een code bestaande uit 6 getallen. Voer deze code hier in. De code is voor eenmalig gebruik en vervalt na 15 minuten.' userNotFound: 'Gebruiker niet gevonden.' email: subject: 'Jouw logincode is {{code}}' diff --git a/locale/no/translations.suml b/locale/no/translations.suml index cbbac48c..f79a7e70 100644 --- a/locale/no/translations.suml +++ b/locale/no/translations.suml @@ -391,7 +391,7 @@ user: # help: 'To log in or create an account you can either use the social media buttons or enter your email in the field below and then confirm the code you will have received in your mailbox.' placeholder: 'Email (eller brukernavn, hvis du allerede er registrert)' action: 'Logg inn' # TODO 'Log in / register' - emailSent: 'Vi har sendt deg en email med en 6 sifret kode. Skriv den ned her. Koden er en engangskode og kan brukes i 15 minutter.' + emailSent: 'Vi har sendt deg en email %email% med en 6 sifret kode. Skriv den ned her. Koden er en engangskode og kan brukes i 15 minutter.' userNotFound: 'Bruker ikke funnet.' email: subject: 'Din Logg inn kode er {{code}}' diff --git a/locale/pl/translations.suml b/locale/pl/translations.suml index 67ebc328..5fa9e2df 100644 --- a/locale/pl/translations.suml +++ b/locale/pl/translations.suml @@ -1186,7 +1186,7 @@ user: help: 'Aby zalogować się lub założyć konto, użyj opcji logowania za pomocą mediów społecznościowych lub wpisz swój email w polu poniżej, a następnie potwierdź kod, który otrzymasz na swoją skrzynkę.' placeholder: 'Email (lub nazwa użytkownicza, jeśli już posiadasz konto)' action: 'Zaloguj / załóż konto' - emailSent: 'Na Twój adres wysłałośmy email z sześciocyfrowym kodem. Wpisz go poniżej. Kod jest jednorazowy i ważny przez 15 minut.' + emailSent: 'Na Twój adres %email% wysłałośmy email z sześciocyfrowym kodem. Wpisz go poniżej. Kod jest jednorazowy i ważny przez 15 minut.' userNotFound: 'Konto nie zostało znalezione.' email: subject: 'Twój kod logowania to {{code}}' diff --git a/locale/pt/translations.suml b/locale/pt/translations.suml index 2707912e..fe3382d7 100644 --- a/locale/pt/translations.suml +++ b/locale/pt/translations.suml @@ -417,7 +417,7 @@ user: help: 'Iniciar sessão ou criar uma conta você pode usar os botões de redes sociais ou insirar seu endereço de e-mail no campo abaixo e confirme o código que você receberá em sua caixa de correio.' placeholder: 'E-mail (ou nome de usuarie, se já está registrade)' action: 'Iniciar sessão / registre-se' - emailSent: 'Te enviamos um email com um código de 6 dígitos. Digite aqui. O código é pode ser usado apenas uma vez e é válido por 15 minutos.' + emailSent: 'Te enviamos um email %email% com um código de 6 dígitos. Digite aqui. O código é pode ser usado apenas uma vez e é válido por 15 minutos.' userNotFound: 'Usuarie não encontrade.' email: subject: 'O código de início da sessão é {{code}}' diff --git a/locale/ru/translations.suml b/locale/ru/translations.suml index 1f9510b1..9642c176 100644 --- a/locale/ru/translations.suml +++ b/locale/ru/translations.suml @@ -508,7 +508,7 @@ user: help: 'Чтобы войти или зарегистрировать аккаунт, вам нужно либо привязать его к социальным сетям, либо ввести адрес электронной почты в соответствующее поле, дождаться письма с кодом и подтвердить аккаунт.' placeholder: 'Адрес электронной почты (или имя пользовател_ьницы, если вы уже зарегистрированы)' action: 'Войти / зарегистрироваться' - emailSent: 'Мы отправили на указанную вами почту письмо с шестизначным кодом. Пожалуйста, введите его сюда. Код одноразовый и работает в течение 15-ти минут.' + emailSent: 'Мы отправили на указанную вами почту %email% письмо с шестизначным кодом. Пожалуйста, введите его сюда. Код одноразовый и работает в течение 15-ти минут.' userNotFound: 'Пользователь не найден.' email: subject: 'Ваш код для авторизации: {{code}}' diff --git a/locale/sv/translations.suml b/locale/sv/translations.suml index 0ca6c5d8..a7ff0ff8 100644 --- a/locale/sv/translations.suml +++ b/locale/sv/translations.suml @@ -466,7 +466,7 @@ user: help: 'För att logga in eller skapa ett konto kan du använda dina sociala medier eller skriva in din e-postadress och bekräfta koden du ska ha fått i din e-post inkorg.' placeholder: 'E-postadress (eller användarnamn, om du redan är registrerad)' action: 'Logga in' - emailSent: 'Vi har skickat ett e-postmeddelande till dig med en 6-siffrig kod. Ange den här. Koden är för engångsbruk och är giltig i 15 minuter.' + emailSent: 'Vi har skickat ett e-postmeddelande %email% till dig med en 6-siffrig kod. Ange den här. Koden är för engångsbruk och är giltig i 15 minuter.' userNotFound: 'Användaren hittades inte.' email: subject: 'Din inloggningskod är %code%' diff --git a/locale/yi/translations.suml b/locale/yi/translations.suml index 504a40c8..371a3b0b 100644 --- a/locale/yi/translations.suml +++ b/locale/yi/translations.suml @@ -385,7 +385,7 @@ user: # help: 'To log in or create an account you can either use the social media buttons or enter your email in the field below and then confirm the code you will have received in your mailbox.' placeholder: 'Email (or username, if you''re already registered)' action: 'Log in' # TODO 'Log in / register' - emailSent: 'We''ve sent you an email with a 6-digit code. Enter it here. The code is single-use and stays valid for 15 minutes.' + emailSent: 'We''ve sent you %email% an email with a 6-digit code. Enter it here. The code is single-use and stays valid for 15 minutes.' userNotFound: 'User not found.' email: subject: 'Your login code is {{code}}' diff --git a/server/routes/user.js b/server/routes/user.js index cb8560e8..b9b00869 100644 --- a/server/routes/user.js +++ b/server/routes/user.js @@ -1,7 +1,7 @@ import { Router } from 'express'; import SQL from 'sql-template-strings'; import {ulid} from "ulid"; -import {buildDict, makeId, now, handleErrorAsync} from "../../src/helpers"; +import {buildDict, makeId, now, handleErrorAsync, obfuscateEmail} from "../../src/helpers"; import jwt from "../../src/jwt"; import mailer from "../../src/mailer"; import { loadSuml } from '../loader'; @@ -125,7 +125,10 @@ const defaultUsername = async (db, email) => { } const fetchOrCreateUser = async (db, user, avatarSource = 'gravatar') => { - let dbUser = await db.get(SQL`SELECT * FROM users WHERE email = ${normalise(user.email)}`); + let dbUser = user.email + ? await db.get(SQL`SELECT * FROM users WHERE email = ${normalise(user.email)}`) + : await db.get(SQL`SELECT * FROM users WHERE usernameNorm = ${normalise(user.username)}`) + if (!dbUser) { dbUser = { id: ulid(), @@ -308,7 +311,16 @@ router.post('/user/init', handleErrorAsync(async (req, res) => { } return res.json({ - token: jwt.sign({...payload, code: null, codeKey}, '15m'), + token: jwt.sign( + { + ...payload, + email: isEmail ? payload.email : null, + emailObfuscated: obfuscateEmail(payload.email), + code: null, + codeKey, + }, + '15m', + ), }); })); diff --git a/src/helpers.js b/src/helpers.js index 1238484c..e2ec6e92 100644 --- a/src/helpers.js +++ b/src/helpers.js @@ -259,3 +259,16 @@ export class ImmutableArray extends Array { return this.length > index ? this[index] : fallback; } } + +export const obfuscateEmail = (email) => { + const [ username, hostname ] = email.toLowerCase().split('@'); + const tld = hostname.split('.').slice(-1).pop(); + + if (tld === 'oauth') { + return null; + } + + const usernamePublic = username.substring(0, username.length <= 5 ? 1 : 3); + + return `${usernamePublic}*****@*****.${tld}`; +}