Пример #1
0
def get_access_token(request):
    if request.GET['state'] != request.session['state']:
        return render_to_response('msg.html',{'msg':'Error, ; not an ethical attempt' },context_instance=RequestContext(request))
    data = {
        'client_id': client_id,
        'client_secret': client_secret,
        'code': request.GET['code'],
        'redirect_uri': host+'/add_hook'
    }
    res = requests.post('https://github.com/login/oauth/access_token',data=data)
    atts = res.text.split('&')
    d={}
    for att in atts:
        keyv = att.split('=')
        d[keyv[0]] = keyv[1]
    access_token = d['access_token']
    request.session['access_token'] = access_token
    update_g(access_token)
    print 'access_token: '+access_token
    rpy_wh = add_webhook(request.session['target_repo'], host+"/add_hook")
    rpy_coll = add_collaborator(request.session['target_repo'], ToolUser)
    error_msg = ""
    if rpy_wh['status'] == False:
        error_msg+=str(rpy_wh['error'])
        print 'error adding webhook: '+error_msg
    if rpy_coll['status'] == False:
        error_msg+=str(rpy_coll['error'])
        print 'error adding collaborator: '+rpy_coll['error']
    else:
        print 'adding collaborator: '+rpy_coll['msg']
    if error_msg != "":
        if 'Hook already exists on this repository' in error_msg:
            error_msg = 'This repository already watched'
        return render_to_response('msg.html',{'msg':error_msg },context_instance=RequestContext(request))
    return render_to_response('msg.html',{'msg':'webhook attached and user added as collaborator' },context_instance=RequestContext(request))
Пример #2
0
def profile(request):
    try:
        pass
    except Exception as e:
        print 'profile preparing log error [normal]: ' + str(e)
    print '************* profile ************'
    print str(datetime.today())
    ouser = OUser.objects.get(email=request.user.email)
    if 'repo' in request.GET:
        repo = request.GET['repo']
        print 'repo :<%s>' % (repo)
        print 'got the repo'
        try:
            print 'trying to validate repo'
            hackatt = True
            for repooo in ouser.repos:
                if repooo.url == repo:
                    hackatt = False
                    break
            if hackatt:  # trying to access a repo that does not belong to the use currently logged in
                return render(request, 'msg.html', {
                    'msg':
                    'This repo is not added, please do so in the main page'
                })
            print 'try to get abs folder'
            if type(autoncore.g) == type(None):
                print 'access token is: ' + request.session['access_token']
                update_g(request.session['access_token'])
            ontologies = parse_online_repo_for_ontologies(repo)
            print 'ontologies: ' + str(len(ontologies))
            for o in ontologies:
                for d in o:
                    print d + ': ' + str(o[d])
            print 'testing redirect'
            print 'will return the Json'
            html = render(request, 'profile_sliders.html', {
                'ontologies': ontologies
            }).content
            return JsonResponse({'ontologies': ontologies, 'sliderhtml': html})
        except Exception as e:
            print 'exception: ' + str(e)
    print 'testing redirect'
    repos = ouser.repos
    for r in repos:
        try:
            if len(r.url.split('/')) != 2:
                ouser.update(pull__repos=r)
                r.delete()
                ouser.save()
                continue
            r.user = r.url.split('/')[0]
            r.rrepo = r.url.split('/')[1]
        except:
            ouser.update(pull__repos=r)
            ouser.save()
    return render(request, 'profile.html', {'repos': repos})
