예제 #1
0
파일: views.py 프로젝트: fnet123/galaxy-1
class RemoveRole(APIView):
    authentication_classes = (TokenAuthentication, SessionAuthentication)
    permission_classes = (IsAuthenticated,)

    def delete(self, request, *args, **kwargs):

        gh_user = request.query_params.get('github_user',None)
        gh_repo = request.query_params.get('github_repo', None)
        
        if not gh_user or not gh_repo:
            raise ValidationError(dict(detail="Invalid request."))

        if not request.user.is_staff:
            # Verify via GitHub API that user has access to requested role
            try:
                token = SocialToken.objects.get(account__user=request.user, account__provider='github')
            except:
                msg = "Failed to get Github account for Galaxy user {0}. ".format(request.user.username) + \
                      "You must first authenticate with Github."
                raise ValidationError(dict(detail=msg))

            try:
                gh_api = Github(token.token)
                gh_api.get_api_status()
            except GithubException, e:
                msg = "Failed to connect to GitHub API. This is most likely a temporary error, " + \
                      "please try again in a few minutes. {0} - {1}".format(e.data, e.status)
                raise ValidationError(dict(detail=msg))
        
            try:
                ghu = gh_api.get_user()
            except:
                raise ValidationError(dict(detail="Failed to get Github authorized user."))

            allowed = False
            repo_full_name = "%s/%s" % (gh_user, gh_repo)
            for r in ghu.get_repos():
                if r.full_name == repo_full_name:
                    allowed = True
                    continue
            if not allowed:
                msg = "Galaxy user {0} does not have access to repo {1}".format(
                    request.user.username, repo_full_name)
                raise ValidationError(dict(detail=msg))

        # User has access. Delete requested role and associated bits.
        response = OrderedDict([
            ('deleted_roles', []),
            ('status', '')
        ])
        
        roles = Role.objects.filter(github_user=gh_user,github_repo=gh_repo)
        cnt = len(roles)
        if cnt == 0: 
            response['status'] = "Role %s.%s not found. Maybe it was deleted previously?" % (gh_user,gh_repo)
            return Response(response)
        elif cnt == 1:
            response['status'] = "Role %s.%s deleted" % (gh_user,gh_repo)
        else:
            response['status'] = "Deleted %d roles associated with %s/%s" % (len(roles),gh_user,gh_repo)

        for role in roles:
            response['deleted_roles'].append({
                "id": role.id,
                "namespace": role.namespace,
                "name": role.name,
                "github_user": role.github_user,
                "github_repo": role.github_repo
            })
            
            for notification in role.notifications.all():
                notification.delete()

            # update ES indexes
            update_custom_indexes.delay(username=role.namespace,
                                        tags=role.get_tags(),
                                        platforms=role.get_unique_platforms())
                
        # Update the repository cache
        for repo in Repository.objects.filter(github_user=gh_user, github_repo=gh_repo):
            repo.is_enabled = False
            repo.save()

        Role.objects.filter(github_user=gh_user, github_repo=gh_repo).delete()
        ImportTask.objects.filter(github_user=gh_user, github_repo=gh_repo).delete()

        return Response(response)
예제 #2
0
파일: tasks.py 프로젝트: fnet123/galaxy-1
        (import_state, warning_count, error_count))

    try:
        import_task.state = import_state
        import_task.finished = timezone.now()
        import_task.save()
        role.imported = timezone.now()
        role.is_valid = True
        role.save()
        transaction.commit()
    except Exception, e:
        fail_import_task(import_task, u"Error saving role: %s" % e.message)

    # Update ES indexes
    update_custom_indexes.delay(username=role.namespace,
                                tags=role.get_tags(),
                                platforms=role.get_unique_platforms())
    return True


@task(name="galaxy.main.celerytasks.tasks.refresh_user", throws=(Exception, ))
@transaction.atomic
def refresh_user_repos(user, token):
    logger.info(u"Refreshing User Repo Cache for {}".format(
        user.username).encode('utf-8').strip())

    try:
        gh_api = Github(token)
    except GithubException as exc:
        user.cache_refreshed = True
        user.save()