       options.sort  = { 'meta.createdAt' : -1 }
       options.limit = Math.min limit ? 10, 25
 
-      group.fetchMembers$ client, {}, options, (err, members) ->
+      group.fetchMembers$ client, {}, options, (err, members_) ->
 
         if err and err.message is 'Access denied'
           params = { name, client, options, token }
-          return handleTokenedRequest params, res, next
+          handleTokenedRequest params, (err, members_) ->
+            return next err  if err
+            members = members_
+            return next()
         else if err
-          return res.status(500).send 'an error occured'
+          return next generateAPIError 500, 'an error occured'
         else
-          return res.status(200).send members
+          members = members_
+          return next()
 
   ]
 
-  async.series queue
+  async.series queue, (err) ->
+    return res.status(err.status).send err.message  if err
+    res.status(200).send members

  { limit, token }  = query
  { JGroup }        = koding.models

  group  = null
  client = null

  queue = [

    (next) ->
      isLoggedIn req, res, (err, loggedIn, account) ->
        return res.status(500).send 'an error occured'  if err
        next()

    (next) ->
      JGroup.one { slug : name }, (err, group_) ->
        return res.status(500).send 'an error occured'  if err
        return res.status(404).send 'no group found'    unless group_
        group = group_
        next()

    (next) ->
      generateFakeClient req, res, (err, client_) ->
        return res.status(500).send 'an error occured'  if err
        client = client_
        next()


koding                 = require './../bongo'
async                  = require 'async'

{ generateFakeClient } = require './../client'
{ isLoggedIn, generateAPIError } = require './../helpers'

# handleTokenedRequest handles the request if it has a token as query param,
# fetchMembers is secured by a permission, that can be turned off by default,
# but we want to show latest members to invited user
handleTokenedRequest = (params, callback) ->

  { JGroup, JInvitation }           = koding.models
  { name, options, token, client }  = params

  group   = null
  members = null

  queue = [

    (next) ->
      return next generateAPIError 403, 'not authorized'  unless token

      # fetch invitation
      JInvitation.byCode token, (err, token_) ->
        return next generateAPIError 403, 'not authorized'  if err or not token_
        next()

    (next) ->
      # fetch the group that we have in token
      JGroup.one { slug : name }, (err, group_) ->
        return next generateAPIError 403, 'an error occured'  if err
        return next generateAPIError 404, 'no group found'    unless group_

        group = group_
        # override group name with the one in token
