You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: docs/advanced/sessions.es.md
+38-37Lines changed: 38 additions & 37 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -1,101 +1,102 @@
1
-
# Sessions
1
+
# Sesiones
2
2
3
-
Sessions allow you to persist a user's data between multiple requests. Sessions work by creating and returning a unique cookie alongside the HTTP response when a new session is initialized. Browsers will automatically detect this cookie and include it in future requests. This allows Vapor to automatically restore a specific user's session in your request handler.
3
+
Las sesiones te permiten conservar los datos de un usuario entre varias solicitudes. Las sesiones funcionan creando y devolviendo una cookie única junto con la respuesta HTTP cuando se inicializa una nueva sesión. Los navegadores detectarán automáticamente esta cookie y la incluirán en futuras solicitudes. Esto permite que Vapor restaure automáticamente la sesión de un usuario específico en su controlador de solicitudes.
4
4
5
-
Sessions are great for front-end web applications built in Vapor that serve HTML directly to web browsers. For APIs, we recommend using stateless, [token-based authentication](../security/authentication.md)to persist user data between requests.
5
+
Las sesiones son ideales para aplicaciones web front-end creadas en Vapor que sirven HTML directamente a los navegadores web. Para APIs, recomendamos usar autenticación sin estado, [autenticación basada en tokens](../security/authentication.md)para persistir los datos del usuario entre solicitudes.
6
6
7
-
## Configuration
7
+
## Configuración
8
8
9
-
10
-
To use sessions in a route, the request must pass through `SessionsMiddleware`. The easiest way to achieve this is by adding this middleware globally. It is recommended that you do add this after you declare the cookie factory. This is because Sessions is a struct, therefore it is a value type, and not a reference type. Since it is a value type, you must set the value before using `SessionsMiddleware`.
9
+
Para usar sesiones en una ruta, la solicitud debe pasar por `SessionsMiddleware`. La forma más fácil de lograr esto es agregando este middleware globalmente. Se recomienda que lo agregues después de declarar la fábrica de cookies. Esto se debe a que Sessions es una estructura, por lo tanto, es un tipo por valor y no un tipo por referencia. Dado que es un tipo por valor, debes establecer el valor antes de usar `SessionsMiddleware`.
11
10
12
11
```swift
13
12
app.middleware.use(app.sessions.middleware)
14
13
```
15
14
16
-
If only a subset of your routes utilize sessions, you can instead add `SessionsMiddleware`to a route group.
15
+
Si solo un subconjunto de tus rutas utiliza sesiones, puedes añadir `SessionsMiddleware`a un grupo de rutas.
17
16
18
17
```swift
19
18
let sessions = app.grouped(app.sessions.middleware)
20
19
```
21
20
22
-
The HTTP cookie generated by sessions can be configured using`app.sessions.configuration`. You can change the cookie name and declare a custom function for generating cookie values.
21
+
La cookie HTTP generada por las sesiones se puede configurar usando`app.sessions.configuration`. Puedes cambiar el nombre de la cookie y declarar una función personalizada para generar valores de las cookies.
23
22
24
23
```swift
25
-
//Change the cookie name to "foo".
24
+
//Cambia el nombre de la cookie a "foo".
26
25
app.sessions.configuration.cookieName="foo"
27
26
28
-
//Configures cookie value creation.
27
+
//Configura la creación del valor de la cookie.
29
28
app.sessions.configuration.cookieFactory= { sessionID in
30
29
.init(string: sessionID.string, isSecure: true)
31
30
}
32
31
33
32
app.middleware.use(app.sessions.middleware)
34
33
```
35
34
36
-
By default, Vapor will use `vapor_session` as the cookie name.
37
-
38
-
## Drivers
35
+
De manera predeterminada, Vapor usará `vapor_session` como nombre de la cookie.
39
36
40
-
Session drivers are responsible for storing and retrieving session data by identifier. You can create custom drivers by conforming to the `SessionDriver` protocol.
37
+
## Controladores
41
38
42
-
!!! warning
43
-
The session driver should be configured _before_ adding `app.sessions.middleware` to your application.
39
+
Los controladores de sesión son responsables de almacenar y recuperar datos de sesión por identificador. Puedes crear controladores personalizados conformando al protocolo `SessionDriver`.
44
40
45
-
### In-Memory
41
+
!!! warning "Advertencia"
42
+
El controlador de sesión debe configurarse _antes_ de añadir `app.sessions.middleware` a tu aplicación.
43
+
44
+
### En Memoria
46
45
47
-
Vapor utilizes in-memory sessions by default. In-memory sessions require zero configuration and do not persist between application launches which makes them great for testing. To enable in-memory sessions manually, use`.memory`:
46
+
Vapor utiliza sesiones en memoria por defecto. Las sesiones en memoria no requieren ninguna configuración y no persisten entre lanzamientos de la aplicación, lo que las hace ideales para realizar pruebas. Para habilitar en memoria las sesiones de forma manual, usa`.memory`:
48
47
49
48
```swift
50
49
app.sessions.use(.memory)
51
50
```
52
51
53
-
For production use cases, take a look at the other session drivers which utilize databases to persist and share sessions across multiple instances of your app.
52
+
Para casos de uso en producción, echa un vistazo a los otros controladores de sesión que utilizan bases de datos para persistir y compartir sesiones a través de múltiples instancias de tu aplicación.
54
53
55
54
### Fluent
56
55
57
-
Fluent includes support for storing session data in your application's database. This section assumes you have [configured Fluent](../fluent/overview.md)and can connect to a database. The first step is to enable the Fluent sessions driver.
56
+
Fluent incluye soporte para almacenar datos de sesión en la base de datos de tu aplicación. Esta sección supone que has [configurado Fluent](../fluent/overview.md)y puedes conectarte a una base de datos. El primer paso es habilitar el controlador de sesiones de Fluent.
58
57
59
58
```swift
60
59
importFluent
61
60
62
61
app.sessions.use(.fluent)
63
62
```
64
63
65
-
This will configure sessions to use the application's default database. To specify a specific database, pass the database's identifier.
64
+
Esto configurará las sesiones para usar la base de datos por defecto de la aplicación. Para especificar una base de datos específica, pasa el identificador de la base de datos.
66
65
67
66
```swift
68
67
app.sessions.use(.fluent(.sqlite))
69
68
```
70
69
71
70
Finally, add `SessionRecord`'s migration to your database's migrations. This will prepare your database for storing session data in the `_fluent_sessions` schema.
72
71
72
+
Por último, añade la migración de `SessionRecord` a las migraciones de tu base de datos. Esto preparará tu base de datos para almacenar datos de sesión en el esquema `_fluent_sessions`.
73
+
73
74
```swift
74
75
app.migrations.add(SessionRecord.migration)
75
76
```
76
77
77
-
Make sure to run your application's migrations after adding the new migration. Sessions will now be stored in your application's database allowing them to persist between restarts and be shared between multiple instances of your app.
78
+
Asegúrate de ejecutar las migraciones de tu aplicación después de añadir la nueva migración. Las sesiones ahora se almacenarán en la base de datos de tu aplicación, permitiendo que se persistan entre reinicios y sean compartidas entre varias instancias de tu aplicación.
78
79
79
80
### Redis
80
81
81
-
Redis provides support for storing session data in your configured Redis instance. This section assumes you have [configured Redis](../redis/overview.md)and can send commands to the Redis instance.
82
+
Redis proporciona soporte para almacenar datos de sesión en tu instancia Redis configurada. Esta sección supone que has [configurado Redis](../redis/overview.md)y puedes enviar comandos a la instancia Redis.
82
83
83
-
To use Redis for Sessions, select it when configuring your application:
84
+
Para usar Redis para sesiones, selecciónalo al configurar tu aplicación:
84
85
85
86
```swift
86
87
importRedis
87
88
88
89
app.sessions.use(.redis)
89
90
```
90
91
91
-
This will configure sessions to use the Redis sessions driver with the default behavior.
92
-
93
-
!!! seealso
94
-
Refer to [Redis → Sessions](../redis/sessions.md) for more detailed information about Redis and Sessions.
92
+
Esto configurará las sesiones para usar el controlador de sesiones Redis con el comportamiento por defecto.
95
93
96
-
## Session Data
94
+
!!! seealso "Ver también"
95
+
Consulte [Redis → Sessions](../redis/sessions.md) para obtener información más detallada sobre Redis y Sessions.
96
+
97
+
## Datos de Sesión
97
98
98
-
Now that sessions are configured, you are ready to persist data between requests. New sessions are initialized automatically when data is added to `req.session`. The example route handler below accepts a dynamic route parameter and adds the value to`req.session.data`.
99
+
Ahora que las sesiones están configuradas, estás listo para persistir datos entre solicitudes. Las nuevas sesiones se inicializan automáticamente cuando se añaden datos a `req.session`. A continuación, el controlador de ruta de ejemplo acepta un parámetro de ruta dinámica y agrega el valor a`req.session.data`.
Notice the `set-cookie`header has been added automatically to the response after adding data to`req.session`. Including this cookie in subsequent requests will allow access to the session data.
123
+
Observa que la cabecera `set-cookie`se ha añadido automáticamente a la respuesta después de añadir datos a`req.session`. Incluir esta cookie en solicitudes posteriores permitirá acceder a los datos de la sesión.
123
124
124
-
Add the following route handler for accessing the name value from the session.
125
+
Añade el siguiente controlador de ruta para acceder al valor del nombre desde la sesión.
125
126
126
127
```swift
127
128
app.get("get") { req ->Stringin
128
129
req.session.data["name"] ??"n/a"
129
130
}
130
131
```
131
132
132
-
Use the following request to access this route while making sure to pass the cookie value from the previous response.
133
+
Utiliza la siguiente solicitud para acceder a esta ruta asegurándote de pasar el valor de la cookie de la respuesta anterior.
133
134
134
135
```http
135
136
GET /get HTTP/1.1
136
137
cookie: vapor-session=123
137
138
```
138
139
139
-
You should see the name Vapor returned in the response. You can add or remove data from the session as you see fit. Session data will be synchronized with the session driver automatically before returning the HTTP response.
140
+
Deberías ver el nombre Vapor devuelto en la respuesta. Puedes añadir o eliminar datos de la sesión como creas conveniente. Los datos de la sesión se sincronizarán con el controlador de sesión automáticamente antes de devolver la respuesta HTTP.
140
141
141
-
To end a session, use`req.session.destroy`. This will delete the data from the session driver and invalidate the session cookie.
142
+
Para finalizar una sesión, utiliza`req.session.destroy`. Esto eliminará los datos del controlador de sesión e invalidará la cookie de sesión.
Copy file name to clipboardExpand all lines: docs/advanced/sessions.md
-1Lines changed: 0 additions & 1 deletion
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -6,7 +6,6 @@ Sessions are great for front-end web applications built in Vapor that serve HTML
6
6
7
7
## Configuration
8
8
9
-
10
9
To use sessions in a route, the request must pass through `SessionsMiddleware`. The easiest way to achieve this is by adding this middleware globally. It is recommended that you do add this after you declare the cookie factory. This is because Sessions is a struct, therefore it is a value type, and not a reference type. Since it is a value type, you must set the value before using `SessionsMiddleware`.
0 commit comments