 { argv }  = require 'optimist'
 KONFIG    = require('koding-config-manager').load("main.#{argv.c}")
+async     = require 'async'
 
-{ daisy }                          = require 'bongo'
-{ checkAuthorizationBearerHeader } = require '../../helpers'
 { sendApiError
   verifyApiToken
   sendApiResponse
   checkApiAvailability }           = require './helpers'
+{ checkAuthorizationBearerHeader } = require '../../helpers'
 
 apiErrors = require './errors'
 


  queue = [

    ->
      verifyApiToken token, (err, apiToken_) ->
        return sendApiError res, err  if err

        apiToken = apiToken_
        queue.next()

    ->
      # checking if user exists
      JAccount.one { 'profile.nickname' : username }, (err, account_) ->
        return sendApiError res, apiErrors.internalError    if err
        return sendApiError res, apiErrors.invalidUsername  unless account_
        account = account_
        queue.next()

    ->
      # checking if user is a member of the group of api token
      client = { connection : { delegate : account } }
      account.checkGroupMembership client, apiToken.group, (err, isMember) ->
        return sendApiError res, apiErrors.internalError    if err
        return sendApiError res, apiErrors.notGroupMember   unless isMember
        queue.next()

    ->
      data    = { username, group : apiToken.group }
      options = { expiresInMinutes : 60 }
      token   = JUser.createJWT data, options

      port       = if publicPort in ['80', '443'] then '' else ":#{publicPort}"

      loginUrl = "#{protocol}://#{host}#{port}/#{URL}"
      sendApiResponse res, { token, loginUrl }
      next()

  ]

  async.series queue



