 
 
 # Get access token with code
-authorizeUser = (req, res) -> (error, response, body) ->
+authorizeUser = (url, req, res) -> (error, response, body) ->
 
   if error or not access_token = body.access_token
-    console.error '[GITLAB][2/3] Failed to get access_token:', error
+    console.error '[GITLAB][3/4] Failed to get access_token:', error
     return fail req, res
 
   options   =
-    url     : getUrlFor '/api/v3/user'
+    url     : getPathFor url, '/api/v3/user'
     method  : 'GET'
     headers : headers
     json    : { access_token }

  "#{url}#{path}"

fail = (req, res) ->
  redirectOauth 'could not get access token', req, res, { provider }

# Get user info with access token
fetchUserInfo = (req, res, access_token) -> (error, response, body) ->

  if error or not id = body.id
    console.error '[GITLAB][3/3] Failed to fetch user info:', error
    return fail req, res

  { username, id, email, name } = body

module.exports = (req, res) ->

  unless code = req.query.code
    console.error '[GITLAB][1/4] Failed to get code from query:', req.query
    return fail req, res

  { clientId } = req.cookies

  fetchGroupSettings clientId, (err, settings) ->

    if err or not settings
      console.error '[GITLAB][2/4] Failed to fetch group settings:', err
      return fail req, res

    { url, applicationId, applicationSecret, redirectUri } = settings

    options           =
      url             : getPathFor url, '/oauth/token'
      method          : 'POST'
      headers         : headers
      json            :
        redirect_uri  : redirectUri
        grant_type    : 'authorization_code'
        client_id     : applicationId
        client_secret : applicationSecret
        code          : code

    request options, authorizeUser url, req, res
