Browse Source

Update to swaf 0.23.4

develop
Alice Gaudon 1 month ago
parent
commit
1f064b5ea1
27 changed files with 3095 additions and 3245 deletions
  1. +2
    -2
      README.md
  2. +1
    -1
      package.json
  3. +58
    -61
      src/App.ts
  4. +13
    -13
      src/LDAPServerComponent.ts
  5. +0
    -6
      src/Mails.ts
  6. +0
    -215
      src/controllers/AccountController.ts
  7. +107
    -0
      src/controllers/AccountMailboxController.ts
  8. +0
    -127
      src/controllers/AuthController.ts
  9. +0
    -3
      src/controllers/MagicLinkActionType.ts
  10. +0
    -51
      src/controllers/MagicLinkController.ts
  11. +1
    -1
      src/controllers/MailAutoConfigController.ts
  12. +9
    -9
      src/controllers/backend/AccountBackendController.ts
  13. +14
    -14
      src/controllers/backend/MailboxBackendController.ts
  14. +1
    -1
      src/main.ts
  15. +0
    -20
      src/migrations/AddNameToUsers.ts
  16. +0
    -21
      src/migrations/AddPasswordToUsers.ts
  17. +11
    -12
      src/migrations/CreateMailTablesMigration.ts
  18. +3
    -3
      src/models/MailDomain.ts
  19. +4
    -4
      src/models/MailIdentity.ts
  20. +3
    -3
      src/models/UserMailIdentityComponent.ts
  21. +0
    -13
      src/models/UserNameComponent.ts
  22. +0
    -109
      src/models/UserPasswordComponent.ts
  23. +68
    -0
      views/account-mailbox.njk
  24. +0
    -159
      views/account.njk
  25. +2
    -4
      views/layouts/base.njk
  26. +0
    -27
      views/mails/add_recovery_email.mjml.njk
  27. +2798
    -2366
      yarn.lock

+ 2
- 2
README.md View File

