[user] show obfuscated email

This commit is contained in:
Andrea 2022-03-19 21:46:34 +01:00
parent 1e10270eeb
commit d4bae3bf44
20 changed files with 60 additions and 21 deletions

View File

@ -70,7 +70,7 @@
<div v-if="message" class="alert alert-success">
<p class="mb-0 narrow-message">
<Icon :v="messageIcon"/>
<T>{{message}}</T>
<T :params="messageParams">{{message}}</T>
</p>
</div>
@ -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([

View File

@ -41,7 +41,7 @@
<div class="alert alert-success">
<p class="mb-0">
<Icon v="envelope-open-text"/>
<T>user.login.emailSent</T>
<T :params="{email: addBrackets(getEmail(payload))}">user.login.emailSent</T>
</p>
</div>
@ -171,6 +171,12 @@
}
})
},
getEmail(payload) {
return payload.email || payload.emailObfuscated || '';
},
addBrackets(str) {
return str ? `(${str})` : '';
},
},
}
</script>

View File

@ -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 <strong>%email%</strong> 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}}'

View File

@ -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 <strong>%email%</strong> 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}}'

View File

@ -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 <strong>%email%</strong> 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}}'

View File

@ -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 <strong>%email%</strong> 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}}'

View File

@ -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 <strong>%email%</strong> 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}}'

View File

@ -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 dutilisateur 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 <strong>%email%</strong> 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 nexiste pas.'
email:
subject: 'Votre code de connexion est {{code}}'

View File

@ -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 <strong>%email%</strong> 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}}'

View File

@ -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 <strong>%email%</strong> 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}}'

View File

@ -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 <strong>%email%</strong> 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%'

View File

@ -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 <strong>%email%</strong> 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}}'

View File

@ -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 <strong>%email%</strong> 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}}'

View File

@ -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 <strong>%email%</strong> 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}}'

View File

@ -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 <strong>%email%</strong> 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}}'

View File

@ -508,7 +508,7 @@ user:
help: 'Чтобы войти или зарегистрировать аккаунт, вам нужно либо привязать его к социальным сетям, либо ввести адрес электронной почты в соответствующее поле, дождаться письма с кодом и подтвердить аккаунт.'
placeholder: 'Адрес электронной почты (или имя пользовател_ьницы, если вы уже зарегистрированы)'
action: 'Войти / зарегистрироваться'
emailSent: 'Мы отправили на указанную вами почту письмо с шестизначным кодом. Пожалуйста, введите его сюда. Код одноразовый и работает в течение 15-ти минут.'
emailSent: 'Мы отправили на указанную вами почту <strong>%email%</strong> письмо с шестизначным кодом. Пожалуйста, введите его сюда. Код одноразовый и работает в течение 15-ти минут.'
userNotFound: 'Пользователь не найден.'
email:
subject: 'Ваш код для авторизации: {{code}}'

View File

@ -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 <strong>%email%</strong> 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%'

View File

@ -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 <strong>%email%</strong> 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}}'

View File

@ -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',
),
});
}));

View File

@ -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}`;
}