Add documentation for multitenancy

This commit is contained in:
Javi Martín
2022-10-19 00:46:25 +02:00
parent b2cb72ae81
commit 0b7ecb7d54
9 changed files with 482 additions and 0 deletions

View File

@@ -45,6 +45,7 @@
* [Recommendations](en/features/recommendations.md) * [Recommendations](en/features/recommendations.md)
* [Configure Census Connection](en/features/census_configuration.md) * [Configure Census Connection](en/features/census_configuration.md)
* [Local Census](en/features/local_census.md) * [Local Census](en/features/local_census.md)
* [Multitenancy](en/features/multitenancy.md)
* [Open Source project](en/open_source/open_source.md) * [Open Source project](en/open_source/open_source.md)
* [Code of conduct](en/open_source/code_of_conduct.md) * [Code of conduct](en/open_source/code_of_conduct.md)
@@ -97,6 +98,7 @@
* [Recomendaciones](es/features/recommendations.md) * [Recomendaciones](es/features/recommendations.md)
* [Configurar conexión con el Censo](es/features/census_configuration.md) * [Configurar conexión con el Censo](es/features/census_configuration.md)
* [Local Census](es/features/local_census.md) * [Local Census](es/features/local_census.md)
* [Multitenancy](es/features/multitenancy.md)
* [Proyecto Open Source](es/open_source/open_source.md) * [Proyecto Open Source](es/open_source/open_source.md)
* [Código de conducta](es/open_source/code_of_conduct.md) * [Código de conducta](es/open_source/code_of_conduct.md)

View File

