from tornado.auth import OAuth2Mixin,_auth_return_future
import settings

class GitLabOAuth2Mixin(OAuth2Mixin):
    _OAUTH_SETTINGS_KEY = 'GITLAB_OAUTH'
    _OAUTH_AUTHORIZE_URL = settings[self._OAUTH_SETTINGS_KEY]['authorize_url']
    _OAUTH_ACCESS_TOKEN_URL = settings[self._OAUTH_SETTINGS_KEY]['access_token_url']
    _OAUTH_USERINFO_URL = settings[self._OAUTH_SETTINGS_KEY]['user_info_url']
    _OAUTH_NO_CALLBACKS = False
    
    @_auth_return_future
    def get_authenticated_user(self, redirect_uri, code, callback):
        http = self.get_auth_http_client()
        body = urllib_parse.urlencode({
            "redirect_uri": redirect_uri,
            "code": code,
            "client_id": settings[self._OAUTH_SETTINGS_KEY]['key'],
            "client_secret": settings[self._OAUTH_SETTINGS_KEY]['secret'],
            "grant_type": "authorization_code",
        })

        http.fetch(self._OAUTH_ACCESS_TOKEN_URL,
                   functools.partial(self._on_access_token, callback),
                   method="POST", headers={'Content-Type': 'application/x-www-form-urlencoded'}, body=body)

    def _on_access_token(self, future, response):
        if response.error:
            future.set_exception(AuthError('Google auth error: %s' % str(response)))
            return

        args = escape.json_decode(response.body)
        future.set_result(args)

@@ -50,16 +50,61 @@
 _future%0A
+from tornado.concurrent import return_future%0A
 import s
@@ -429,24 +429,101 @@
 _info_url'%5D%0A
+    _OAUTH_REDIRECT_URL = settings%5Bself._OAUTH_SETTINGS_KEY%5D%5B'redirect_url'%5D%0A
     _OAUTH_N
@@ -608,30 +608,16 @@
 er(self,
- redirect_uri,
  code, c
@@ -737,28 +737,40 @@
 t_uri%22: 
-redirect_uri
+self._OAUTH_REDIRECT_URL
 ,%0A      
@@ -1484,8 +1484,1069 @@
 t(args)%0A
+    %0A    @return_future%0A    def authorize_redirect(self,extra_params=None,callback=None):%0A        args = %7B%0A            %22redirect_uri%22: self._OAUTH_REDIRECT_URL,%0A            %22client_id%22: settings%5Bself._OAUTH_SETTINGS_KEY%5D%5B'key'%5D,%0A            %22response_type%22: %22code%22%0A        %7D%0A        self.redirect(url_concat(self._OAUTH_AUTHORIZE_URL, args))%0A        callback()%0A        %0A    @_auth_return_future%0A    def get_user_info(self,callback,access_token=None,post_args=None, **args):%0A        url = self._OAUTH_USERINFO_URL%0A        all_args = %7B%7D%0A        if access_token:%0A            all_args%5B%22access_token%22%5D = access_token%0A            all_args.update(args)%0A%0A        if all_args:%0A            url += %22?%22 + urllib_parse.urlencode(all_args)%0A        callback = functools.partial(self._on_oauth2_request, callback)%0A        http = self.get_auth_http_client()%0A        if post_args is not None:%0A            http.fetch(url, method=%22POST%22, body=urllib_parse.urlencode(post_args),%0A                       callback=callback)%0A        else:%0A            http.fetch(url, callback=callback)%0A

Update oauth.py