Пример #3
0
def profile(request):
    try:
        #pass
        prepare_log(request.user.email)
    except Exception as e:
        print 'profile preparing log error [normal]: '+str(e)
    print '************* profile ************'
    #f=prepare_log('webinterface-'+request.user.email) # I am disabling this for now
    print str(datetime.today())
    ouser = OUser.objects.get(email=request.user.email)
    if 'repo' in request.GET:
        repo = request.GET['repo']
        print 'repo :<%s>'%(repo)
        print 'got the repo'
        #if True:
        try:
            print 'trying to validate repo' 
            hackatt = True
            for repooo  in  ouser.repos:
                if repooo.url == repo:
                    hackatt=False
                    break
            if hackatt: # trying to access a repo that does not belong to the use currently logged in
                return render(request,'msg.html',{'msg': 'This repo is not added, please do so in the main page'})
            print 'try to get abs folder'
            #ontologies_abs_folder = clone_repo('[email protected]:'+repo, request.user.email, dosleep=False)
            #ontologies_abs_folder ='/Users/blakxu/test123/OnToologyTestEnv/temp/[email protected]'
            #print 'abs folder: '+ontologies_abs_folder
            #ontologies = parse_folder_for_ontologies(ontologies_abs_folder)
            if type(autoncore.g) == type(None):
                print 'access token is: '+request.session['access_token']
                update_g(request.session['access_token'])
            ontologies = parse_online_repo_for_ontologies(repo)
            print 'ontologies: '+str(len(ontologies))
            for o in ontologies:
                for d in o:
                    print d+': '+str(o[d])
            #return_default_log()
            print 'testing redirect'
            #f.close()
            print 'will return the Json'
            #return JsonResponse({'foo': 'bar'})
            html = render(request,'profile_sliders.html',{'ontologies':ontologies}).content
            return JsonResponse({'ontologies':ontologies, 'sliderhtml': html})
            #return render(request,'profile.html',{'repos': get_repos_formatted(ouser.repos), 'ontologies': ontologies})
        #else:
        except Exception as e:
            print 'exception: '+str(e)
#     sys.stdout= sys.__stdout__
#     sys.stderr = sys.__stderr__
    print 'testing redirect'
    #f.close()
    return render(request,'profile.html',{'repos': get_repos_formatted(ouser.repos)})
Пример #4
0
def profile(request):
    try:
        pass
    except Exception as e:
        print 'profile preparing log error [normal]: ' + str(e)
    print '************* profile ************'
    print str(datetime.today())
    ouser = OUser.objects.get(email=request.user.email)
    if 'repo' in request.GET:
        repo = request.GET['repo']
        print 'repo :<%s>' % (repo)
        print 'got the repo'
        try:
            print 'trying to validate repo'
            hackatt = True
            for repooo in ouser.repos:
                if repooo.url == repo:
                    hackatt = False
                    break
            if hackatt:  # trying to access a repo that does not belong to the use currently logged in
                return render(request, 'msg.html', {'msg': 'This repo is not added, please do so in the main page'})
            print 'try to get abs folder'
            if type(autoncore.g) == type(None):
                print 'access token is: ' + request.session['access_token']
                update_g(request.session['access_token'])
            ontologies = parse_online_repo_for_ontologies(repo)
            print 'ontologies: ' + str(len(ontologies))
            for o in ontologies:
                for d in o:
                    print d + ': ' + str(o[d])
            print 'testing redirect'
            print 'will return the Json'
            html = render(request, 'profile_sliders.html', {'ontologies': ontologies}).content
            return JsonResponse({'ontologies': ontologies, 'sliderhtml': html})
        except Exception as e:
            print 'exception: ' + str(e)
    print 'testing redirect'
    repos = ouser.repos
    for r in repos:
        try:
            if len(r.url.split('/')) != 2:
                ouser.update(pull__repos=r)
                r.delete()
                ouser.save()
                continue
            r.user = r.url.split('/')[0]
            r.rrepo = r.url.split('/')[1]
        except:
            ouser.update(pull__repos=r)
            ouser.save()
    return render(request, 'profile.html', {'repos': repos})
