import urlparse class OAuthConfig(object): def __init__(self, app, key_name): self.key_name = key_name self.config = app.config.get(key_name) or {} def service_name(self): raise NotImplementedError def token_endpoint(self): raise NotImplementedError def user_endpoint(self): raise NotImplementedError def login_endpoint(self): raise NotImplementedError def client_id(self): return self.config.get('CLIENT_ID') def client_secret(self): return self.config.get('CLIENT_SECRET') def _get_url(self, endpoint, *args): for arg in args: endpoint = urlparse.urljoin(endpoint, arg) return endpoint class GithubOAuthConfig(OAuthConfig): def __init__(self, app, key_name): super(GithubOAuthConfig, self).__init__(app, key_name) def service_name(self): return 'GitHub' def _endpoint(self): endpoint = self.config.get('GITHUB_ENDPOINT', 'https://github.com') if not endpoint.endswith('/'): endpoint = endpoint + '/' return endpoint def authorize_endpoint(self): return self._get_url(self._endpoint(), '/login/oauth/authorize') + '?' def token_endpoint(self): return self._get_url(self._endpoint(), '/login/oauth/access_token') def _api_endpoint(self): return self.config.get('API_ENDPOINT', self._get_url(self._endpoint(), '/api/v3/')) def api_endpoint(self): return self._api_endpoint()[0:-1] def user_endpoint(self): api_endpoint = self._api_endpoint() return self._get_url(api_endpoint, 'user') def email_endpoint(self): api_endpoint = self._api_endpoint() return self._get_url(api_endpoint, 'user/emails') def get_public_config(self): return { 'CLIENT_ID': self.client_id(), 'AUTHORIZE_ENDPOINT': self.authorize_endpoint(), 'GITHUB_ENDPOINT': self._endpoint() } class GoogleOAuthConfig(OAuthConfig): def __init__(self, app, key_name): super(GoogleOAuthConfig, self).__init__(app, key_name) def service_name(self): return 'Google' def authorize_endpoint(self): return 'https://accounts.google.com/o/oauth2/auth?response_type=code&' def token_endpoint(self): return 'https://accounts.google.com/o/oauth2/token' def user_endpoint(self): return 'https://www.googleapis.com/oauth2/v1/userinfo' def get_public_config(self): return { 'CLIENT_ID': self.client_id(), 'AUTHORIZE_ENDPOINT': self.authorize_endpoint() }