@@ -0,0 +1,240 @@
# Multitenancy
## What's multitenancy and how does it work
The multitenancy feature allows managing several independent institutions ("tenants") using the same application. For example, in our case, a user who signs up for a certain tenant will only be able to sign in on that tenant, and that user's data won't be available from any other tenant.
Which tenant we're accessing depends on the URL we're using in the browser to access the application. In CONSUL, the current tenant is established by the subdomain used in this URL. For example, if we used the domain `solarsystemexample.org` to manage the planets in the Solar System, using the URL `https://mercury.solarsystemexample.org` we'd access data from the planet Mercury while using the URL `https://venus.solarsystemexample.org` we'd access data from the planet Venus. It's also be possible to use different domains per tenant (for example, `earthexample.org`).
## Enabling multitenancy
### Preliminary steps after upgrading from CONSUL version 1.5.0
If you're upgrading a CONSUL installation to version 2.0.0 from version 1.5.0, you'll have to follow these steps before enabling multitenancy. These steps aren't necessary on new CONSUL installations.
First, after deploying version 2.0.0 to your production server, execute the release tasks:
```
RAILS_ENV=production bin/rails consul:execute_release_tasks
```
After runing this command, you might get the following warning:
> The database search path has been updated. Restart the application to apply the changes.
If that's the case, restart the application. If not, make sure the `config/database.yml` file contains the line `schema_search_path: "public,shared_extensions"` and, if that's not the case, add it for example below the line saying `adapter: postgresql` and restart the application.
Next, open a database console with a user having permission to create and manage database extensions:
```
sudo -u postgres psql -d consul_production
```
If you didn't use the [installer](https://github.com/consul/installer/) to install CONSUL, you might need to execute a couple of queries to make sure the Rails database user has permission to create schemas and the shared extensions schema has the right permissions:
```
CREATE SCHEMA shared_extensions AUTHORIZATION <replace_with_rails_database_username>;
GRANT CREATE ON DATABASE consul_production TO <replace_with_rails_database_username>;
GRANT usage ON SCHEMA shared_extensions TO public;
```
Whether or not you installed CONSUL with the installer, run:
```
ALTER EXTENSION pg_trgm SET SCHEMA shared_extensions;
ALTER EXTENSION unaccent SET SCHEMA shared_extensions;
```
### Common step for all CONSUL installations
There are two possible ways to enable multitenancy:
* Adding `config.multitenancy = true` inside the `class Application < Rails::Application` class in the `config/application_custom.rb` file
* Replacing the line `multitenancy: false` with `multitenancy: true` (or adding it if it isn't already there) in the `config/secrets.yml` file
The difference between these options is that the first one uses a file under version control while the second one uses a file which isn't under version control. Choose the first option if you'd like to have this change in your git repository; otherwise, use the second one.
After enabling this option, restart the application.
## Managing tenants
Once multitenancy has been enabled and the application has been restarted, you'll see a new "Multitenancy" section inside the "Settings" menu in the CONSUL admin panel.
![New section with the list of tenants, with their name and domain or subdomain](../../img/multitenancy/index-en.png)
This section will only be available from the "main" tenant (the one which is created by default). It will not be possible to add/edit tenants by accessing the admin section of any other tenant.
Since removing a tenant would delete **all** its associated data, making it impossible to restore it, CONSUL doesn't allow deleting a tenant using the admin panel. However, it's possible to disable a tenant so it cannot be accessed.
The interface to manage tenants is very simple, needing just a name and a domain or subdomain.
![Form to edit a tenant, with name and domain or subdomain fields; radio buttons are used to choose domain or subdomain](../../img/multitenancy/form-en.png)
The name will be used to set the default site name for new tenants. Note that, once a tenant is created, changing this name will have no effect. To change the site name of an existing tenant, edit it in the "Global settings" section in the administration of that tenant.
The domain or subdomain will be used to access this tenant. If you've got a domain like `solarsystemexample.org` and would like to access tenants using subdomains (like `mars.solarsystemexample.org`), choose "Use a subdomain". If you're using a different domain for the tenant (like `marsexample.org`), choose "Use a different domain".
Note that, if you use a different domain for a tenant, you'll have to configure your SSL certificates, web server and DNS so they support that domain and point to your CONSUL application.
When adding a new tenant, an admin user **copying the same login data as the administrator creating the tenant** will be automatically created. Note this user is stored in the database schema of the new tenant, so changing their password in one tenant won't change their password in any other tenants.
## Steps to take after adding a tenant
### SSL certificates
In order to make it possible to access the application using secure HTTPS/SSL connections, you'll need a valid SSL certificate for the tenant you've just added. Since every institution using CONSUL has a different system to manage these certificates, getting a valid SSL certificate for the new tenant will need a different process depending on the way your institution manages these certificates.
If you've installed CONSUL using the installer and are using Certbot to manage these certificates, you have two options.
One option would be adding each certificate manually every time you create a tenant. For example, in orer to add a tenant using the `mars` subdomain in the `solarsystemexample.org` domain, run:
```
sudo certbot certonly --nginx --noninteractive --agree-tos --expand -d solarsystemexample.org,mars.solarsystemexample.org
```
If you're going to add many subdomains at different times, this task can be tedious. Another option is enabling any subdomain. In order to achieve this goal, you need access to your DNS configuration in order to follow the instructions you'll get by either using one of the [Certbot DNS plugins](https://eff-certbot.readthedocs.io/en/stable/using.html#dns-plugins) or the [manual generation of the certificate](https://eff-certbot.readthedocs.io/en/stable/using.html#manual) with the following command:
```
sudo certbot certonly --manual --agree-tos --expand -d solarsystemexample.org,*.solarsystemexample.org
```
You'll be asked to create a DNS TXT record with the subdomain `_acme-challenge` on your domain, with a certain value. You might also be asked to create a file with a certain name containing a certain content (usually in a `.well-known/acme-challenge` folder); if that's the case, assuming you're using CONSUL's default folders, create it in `/home/deploy/consul/current/public/.well-known/acme-challenge/`.
After doing so, update your web server configuration file (by default `/etc/nginx/sites-enabled/default`) so it uses the generated certificate, and restart the web server with `sudo systemctl restart nginx`.
### Sending e-mails
In order to reduce the chance your application sends emails which are erronously identified as spam, you might want to edit the fields "Sender email name" and "Sender email address" in the administration panel of the new tenant. The default values for these fields are the name and subdomain introduced when creating the tenant.
![Fields to edit sender email name and address](../../img/multitenancy/email-settings-en.png)
If you'd like to use a different mail configuration for the new tenant, like one for a hypothetical `jupiter` subdomain, edit the `config/secrets.yml` file this way:
```
production:
# (...) Other secrets
multitenancy: true
tenants:
jupiter:
mailer_delivery_method: :smtp
smtp_settings:
:address: <mail_server>
:port: <port>
:domain: <your_domain>
:user_name: <username>
:password: <password>
:authentication: "plain"
:enable_starttls_auto: true
# (...) Other secrets
```
After editing this file, restart the application.
### Sign in via social networks
If you've configured applications so users can sign in via Twitter, Google, Facebook or Wordpress, you need to allow the new tenant to access these applications. You have two options.
The first option is changing your existing application using the Twitter/Google/Facebook/Wordpress dashboard and add the new tenant's URL to the list of allowed domains. When doing so, take into account your application's terms and conditions settings, which might not be compatible with this option.
The other option is creating a new Twitter/Google/Facebook/Wordpress application and configuring it so it can be used from the new tenant. In this case, you'll have to add the configuration of this application to the `config/secrets.yml` file. For example, if you've added a tenant using the `saturn` subdomain, edit the file this way, filling in the keys and secrets of the services you're using:
```
production:
# (...) Other secrets
multitenancy: true
tenants:
saturn:
twitter_key: <twitter_key>
twitter_secret: <twitter_secret>
facebook_key: <facebook_key>
facebook_secret: <facebook_secret>
google_oauth2_key: <google_key>
google_oauth2_secret: <google_secret>
wordpress_oauth2_key: <wordpress_key>
wordpress_oauth2_secret: <wordpress_secret>
wordpress_oauth2_site: <wordpress_site>
# (...) Other secrets
```
After editing this file, restart the application.
## Information to take into account during development
### Maintenance of the schema.rb file
When CONSUL creates a tenant, it loads the content of the `db/schema.rb` file to create a new database schema for the new tenant. This means that if for some reason this file doesn't contain the same database structure you'd get by creating a new database and running the migrations with `rake db:migrate`, you could end up with different database table or columns on different tenants. This could result in a disastrous situation.
In order to avoid it, we recommend checking the integrity of the `db/schema.rb` file in your continuous integration system. If you're doing continuous intergration using GitHub Actions, you can use the workflow already included in CONSUL. Pull requests adding this check on GitLab CI or other continuous intergration environments are welcome.
### Using custom styles for a tenant with CSS
When the multitenancy feature is enabled, CONSUL adds a class to the `<html>` element, making it possible to apply styles (or JavaScript events) to just a specific tenant. For example, the tenant with the `uranus` subdomain would have the `tenant-uranus` class.
This way, it'll be possible to overwrite the default styles for just this tenant by creating a new stylesheet in the `app/assets/stylesheets/custom/` folder:
```
.tenant-uranus {
// Styles that will only be applied to the Uranus tenant
}
```
To easily change the default colors on a specific tenant, you can use CSS variables; their usage is documented in the [app/assets/stylesheets/custom/tenants.scss](https://github.com/consul/consul/blob/master/app/assets/stylesheets/custom/tenants.scss) file. For example, to make the brand colors green on the tenant with the `uranus` subdomain, write:
```
.tenant-uranus {
--brand: #350;
--brand-secondary: #173a00;
}
```
### Using different custom ERB views for a tenant
Sometimes it might be convenient to use completely different views for different tenants. For example, a certain tenant might use a footer that has nothing to do with the default one.
In these cases, instead of adding conditions like `case Tenant.current_schema` to the view, using a different file might result in code easier to maintain.
For this purpose, we can use [Rails variants](https://guides.rubyonrails.org/layouts_and_rendering.html#the-variants-option), which means that, for example, a tenant named `milky-way` will use a view file ending with `.html+milky-way.erb` if it's available. That is, in order to use a different `application.html.erb` layout for the `milky-way` tenant, add a new file under `app/views/custom/layouts/application.html+milky-way.erb`.
We recommend only using this feature when there are substantial differences between the default view and the specific view for a tenant. If the differences are small, use `if` or `case` conditions instead in order to avoid code duplication.
The same principle works for components too, but in this case, when using the `custom/` folder to add ERB files for a tenant, the default tenant ERB file needs to be added to the `custom/` folder as well; if there aren't changes to this file, a symbolic link will do.
For example, if you're writing a custom `admin/action_component` component view for the `milky-way` tenant but don't need to change this file for the default tenant:
1. Create the `app/components/custom/admin/action_component.rb` file according to the [components customization documentation](../customization/components.md)
1. Create the custom view for the `milky-way` tenant and save it under `app/components/custom/admin/action_component.html+milky-way.erb`
1. Enter the `app/components/custom/admin/` folder and run `ln -s ../../admin/action_component.html.erb`
## Current limitations of multitenancy
The multitenancy feature was first included in CONSUL 2.0.0 and there are a few things that are still missing.
### Applications which can be accessed from multiple domains
You might have a CONSUL application which can be accessed from two different domains; for example, `solarsystemexample.org` and a domain in Spanish named `ejemplodesistemasolar.org`.
In this case, the source code needs to be changed a little so multitenancy works with both domains. In particular, the `allowed_domains` method in the `Tenant` class needs to be changed in order to include both domains. See the [models customization documentation](../customization/models.md) for examples on how to customize methods like this one.
### Custom images per tenant
The administration panel in CONSUL contains a "Custom images" section, where you can customize some (but not all) images appearing in the application. Using this interface allows having different images per tenant.
Sometimes it's useful to have a certain image under version control, though. For instance, if we'd like to use a different logo for a tenant with the `neptune` subdomain, we'd put that file under `app/assets/images/custom/tenants/neptune/logo_header.png`.
However, this will only work for images which can already be configured through the administration interface. If you'd like to customize a different image, you'll have to change the code rendering it. For instance, to make it possible to customize the `avatar_admin.png` image, replace the code `image_tag("avatar_admin.png")` with `image_tag(image_path_for("avatar_admin.png"))`.
### Databases on different servers for different tenants
In CONSUL 2.0.0, data from all tenants is stored in the same database and so it isn't possible to use several databases on different servers.
If this feature is requested often, it'll be possible to include it in CONSUL in the future. However, CONSUL 2.0.0 uses Rails 6.0 and this feature will require upgrading to Rails 6.1 or even Rails 7.0.
### Different languages per tenant
In CONSUL 2.0.0, every tenant is available in the same languages, so it wouldn't be possible (for instance) to enable French in one tenant and German in a different one; you'd have to enable both languages in both tenants.
Implementing this feature is planned for CONSUL 2.1.0.
### Deleting tenants
Since removing a tenant would delete **all** its associated data, making it impossible to restore it, CONSUL doesn't allow deleting tenants using the admin panel and only allows disabling them so they cannot be accessed. To completely delete a tenant, use the Rails console.

View File

@@ -0,0 +1,240 @@
# Multientidad
## Qué es multientidad y cómo funciona
La funcionalidad denominada "multientidad" permite la gestión de varias instituciones ("entidades") independientes dentro de una misma aplicación. Por ejemplo, en nuestro caso, un usuario que se dé de alta en una entidad estará solamente dado de alta en esa entidad y sus datos no serán accesibles desde ninguna de las otras entidades.
A qué entidad accedemos se determina a partir de la URL a la que se accede con el navegador. En CONSUL se determina esta entidad a partir del subdominio de esta URL; por ejemplo, si utilizásemos el dominio `ejemplodesistemasolar.org` para gestionar los diferentes planetas del sistema solar, al acceder a `https://mercurio.ejemplodesistemasolar.org` accederíamos a los datos del planeta Mercurio mientras que al acceder a `https://venus.ejemplodesistemasolar.org` accederíamos a los datos del planeta Venus. También es posible utilizar distintos dominios por entidad (por ejemplo, `ejemplodetierra.org`).
## Habilitar multientidad
### Pasos preliminares tras actualizar desde la versión 1.5.0 de CONSUL
Si has actualizado una instalación de CONSUL a la versión 2.0.0 desde la versión 1.5.0, deberás realizar los siguientes pasos antes de habilitar multientidad. Estos pasos no son necesarios en nuevas instalaciones de CONSUL.
Así, en primer lugar, tras subir la versión 2.0.0 al servidor de producción, tendrás que ejecutar las tareas de actualización de versión:
```
RAILS_ENV=production bin/rails consul:execute_release_tasks
```
Es posible que, tras ejecutar esta orden, veas el siguiente aviso:
> The database search path has been updated. Restart the application to apply the changes.
Si es así, reincia la aplicación. Si no has recibido este aviso, comprueba que el fichero `config/database.yml` contiene la línea `schema_search_path: "public,shared_extensions"` y, de no ser así, añádela por ejemplo bajo la línea que dice `adapter: postgresql` y reincia la aplicación.
Una vez hecho esto, deberás abrir una consola de base de datos utilizando un usuario que tenga permisos para crear y modificar extensiones de base de datos:
```
sudo -u postgres psql -d consul_production
```
Si no usaste el [instalador](https://github.com/consul/installer/) para instalar CONSUL, es posible que tengas que ejecutar las siguientes consultas de base de datos para garantizar los permisos del usuario de Rails para crear esquemas así como el acceso al esquema de extensiones compartidas:
```
CREATE SCHEMA shared_extensions AUTHORIZATION <reemplazar_con_usuario_de_rails_de_base_de_datos>;
GRANT CREATE ON DATABASE consul_production TO <reemplazar_con_usuario_de_rails_de_base_de_datos>;
GRANT usage ON SCHEMA shared_extensions TO public;
```
Tanto si usaste el instalador como si no, ejecuta:
```
ALTER EXTENSION pg_trgm SET SCHEMA shared_extensions;
ALTER EXTENSION unaccent SET SCHEMA shared_extensions;
```
### Paso común a todas las instalaciones de CONSUL
Existen dos posibles maneras de habilitar multientidad:
* Añadiendo `config.multitenancy = true` dentro de la clase `class Application < Rails::Application` del fichero `config/application_custom.rb`
* Cambiando la línea `multitenancy: false` por `multitenancy: true` (o añadiéndola si no está ya ahí) en el fichero `config/secrets.yml`
La diferencia entre ambas opciones está en que la primera utiliza un fichero que se encuentra bajo control de versiones y la segunda un fichero que no se encuentra bajo control de versiones. Elige la primera opción si deseas este cambio en el código de tu repositorio git y la segunda opción en caso contrario.
Tras habilitar esta opción, reinicia la aplicación.
## Gestión de entidades
Una vez habilitada la funcionalidad de multientidad y reiniciada la aplicación, aparecerá una nueva sección "Multientidad" dentro del menú "Configuración" de la administración de CONSUL.
![Nueva sección con el listado de entidades, con su nombre y dominio o subdominio](../../img/multitenancy/index-es.png)
Esta sección solamente estará disponible desde la entidad "principal" (la que se crea por defecto). Las entidades que se creen desde aquí no tendrán acceso a esta sección y por tanto no podrán a su vez añadir o editar nuevas entidades.
Dado que eliminar una entidad borraría **todos** los datos relacionados con esa entidad y no se podrían restaurar, no existe la opción de eliminar una entidad ya creada desde este panel de administración. Sin embargo, es posible deshabilitar una entidad, haciendo que sea imposible acceder a la misma.
La interfaz de administración de entidades es muy sencilla, necesitando solamente un nombre y un subdominio.
![Formulario de edición de entidad, con nombre y dominio o subdominio; es posible seleccionar si se utiliza un dominio o un subdominio](../../img/multitenancy/form-es.png)
El nombre se usará como nombre del sitio por defecto para nuevas entidades. Nótese que, una vez una entidad se ha creado, cambiar este nombre no tendrá ningún efecto. Para cambiar el nombre del sitio de una entidad existente, edítalo en la sección "Configuración global" de la administración de esa entidad.
El dominio o subdominio será el que la aplicación utilice para acceder a la entidad. Si tienes un dominio como `ejemplodesistemasolar.org` y quieres acceder a las entidades utilizando subdominios (como `marte.ejemplodesistemasolar.org`), elige "Utiliza un subdominio". Si estás usando un dominio diferente para la entidad (como `ejemplodemarte.org`), elige "Utiliza un dominio distinto".
Nótese que, si estás usando un dominio distinto para una entidad, tendrás que configurar tus certificados SSL, servidor web y DNS para que acepten ese dominio y apunten a tu aplicación CONSUL.
Al añadir una nueva entidad, se creará automáticamente un usuario con permiso de administrador para esta nueva entidad **cuyos datos de acceso serán una copia de los del administrador que crea la entidad**. Este usuario se almacenará en el esquema de base de datos de la nueva entidad, con lo que cambiar su contraseña en una entidad no cambiará su contraseña en otras entidades.
## Pasos a realizar tras añadir una entidad
### Certificados SSL
Para que la aplicación sea accesible utilizando conexiones seguras de HTTPS/SSL, deberás tener un certificado SSL válido para la entidad que acabas de añadir. Dado que cada institución que utiliza CONSUL tiene su propio sistema para gestionar estos certificados, conseguir un certificado para la nueva entidad variará en función del sistema que utilice tu institución.
Si has instalado CONSUL usando el instalador y estás usando Certbot para gestionar estos certificados, tienes dos opciones.
Una opción es añadir manualmente cada certificado cada vez que creas una entidad. Por ejemplo, para añadir la entidad con subdominio `marte` al dominio `ejemplodesistemasolar.org`, ejecuta:
```
sudo certbot certonly --nginx --noninteractive --agree-tos --expand -d ejemplodesistemasolar.org,marte.ejemplodesistemasolar.org
```
Si vas a añadir muchos subdominios en distintos momentos, esta tarea puede resultar tediosa. Una alternativa es habilitar cualquier subdominio. Para conseguir esto, deberás tener acceso al panel de administración de tu dominio (DNS) para poder seguir las instrucciones al utilizar bien alguno de los [plugins DNS de Certbot](https://eff-certbot.readthedocs.io/en/stable/using.html#dns-plugins) o la [generación manual del certificado](https://eff-certbot.readthedocs.io/en/stable/using.html#manual) con la siguiente orden:
```
sudo certbot certonly --manual --agree-tos --expand -d ejemplodesistemasolar.org,*.ejemplodesistemasolar.org
```
Se te pedirá crear un registro TXT en el DNS de tu dominio con el subdominio `_acme-challenge` y con un cierto valor. También es posible que se te pida crear un archivo con un cierto nombre y un cierto contenido (normalmente en un directorio llamado `.well-known/acme-challenge`); si ese es el caso, asumiendo que estás usando los directorios por defecto de CONSUL, crea el fichero en `/home/deploy/consul/current/public/.well-known/acme-challenge/`.
Después de esto, actualiza la configuración de tu servidor web (por defecto, `/etc/nginx/sites-enabled/default`) para que use el certificado que se ha generado, y reinicia el servidor web con `sudo systemctl restart nginx`.
### Envío de correos electrónicos
Para disminuir la probabilidad de que los correos enviados por la aplicación sean identificados como fraudulentos, puede que quieras editar los campos "Nombre email remitente" y "Dirección email remitente" en el panel de administración de la nueva entidad. Los valores por defecto de estos campos son el nombre y el subdominio que se utilizaron al crear la entidad.
![Campos para editar el nombre y la dirección del remitente](../../img/multitenancy/email-settings-es.png)
Si quieres utilizar una configuración de envío de correo electrónico diferente para una entidad, como podría ser una que utilice `jupiter` como subdominio, edita el fichero `config/secrets.yml` de la siguiente manera:
```
production:
# (...) Otros secretos
multitenancy: true
tenants:
jupiter:
mailer_delivery_method: :smtp
smtp_settings:
:address: <servidor_de_correo>
:port: <puerto>
:domain: <tu_dominio>
:user_name: <usuario>
:password: <contraseña>
:authentication: "plain"
:enable_starttls_auto: true
# (...) Otros secretos
```
Tras editar el fichero, reinicia la aplicación.
### Identificación mediante redes sociales
Si utilizas aplicaciones para que los usuarios puedan identificarse mediante Twitter, Google, Facebook o Wordpress, deberás hacer que la nueva entidad pueda identificarse con estos servicios. Para ello, tienes dos opciones.
Como primera opción, en el panel de configuración de Twitter/Google/Facebook/Wordpress, puedes modificar tu aplicación existente y añadir la URL de la nueva entidad en la lista de dominios permitidos. Al hacer esto, ten en cuenta la configuración de los términos y condiciones de tu aplicación, que puede no siempre ser compatible con esta opción.
Y como segunda opción, puedes crear una nueva aplicación de Twitter/Google/Facebook/Wordpress y configurarla para su uso desde el dominio de la nueva entidad. En este caso, deberás añadir la configuración de esta aplicación al fichero `config/secrets.yml`. Por ejemplo, si administrases una entidad con el subdominio `saturno`, edita el fichero de esta manera, rellenando la información de aquellos servicios que estés utilizando:
```
production:
# (...) Otros secretos
multitenancy: true
tenants:
saturno:
twitter_key: <clave_twitter>
twitter_secret: <secreto_twitter>
facebook_key: <clave_facebook>
facebook_secret: <secreto_facebook>
google_oauth2_key: <clave_google>
google_oauth2_secret: <secreto_google>
wordpress_oauth2_key: <clave_wordpress>
wordpress_oauth2_secret: <secreto_wordpress>
wordpress_oauth2_site: <sitio_wordpress>
# (...) Otros secretos
```
Tras editar el fichero, reinicia la aplicación.
## Información a tener en cuenta al realizar desarrollos
### Mantenimiento del fichero schema.rb
Cuando CONSUL crea una entidad, utiliza el fichero `db/schema.rb` para crear un nuevo esquema de la base de datos para esta entidad. Esto significa que, si por alguna razón este fichero no contiene la misma estructura de base de datos que se generaría creando una nueva base de datos y ejecutando las migraciones con `rake db:migrate`, podría darse el caso de que diferentes entidades tuvieran diferentes tablas o columnas en sus esquemas de base de datos. Las consecuencias de esta configuración podrían ser fatales.
Para evitarlo, recomendamos encarecidamente comprobar en tu sistema de integración continua que el fichero `db/schema.rb` que se encuentra en control de versiones es correcto. CONSUL incluye ya esta comprobación si realizas la integración continua con GitHub Actions. Contribuciones incluyendo esta comprobación en GitLab CI u otros entornos son más que bienvenidas.
### Estilos personalizados para cada entidad mediante CSS
Cuando la funcionalidad de multientidad está activada, CONSUL añade una clase al elemento `<html>` para que sea posible aplicar estilos (o eventos de JavaScript) solamente en ciertas entidades. Por ejemplo, en la entidad con subdominio `urano` este elemento tendría la clase `tenant-urano`.
Así, es posible sobrescribir los estilos para una entidad específica añadiendo a alguna hoja de estilos en la carpeta `app/assets/stylesheets/custom/`:
```
.tenant-urano {
// Estilos que solamente se aplican a Urano
}
```
Para cambiar los colores en una determinada entidad de forma sencilla, puedes utilizar variables de CSS; su uso aparece documentado en el fichero [app/assets/stylesheets/custom/tenants.scss](https://github.com/consul/consul/blob/master/app/assets/stylesheets/custom/tenants.scss). Por ejemplo, para utilizar tonos de verde en los colores principales de la entidad con subdominio `urano`, puedes escribir:
```
.tenant-urano {
--brand: #350;
--brand-secondary: #173a00;
}
```
### Vistas personalizadas para cada entidad con ERB
En ocasiones puede resultar conveniente utilizar vistas completamente distintas. Por ejemplo, una entidad podría usar un pie de página que no tuviera nada que ver con el de otras entidades.
En estos casos, en lugar de añadir condiciones como `case Tenant.current_schema` a la vista, usar un fichero distinto podría resultar en código más fácil de mantener.
Para esto, podemos usar las "[variantes](https://guides.rubyonrails.org/layouts_and_rendering.html#the-variants-option)" que ofrece Rails, que hacen que por ejemplo una entidad llamada `via-lactea` use como vista un fichero terminado en `.html+via-lactea.erb` si este fichero existe. Es decir, para usar un archivo `application.html.erb` diferente para la entidad `via-lactea`, crea un nuevo archivo en `app/views/custom/layouts/application.html+via-lactea.erb`.
Recomendamos utilizar esta funcionalidad solamente cuando haya diferencias sustanciales entre la vista por defecto y la vista específica para una entidad. Si las diferencias son pequeñas, usa condiciones `if` o `case` en su lugar para evitar duplicación de código.
El mismo principio funciona también con componentes, solo que en este caso, al usar el directorio `custom/` para añadir archivos ERB para una entidad, el archivo ERB de la entidad por defecto también tiene que añadirse al directorio `custom/`; si no hay cambios en este fichero, valdrá con un enlace simbólico.
Por ejemplo, si estás escribiendo una vista personalizada del componente `admin/action_component` para la entidad `via-lactea` pero no vas a cambiar esta vista para la entidad por defecto:
1. Crea el archivo `app/components/custom/admin/action_component.rb` tal y como se indica en la [documentación de personalización de componentes](../customization/components.md)
1. Crea la vista personalizada para la entidad `via-lactea` y guárdala en `app/components/custom/admin/action_component.html+via-lactea.erb`
1. Entra en el directorio `app/components/custom/admin/` y ejecuta `ln -s ../../admin/action_component.html.erb`
## Limitaciones actuales de multientidad
La funcionalidad de multientidad se incluyó por primera vez en CONSUL 2.0.0 y hay algunas cosas que todavía no están disponibles.
### Aplicaciones disponibles desde múltiples dominios
Es posible que permitas acceder a tu aplicación de CONSUL desde dos dominios distintos; por ejemplo, `ejemplodesistemasolar.org` y un dominio en inglés llamado `solarsystemexample.org`.
En este caso, para conseguir que multientidad funcione con ambos dominios, es necesario cambiar ligeramente el código fuente de la aplicación. En concreto, hay que cambiar el método `allowed_domains` de la clase `Tenant` para que incluya ambos dominios. En la [documentación de personalización de modelos](../customization/models.md) puedes ver ejemplos de cómo personalizar métodos como este.
### Imágenes personalizadas por entidad
El panel de administración de CONSUL contiene una sección llamada "Personalizar imágenes", donde es posible personalizar algunas (aunque no todas) de las imágenes que aparecen en la aplicación. Usar esta interfaz permite tener imágenes distintas para cada entidad.
A veces, sin embargo, es útil incluir ciertas imágenes bajo control de versiones. Por ejemplo, si quisiéramos usar un logo distinto para una entidad en el subdominio `neptuno`, pondríamos ese archivo en `app/assets/images/custom/tenants/neptuno/logo_header.png`.
Este sistema tiene una limitación y es que solamente funcionará para imágenes que se pueden cambiar desde la interfaz de administración. Si quieres personalizar otra imagen, tendrás que cambiar el código que la renderiza. Por ejemplo, para que sea posible personalizar la imagen `avatar_admin.png`, cambia el código `image_tag("avatar_admin.png")` por `image_tag(image_path_for("avatar_admin.png"))`.
### Bases de datos en distintos servidores para cada entidad
En la versión 2.0.0 de CONSUL, los datos de todas las entidades se almacenan en la misma base de datos y por tanto no es posible usar bases de datos en distintos servidores.
En caso de que esta funcionalidad sea suficientemente solicitada, podrá incluirse en CONSUL en el futuro. Hay que tener en cuenta que la versión 2.0.0 de CONSUL utiliza Rails 6.0 y que para esta funcionalidad será necesario usar Rails 6.1 o incluso Rails 7.0.
### Idiomas distintos para distintas entidades
En la versión 2.0.0 de COSNSUL, todas las entidades están disponibles en los mismos idiomas, con lo que no sería posible (por ejemplo) que una entidad estuviera disponible en francés y otra en alemán, sino que ambas tendrían que estar disponibles en ambos idiomas.
Implementar esta posibilidad está planeado para la versión 2.1.0 de CONSUL.
### Borrado de entidades
Dado que eliminar una entidad borraría **todos** los datos relacionados con esa entidad y no se podrían restaurar, CONSUL no ofrece la opción de eliminar una entidad ya creada desde el panel de administración y solamente permite deshabilitarlas para que no sea posible acceder a ellas. Para eliminar una entidad, utiliza la consola de Rails.

Binary file not shown.

After

Width:  |  Height:  |  Size: 31 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 34 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 111 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 120 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 88 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 91 KiB