Пример #5
0
def get_access_token(request):
    if request.GET['state'] != request.session['state']:
        return render_to_response('msg.html',
                                  {'msg': 'Error, ; not an ethical attempt'},
                                  context_instance=RequestContext(request))
    data = {
        'client_id': client_id,
        'client_secret': client_secret,
        'code': request.GET['code'],
        'redirect_uri': host + '/add_hook'
    }
    res = requests.post('https://github.com/login/oauth/access_token',
                        data=data)
    atts = res.text.split('&')
    d = {}
    for att in atts:
        keyv = att.split('=')
        d[keyv[0]] = keyv[1]
    access_token = d['access_token']
    request.session['access_token'] = access_token
    update_g(access_token)
    print 'access_token: ' + access_token
    rpy_wh = add_webhook(request.session['target_repo'], host + "/add_hook")
    rpy_coll = add_collaborator(request.session['target_repo'], ToolUser)
    error_msg = ""
    if rpy_wh['status'] == False:
        error_msg += str(rpy_wh['error'])
        print 'error adding webhook: ' + error_msg
    if rpy_coll['status'] == False:
        error_msg += str(rpy_coll['error'])
        print 'error adding collaborator: ' + rpy_coll['error']
    else:
        print 'adding collaborator: ' + rpy_coll['msg']
    if error_msg != "":
        if 'Hook already exists on this repository' in error_msg:
            error_msg = 'This repository already watched'
        return render_to_response('msg.html', {'msg': error_msg},
                                  context_instance=RequestContext(request))
    return render_to_response(
        'msg.html', {'msg': 'webhook attached and user added as collaborator'},
        context_instance=RequestContext(request))
Пример #6
0
def profile(request):
    print '************* profile ************'
    print str(datetime.today())
    error_msg = ''
    user = request.user
    if 'repo' in request.GET and 'name' not in request.GET:  # asking for ontologies in a repo
        repo = request.GET['repo']
        print 'repo :<%s>' % (repo)
        print 'got the repo'
        try:
            print 'trying to validate repo'
            hackatt = True
            for repooo in user.repos:
                if repooo.url == repo:
                    hackatt = False
                    break
            if hackatt:  # trying to access a repo that does not belong to the use currently logged in
                return render(request, 'msg.html', {
                    'msg':
                    'This repo is not added, please do so in the main page'
                })
            print 'try to get abs folder'
            if type(autoncore.g) == type(None):
                print 'access token is: ' + request.session['access_token']
                update_g(request.session['access_token'])
            try:
                ontologies = parse_online_repo_for_ontologies(repo)
                ontologies = autoncore.add_themis_results(repo, ontologies)
                print 'ontologies: ' + str(len(ontologies))
                arepo = Repo.objects.get(url=repo)
                pnames = PublishName.objects.filter(user=user, repo=arepo)
                for o in ontologies:
                    print '--------\n%s\n' % o
                    o['published'] = False
                    o['pname'] = ''
                    for pn in pnames:
                        if pn.ontology == o[
                                'ontology']:  # to compare without the leading /
                            o['published'] = True
                            o['pname'] = pn.name
                            break
                    for d in o:
                        print '   ' + d + ': ' + str(o[d])
                print 'testing redirect'
                print 'will return the Json'
                jresponse = JsonResponse({'ontologies': ontologies})
                jresponse.__setitem__('Content-Length', len(jresponse.content))
                sys.stdout.flush()
                sys.stderr.flush()
                return jresponse
            except Exception as e:
                print "exception in getting the ontologies for the repo: " + str(
                    repo)
                print "exception:  " + str(e)
                arepo = Repo.objects.get(url=repo)
                arepo.state = 'Invalid repository'
                arepo.save()
                ontologies = []
                jresponse = JsonResponse({'ontologies': ontologies})
                jresponse.__setitem__('Content-Length', len(jresponse.content))
                sys.stdout.flush()
                sys.stderr.flush()
                return jresponse
        except Exception as e:
            print 'exception: ' + str(e)

    elif 'delete-name' in request.GET:
        name = request.GET['delete-name']
        p = PublishName.objects.filter(name=name)
        if len(p) == 0:
            error_msg += 'This name is not reserved'
        elif p[0].user.id == user.id:
            pp = p[0]
            pp.delete()
            pp.save()
            comm = 'rm -Rf ' + os.path.join(publish_dir, name)
            call(comm, shell=True)
        else:
            error_msg += 'You are trying to delete a name that does not belong to you'
    print 'testing redirect'
    repos = user.repos
    for r in repos:
        try:
            if len(r.url.split('/')) != 2:
                user.update(pull__repos=r)
                r.delete()
                user.save()
                continue
            r.user = r.url.split('/')[0]
            r.rrepo = r.url.split('/')[1]
        except:
            user.update(pull__repos=r)
            user.save()
    request.GET = []
    sys.stdout.flush()
    sys.stderr.flush()

    if request.user.email in get_managers():
        num_pending_msgs = rabbit.get_pending_messages()
        num_of_rabbit_processes = get_num_of_processes_of_rabbit()
    else:
        num_pending_msgs = -2
        num_of_rabbit_processes = -2

    return render(
        request, 'profile.html', {
            'repos': repos,
            'pnames': PublishName.objects.filter(user=user),
            'num_pending_msgs': num_pending_msgs,
            'num_of_rabbit_processes': num_of_rabbit_processes,
            'error': error_msg,
            'manager': request.user.email in get_managers()
        })
