 module.exports = (req, res) ->
 
   unless code = req.query.code
-    console.error '[GITLAB][1/3] Failed to get code from query:', req.query
+    console.error '[GITLAB][1/4] Failed to get code from query:', req.query
     return fail req, res
 
-  options           =
-    url             : getUrlFor '/oauth/token'
-    method          : 'POST'
-    headers         : headers
-    json            :
-      redirect_uri  : gitlab.redirectUri
-      grant_type    : 'authorization_code'
-      client_id     : gitlab.applicationId
-      client_secret : gitlab.applicationSecret
-      code          : code
+  { clientId } = req.cookies
 
-  request options, authorizeUser req, res
+  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



# Get access token with code
authorizeUser = (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
    return fail req, res

  options   =
    url     : getUrlFor '/api/v3/user'
    method  : 'GET'
    headers : headers
    json    : { access_token }

  "#{url}#{path}"

fail = (req, res) ->
  redirectOauth 'could not grant access', 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][4/4] Failed to fetch user info:', error
    return fail req, res

  { username, id, email, name } = body
