def bitbucket_hgrid_data(node_settings, auth, **kwargs): # Quit if no repo linked if not node_settings.complete: return connection = BitbucketClient(access_token=node_settings.external_account.oauth_key) node = node_settings.owner if node.is_public and not node.is_contributor(auth.user): repo = connection.repo(node_settings.user, node_settings.repo) if not repo: # TODO: Add warning message logger.error('Could not access Bitbucket repo') return None try: branch, sha, branches = get_refs( node_settings, branch=kwargs.get('branch'), sha=kwargs.get('sha'), connection=connection, ) except (NotFoundError, Exception): # TODO: Show an alert or change Bitbucket configuration? logger.error('Bitbucket repo not found') return ref = None if branch is None else ref_to_params(branch, sha) name_tpl = '{user}/{repo}'.format( user=node_settings.user, repo=node_settings.repo ) permissions = { 'edit': False, 'view': True, 'private': node_settings.is_private } urls = { 'upload': None, 'fetch': node_settings.owner.api_url + 'bitbucket/hgrid/' + (ref or ''), 'branch': node_settings.owner.api_url + 'bitbucket/hgrid/root/', 'zip': node_settings.owner.api_url + 'bitbucket/zipball/' + (ref or ''), 'repo': 'https://bitbucket.com/{0}/{1}/branch/'.format(node_settings.user, node_settings.repo) } branch_names = [each['name'] for each in branches] if not branch_names: branch_names = [branch] # if repo un-init-ed then still add default branch to list of branches return [rubeus.build_addon_root( node_settings, name_tpl, urls=urls, permissions=permissions, branches=branch_names, defaultBranch=branch, private_key=kwargs.get('view_only', None), )]
def to_json(self, user): ret = super(NodeSettings, self).to_json(user) user_settings = user.get_addon('bitbucket') ret.update({ 'user_has_auth': user_settings and user_settings.has_auth, 'is_registration': self.owner.is_registration, }) if self.user_settings and self.user_settings.has_auth: connection = BitbucketClient( access_token=self.api.fetch_access_token()) valid_credentials = True try: mine = connection.repos() ours = connection.team_repos() repo_names = [ '{0} / {1}'.format(repo['owner']['username'], repo['slug']) for repo in mine + ours ] except Exception: repo_names = [] valid_credentials = False owner = self.user_settings.owner if owner == user: ret.update({'repo_names': repo_names}) ret.update({ 'node_has_auth': True, 'bitbucket_user': self.user or '', 'bitbucket_repo': self.repo or '', 'bitbucket_repo_full_name': '{0} / {1}'.format(self.user, self.repo) if (self.user and self.repo) else '', 'auth_osf_name': owner.fullname, 'auth_osf_url': owner.url, 'auth_osf_id': owner._id, 'bitbucket_user_name': self.external_account.display_name, 'bitbucket_user_url': self.external_account.profile_url, 'is_owner': owner == user, 'valid_credentials': valid_credentials, 'addons_url': web_url_for('user_addons'), 'files_url': self.owner.web_url_for('collect_file_trees') }) return ret
def handle_callback(self, response): """View called when the OAuth flow is completed. Adds a new BitbucketUserSettings record to the user and saves the account info. """ client = BitbucketClient(access_token=response['access_token']) user_info = client.user() return { 'provider_id': user_info['uuid'], 'profile_url': user_info['links']['html']['href'], 'display_name': user_info['username'] }
def bitbucket_download_starball(node_addon, **kwargs): archive = kwargs.get('archive', 'tar') ref = request.args.get('sha', 'master') connection = BitbucketClient( access_token=node_addon.external_account.oauth_key) headers, data = connection.starball(node_addon.user, node_addon.repo, archive, ref) resp = make_response(data) for key, value in headers.iteritems(): resp.headers[key] = value return resp
def bitbucket_download_starball(node_addon, **kwargs): archive = kwargs.get('archive', 'tar') ref = request.args.get('sha', 'master') connection = BitbucketClient(access_token=node_addon.external_account.oauth_key) headers, data = connection.starball( node_addon.user, node_addon.repo, archive, ref ) resp = make_response(data) for key, value in headers.items(): resp.headers[key] = value return resp
def get_refs(addon, branch=None, sha=None, connection=None): """Get the appropriate branch name and sha given the addon settings object, and optionally the branch and sha from the request arguments. :param str branch: Branch name. If None, return the default branch from the repo settings. :param str sha: The SHA. :param Bitbucket connection: Bitbucket API object. If None, one will be created from the addon's user settings. """ connection = connection or BitbucketClient(access_token=addon.external_account.oauth_key) if sha and not branch: raise HTTPError(http.BAD_REQUEST) # Get default branch if not provided if not branch: branch = connection.repo_default_branch(addon.user, addon.repo) if branch is None: return None, None, None # Get branch list from Bitbucket API branches = connection.branches(addon.user, addon.repo) # identify commit sha for requested branch for each in branches: if branch == each['name']: sha = each['target']['hash'] break return branch, sha, [ {'name': x['name'], 'sha': x['target']['hash']} for x in branches ]
def to_json(self, user): ret = super(NodeSettings, self).to_json(user) user_settings = user.get_addon('bitbucket') ret.update({ 'user_has_auth': user_settings and user_settings.has_auth, 'is_registration': self.owner.is_registration, }) if self.user_settings and self.user_settings.has_auth: connection = BitbucketClient(access_token=self.api.fetch_access_token()) valid_credentials = True try: mine = connection.repos() ours = connection.team_repos() repo_names = [ '{0} / {1}'.format(repo['owner']['username'], repo['slug']) for repo in mine + ours ] except Exception: repo_names = [] valid_credentials = False owner = self.user_settings.owner if owner == user: ret.update({'repo_names': repo_names}) ret.update({ 'node_has_auth': True, 'bitbucket_user': self.user or '', 'bitbucket_repo': self.repo or '', 'bitbucket_repo_full_name': '{0} / {1}'.format(self.user, self.repo) if (self.user and self.repo) else '', 'auth_osf_name': owner.fullname, 'auth_osf_url': owner.url, 'auth_osf_id': owner._id, 'bitbucket_user_name': self.external_account.display_name, 'bitbucket_user_url': self.external_account.profile_url, 'is_owner': owner == user, 'valid_credentials': valid_credentials, 'addons_url': web_url_for('user_addons'), 'files_url': self.owner.web_url_for('collect_file_trees') }) return ret
class TestBitbucketSerializer(StorageAddonSerializerTestSuiteMixin, OsfTestCase): addon_short_name = 'bitbucket' Serializer = BitbucketSerializer ExternalAccountFactory = BitbucketAccountFactory client = BitbucketClient() def set_provider_id(self, pid): self.node_settings.repo = pid
def bitbucket_set_config(auth, **kwargs): node_settings = kwargs.get('node_addon', None) node = kwargs.get('node', None) user_settings = kwargs.get('user_addon', None) try: if not node: node = node_settings.owner if not user_settings: user_settings = node_settings.user_settings except AttributeError: raise HTTPError(http.BAD_REQUEST) # Parse request bitbucket_user_name = request.json.get('bitbucket_user', '') bitbucket_repo_name = request.json.get('bitbucket_repo', '') if not bitbucket_user_name or not bitbucket_repo_name: raise HTTPError(http.BAD_REQUEST) # Verify that repo exists and that user can access connection = BitbucketClient( access_token=node_settings.external_account.oauth_key) repo = connection.repo(bitbucket_user_name, bitbucket_repo_name) if repo is None: if user_settings: message = ('Cannot access repo. Either the repo does not exist ' 'or your account does not have permission to view it.') else: message = ('Cannot access repo.') return {'message': message}, http.BAD_REQUEST changed = (bitbucket_user_name != node_settings.user or bitbucket_repo_name != node_settings.repo) # Update hooks if changed: # # Delete existing hook, if any # node_settings.delete_hook() # Update node settings node_settings.user = bitbucket_user_name node_settings.repo = bitbucket_repo_name # Log repo select node.add_log( action='bitbucket_repo_linked', params={ 'project': node.parent_id, 'node': node._id, 'bitbucket': { 'user': bitbucket_user_name, 'repo': bitbucket_repo_name, } }, auth=auth, ) # # Add new hook # if node_settings.user and node_settings.repo: # node_settings.add_hook(save=False) node_settings.save() return {}
def bitbucket_set_config(auth, **kwargs): node_settings = kwargs.get('node_addon', None) node = kwargs.get('node', None) user_settings = kwargs.get('user_addon', None) try: if not node: node = node_settings.owner if not user_settings: user_settings = node_settings.user_settings except AttributeError: raise HTTPError(http.BAD_REQUEST) # Parse request bitbucket_user_name = request.json.get('bitbucket_user', '') bitbucket_repo_name = request.json.get('bitbucket_repo', '') if not bitbucket_user_name or not bitbucket_repo_name: raise HTTPError(http.BAD_REQUEST) # Verify that repo exists and that user can access connection = BitbucketClient(access_token=node_settings.external_account.oauth_key) repo = connection.repo(bitbucket_user_name, bitbucket_repo_name) if repo is None: if user_settings: message = ( 'Cannot access repo. Either the repo does not exist ' 'or your account does not have permission to view it.' ) else: message = ( 'Cannot access repo.' ) return {'message': message}, http.BAD_REQUEST changed = ( bitbucket_user_name != node_settings.user or bitbucket_repo_name != node_settings.repo ) # Update hooks if changed: # # Delete existing hook, if any # node_settings.delete_hook() # Update node settings node_settings.user = bitbucket_user_name node_settings.repo = bitbucket_repo_name # Log repo select node.add_log( action='bitbucket_repo_linked', params={ 'project': node.parent_id, 'node': node._id, 'bitbucket': { 'user': bitbucket_user_name, 'repo': bitbucket_repo_name, } }, auth=auth, ) # # Add new hook # if node_settings.user and node_settings.repo: # node_settings.add_hook(save=False) node_settings.save() return {}
def fetch_repo(self): connection = BitbucketClient(access_token=self.api.fetch_access_token()) return connection.repo(user=self.user, repo=self.repo)
def bitbucket_hgrid_data(node_settings, auth, **kwargs): # Quit if no repo linked if not node_settings.complete: return connection = BitbucketClient( access_token=node_settings.external_account.oauth_key) node = node_settings.owner if node.is_public and not node.is_contributor(auth.user): repo = connection.repo(node_settings.user, node_settings.repo) if not repo: # TODO: Add warning message logger.error('Could not access Bitbucket repo') return None try: branch, sha, branches = get_refs( node_settings, branch=kwargs.get('branch'), sha=kwargs.get('sha'), connection=connection, ) except (NotFoundError, Exception): # TODO: Show an alert or change Bitbucket configuration? logger.error('Bitbucket repo not found') return ref = None if branch is None else ref_to_params(branch, sha) name_tpl = '{user}/{repo}'.format(user=node_settings.user, repo=node_settings.repo) permissions = { 'edit': False, 'view': True, 'private': node_settings.is_private } urls = { 'upload': None, 'fetch': node_settings.owner.api_url + 'bitbucket/hgrid/' + (ref or ''), 'branch': node_settings.owner.api_url + 'bitbucket/hgrid/root/', 'zip': node_settings.owner.api_url + 'bitbucket/zipball/' + (ref or ''), 'repo': 'https://bitbucket.com/{0}/{1}/branch/'.format(node_settings.user, node_settings.repo) } branch_names = [each['name'] for each in branches] if not branch_names: branch_names = [ branch ] # if repo un-init-ed then still add default branch to list of branches return [ rubeus.build_addon_root( node_settings, name_tpl, urls=urls, permissions=permissions, branches=branch_names, defaultBranch=branch, private_key=kwargs.get('view_only', None), ) ]