Пример #7
0
def get_access_token(request):
    print "get_access_token"
    global is_private, client_id, client_secret
    if 'state' not in request.session or request.GET[
            'state'] != request.session['state']:
        return HttpResponseRedirect('/')
    data = {
        'client_id': client_id,
        'client_secret': client_secret,
        'code': request.GET['code'],
        'redirect_uri': host + '/add_hook'
    }
    res = requests.post('https://github.com/login/oauth/access_token',
                        data=data)
    try:
        atts = res.text.split('&')
        d = {}
        for att in atts:
            keyv = att.split('=')
            d[keyv[0]] = keyv[1]
    except Exception as e:
        print "Exception: %s" % str(e)
        print "response: %s" % str(res.text)
        return render(request, 'msg.html', {
            'Error getting the token from GitHub. please try again or contact us'
        })
    if 'access_token' not in d:
        print 'access_token is not there'
        print d
        return HttpResponseRedirect('/')

    access_token = d['access_token']
    request.session['access_token'] = access_token
    update_g(access_token)
    print 'access_token: ' + access_token

    if request.user.is_authenticated(
    ) and request.session['access_token_time'] == '1':
        request.session['access_token_time'] = '2'  # so we do not loop
        webhook_access_url, state = webhook_access(client_id,
                                                   host + '/get_access_token',
                                                   is_private)
        request.session['state'] = state
        return HttpResponseRedirect(webhook_access_url)

    rpy_wh = add_webhook(request.session['target_repo'], host + "/add_hook")
    rpy_coll = add_collaborator(request.session['target_repo'], ToolUser)
    error_msg = ""
    if rpy_wh['status'] == False:
        error_msg += str(rpy_wh['error'])
        print 'error adding webhook: ' + error_msg
    if rpy_coll['status'] == False:
        error_msg += str(rpy_coll['error'])
        print 'error adding collaborator: ' + rpy_coll['error']
    else:
        print 'adding collaborator: ' + rpy_coll['msg']
    if error_msg != "":
        if 'Hook already exists on this repository' in error_msg:
            error_msg = 'This repository already watched'
        elif '404' in error_msg:  # so no enough access according to Github troubleshooting guide
            error_msg = """You don\'t have permission to add collaborators and create webhooks to this repo or this
            repo does not exist. Note that if you can fork this repo, you can add it here"""
            return render(request, 'msg.html', {'msg': error_msg})
        else:
            print "error message not hook and not 404: " + error_msg
            print "target repo: " + request.session['target_repo']
            print "ToolUser: "******"My repositories" page, you can see the
          status of each repo.'''
    target_repo = request.session['target_repo']
    try:
        repo = Repo.objects.get(url=target_repo)
    except Exception as e:
        print str(e)
        repo = Repo()
        repo.url = target_repo
        repo.save()
    if request.user.is_authenticated():
        ouser = OUser.objects.get(email=request.user.email)
        if repo not in ouser.repos:
            ouser.repos.append(repo)
            ouser.save()
            generateforall(repo.url, ouser.email)
    return render(request, 'msg.html', {'msg': msg})
Пример #8
0
def profile(request):
    print '************* profile ************'
    print str(datetime.today())
    error_msg = ''
    user = request.user
    if 'repo' in request.GET and 'name' not in request.GET:  # asking for ontologies in a repo
        repo = request.GET['repo']
        print 'repo :<%s>' % (repo)
        print 'got the repo'
        try:
            print 'trying to validate repo'
            hackatt = True
            for repooo in user.repos:
                if repooo.url == repo:
                    hackatt = False
                    break
            if hackatt:  # trying to access a repo that does not belong to the use currently logged in
                return render(request, 'msg.html', {
                    'msg':
                    'This repo is not added, please do so in the main page'
                })
            print 'try to get abs folder'
            if type(autoncore.g) == type(None):
                print 'access token is: ' + request.session['access_token']
                update_g(request.session['access_token'])
            try:
                ontologies = parse_online_repo_for_ontologies(repo)
                print 'ontologies: ' + str(len(ontologies))
                arepo = Repo.objects.get(url=repo)
                pnames = PublishName.objects.filter(user=user, repo=arepo)
                for o in ontologies:
                    print '--------\n%s\n' % o
                    o['published'] = False
                    o['pname'] = ''
                    for pn in pnames:
                        if pn.ontology == o[
                                'ontology']:  # to compare without the leading /
                            o['published'] = True
                            o['pname'] = pn.name
                            break
                    for d in o:
                        print '   ' + d + ': ' + str(o[d])
                print 'testing redirect'
                print 'will return the Json'
                jresponse = JsonResponse({'ontologies': ontologies})
                jresponse.__setitem__('Content-Length', len(jresponse.content))
                sys.stdout.flush()
                sys.stderr.flush()
                return jresponse
            except Exception as e:
                print "exception in getting the ontologies for the repo: " + str(
                    repo)
                print "exception:  " + str(e)
                arepo = Repo.objects.get(url=repo)
                arepo.state = 'Invalid repository'
                arepo.save()
                ontologies = []
                jresponse = JsonResponse({'ontologies': ontologies})
                jresponse.__setitem__('Content-Length', len(jresponse.content))
                sys.stdout.flush()
                sys.stderr.flush()
                return jresponse
        except Exception as e:
            print 'exception: ' + str(e)
    # elif 'name' in request.GET:  # publish with a new name
    #     print request.GET
    #     name = request.GET['name']
    #     target_repo = request.GET['repo']
    #     ontology_rel_path = request.GET['ontology']
    #     found = False
    #     for r in user.repos:
    #         if target_repo == r.url:
    #             found = True
    #             repo = r
    #             break
    #     if found:  # if the repo belongs to the user
    #
    #         if len(PublishName.objects.filter(name=name)) > 1:
    #             error_msg = 'a duplicate published names, please contact us ASAP to fix it'
    #
    #         elif len(PublishName.objects.filter(name=name)) == 0 or (PublishName.objects.get(name=name).user == user and
    #                                                                  PublishName.objects.get(name=name).repo == repo and
    #                                                                  PublishName.objects.get(
    #                                                                      name=name).ontology == ontology_rel_path):
    #             if (len(PublishName.objects.filter(name=name)) == 0 and
    #                     len(PublishName.objects.filter(user=user, ontology=ontology_rel_path, repo=repo)) > 0):
    #                 error_msg += 'can not reserve multiple names for the same ontology'
    #             else:
    #                 autoncore.prepare_log(user.email)
    #                 # cloning_repo should look like '[email protected]:user/reponame.git'
    #                 cloning_repo = '[email protected]:%s.git' % target_repo
    #                 sec = ''.join([random.choice(string.ascii_letters + string.digits) for _ in range(4)])
    #                 folder_name = 'pub-' + sec
    #                 clone_repo(cloning_repo, folder_name, dosleep=True)
    #                 repo_dir = os.path.join(autoncore.home, folder_name)
    #                 doc_dir = os.path.join(repo_dir, 'OnToology', ontology_rel_path[1:], 'documentation')
    #                 print 'repo_dir: %s' % repo_dir
    #                 print 'doc_dir: %s' % doc_dir
    #                 htaccess_f = os.path.join(doc_dir, '.htaccess')
    #                 if not os.path.exists(htaccess_f):
    #                     print 'htaccess is not found'
    #                     # error_msg += 'make sure your ontology has documentation and htaccess'
    #                     error_msg += 'We couldn\'t reserve your w3id. Please make sure that your ontology has ' \
    #                                  'documentation and htacess. For that, click on "Generate documentation, diagrams' \
    #                                  ' and evaluation" on the menu, and once the process is completed, accept the ' \
    #                                  'pull request on you GitHub repository'
    #                 else:
    #                     print 'found htaccesss'
    #                     f = open(htaccess_f, 'r')
    #                     file_content = f.read()
    #                     f.close()
    #                     f = open(htaccess_f, 'w')
    #                     for line in file_content.split('\n'):
    #                         if line[:11] == 'RewriteBase':
    #                             f.write('RewriteBase /publish/%s \n' % name)
    #                         else:
    #                             f.write(line + '\n')
    #                     f.close()
    #                     # comm = 'rm -Rf /home/ubuntu/publish/%s' % name
    #                     comm = 'rm -Rf ' + os.path.join(publish_dir, name)
    #                     print(comm)
    #                     call(comm, shell=True)
    #                     # comm = 'mv %s /home/ubuntu/publish/%s' % (doc_dir, name)
    #                     comm = 'mv %s %s' % (doc_dir, os.path.join(publish_dir, name))
    #                     print comm
    #                     call(comm, shell=True)
    #                     if len(PublishName.objects.filter(name=name)) == 0:
    #                         p = PublishName(name=name, user=user, repo=repo, ontology=ontology_rel_path)
    #                         p.save()
    #         else:
    #             if PublishName.objects.get(name=name).user == user:
    #                 print 'same user'
    #             if PublishName.objects.get(name=name).repo == repo:
    #                 print 'same repo'
    #             if PublishName.objects.get(name=name).ontology == ontology_rel_path:
    #                 print 'same ontology'
    #             error_msg += ' Name already taken'
    #     else:  # not found
    #         error_msg += 'You should add this repo to OnToology first'

    elif 'delete-name' in request.GET:
        name = request.GET['delete-name']
        p = PublishName.objects.filter(name=name)
        if len(p) == 0:
            error_msg += 'This name is not reserved'
        elif p[0].user.id == user.id:
            pp = p[0]
            pp.delete()
            pp.save()
            # comm = 'rm -Rf /home/ubuntu/publish/%s' % name
            comm = 'rm -Rf ' + os.path.join(publish_dir, name)
            call(comm, shell=True)
        else:
            error_msg += 'You are trying to delete a name that does not belong to you'
    print 'testing redirect'
    repos = user.repos
    for r in repos:
        try:
            if len(r.url.split('/')) != 2:
                user.update(pull__repos=r)
                r.delete()
                user.save()
                continue
            r.user = r.url.split('/')[0]
            r.rrepo = r.url.split('/')[1]
        except:
            user.update(pull__repos=r)
            user.save()
    request.GET = []
    sys.stdout.flush()
    sys.stderr.flush()
    return render(
        request, 'profile.html', {
            'repos': repos,
            'pnames': PublishName.objects.filter(user=user),
            'error': error_msg,
            'manager': request.user.email in get_managers()
        })
Пример #9
0
def profile(request):
    try:
        #pass
        prepare_log(request.user.email)
    except Exception as e:
        print 'profile preparing log error [normal]: ' + str(e)
    print '************* profile ************'
    #f=prepare_log('webinterface-'+request.user.email) # I am disabling this for now
    print str(datetime.today())
    ouser = OUser.objects.get(email=request.user.email)
    if 'repo' in request.GET:
        repo = request.GET['repo']
        print 'repo :<%s>' % (repo)
        print 'got the repo'
        #if True:
        try:
            print 'trying to validate repo'
            hackatt = True
            for repooo in ouser.repos:
                if repooo.url == repo:
                    hackatt = False
                    break
            if hackatt:  # trying to access a repo that does not belong to the use currently logged in
                return render(request, 'msg.html', {
                    'msg':
                    'This repo is not added, please do so in the main page'
                })
            print 'try to get abs folder'
            #ontologies_abs_folder = clone_repo('[email protected]:'+repo, request.user.email, dosleep=False)
            #ontologies_abs_folder ='/Users/blakxu/test123/OnToologyTestEnv/temp/[email protected]'
            #print 'abs folder: '+ontologies_abs_folder
            #ontologies = parse_folder_for_ontologies(ontologies_abs_folder)
            if type(autoncore.g) == type(None):
                print 'access token is: ' + request.session['access_token']
                update_g(request.session['access_token'])
            ontologies = parse_online_repo_for_ontologies(repo)
            print 'ontologies: ' + str(len(ontologies))
            for o in ontologies:
                for d in o:
                    print d + ': ' + str(o[d])
            #return_default_log()
            print 'testing redirect'
            #f.close()
            print 'will return the Json'
            #return JsonResponse({'foo': 'bar'})
            html = render(request, 'profile_sliders.html', {
                'ontologies': ontologies
            }).content
            return JsonResponse({'ontologies': ontologies, 'sliderhtml': html})
            #return render(request,'profile.html',{'repos': get_repos_formatted(ouser.repos), 'ontologies': ontologies})
        #else:
        except Exception as e:
            print 'exception: ' + str(e)


#     sys.stdout= sys.__stdout__
#     sys.stderr = sys.__stderr__
    print 'testing redirect'
    #f.close()
    return render(request, 'profile.html',
                  {'repos': get_repos_formatted(ouser.repos)})
Пример #10
0
def get_access_token(request):
    if 'state' not in request.session or request.GET[
            'state'] != request.session['state']:
        return HttpResponseRedirect('/')
    data = {
        'client_id': client_id,
        'client_secret': client_secret,
        'code': request.GET['code'],
        'redirect_uri': host + '/add_hook'
    }
    res = requests.post('https://github.com/login/oauth/access_token',
                        data=data)
    atts = res.text.split('&')
    d = {}
    for att in atts:
        keyv = att.split('=')
        d[keyv[0]] = keyv[1]
    if 'access_token' not in d:
        print 'access_token is not there'
        return HttpResponseRedirect('/')
    access_token = d['access_token']
    request.session['access_token'] = access_token
    update_g(access_token)
    print 'access_token: ' + access_token

    if request.user.is_authenticated(
    ) and request.session['access_token_time'] == '1':
        request.session['access_token_time'] = '2'  # so we do not loop
        isprivate = get_proper_loggedin_scope(
            OUser.objects.get(username=request.user.username),
            request.session['target_repo'])
        print 'isprivate is: ' + str(isprivate)
        webhook_access_url, state = webhook_access(client_id,
                                                   host + '/get_access_token',
                                                   isprivate)
        request.session['state'] = state
        return HttpResponseRedirect(webhook_access_url)

    rpy_wh = add_webhook(request.session['target_repo'], host + "/add_hook")
    rpy_coll = add_collaborator(request.session['target_repo'], ToolUser)
    error_msg = ""
    if rpy_wh['status'] == False:
        error_msg += str(rpy_wh['error'])
        print 'error adding webhook: ' + error_msg
    if rpy_coll['status'] == False:
        error_msg += str(rpy_coll['error'])
        print 'error adding collaborator: ' + rpy_coll['error']
    else:
        print 'adding collaborator: ' + rpy_coll['msg']
    if error_msg != "":
        if 'Hook already exists on this repository' in error_msg:
            error_msg = 'This repository already watched'
        elif '404' in error_msg:  # so no enough access according to Github troubleshooting guide
            error_msg = """You don\'t have permission to add collaborators and create webhooks to this repo or this
            repo does not exist. Note that if you can fork this repo, you can add it here"""
            return render_to_response('msg.html', {'msg': error_msg},
                                      context_instance=RequestContext(request))
        msg = error_msg
    else:
        msg = 'webhook attached and user added as collaborator'
    target_repo = request.session['target_repo']
    try:
        repo = Repo.objects.get(url=target_repo)
    except Exception as e:
        print str(e)
        repo = Repo()
        repo.url = target_repo
        repo.save()
    if request.user.is_authenticated():
        ouser = OUser.objects.get(email=request.user.email)
        if repo not in ouser.repos:
            ouser.repos.append(repo)
            ouser.save()
            generateforall(repo.url, ouser.email)
    return render_to_response('msg.html', {'msg': msg},
                              context_instance=RequestContext(request))
Пример #11
0
def get_access_token(request):
    if 'state' not in request.session or request.GET['state'] != request.session['state']:
        return HttpResponseRedirect('/')
    data = {
        'client_id': client_id,
        'client_secret': client_secret,
        'code': request.GET['code'],
        'redirect_uri': host + '/add_hook'
    }
    res = requests.post('https://github.com/login/oauth/access_token', data=data)
    atts = res.text.split('&')
    d = {}
    for att in atts:
        keyv = att.split('=')
        d[keyv[0]] = keyv[1]
    if 'access_token' not in d:
        print 'access_token is not there'
        return HttpResponseRedirect('/')
    access_token = d['access_token']
    request.session['access_token'] = access_token
    update_g(access_token)
    print 'access_token: ' + access_token

    if request.user.is_authenticated() and request.session['access_token_time'] == '1':
        request.session['access_token_time'] = '2'  # so we do not loop
        isprivate = get_proper_loggedin_scope(OUser.objects.get(username=request.user.username),
                                              request.session['target_repo'])
        print 'isprivate is: ' + str(isprivate)
        webhook_access_url, state = webhook_access(client_id, host + '/get_access_token', isprivate)
        request.session['state'] = state
        return HttpResponseRedirect(webhook_access_url)

    rpy_wh = add_webhook(request.session['target_repo'], host + "/add_hook")
    rpy_coll = add_collaborator(request.session['target_repo'], ToolUser)
    error_msg = ""
    if rpy_wh['status'] == False:
        error_msg += str(rpy_wh['error'])
        print 'error adding webhook: ' + error_msg
    if rpy_coll['status'] == False:
        error_msg += str(rpy_coll['error'])
        print 'error adding collaborator: ' + rpy_coll['error']
    else:
        print 'adding collaborator: ' + rpy_coll['msg']
    if error_msg != "":
        if 'Hook already exists on this repository' in error_msg:
            error_msg = 'This repository already watched'
        elif '404' in error_msg:  # so no enough access according to Github troubleshooting guide
            error_msg = """You don\'t have permission to add collaborators and create webhooks to this repo or this
            repo does not exist. Note that if you can fork this repo, you can add it here"""
            return render_to_response('msg.html', {'msg': error_msg}, context_instance=RequestContext(request))
        msg = error_msg
    else:
        msg = 'webhook attached and user added as collaborator'
    target_repo = request.session['target_repo']
    try:
        repo = Repo.objects.get(url=target_repo)
    except Exception as e:
        print str(e)
        repo = Repo()
        repo.url = target_repo
        repo.save()
    if request.user.is_authenticated():
        ouser = OUser.objects.get(email=request.user.email)
        if repo not in ouser.repos:
            ouser.repos.append(repo)
            ouser.save()
            generateforall(repo.url, ouser.email)
    return render_to_response('msg.html', {'msg': msg},
                              context_instance=RequestContext(request))