| 1 | module veb_middleware |
| 2 | |
| 3 | import x.sessions |
| 4 | import veb |
| 5 | |
| 6 | // create can be used to add session middleware to your veb app to ensure |
| 7 | // a valid session always exists. If a valid session exists the session data will |
| 8 | // be loaded into `session_data`, else a new session id will be generated. |
| 9 | // You have to pass the Context type as the generic type. |
| 10 | pub fn create[T, X](mut s sessions.Sessions[T]) veb.MiddlewareOptions[X] { |
| 11 | return veb.MiddlewareOptions[X]{ |
| 12 | handler: fn [mut s] [T, X](mut ctx X) bool { |
| 13 | // a session id is retrieved from the client, so it must be considered |
| 14 | // untrusted and has to be verified on every request |
| 15 | sid, valid := s.validate_session(ctx) |
| 16 | |
| 17 | if !valid { |
| 18 | if s.save_uninitialized { |
| 19 | // invalid session id, so create a new one |
| 20 | s.set_session_id(mut ctx) |
| 21 | } |
| 22 | return true |
| 23 | } |
| 24 | |
| 25 | ctx.CurrentSession.session_id = sid |
| 26 | if data := s.store.get(sid, s.max_age) { |
| 27 | ctx.CurrentSession.session_data = data |
| 28 | } |
| 29 | |
| 30 | return true |
| 31 | } |
| 32 | } |
| 33 | } |
| 34 | |