import orientoDb from './orientoDb'
import mapObjectToResource from '../db/mapObjectToResource'

export default async function cookieAuthMiddleware(request, response, next) {
  if (!request.cookies.accessToken) {
    return next()
  }

  try {
    const token = await orientoDb
      .select()
      .from('AccessToken')
      .where({hash: request.cookies.accessToken})
      .one()

    const tokenResource = await mapObjectToResource(orientoDb, token)

    const user = await orientoDb
      .select()
      .from('User')
      .where({
        '@rid': request.tokenResource.relationships.user.data[0].id // TODO: fix
      })
      .one()

    const userResource = await mapObjectToResource(orientoDb, user)

    request.tokenResource = tokenResource
    request.userResource = userResource
  } finally {
    next()
  }
}

@@ -370,32 +370,70 @@
 )%0A      .one()%0A%0A
+    if (!token) %7B%0A      return%0A    %7D%0A%0A
     const tokenR
@@ -487,16 +487,96 @@
 token)%0A%0A
+    if (tokenResource.relationships.user.data.length %3C 1) %7B%0A      return%0A    %7D%0A%0A
     cons
@@ -667,24 +667,16 @@
 '@rid': 
-request.
 tokenRes
@@ -714,21 +714,8 @@
 %5D.id
- // TODO: fix
 %0A   
@@ -730,24 +730,61 @@
     .one()%0A%0A
+    if (!user) %7B%0A      return%0A    %7D%0A%0A
     const us
@@ -930,31 +930,59 @@
   %7D 
-finally %7B%0A    next()%0A  %7D
+catch (error) %7B%0A    return next(error)%0A  %7D%0A%0A  next()
 %0A%7D%0A

Fix cookieAuthMiddleware