swiftvaporserver-side-swift

Vapor - Create a room session with ID


I'm working on a Vapor backend and I'm looking to create sessions for single entry. The client should ask to create the session and the backend will return a session ID that the client can use.
This is the outline:

// routes.swift

func routes(_ app: App) throws {
    app.post("create_room") { req -> BaseResponse<CreateRoomResponse> in
        let roomName = try req.content.decode(CreateRoomRequest.self).name
        let roomId = "ABCD"
        
        // Create a session, store credentials...
        ...

        return CreateRoomResponse(status: .ok, payload: roomId)
    }
}

Now, I'm trying to figure out where to store the session data and ID for later use, and potentially destruction after x amount of time.
I've read in the Vapor documentation about both Authorization and Sessions but couldn't quite found something that fits my needs, or at least not in a way I can intuitively implement as my experience with backend programming is not great.
How would I go about to implement a session like this? Where do I store the credentials and how do I access them later down the way?
Thanks a lot in advance!


Solution

  • This should destroy the session and any data you have stored in session.data. If it is the first request in a session then the initialisation of lastRequestTimeStamp fails and defaults to the current time. It then stores the current time in session.data. If the request is more than 20 minutes since the last one, it logs the user out (which destroys the session) and re-directs to "/".

     struct SessionTimeoutMiddleware: Middleware {
         func respond(to request: Request, chainingTo next: Responder) -> EventLoopFuture<Response> {
             let lastRequestTimeStamp = Double(request.session.data["lastRequest"] ?? "BAD") ?? Date().timeIntervalSince1970
             request.session.data[C.Dict.Key.LastRequest] = String(Date().timeIntervalSince1970)
             if Date().timeIntervalSince1970 - lastRequestTimeStamp > 1200 { 
                 request.auth.logout(User.self)
                 return request.eventLoop.makeSucceededFuture(request.redirect(to: "/"))
             }
             return next.respond(to: request)
         }
     }
    

    And, finally, register the middleware in configure.swift.

    app.middleware.use(InternalErrorMiddleware())