@ -9,7 +9,7 @@ Please feel free to contribute by making issues, bug reports and pull requests.
## /!\ THIS PROJECT STILL LACKS ESSENTIAL FEATURES SUCH AS: /!\
- [x] ~~Change password~~
- [ ] Password recovery (recovery emails are unused yet)
- [ ] Password reset (a magic link to remove your password, see [this issue](https://eternae.ink/arisu/swaf/issues/23))
- [ ] Quota management
- [ ] Editable terms of service
- [ ] Complex permissions system
@ -56,7 +56,7 @@ Note that a user only has one mailbox once they create their first address and c
### Configuration
Create a `config/local.json5` file and override all wanted parameters. See `config/{default,prouction}.json5` and `node_modules/wms-core/config/{default,production}.json5` for defaults.
Create a `config/local.json5` file and override all wanted parameters. See `config/{default,prouction}.json5` and `node_modules/swaf/config/{default,production}.json5` for defaults.
## Postfix and dovecot mysql queries


+ 1
- 1
package.json View File

@ -4,7 +4,7 @@
"description": "ISP mail provider manager with mysql and integrated LDAP server",
"repository": "https://gitlab.com/ArisuOngaku/rainbox.email",
"author": "Alice Gaudon <alice@gaudon.pro>",
"main": "dist/src/main.js",
"main": "dist/main.js",
"license": "AGPL-3.0-only",
"scripts": {
"test": "jest --verbose --runInBand",


+ 58
- 61
src/App.ts View File

@ -1,50 +1,49 @@
import Application from "wms-core/Application";
import Migration, {MigrationType} from "wms-core/db/Migration";
import ExpressAppComponent from "wms-core/components/ExpressAppComponent";
import NunjucksComponent from "wms-core/components/NunjucksComponent";
import MysqlComponent from "wms-core/components/MysqlComponent";
import LogRequestsComponent from "wms-core/components/LogRequestsComponent";
import RedisComponent from "wms-core/components/RedisComponent";
import ServeStaticDirectoryComponent from "wms-core/components/ServeStaticDirectoryComponent";
import MaintenanceComponent from "wms-core/components/MaintenanceComponent";
import MailComponent from "wms-core/components/MailComponent";
import SessionComponent from "wms-core/components/SessionComponent";
import FormHelperComponent from "wms-core/components/FormHelperComponent";
import CsrfProtectionComponent from "wms-core/components/CsrfProtectionComponent";
import WebSocketServerComponent from "wms-core/components/WebSocketServerComponent";
import Application from "swaf/Application";
import Migration, {MigrationType} from "swaf/db/Migration";
import ExpressAppComponent from "swaf/components/ExpressAppComponent";
import NunjucksComponent from "swaf/components/NunjucksComponent";
import MysqlComponent from "swaf/components/MysqlComponent";
import LogRequestsComponent from "swaf/components/LogRequestsComponent";
import RedisComponent from "swaf/components/RedisComponent";
import ServeStaticDirectoryComponent from "swaf/components/ServeStaticDirectoryComponent";
import MaintenanceComponent from "swaf/components/MaintenanceComponent";
import MailComponent from "swaf/components/MailComponent";
import SessionComponent from "swaf/components/SessionComponent";
import FormHelperComponent from "swaf/components/FormHelperComponent";
import CsrfProtectionComponent from "swaf/components/CsrfProtectionComponent";
import WebSocketServerComponent from "swaf/components/WebSocketServerComponent";
import HomeController from "./controllers/HomeController";
import AuthController from "./controllers/AuthController";
import AuthComponent from "wms-core/auth/AuthComponent";
import AuthGuard from "wms-core/auth/AuthGuard";
import {PasswordAuthProof} from "./models/UserPasswordComponent";
import AuthComponent from "swaf/auth/AuthComponent";
import LDAPServerComponent from "./LDAPServerComponent";
import AutoUpdateComponent from "wms-core/components/AutoUpdateComponent";
import DummyMigration from "wms-core/migrations/DummyMigration";
import DropLegacyLogsTable from "wms-core/migrations/DropLegacyLogsTable";
import AccountController from "./controllers/AccountController";
import CreateMigrationsTable from "wms-core/migrations/CreateMigrationsTable";
import CreateUsersAndUserEmailsTable from "wms-core/auth/migrations/CreateUsersAndUserEmailsTable";
import AddPasswordToUsers from "./migrations/AddPasswordToUsers";
import CreateMagicLinksTable from "wms-core/auth/migrations/CreateMagicLinksTable";
import MailController from "wms-core/auth/MailController";
import MagicLinkController from "./controllers/MagicLinkController";
import MagicLinkWebSocketListener from "wms-core/auth/magic_link/MagicLinkWebSocketListener";
import BackendController from "wms-core/helpers/BackendController";
import AddApprovedFieldToUsersTable from "wms-core/auth/migrations/AddApprovedFieldToUsersTable";
import FixUserMainEmailRelation from "wms-core/auth/migrations/FixUserMainEmailRelation";
import DropNameFromUsers from "wms-core/auth/migrations/DropNameFromUsers";
import MagicLink from "wms-core/auth/models/MagicLink";
import AddNameToUsers from "./migrations/AddNameToUsers";
import CreateMailTables from "./migrations/CreateMailTables";
import AutoUpdateComponent from "swaf/components/AutoUpdateComponent";
import DummyMigration from "swaf/migrations/DummyMigration";
import DropLegacyLogsTable from "swaf/migrations/DropLegacyLogsTable";
import AccountMailboxController from "./controllers/AccountMailboxController";
import CreateMigrationsTable from "swaf/migrations/CreateMigrationsTable";
import MagicLinkWebSocketListener from "swaf/auth/magic_link/MagicLinkWebSocketListener";
import BackendController from "swaf/helpers/BackendController";
import CreateMailTablesMigration from "./migrations/CreateMailTablesMigration";
import MailboxBackendController from "./controllers/backend/MailboxBackendController";
import RedirectBackComponent from "wms-core/components/RedirectBackComponent";
import MailAutoConfigController from "./controllers/MailAutoConfigController";
import AccountBackendController from "./controllers/backend/AccountBackendController";
import CreateUsersAndUserEmailsTableMigration from "swaf/auth/migrations/CreateUsersAndUserEmailsTableMigration";
import AddPasswordToUsersMigration from "swaf/auth/password/AddPasswordToUsersMigration";
import CreateMagicLinksTableMigration from "swaf/auth/magic_link/CreateMagicLinksTableMigration";
import AddApprovedFieldToUsersTableMigration from "swaf/auth/migrations/AddApprovedFieldToUsersTableMigration";
import AddNameToUsersMigration from "swaf/auth/migrations/AddNameToUsersMigration";
import PreviousUrlComponent from "swaf/components/PreviousUrlComponent";
import MagicLinkAuthMethod from "swaf/auth/magic_link/MagicLinkAuthMethod";
import {MAGIC_LINK_MAIL} from "swaf/Mails";
import PasswordAuthMethod from "swaf/auth/password/PasswordAuthMethod";
import MagicLinkController from "swaf/auth/magic_link/MagicLinkController";
import AuthController from "swaf/auth/AuthController";
import MailController from "swaf/mail/MailController";
import AccountController from "swaf/auth/AccountController";
import packageJson = require('./package.json');
import AddUsedToMagicLinksMigration from "swaf/auth/magic_link/AddUsedToMagicLinksMigration";
import MakeMagicLinksSessionNotUniqueMigration from "swaf/auth/magic_link/MakeMagicLinksSessionNotUniqueMigration";
export default class App extends Application {
private magicLinkWebSocketListener?: MagicLinkWebSocketListener<this>;
public constructor(
private readonly addr: string,
private readonly port: number,
@ -56,15 +55,17 @@ export default class App extends Application {
return [
CreateMigrationsTable,
DummyMigration,
CreateUsersAndUserEmailsTable,
AddPasswordToUsers,
CreateMagicLinksTable,
AddApprovedFieldToUsersTable,
FixUserMainEmailRelation,
DropNameFromUsers,
AddNameToUsers,
CreateMailTables,
CreateUsersAndUserEmailsTableMigration,
AddPasswordToUsersMigration,
CreateMagicLinksTableMigration,
AddApprovedFieldToUsersTableMigration,
DummyMigration,
DummyMigration,
AddNameToUsersMigration,
CreateMailTablesMigration,
DropLegacyLogsTable,
AddUsedToMagicLinksMigration,
MakeMagicLinksSessionNotUniqueMigration,
];
}
@ -108,12 +109,7 @@ export default class App extends Application {
this.use(new CsrfProtectionComponent());
// Auth
this.use(new AuthComponent(new class extends AuthGuard<PasswordAuthProof | MagicLink> {
public async getProofForSession(session: Express.Session): Promise<PasswordAuthProof | MagicLink | null> {
return PasswordAuthProof.getProofForSession(session) ||
await MagicLink.bySessionId(session.id);
}
}(this)));
this.use(new AuthComponent(this, new MagicLinkAuthMethod(this, MAGIC_LINK_MAIL), new PasswordAuthMethod(this)));
// WebSocket server
this.use(new WebSocketServerComponent(this, this.as(ExpressAppComponent), this.as(RedisComponent)));
@ -123,22 +119,23 @@ export default class App extends Application {
}
private registerWebSocketListeners() {
this.magicLinkWebSocketListener = new MagicLinkWebSocketListener();
this.use(this.magicLinkWebSocketListener);
this.use(new MagicLinkWebSocketListener());
}
private registerControllers() {
// Priority routes / interrupting middlewares
this.use(new MailAutoConfigController()); // Needs to override MailController
this.use(new MailController());
this.use(new AuthController());
this.use(new AccountController());
this.use(new MagicLinkController(this.as(MagicLinkWebSocketListener)));
this.use(new AccountMailboxController());
this.use(new MagicLinkController(this.as<MagicLinkWebSocketListener<this>>(MagicLinkWebSocketListener)));
// Core functionality
this.use(new BackendController());
this.use(new MailboxBackendController());
this.use(new AccountBackendController());
this.use(new AuthController());
this.use(new MailAutoConfigController()); // Needs to override MailController
// Core functionality
this.use(new MailController());
// Other functionnality


+ 13
- 13
src/LDAPServerComponent.ts View File

@ -1,9 +1,9 @@
import ApplicationComponent from "wms-core/ApplicationComponent";
import ApplicationComponent from "swaf/ApplicationComponent";
import ldap, {InvalidCredentialsError, Server} from "ldapjs";
import {log} from "wms-core/Logger";
import UserPasswordComponent from "./models/UserPasswordComponent";
import Throttler from "wms-core/Throttler";
import User from "wms-core/auth/models/User";
import {logger} from "swaf/Logger";
import Throttler from "swaf/Throttler";
import User from "swaf/auth/models/User";
import UserPasswordComponent from "swaf/auth/password/UserPasswordComponent";
export default class LDAPServerComponent extends ApplicationComponent {
private server?: Server;
@ -24,12 +24,12 @@ export default class LDAPServerComponent extends ApplicationComponent {
}
}
log.debug('Matrix authentication attempt:', username, email);
logger.debug('Matrix authentication attempt:', username, email);
try {
Throttler.throttle('ldap_auth', 3, 30 * 1000, username);
} catch (e) {
log.debug('Too many auth requests');
logger.debug('Too many auth requests');
next(new InvalidCredentialsError());
return;
}
@ -39,31 +39,31 @@ export default class LDAPServerComponent extends ApplicationComponent {
const email = await user.mainEmail.get();
if (email) {
if (await user.as(UserPasswordComponent).verifyPassword(req.credentials)) {
log.debug('Success');
logger.debug('Success');
res.end();
return;
}
}
}
log.debug('Fail');
logger.debug('Fail');
next(new InvalidCredentialsError());
});
this.server.unbind((req: unknown, res: unknown, next: () => void) => {
log.debug('Unbind', req);
logger.debug('Unbind', req);
next();
});
this.server.listen(8389, '127.0.0.1', () => {
log.info(`LDAP server listening on ${this.server?.url}`);
logger.info(`LDAP server listening on ${this.server?.url}`);
});
this.server.on('close', () => {
log.info('LDAP server closed.');
logger.info('LDAP server closed.');
});
}
public async stop(): Promise<void> {
await new Promise(resolve => {
await new Promise<void>(resolve => {
if (this.server) {
this.server.close(() => {
resolve();


+ 0
- 6
src/Mails.ts View File

@ -1,6 +0,0 @@
import {MailTemplate} from "wms-core/Mail";
export const ADD_RECOVERY_EMAIL_MAIL_TEMPLATE: MailTemplate = new MailTemplate(
'add_recovery_email',
(data) => 'Add ' + data.email + ' as you recovery email.',
);

+ 0
- 215
src/controllers/AccountController.ts View File

@ -1,215 +0,0 @@
import Controller from "wms-core/Controller";
import {RequireAuthMiddleware} from "wms-core/auth/AuthComponent";
import {Request, Response} from "express";
import {ADD_RECOVERY_EMAIL_MAIL_TEMPLATE} from "../Mails";
import Validator, {EMAIL_REGEX, InvalidFormatValidationError, ValidationBag} from "wms-core/db/Validator";
import MagicLinkController from "./MagicLinkController";
import {MagicLinkActionType} from "./MagicLinkActionType";
import UserEmail from "wms-core/auth/models/UserEmail";
import {BadRequestError, ForbiddenHttpError, NotFoundHttpError, ServerError} from "wms-core/HttpError";
import MailDomain from "../models/MailDomain";
import UserMailIdentityComponent from "../models/UserMailIdentityComponent";
import MailIdentity from "../models/MailIdentity";
import UserNameComponent from "../models/UserNameComponent";
import {WhereOperator, WhereTest} from "wms-core/db/ModelQuery";
import UserPasswordComponent from "../models/UserPasswordComponent";
export default class AccountController extends Controller {
public getRoutesPrefix(): string {
return '/account';
}
public routes(): void {
this.get('/', this.getAccount, 'account', RequireAuthMiddleware);
this.post('/change-password', this.postChangePassword, 'change-password', RequireAuthMiddleware);
this.post('/add-recovery-email', this.addRecoveryEmail, 'add-recovery-email', RequireAuthMiddleware);
this.post('/set-main-email', this.postSetMainRecoveryEmail, 'set-main-recovery-email', RequireAuthMiddleware);
this.post('/remove-email', this.postRemoveRecoveryEmail, 'remove-recovery-email', RequireAuthMiddleware);
this.post('/create-mail-identity', this.postCreateMailIdentity, 'create-mail-identity', RequireAuthMiddleware);
this.post('/delete-mail-identity', this.postDeleteMailIdentity, 'delete-mail-identity', RequireAuthMiddleware);
}
protected async getAccount(req: Request, res: Response): Promise<void> {
const user = req.as(RequireAuthMiddleware).getUser();
const userMailIdentity = user.as(UserMailIdentityComponent);
res.render('account', {
main_email: await user.mainEmail.get(),
emails: await user.emails.get(),
mailboxIdentity: await (await userMailIdentity.mainMailIdentity.get())?.toEmail(),
identities: await Promise.all((await userMailIdentity.mailIdentities.get()).map(async identity => ({
id: identity.id,
email: await identity.toEmail(),
}))),
domains: (await MailDomain.select()
.where('user_id', user.id)
.where('user_id', null, WhereTest.EQ, WhereOperator.OR)
.sortBy('user_id', 'DESC')
.get())
.map(d => ({
value: d.id,
display: d.name,
})),
});
}
protected async postChangePassword(req: Request, res: Response): Promise<void> {
await this.validate({
'current_password': new Validator().defined(),
'new_password': new Validator().defined(),
'new_password_confirmation': new Validator().sameAs('new_password', req.body.new_password),
}, req.body);
const user = req.as(RequireAuthMiddleware).getUser();
if (!await user.as(UserPasswordComponent).verifyPassword(req.body.current_password)) {
req.flash('error', 'Invalid current password.');
res.redirectBack(Controller.route('account'));
return;
}
await user.as(UserPasswordComponent).setPassword(req.body.new_password, 'new_password');
await user.save();
req.flash('success', 'Password change successfully.');
res.redirectBack(Controller.route('account'));
}
protected async addRecoveryEmail(req: Request, res: Response): Promise<void> {
await this.validate({
email: new Validator().defined().regexp(EMAIL_REGEX),
}, req.body);
const email = req.body.email;
// Existing email
if (await UserEmail.select().where('email', email).first()) {
const bag = new ValidationBag();
const error = new InvalidFormatValidationError('You already have this email.');
error.thingName = 'email';
bag.addMessage(error);
throw bag;
}
if (!req.sessionID) throw new ServerError('Session not initialized.');
await MagicLinkController.sendMagicLink(
this.getApp(),
req.sessionID,
MagicLinkActionType.ADD_RECOVERY_EMAIL,
Controller.route('account'),
email,
ADD_RECOVERY_EMAIL_MAIL_TEMPLATE,
{},
);
res.redirect(Controller.route('magic_link_lobby', undefined, {
redirect_uri: Controller.route('account'),
}));
}
protected async postSetMainRecoveryEmail(req: Request, res: Response): Promise<void> {
if (!req.body.id)
throw new BadRequestError('Missing id field', 'Check form parameters.', req.url);
const user = req.as(RequireAuthMiddleware).getUser();
const userEmail = await UserEmail.getById(req.body.id);
if (!userEmail)
throw new NotFoundHttpError('email', req.url);
if (userEmail.user_id !== user.id)
throw new ForbiddenHttpError('email', req.url);
if (userEmail.id === user.main_email_id)
throw new BadRequestError('This address is already your main address', 'Try refreshing the account page.', req.url);
user.main_email_id = userEmail.id;
await user.save();
req.flash('success', 'This email was successfully set as your main address.');
res.redirectBack();
}
protected async postRemoveRecoveryEmail(req: Request, res: Response): Promise<void> {
if (!req.body.id)
throw new BadRequestError('Missing id field', 'Check form parameters.', req.url);
const user = req.as(RequireAuthMiddleware).getUser();
const userEmail = await UserEmail.getById(req.body.id);
if (!userEmail)
throw new NotFoundHttpError('email', req.url);
if (userEmail.user_id !== user.id)
throw new ForbiddenHttpError('email', req.url);
if (userEmail.id === user.main_email_id)
throw new BadRequestError('Cannot remove main email address', 'Try refreshing the account page.', req.url);
await userEmail.delete();
req.flash('success', 'This email was successfully removed from your account.');
res.redirectBack();
}
protected async postCreateMailIdentity(req: Request, res: Response): Promise<void> {
const domain = await MailDomain.getById(req.body.mail_domain_id);
if (!domain) throw new NotFoundHttpError('domain', req.url);
const user = req.as(RequireAuthMiddleware).getUser();
const mailIdentityComponent = user.as(UserMailIdentityComponent);
const identity = MailIdentity.create({
user_id: user.id,
name: req.body.name,
mail_domain_id: req.body.mail_domain_id,
});
// Check whether this identity can be created by this user
if (domain.isPublic()) {
await this.validate({
name: new Validator<string>().defined().equals(user.as(UserNameComponent).name),
}, req.body);
const actualPublicAddressesCount = await mailIdentityComponent.getPublicAddressesCount();
const maxPublicAddressesCount = mailIdentityComponent.getMaxPublicAddressesCount();
if (actualPublicAddressesCount >= maxPublicAddressesCount) {
req.flash('error', 'You have reached maximum public email addresses.');
res.redirectBack();
return;
}
} else {
if (!domain.canCreateAddresses(user)) {
throw new ForbiddenHttpError('domain', req.url);
}
}
// Save identity
await identity.save();
// Set main mail identity if not already set
if (!mailIdentityComponent.main_mail_identity_id) {
mailIdentityComponent.main_mail_identity_id = identity.id;
await user.save();
req.flash('info', 'Congratulations! You just created your mailbox.');
}
req.flash('success', 'Mail identity ' + await identity.toEmail() + ' successfully created.');
res.redirectBack();
}
protected async postDeleteMailIdentity(req: Request, res: Response): Promise<void> {
const user = req.as(RequireAuthMiddleware).getUser();
const identity = await MailIdentity.getById(req.body.id);
if (!identity) throw new NotFoundHttpError('Mail identity', req.url);
if (identity.user_id !== user.id) throw new ForbiddenHttpError('mail identity', req.url);
if (user.as(UserMailIdentityComponent).main_mail_identity_id === identity.id) {
req.flash('error', 'Cannot delete your mailbox identity.');
res.redirectBack();
return;
}
await identity.delete();
req.flash('success', 'Identity ' + await identity.toEmail() + ' successfully deleted.');
res.redirectBack();
}
}

+ 107
- 0
src/controllers/AccountMailboxController.ts View File

@ -0,0 +1,107 @@
import Controller from "swaf/Controller";
import {RequireAuthMiddleware} from "swaf/auth/AuthComponent";
import {Request, Response} from "express";
import Validator from "swaf/db/Validator";
import {ForbiddenHttpError, NotFoundHttpError} from "swaf/HttpError";
import MailDomain from "../models/MailDomain";
import UserMailIdentityComponent from "../models/UserMailIdentityComponent";
import MailIdentity from "../models/MailIdentity";
import {WhereOperator, WhereTest} from "swaf/db/ModelQuery";
import UserNameComponent from "swaf/auth/models/UserNameComponent";
export default class AccountMailboxController extends Controller {
public getRoutesPrefix(): string {
return '/account/mailbox';
}
public routes(): void {
this.get('/', this.getAccountMailbox, 'account-mailbox', RequireAuthMiddleware);
this.post('/create-mail-identity', this.postCreateMailIdentity, 'create-mail-identity', RequireAuthMiddleware);
this.post('/delete-mail-identity', this.postDeleteMailIdentity, 'delete-mail-identity', RequireAuthMiddleware);
}
protected async getAccountMailbox(req: Request, res: Response): Promise<void> {
const user = req.as(RequireAuthMiddleware).getUser();
const userMailIdentity = user.as(UserMailIdentityComponent);
res.render('account-mailbox', {
mailboxIdentity: await (await userMailIdentity.mainMailIdentity.get())?.toEmail(),
identities: await Promise.all((await userMailIdentity.mailIdentities.get()).map(async identity => ({
id: identity.id,
email: await identity.toEmail(),
}))),
domains: (await MailDomain.select()
.where('user_id', user.id)
.where('user_id', null, WhereTest.EQ, WhereOperator.OR)
.sortBy('user_id', 'DESC')
.get())
.map(d => ({
value: d.id,
display: d.name,
})),
});
}
protected async postCreateMailIdentity(req: Request, res: Response): Promise<void> {
const domain = await MailDomain.getById(req.body.mail_domain_id);
if (!domain) throw new NotFoundHttpError('domain', req.url);
const user = req.as(RequireAuthMiddleware).getUser();
const mailIdentityComponent = user.as(UserMailIdentityComponent);
const identity = MailIdentity.create({
user_id: user.id,
name: req.body.name,
mail_domain_id: req.body.mail_domain_id,
});
// Check whether this identity can be created by this user
if (domain.isPublic()) {
await Validator.validate({
name: new Validator<string>().defined().equals(user.as(UserNameComponent).name),
}, req.body);
const actualPublicAddressesCount = await mailIdentityComponent.getPublicAddressesCount();
const maxPublicAddressesCount = mailIdentityComponent.getMaxPublicAddressesCount();
if (actualPublicAddressesCount >= maxPublicAddressesCount) {
req.flash('error', 'You have reached maximum public email addresses.');
res.redirect(Controller.route('account-mailbox'));
return;
}
} else {
if (!domain.canCreateAddresses(user)) {
throw new ForbiddenHttpError('domain', req.url);
}
}
// Save identity
await identity.save();
// Set main mail identity if not already set
if (!mailIdentityComponent.main_mail_identity_id) {
mailIdentityComponent.main_mail_identity_id = identity.id;
await user.save();
req.flash('info', 'Congratulations! You just created your mailbox.');
}
req.flash('success', 'Mail identity ' + await identity.toEmail() + ' successfully created.');
res.redirect(Controller.route('account-mailbox'));
}
protected async postDeleteMailIdentity(req: Request, res: Response): Promise<void> {
const user = req.as(RequireAuthMiddleware).getUser();
const identity = await MailIdentity.getById(req.body.id);
if (!identity) throw new NotFoundHttpError('Mail identity', req.url);
if (identity.user_id !== user.id) throw new ForbiddenHttpError('mail identity', req.url);
if (user.as(UserMailIdentityComponent).main_mail_identity_id === identity.id) {
req.flash('error', 'Cannot delete your mailbox identity.');
res.redirect(Controller.route('account-mailbox'));
return;
}
await identity.delete();
req.flash('success', 'Identity ' + await identity.toEmail() + ' successfully deleted.');
res.redirect(Controller.route('account-mailbox'));
}
}

+ 0
- 127
src/controllers/AuthController.ts View File

@ -1,127 +0,0 @@
import Controller from "wms-core/Controller";
import AuthComponent, {RequireAuthMiddleware, RequireGuestMiddleware} from "wms-core/auth/AuthComponent";
import {Request, Response} from "express";
import Validator, {InvalidFormatValidationError, ValidationBag} from "wms-core/db/Validator";
import UserPasswordComponent, {PasswordAuthProof} from "../models/UserPasswordComponent";
import UserNameComponent, {USERNAME_REGEXP} from "../models/UserNameComponent";
import _AuthController from "wms-core/auth/AuthController";
import {NotFoundHttpError, ServerError} from "wms-core/HttpError";
import {AuthError, PendingApprovalAuthError, RegisterCallback} from "wms-core/auth/AuthGuard";
import User from "wms-core/auth/models/User";
import Throttler from "wms-core/Throttler";
export default class AuthController extends _AuthController {
public routes(): void {
this.get('/login', this.getLogin, 'auth', RequireGuestMiddleware);
this.post('/login', this.postLogin, 'auth', RequireGuestMiddleware);
this.get('/register', this.getRegister, 'register', RequireGuestMiddleware);
this.post('/register', this.postRegister, 'register', RequireGuestMiddleware);
this.post('/logout', this.postLogout, 'logout', RequireAuthMiddleware);
}
protected async getLogin(req: Request, res: Response): Promise<void> {
res.render('login');
}
protected async postLogin(req: Request, res: Response): Promise<void> {
await this.validate({
username: new Validator().defined().exists(User, 'name'),
password: new Validator().acceptUndefined(),
}, req.body);
const user = await User.select()
.where('name', req.body.username)
.first();
if (!user) throw new NotFoundHttpError(`Couldn't find a user with name ${req.body.username}`, req.url);
if (!req.session) throw new ServerError('Session not initialized.');
const passwordAuthProof = PasswordAuthProof.createProofForLogin(req.session);
passwordAuthProof.setResource(user);
await passwordAuthProof.authorize(req.body.password);
try {
await this.getApp().as(AuthComponent).getAuthGuard().authenticateOrRegister(req.session, passwordAuthProof);
} catch (e) {
if (e instanceof AuthError) {
Throttler.throttle('login_failed_attempts_user', 3, 180000, <string>user.getOrFail('name'), 1000, 60000);
Throttler.throttle('login_failed_attempts_ip', 5, 60000, req.ip, 1000, 60000);
if (e instanceof PendingApprovalAuthError) {
req.flash('error', 'Your account is still being reviewed.');
res.redirectBack();
return;
} else {
const bag = new ValidationBag();
const err = new InvalidFormatValidationError('Invalid password.');
err.thingName = 'password';
bag.addMessage(err);
throw bag;
}
} else {
throw e;
}
}
req.flash('success', `Welcome, ${user.name}.`);
res.redirect(Controller.route('home'));
}
protected async getRegister(req: Request, res: Response): Promise<void> {
res.render('register');
}
protected async postRegister(req: Request, res: Response): Promise<void> {
Throttler.throttle('register_password', 10, 30000, req.ip);
await this.validate({
username: new Validator().defined().between(3, 64).regexp(USERNAME_REGEXP).unique(User, 'name'),
password: new Validator().defined().minLength(8),
password_confirmation: new Validator().defined().sameAs('password', req.body.password),
terms: new Validator().defined(),
}, req.body);
if(!req.session) throw new ServerError('Session not initialized.');
const passwordAuthProof = PasswordAuthProof.createAuthorizedProofForRegistration(req.session);
try {
await this.getApp().as(AuthComponent).getAuthGuard().authenticateOrRegister(req.session, passwordAuthProof,
undefined, async (connection, user) => {
const callbacks: RegisterCallback[] = [];
// Password
await user.as(UserPasswordComponent).setPassword(req.body.password);
// Username
user.as(UserNameComponent).name = req.body.username;
return callbacks;
}, async (connection, user) => {
passwordAuthProof.setResource(user);
return [];
});
} catch (e) {
if (e instanceof PendingApprovalAuthError) {
req.flash('info', `Your account was successfully created and is pending review from an administrator.`);
res.redirect(Controller.route('home'));
return;
} else {
throw e;
}
}
const user = await passwordAuthProof.getResource();
req.flash('success', `Your account was successfully created! Welcome, ${user?.as(UserNameComponent).name}.`);
res.redirect(Controller.route('home'));
}
protected async getCheckAuth(): Promise<void> {
throw new ServerError('Not implemented.');
}
protected async postAuth(): Promise<void> {
throw new ServerError('Not implemented.');
}
}

+ 0
- 3
src/controllers/MagicLinkActionType.ts View File

@ -1,3 +0,0 @@
export enum MagicLinkActionType {
ADD_RECOVERY_EMAIL = 'Add a recovery email',
}

+ 0
- 51
src/controllers/MagicLinkController.ts View File

@ -1,51 +0,0 @@
import _MagicLinkController from "wms-core/auth/magic_link/MagicLinkController";
import MagicLink from "wms-core/auth/models/MagicLink";
import {Request, Response} from "express";
import MagicLinkWebSocketListener from "wms-core/auth/magic_link/MagicLinkWebSocketListener";
import {MagicLinkActionType} from "./MagicLinkActionType";
import Controller from "wms-core/Controller";
import {BadOwnerMagicLink} from "wms-core/auth/magic_link/MagicLinkAuthController";
import UserEmail from "wms-core/auth/models/UserEmail";
import App from "../App";
import AuthComponent from "wms-core/auth/AuthComponent";
export default class MagicLinkController extends _MagicLinkController<App> {
public constructor(magicLinkWebSocketListener: MagicLinkWebSocketListener<App>) {
super(magicLinkWebSocketListener);
}
protected async performAction(magicLink: MagicLink, req: Request, res: Response): Promise<void> {
if (magicLink.action_type === MagicLinkActionType.ADD_RECOVERY_EMAIL) {
if (!req.session || !req.sessionID || magicLink.session_id !== req.sessionID) throw new BadOwnerMagicLink();
await magicLink.delete();
const authGuard = this.getApp().as(AuthComponent).getAuthGuard();
const proof = await authGuard.isAuthenticated(req.session);
const user = await proof?.getResource();
if (!user) return;
const email = await magicLink.getOrFail('email');
if (await UserEmail.select().with('user').where('email', email).first()) {
req.flash('error', 'An account already exists with this email address. Please first remove it there before adding it here.');
res.redirect(Controller.route('account'));
return;
}
const userEmail = UserEmail.create({
user_id: user.id,
email: email,
main: false,
});
await userEmail.save();
if (!user.main_email_id) {
user.main_email_id = userEmail.id;
await user.save();
}
req.flash('success', `Recovery email ${userEmail.email} successfully added.`);
res.redirect(Controller.route('account'));
}
}
}

+ 1
- 1
src/controllers/MailAutoConfigController.ts View File

@ -1,4 +1,4 @@
import Controller from "wms-core/Controller";
import Controller from "swaf/Controller";
import {Request, Response} from "express";
import MailDomain from "../models/MailDomain";
import config from "config";


+ 9
- 9
src/controllers/backend/AccountBackendController.ts View File

@ -1,12 +1,12 @@
import Controller from "wms-core/Controller";
import BackendController from "wms-core/helpers/BackendController";
import {RequireAdminMiddleware, RequireAuthMiddleware} from "wms-core/auth/AuthComponent";
import Controller from "swaf/Controller";
import BackendController from "swaf/helpers/BackendController";
import {RequireAdminMiddleware, RequireAuthMiddleware} from "swaf/auth/AuthComponent";
import {Request, Response} from "express";
import User from "wms-core/auth/models/User";
import {NotFoundHttpError} from "wms-core/HttpError";
import Validator from "wms-core/db/Validator";
import UserPasswordComponent from "../../models/UserPasswordComponent";
import UserNameComponent from "../../models/UserNameComponent";
import User from "swaf/auth/models/User";
import {NotFoundHttpError} from "swaf/HttpError";
import Validator from "swaf/db/Validator";
import UserPasswordComponent from "swaf/auth/password/UserPasswordComponent";
import UserNameComponent from "swaf/auth/models/UserNameComponent";
export default class AccountBackendController extends Controller {
@ -51,7 +51,7 @@ export default class AccountBackendController extends Controller {
const user = await User.getById(req.params.user_id);
if (!user) throw new NotFoundHttpError('user', req.url);
await this.validate({
await Validator.validate({
'new_password': new Validator().defined(),
'new_password_confirmation': new Validator().sameAs('new_password', req.body.new_password),
}, req.body);


+ 14
- 14
src/controllers/backend/MailboxBackendController.ts View File

@ -1,14 +1,14 @@
import Controller from "wms-core/Controller";
import Controller from "swaf/Controller";
import {Request, Response} from "express";
import User from "wms-core/auth/models/User";
import {WhereTest} from "wms-core/db/ModelQuery";
import UserNameComponent from "../../models/UserNameComponent";
import User from "swaf/auth/models/User";
import {WhereTest} from "swaf/db/ModelQuery";
import UserMailIdentityComponent from "../../models/UserMailIdentityComponent";
import {NotFoundHttpError} from "wms-core/HttpError";
import {NotFoundHttpError} from "swaf/HttpError";
import MailDomain from "../../models/MailDomain";
import BackendController from "wms-core/helpers/BackendController";
import BackendController from "swaf/helpers/BackendController";
import MailIdentity from "../../models/MailIdentity";
import {RequireAdminMiddleware, RequireAuthMiddleware} from "wms-core/auth/AuthComponent";
import {RequireAdminMiddleware, RequireAuthMiddleware} from "swaf/auth/AuthComponent";
import UserNameComponent from "swaf/auth/models/UserNameComponent";
export default class MailboxBackendController extends Controller {
public constructor() {
@ -104,7 +104,7 @@ export default class MailboxBackendController extends Controller {
const domain = MailDomain.create(req.body);
await domain.save();
req.flash('success', `Domain ${domain.name} successfully added with owner ${(await domain.owner.get())?.name}`);
res.redirectBack();
res.redirect(Controller.route('backend-mailboxes'));
}
protected async getEditDomain(req: Request, res: Response): Promise<void> {
@ -133,7 +133,7 @@ export default class MailboxBackendController extends Controller {
await domain.save();
req.flash('success', `Domain ${domain.name} updated successfully.`);
res.redirectBack();
res.redirect(Controller.route('backend-mailboxes'));
}
protected async postRemoveDomain(req: Request, res: Response): Promise<void> {
@ -146,14 +146,14 @@ export default class MailboxBackendController extends Controller {
// Don't delete that domain if it still has identities
if ((await domain.identities.get()).length > 0) {
req.flash('error', `This domain still has identities. Please remove all of these first (don't forget to rename mailboxes).`);
res.redirectBack();
res.redirect(Controller.route('backend-mailboxes'));
return;
}
await domain.delete();
req.flash('success', `Domain ${domain.name} successfully deleted.`);
res.redirectBack();
res.redirect(Controller.route('backend-mailboxes'));
}
protected async postCreateMailIdentity(req: Request, res: Response): Promise<void> {
@ -184,7 +184,7 @@ export default class MailboxBackendController extends Controller {
}
req.flash('success', 'Mail identity ' + await identity.toEmail() + ' successfully created.');
res.redirectBack();
res.redirect(Controller.route('backend-mailbox', req.params.id));
}
protected async postDeleteMailIdentity(req: Request, res: Response): Promise<void> {
@ -197,12 +197,12 @@ export default class MailboxBackendController extends Controller {
const user = await identity.user.get();
if (user?.as(UserMailIdentityComponent).main_mail_identity_id === identity.id) {
req.flash('error', `Cannot delete this user's mailbox identity.`);
res.redirectBack();
res.redirect(Controller.route('backend-mailbox', req.params.id));
return;
}
await identity.delete();
req.flash('success', 'Identity ' + await identity.toEmail() + ' successfully deleted.');
res.redirectBack();
res.redirect(Controller.route('backend-mailbox', req.params.id));
}
}

+ 1
- 1
src/main.ts View File

@ -4,7 +4,7 @@ import {delimiter} from "path";
process.env['NODE_CONFIG_DIR'] =
__dirname + '/../node_modules/swaf/config/'
+ delimiter
+ (process.env['NODE_CONFIG_DIR'] || __dirname + '/../../config/');
+ (process.env['NODE_CONFIG_DIR'] || __dirname + '/../config/');
import {logger} from "swaf/Logger";
import App from "./App";


+ 0
- 20
src/migrations/AddNameToUsers.ts View File

@ -1,20 +0,0 @@
import Migration from "wms-core/db/Migration";
import ModelFactory from "wms-core/db/ModelFactory";
import User from "wms-core/auth/models/User";
import UserNameComponent from "../models/UserNameComponent";
import {Connection} from "mysql";
export default class AddNameToUsers extends Migration {
public async install(connection: Connection): Promise<void> {
await this.query(`ALTER TABLE users
ADD COLUMN name VARCHAR(64) UNIQUE NOT NULL`, connection);
}
public async rollback(connection: Connection): Promise<void> {
await this.query('ALTER TABLE users DROP COLUMN name', connection);
}
public registerModels(): void {
ModelFactory.get(User).addComponent(UserNameComponent);
}
}

+ 0
- 21
src/migrations/AddPasswordToUsers.ts View File

@ -1,21 +0,0 @@
import Migration from "wms-core/db/Migration";
import {Connection} from "mysql";
import ModelFactory from "wms-core/db/ModelFactory";
import User from "wms-core/auth/models/User";
import UserPasswordComponent from "../models/UserPasswordComponent";
export default class AddPasswordToUsers extends Migration {
public async install(connection: Connection): Promise<void> {
await this.query(`ALTER TABLE users
ADD COLUMN password VARCHAR(128) NOT NULL`, connection);
}
public async rollback(connection: Connection): Promise<void> {
await this.query(`ALTER TABLE users
DROP COLUMN password`, connection);
}
public registerModels(): void {
ModelFactory.get(User).addComponent(UserPasswordComponent);
}
}

src/migrations/CreateMailTables.ts → src/migrations/CreateMailTablesMigration.ts View File

@ -1,13 +1,12 @@
import Migration from "wms-core/db/Migration";
import {Connection} from "mysql";
import ModelFactory from "wms-core/db/ModelFactory";
import Migration from "swaf/db/Migration";
import ModelFactory from "swaf/db/ModelFactory";
import MailDomain from "../models/MailDomain";
import MailIdentity from "../models/MailIdentity";
import User from "wms-core/auth/models/User";
import User from "swaf/auth/models/User";
import UserMailIdentityComponent from "../models/UserMailIdentityComponent";
export default class CreateMailTables extends Migration {
public async install(connection: Connection): Promise<void> {
export default class CreateMailTablesMigration extends Migration {
public async install(): Promise<void> {
await this.query(`CREATE TABLE mail_domains
(
id INT NOT NULL AUTO_INCREMENT,
@ -15,7 +14,7 @@ export default class CreateMailTables extends Migration {
user_id INT,
PRIMARY KEY (id),
FOREIGN KEY (user_id) REFERENCES users (id) ON DELETE SET NULL
)`, connection);
)`);
await this.query(`CREATE TABLE mail_identities
(
id INT NOT NULL AUTO_INCREMENT,
@ -27,17 +26,17 @@ export default class CreateMailTables extends Migration {
UNIQUE (mail_domain_id, name),
FOREIGN KEY (user_id) REFERENCES users (id) ON DELETE CASCADE,
FOREIGN KEY (mail_domain_id) REFERENCES mail_domains (id) ON DELETE CASCADE
)`, connection);
)`);
await this.query(`ALTER TABLE users
ADD COLUMN main_mail_identity_id INT,
ADD FOREIGN KEY main_mail_identity_fk (main_mail_identity_id) REFERENCES mail_identities (id)`, connection);
ADD FOREIGN KEY main_mail_identity_fk (main_mail_identity_id) REFERENCES mail_identities (id)`);
}
public async rollback(connection: Connection): Promise<void> {
public async rollback(): Promise<void> {
await this.query(`ALTER TABLE users
DROP FOREIGN KEY main_mail_identity_fk,
DROP COLUMN main_mail_identity_id`, connection);
await this.query(`DROP TABLE IF EXISTS mail_identities, mail_domains`, connection);
DROP COLUMN main_mail_identity_id`);
await this.query(`DROP TABLE IF EXISTS mail_identities, mail_domains`);
}
public registerModels(): void {

+ 3
- 3
src/models/MailDomain.ts View File

@ -1,6 +1,6 @@
import Model from "wms-core/db/Model";
import User from "wms-core/auth/models/User";
import {ManyModelRelation, OneModelRelation} from "wms-core/db/ModelRelation";
import Model from "swaf/db/Model";
import User from "swaf/auth/models/User";
import {ManyModelRelation, OneModelRelation} from "swaf/db/ModelRelation";
import MailIdentity from "./MailIdentity";
export default class MailDomain extends Model {


+ 4
- 4
src/models/MailIdentity.ts View File

@ -1,8 +1,8 @@
import Model from "wms-core/db/Model";
import User from "wms-core/auth/models/User";
import Model from "swaf/db/Model";
import User from "swaf/auth/models/User";
import MailDomain from "./MailDomain";
import {OneModelRelation} from "wms-core/db/ModelRelation";
import {EMAIL_REGEX} from "wms-core/db/Validator";
import {OneModelRelation} from "swaf/db/ModelRelation";
import {EMAIL_REGEX} from "swaf/db/Validator";
export default class MailIdentity extends Model {
public static get table(): string {


+ 3
- 3
src/models/UserMailIdentityComponent.ts View File

@ -1,6 +1,6 @@
import ModelComponent from "wms-core/db/ModelComponent";
import User from "wms-core/auth/models/User";
import {ManyModelRelation, OneModelRelation} from "wms-core/db/ModelRelation";
import ModelComponent from "swaf/db/ModelComponent";
import User from "swaf/auth/models/User";
import {ManyModelRelation, OneModelRelation} from "swaf/db/ModelRelation";
import MailIdentity from "./MailIdentity";
import MailDomain from "./MailDomain";


+ 0
- 13
src/models/UserNameComponent.ts View File

@ -1,13 +0,0 @@
import User from "wms-core/auth/models/User";
import ModelComponent from "wms-core/db/ModelComponent";
export const USERNAME_REGEXP = /^[0-9a-z_-]+$/;
export default class UserNameComponent extends ModelComponent<User> {
public name?: string = undefined;
public init(): void {
this.setValidation('name').defined().between(3, 64).regexp(USERNAME_REGEXP).unique(this._model);
}
}

+ 0
- 109
src/models/UserPasswordComponent.ts View File

@ -1,109 +0,0 @@
import Validator from "wms-core/db/Validator";
import User from "wms-core/auth/models/User";
import argon2, {argon2id} from "argon2";
import AuthProof from "wms-core/auth/AuthProof";
import ModelComponent from "wms-core/db/ModelComponent";
export default class UserPasswordComponent extends ModelComponent<User> {
private password?: string = undefined;
public init(): void {
this.setValidation('password').acceptUndefined().maxLength(128);
}
public async setPassword(rawPassword: string, fieldName: string = 'password'): Promise<void> {
await new Validator<string>().defined().minLength(8).maxLength(512)
.execute(fieldName, rawPassword, true);
this.password = await argon2.hash(rawPassword, {
timeCost: 10,
memoryCost: 65536,
parallelism: 4,
type: argon2id,
hashLength: 32,
});
}
public async verifyPassword(passwordGuess: string): Promise<boolean> {
if (!this.password) return false;
return await argon2.verify(this.password, passwordGuess);
}
}
export class PasswordAuthProof implements AuthProof<User> {
public static getProofForSession(session: Express.Session): PasswordAuthProof | null {
return session.auth_password_proof ? new PasswordAuthProof(session) : null;
}
public static createAuthorizedProofForRegistration(session: Express.Session): PasswordAuthProof {
const proofForSession = new PasswordAuthProof(session);
proofForSession.authorized = true;
proofForSession.forRegistration = true;
proofForSession.save();
return proofForSession;
}
public static createProofForLogin(session: Express.Session): PasswordAuthProof {
return new PasswordAuthProof(session);
}
private readonly session: Express.Session;
private authorized: boolean;
private forRegistration: boolean = false;
private userId: number | null;
private userPassword: UserPasswordComponent | null = null;
private constructor(session: Express.Session) {
this.session = session;
this.authorized = session.auth_password_proof?.authorized || false;
this.forRegistration = session.auth_password_proof?.forRegistration || false;
this.userId = session.auth_password_proof?.userId || null;
}
public async getResource(): Promise<User | null> {
if (typeof this.userId !== 'number') return null;
return await User.getById(this.userId);
}
public setResource(user: User): void {
this.userId = user.getOrFail('id');
this.save();
}
public async isAuthorized(): Promise<boolean> {
return this.authorized;
}
public async isValid(): Promise<boolean> {
return (this.forRegistration || Boolean(await this.getResource())) &&
await this.isAuthorized();
}
public async revoke(): Promise<void> {
this.session.auth_password_proof = undefined;
}
private async getUserPassword(): Promise<UserPasswordComponent | null> {
if (!this.userPassword) {
this.userPassword = (await User.getById(this.userId))?.as(UserPasswordComponent) || null;
}
return this.userPassword;
}
public async authorize(passwordGuess: string): Promise<boolean> {
const password = await this.getUserPassword();
if (!password || !await password.verifyPassword(passwordGuess)) return false;
this.authorized = true;
this.save();
return true;
}
private save() {
this.session.auth_password_proof = {
authorized: this.authorized,
forRegistration: this.forRegistration,
userId: this.userId,
};
}
}

+ 68
- 0
views/account-mailbox.njk View File

@ -0,0 +1,68 @@
{% extends 'layouts/base.njk' %}
{% set title = app.name + ' - Account' %}
{% block body %}
<main class="container">
<h1>My mailbox</h1>
<section class="panel">
<h2><i data-feather="mail"></i> {{ mailboxIdentity | default('Mailbox') }}</h2>
<p class="center">{% if mailboxIdentity == null %}(Not created yet){% else %}{{ mailboxIdentity }}{% endif %}</p>
<table class="data-table">
<thead>
<tr>
<th>#</th>
<th>Email</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
{% for identity in identities %}
<tr>
<td>{{ identity.id }}</td>
<td>{{ identity.email }}</td>
<td class="actions">
<form action="{{ route('delete-mail-identity') }}" method="POST">
<input type="hidden" name="id" value="{{ identity.id }}">
<button class="danger"
onclick="return confirm('Are you sure you want to delete {{ identity.email }}?')">
<i data-feather="trash"></i> <span class="tip">Delete</span>
</button>
{{ macros.csrf(getCsrfToken) }}
</form>
</td>
</tr>
{% else %}
<tr>
<td colspan="3">No identity (yet).</td>
</tr>
{% endfor %}
</tbody>
</table>
<form action="{{ route('create-mail-identity') }}" method="POST" class="sub-panel">
<h3>{% if mailboxIdentity == null %}Create your mailbox{% else %}Create a new mail identity{% endif %}</h3>
<div class="inline-fields">
{{ macros.field(_locals, 'text', 'name', user.name, 'Email name', null, 'required') }}
<span>@</span>
{{ macros.field(_locals, 'select', 'mail_domain_id', null, 'Choose the email domain', null, 'required', domains) }}
</div>
<div class="hint">
<i data-feather="info"></i>
If using a "public" domain, can only be set to your username.
</div>
<button><i data-feather="plus"></i> Create</button>
{{ macros.csrf(getCsrfToken) }}
</form>
</section>
</main>
{% endblock %}

+ 0
- 159
views/account.njk View File

@ -1,159 +0,0 @@
{% extends 'layouts/base.njk' %}
{% set title = app.name + ' - Account' %}
{% block body %}
<main class="container">
<h1>My account</h1>
{% if emails | length <= 0 %}
{{ macros.message('warning', 'To avoid losing access to your account, please add a recovery email address.') }}
{% endif %}
<section class="panel">
<h2><i data-feather="user"></i> Personnal info</h2>
<p>Name: {{ user.name }}</p>
<p>Contact email: {{ main_email.email | default('-') }}</p>
</section>
<section class="panel">
<h2><i data-feather="key"></i> Change password</h2>
<form action="{{ route('change-password') }}" method="POST">
{{ macros.field(_locals, 'password', 'current_password', null, 'Current password') }}
{{ macros.field(_locals, 'password', 'new_password', null, 'New password') }}
{{ macros.field(_locals, 'password', 'new_password_confirmation', null, 'New password confirmation') }}
<button type="submit"><i data-feather="save"></i> Save</button>
{{ macros.csrf(getCsrfToken) }}
</form>
</section>
<section class="panel">
<h2><i data-feather="shield"></i> Recovery email addresses</h2>
<table class="data-table">
<thead>
<tr>
<th>Type</th>
<th>Address</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
{% for email in emails %}
{% if email.id == user.main_email_id %}
<tr>
<td>Main</td>
<td>{{ email.email }}</td>
<td></td>
</tr>
{% endif %}
{% endfor %}
{% for email in emails %}
{% if email.id != user.main_email_id %}
<tr>
<td>Secondary</td>
<td>{{ email.email }}</td>
<td class="actions">
<form action="{{ route('set-main-recovery-email') }}" method="POST">
<input type="hidden" name="id" value="{{ email.id }}">
<button class="warning"
onclick="return confirm('Are you sure you want to set {{ email.email }} as your main address?');">
<i data-feather="refresh-ccw"></i> <span class="tip">Set as main address</span>
</button>
{{ macros.csrf(getCsrfToken) }}
</form>
<form action="{{ route('remove-recovery-email') }}" method="POST">
<input type="hidden" name="id" value="{{ email.id }}">
<button class="danger"
onclick="return confirm('Are you sure you want to delete {{ email.email }}?');">
<i data-feather="trash"></i> <span class="tip">Remove</span>
</button>
{{ macros.csrf(getCsrfToken) }}
</form>
</td>
</tr>
{% endif %}
{% endfor %}
</tbody>
</table>
<form action="{{ route('add-recovery-email') }}" method="POST" class="sub-panel">
<h3>Add a recovery email address:</h3>
{{ macros.field(_locals, 'email', 'email', null, 'Choose a safe email address', 'An email we can use to identify you in case you lose access to your account', 'required') }}
<button><i data-feather="plus"></i> Add recovery email</button>
{{ macros.csrf(getCsrfToken) }}
</form>
</section>
<section class="panel">
<h2><i data-feather="mail"></i> Mailbox</h2>
<p class="center">{% if mailboxIdentity == null %}(Not created yet){% else %}{{ mailboxIdentity }}{% endif %}</p>
<table class="data-table">
<thead>
<tr>
<th>#</th>
<th>Email</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
{% for identity in identities %}
<tr>
<td>{{ identity.id }}</td>
<td>{{ identity.email }}</td>
<td class="actions">
<form action="{{ route('delete-mail-identity') }}" method="POST">
<input type="hidden" name="id" value="{{ identity.id }}">
<button class="danger"
onclick="return confirm('Are you sure you want to delete {{ identity.email }}?')">
<i data-feather="trash"></i> <span class="tip">Delete</span>
</button>
{{ macros.csrf(getCsrfToken) }}
</form>
</td>
</tr>
{% else %}
<tr>
<td colspan="3">No identity (yet).</td>
</tr>
{% endfor %}
</tbody>
</table>
<form action="{{ route('create-mail-identity') }}" method="POST" class="sub-panel">
<h3>{% if mailboxIdentity == null %}Create your mailbox{% else %}Create a new mail identity{% endif %}</h3>
<div class="inline-fields">
{{ macros.field(_locals, 'text', 'name', user.name, 'Email name', null, 'required') }}
<span>@</span>
{{ macros.field(_locals, 'select', 'mail_domain_id', null, 'Choose the email domain', null, 'required', domains) }}
</div>
<div class="hint">
<i data-feather="info"></i>
If using a "public" domain, can only be set to your username.
</div>
<button><i data-feather="plus"></i> Create</button>
{{ macros.csrf(getCsrfToken) }}
</form>
</section>
</main>
{% endblock %}

+ 2
- 4
views/layouts/base.njk View File

@ -17,7 +17,6 @@
<button id="menu-button"><i data-feather="menu"></i></button>
<ul id="main-menu">
<li><a href="{{ app.webmail_url }}" target="_blank"><i data-feather="mail"></i> <span class="tip">Webmail</span></a></li>
{# <li><a href="{{ route('about') }}"><i data-feather="info"></i> <span class="tip">About</span></a></li>#}
{% if user %}
{% if user.is_admin %}
<li><a href="{{ route('backend') }}"><i data-feather="settings"></i> <span class="tip">Backend</span></a></li>
@ -25,6 +24,7 @@
<li><a href="{{ route('account') }}"><i data-feather="user"></i>
<span class="tip">{{ user.name }}</span></a></li>
<li><a href="{{ route('account-mailbox') }}"><i data-feather="mail"></i> <span class="tip">Mailbox settings</span></a></li>
<li>
<form action="{{ route('logout') }}" method="POST">
<button><i data-feather="log-out"></i> <span class="tip">Logout</span></button>
@ -32,9 +32,7 @@
</form>
</li>
{% else %}
<li><a href="{{ route('auth') }}"><i data-feather="log-in"></i> <span class="tip">Login</span></a></li>
<li><a href="{{ route('register') }}"><i data-feather="user-plus"></i>
<span class="tip">Register</span></a></li>
<li><a href="{{ route('auth') }}"><i data-feather="log-in"></i> <span class="tip">Login / Register</span></a></li>
{% endif %}
</ul>
</nav>


+ 0
- 27
views/mails/add_recovery_email.mjml.njk View File

@ -1,27 +0,0 @@
{% extends 'mails/base_layout.mjml.njk' %}
{% block body %}
<mj-section>
<mj-column>
<mj-text mj-class="title">
Add this email as recovery for {{ app.name }}
</mj-text>
<mj-text>
Someone wants to add <strong>{{ mail_to }}</strong> as a recovery email to their account.
<br><br>
<strong>Do not click on this if this is not you!</strong>
</mj-text>
<mj-button href="{{ link | safe }}">
Add as recovery email
</mj-button>
</mj-column>
</mj-section>
{% endblock %}
{% block text %}
Hi!
Someone wants to add {{ mail_to }} as a recovery email to their account.
To add it as a recovery email, please follow this link: {{ link|safe }}
{% endblock %}

+ 2798
- 2366
yarn.lock
File diff suppressed because it is too large
View File


Loading…
Cancel
Save