def index(request):
    """
    Step 1 of Google OAuth 2.0 flow.
    """
    # Create and store the per-user flow object
    FLOW = flow_from_clientsecrets(
        settings.GOOGLE_OAUTH2_CLIENT_SECRET_FILEPATH,
        scope=request.session.get('gauth_scope', ''),
        redirect_uri=request.build_absolute_uri(reverse('gauth_callback')))

    FLOW.params['access_type'] = 'offline'
    FLOW.params['approval_prompt'] = 'force'  # Properly gets refresh token
    FLOW.params['include_granted_scopes'] = 'true'  # incremental authorization
    FLOW.params['state'] = xsrfutil.generate_token(settings.SECRET_KEY,
                                                   request.user)

    authorize_url = FLOW.step1_get_authorize_url()
    flow_storage = DjangoORMStorage(FlowModel, 'id', request.user, 'flow')
    flow_storage.put(FLOW)

    # Don't worry if a next parameter is not set. `auth_return` will use the
    # homepage by default. Allows for `next_view` to be set from other places.
    try:
        request.session['next_view'] = request.GET['next']
    except KeyError:
        pass

    return redirect(authorize_url)
Exemple #2
0
def auth_return(request):
    if not xsrfutil.validate_token(settings.SECRET_KEY, request.GET['state'].encode('UTF-8'), request.user):
        return HttpResponseBadRequest()
    credential = FLOW.step2_exchange(request.GET)
    storage = DjangoORMStorage(CredentialsModel, 'id', request.user, 'credential')
    storage.put(credential)
    return HttpResponseRedirect("/")
Exemple #3
0
def get_user_credentials(client_service, client_id, client_secret):
    """Retrives the clients credentials from storage"""
    storage = DjangoORMStorage(Credentials, "id", client_service, "credential")
    local_credentials = storage.get(
    )  # load the user's credentials from storage
    if local_credentials:
        credentials = OAuth2Credentials(
            access_token=local_credentials.access_token,
            client_id=client_id,
            client_secret=client_secret,
            refresh_token=local_credentials.refresh_token,
            token_expiry=local_credentials.token_expiry,
            token_uri=local_credentials.token_uri,
            user_agent=local_credentials.user_agent,
            scopes=settings.GOOGLE_OAUTH2_CLIENT['scope'])
        try:
            if credentials.access_token_expired:
                credentials.refresh(httplib2.Http())  # Refresh access token
                storage.put(credentials)
            return credentials
        except AccessTokenRefreshError:
            # The access token is stale. Should be storing the refresh tokens?
            return None
    else:
        return None
Exemple #4
0
def auth_return(request):
    if not xsrfutil.validate_token(SECRET_KEY, request.GET.get('state').encode("ascii"), request.user):
        return  HttpResponseBadRequest('XSRF token could not be validated')
    credential = FLOW.step2_exchange(request.GET)
    storage = Storage(CredentialsModel, 'id', request.user, 'credential')
    storage.put(credential)
    return HttpResponseRedirect('/admin/haslerentries/entryset/')
Exemple #5
0
def auth_return(request):
    print(request.GET)
    if not xsrfutil.validate_token(settings.SECRET_KEY,
                                   request.GET['state'].encode('UTF-8'),
                                   request.user):
        return HttpResponseBadRequest()

    credential = FLOW.step2_exchange(request.GET)
    http = httplib2.Http()
    http = credential.authorize(http)
    service = build("gmail", "v1", http=http)
    try:
        label_object = {
            'messageListVisibility': "show",
            'name': "IFP",
            'labelListVisibility': "labelShow"
        }
        label = service.users().labels().create(userId='me',
                                                body=label_object).execute()
        print(label['id'])
    except errors.HttpError:
        print('An error occurred')
    storage = DjangoORMStorage(CredentialsModel, 'id', request.user,
                               'credential')
    storage.put(credential)
    return HttpResponseRedirect("/")
Exemple #6
0
def index(request):
    """
    Step 1 of Google OAuth 2.0 flow.
    """
    # Create and store the per-user flow object
    FLOW = flow_from_clientsecrets(
        settings.GOOGLE_OAUTH2_CLIENT_SECRET_FILEPATH,
        scope=request.session.get('gauth_scope', ''),
        redirect_uri=request.build_absolute_uri(reverse('gauth_callback')))

    FLOW.params['access_type'] = 'offline'
    FLOW.params['approval_prompt'] = 'force'  # Properly gets refresh token
    FLOW.params['include_granted_scopes'] = 'true'  # incremental authorization
    FLOW.params['state'] = xsrfutil.generate_token(settings.SECRET_KEY,
                                                   request.user)

    authorize_url = FLOW.step1_get_authorize_url()
    flow_storage = DjangoORMStorage(FlowModel, 'id', request.user, 'flow')
    flow_storage.put(FLOW)

    # Don't worry if a next parameter is not set. `auth_return` will use the
    # homepage by default. Allows for `next_view` to be set from other places.
    try:
        request.session['next_view'] = request.GET['next']
    except KeyError:
        pass

    return redirect(authorize_url)
Exemple #7
0
    def get(self, request, *args, **kwargs):
        """
        Defines view that handles redirect information from Google when authorizing access to a given navigator's
        Google Calendar

        :param request: django request instance object
        :rtype: HttpResponse
        """

        state_string = request.GET['state']
        state_dict = json.loads(
            base64.urlsafe_b64decode(state_string).decode('ascii'))
        if not xsrfutil.validate_token(settings.SECRET_KEY,
                                       bytes(state_dict['token'], 'utf-8'),
                                       state_dict["nav_id"]):
            return HttpResponseBadRequest()
        # if not xsrfutil.validate_token(SECRET_KEY, bytes(request.GET['state'], 'utf-8'), search_params["nav_id"]):
        #     return HttpResponseBadRequest()
        credential = FLOW.step2_exchange(request.REQUEST)
        storage = DjangoORMStorage(
            CredentialsModel, 'id',
            Navigators.objects.get(id=state_dict["nav_id"]), 'credential')
        storage.put(credential)
        return HttpResponseRedirect("/v2/calendar_auth/?nav_id={!s}".format(
            state_dict["nav_id"]))
Exemple #8
0
def google_auth_return(request):
    if not xsrfutil.validate_token(settings.SECRET_KEY, str(request.GET['state']),
                                   request.user):
        return HttpResponseBadRequest('Missing fields in request data')
    credential = FLOW.step2_exchange(request.GET)
    storage = DjangoORMStorage(UserProfile, 'user', request.user, 'google_credential')
    storage.put(credential)
    return HttpResponseRedirect("/timetable")
Exemple #9
0
 def get(self, request, *args, **kwargs):
     if not xsrfutil.validate_token(settings.SECRET_KEY, request.GET.get('state').encode(),request.user):
         return HttpResponseBadRequest()
     credential = flow.step2_exchange(request.GET)
     storage = DjangoORMStorage(
         CredentialsModel, 'id', request.user.id, 'credential')
     storage.put(credential)
     return redirect('/')
def auth_return(request):
  if not xsrfutil.validate_token(settings.SECRET_KEY, request.REQUEST['state'],
                                 request.user):
    return  HttpResponseBadRequest()
  credential = FLOW.step2_exchange(request.REQUEST)
  storage = DjangoORMStorage(CredentialsModel, 'id', request.user, 'credential')
  storage.put(credential)
  return HttpResponseRedirect("/")
Exemple #11
0
def authorize(request):
    global credentials
    global is_authorize
    credentials = flow.step2_exchange(request.GET)
    storage = DjangoORMStorage(CredentialsModel,'id',request.user.id,'credentials')
    storage.put(credentials)
    is_authorize = True
    return redirect('generate')
Exemple #12
0
def oauth2redirect(request):
    global flow
    # It is called after user allows the calender permission
    # stores the credentials and redirects to next
    credential = flow.step2_exchange(request.GET['code'])
    storage = Storage(SiteUser, 'user', request.user, 'credential')
    storage.put(credential)
    return HttpResponseRedirect(request.session.pop('redirect_url'))
Exemple #13
0
    def connect(self, flow, code):

        credentials = flow.step2_exchange(code)

        storage = DjangoORMStorage(YoutubeProfile, 'user', self.user, 'credentials')

        storage.put(credentials)

        return True
def calendar_auth_return(request):
    if not xsrfutil.validate_token(settings.SECRET_KEY,
                                   bytes(request.GET['state'], 'utf-8'),
                                   request.user):
        return HttpResponseBadRequest()
    credential = CALENDAR_FLOW.step2_exchange(request.GET)
    storage = DjangoORMStorage(CredentialsModel, 'user', request.user,
                               'credential')
    storage.put(credential)
    return redirect('calendar')
Exemple #15
0
 def get(self, request, *args, **kwargs):
     credential = self.retrieve_credential(request.user, authorize=False)
     if 'oauth2' in request.path:
         credential = self.FLOW.fetch_token(code=request.GET['code'])
         credential = self.FLOW.credentials
         storage = DjangoORMStorage(Staff, 'id', request.user.staff.id,
                                    'credential')
         storage.put(credential)
     elif credential is None:
         return self.create_google_url()
def auth_return(request):
    get_state = bytes(request.GET.get('state'), 'utf8')
    if not xsrfutil.validate_token(settings.SOCIAL_AUTH_GOOGLE_SECRET, get_state,
                                   request.user):
        return HttpResponseBadRequest()
    credential = FLOW.step2_exchange(request.GET.get('code'))
    storage = DjangoORMStorage(CredentialsModel, 'id', request.user, 'credential')
    storage.put(credential)
    print("access_token: %s" % credential.access_token)
    return HttpResponseRedirect("login/home")
Exemple #17
0
def oauth2_callback(request):
    state = request.GET.dict()['state'].encode('UTF-8')
    if not xsrfutil.validate_token(settings.SECRET_KEY, state, request.user):
        return  HttpResponseBadRequest()
    flow.redirect_uri = '%s%s' % (request.META['HTTP_REFERER'],'oauth2callback')
    credentials = flow.step2_exchange(request.GET.dict()['code'])
    storage = DjangoORMStorage(CredentialsModel, 'id', request.user, 'credential')
    storage.put(credentials)
    # TODO: need to somehow call the sync_sheet view again but need the user and game_id
    return HttpResponseRedirect("/")
Exemple #18
0
 def update_user_credential(self):
     # Create credential
     request = self.request
     credential = self.flow.step2_exchange(request.GET)
     storage = DjangoORMStorage(CredentialsModel, 'id', request.user,
                                'credential')
     # Write credential
     storage.put(credential)
     cred, created = CredentialsModel.objects.update_or_create(
         id=request.user, credential=credential)
     return cred, created
Exemple #19
0
class Cred:

    SCOPES = 'https://www.googleapis.com/auth/spreadsheets'
    CLIENT_SECRET_FILE = settings.GOOGLE_OAUTH2_CLIENT_SECRETS_JSON
    APPLICATION_NAME = 'ParseBot-SheetOutput'
    REDIRECT_URI = 'http://localhost:8080/oath2callback'

    def __init__(self):
        self.storage = DjangoORMStorage(CredetialsModel, 'user_id', 1,
                                        'credential')
        self.cred = self.storage.get()
        self.check_token()
        return

    def get_cred(self):
        return self.cred

    def force_refresh(self):
        print('refreshing_token...')

        requestt = google.auth.transport.requests.Request()
        self.cred.refresh(requestt)
        self.storage.put(self.cred)
        return

    def check_token(self):
        if self.cred is None:
            print('Please Authenticate App with Browser')
            return
        if self.cred.expired == True:
            self.force_refresh()
        return

    def cred_to_dict(self):
        return {
            'token': credentials.token,
            'refresh_token': self.cred.refresh_token,
            'expiry': self.cred.expiry,
            'expired': self.cred.expired,
            'token_uri': self.cred.token_uri,
            'scopes': self.cred.scopes
        }

    def __str__(self):
        dictt = self.cred_to_dict()
        return 'Creds {\n' + '\n'.join([
            "\t'{}': {},".format(str(item), str(dictt[item])) for item in dictt
        ]) + '\n}'

    def __repr__(self):
        dictt = self.cred_to_dict()
        return 'Creds {\n' + '\n'.join([
            "\t'{}': {},".format(str(item), str(dictt[item])) for item in dictt
        ]) + '\n}'
def auth_return(request):
    state = str(request.GET.get("state"))
    token_valid = xsrfutil.validate_token(
        settings.SECRET_KEY, bytearray(state, "utf-8"), request.user
    )
    if not token_valid or not state:
        return HttpResponseRedirect("/jobs/")
    credential = FLOW.step2_exchange(request.GET)
    storage = DjangoORMStorage(CredentialsModel, "id", request.user, "credential")
    storage.put(credential)
    return HttpResponseRedirect(reverse("pjob:job_add_event"))
Exemple #21
0
 def get(self, request):
     get_state = bytes(request.GET.get('state'), 'utf8')
     if not xsrfutil.validate_token(settings.SECRET_KEY, get_state,
                                    request.user):
         return HttpResponseBadRequest()
     credential = FLOW.step2_exchange(request.GET.get('code'))
     storage = DjangoORMStorage(CredentialsModel, 'id', request.user,
                                'credential')
     storage.put(credential)
     print("access_token: %s" % credential.access_token)
     return HttpResponseRedirect("../admin/hiringapp/submission/")
Exemple #22
0
 def get(self, request, *args, **kwargs):
     if not xsrfutil.validate_token(settings.SECRET_KEY,
                                    request.GET.get('state').encode(),
                                    request.user):
         return HttpResponseBadRequest()
     global flow
     credentials = flow.step2_exchange(request.GET)
     storage = DjangoORMStorage(GoogleAPIOauthInfo, 'id', request.user.id,
                                'credentials')
     storage.put(credentials)
     return redirect('/upload/')
Exemple #23
0
def auth_return(request):
    if not xsrfutil.validate_token(settings.SECRET_KEY,
                                   request.REQUEST['state'], request.user):
        print request.user
        return HttpResponseBadRequest("/")
    credential = FLOW.step2_exchange(request.REQUEST)
    print credential
    storage = DjangoORMStorage(CredentialsModel, 'id', request.user,
                               'credential')
    storage.put(credential)
    return HttpResponseRedirect("/")
Exemple #24
0
def auth_return(request):
    # validate token
    if not xsrfutil.validate_token(settings.SECRET_KEY, request.GET['state'],
                                   request.user):
        return HttpResponseBadRequest()

    # get creadentials and store them
    credential = FLOW.step2_exchange(request.GET)
    storage = DjangoORMStorage(CredentialsModel, 'id', request.user,
                               'credential')
    storage.put(credential)
    return HttpResponseRedirect("/profile/mails")
Exemple #25
0
 def get(self, request):
     if not xsrfutil.validate_token(
             settings.SECRET_KEY, str(request.GET['state']),
             request.user):
         return HttpResponseBadRequest()
     flow = get_flow(request)
     credential = flow.step2_exchange(code=request.GET['code'])
     storage = DjangoORMStorage(
         Credentials, 'email', settings.PRIMARY_YOUTUBE_ACCOUNT,
         'credential')
     storage.put(credential)
     return HttpResponseRedirect("/")
Exemple #26
0
def auth_return(request):
    state = str(request.GET.get('state'))
    token_valid = xsrfutil.validate_token(settings.SECRET_KEY,
                                          bytearray(state, 'utf-8'),
                                          request.user)
    if not token_valid or not state:
        return HttpResponseRedirect('/jobs/')
    credential = FLOW.step2_exchange(request.GET)
    storage = DjangoORMStorage(CredentialsModel, 'id', request.user,
                               'credential')
    storage.put(credential)
    return HttpResponseRedirect(reverse('pjob:job_add_event'))
Exemple #27
0
def auth_return(request):
    get_state = bytes(request.GET.get('state'), 'utf8')
    if not xsrfutil.validate_token(settings.SECRET_KEY, get_state,
                                   request.user):
        return HttpResponseBadRequest()
    credential = FLOW.step2_exchange(request.GET.get('code'))
    storage = DjangoORMStorage(CredentialsModel, 'id', request.user,
                               'credential')
    storage.put(credential)
    print("access_token: %s" % credential.access_token)

    response = HttpResponse("User authenticated")
    return response
Exemple #28
0
def auth_return(request):
    print('request get: ', request.GET['state'], request.user)

    a = xsrfutil.validate_token(settings.SECRET_KEY,
                                request.GET['state'].encode(), request.user)
    print('a:', a)
    if not a:
        return HttpResponseBadRequest()
    credential = FLOW.step2_exchange(request.GET)
    print('credential:', credential)
    storage = DjangoORMStorage(CredentialsModel, 'id', request.user,
                               'credential')
    print('storage:', storage)
    storage.put(credential)
    return HttpResponseRedirect("/home")
Exemple #29
0
def oauth2callback(request):
    google_client_id = request.user.profile.google_client_id
    google_client_secret = request.user.profile.google_client_secret
    request_get = request.GET
    state = request_get.get('state', '')
    flow = OAuth2WebServerFlow(
        client_id=google_client_id,
        client_secret=google_client_secret,
        scope=settings.GOOGLE_OAUTH2_CLIENT['scope'],
        redirect_uri=settings.GOOGLE_OAUTH2_CLIENT['redirect_uri'])
    credential = flow.step2_exchange(request_get)
    state_data = ast.literal_eval(
        json.loads(json.dumps(base64.b64decode(state).decode('utf-8'))))
    user_id = state_data['user_id']
    client_service = User.objects.get(pk=user_id)
    storage = DjangoORMStorage(Credentials, "id", client_service, "credential")
    storage.put(credential)  # Store the token with reference to this user
    return HttpResponseRedirect('/calender/list/')
Exemple #30
0
def oauth2redirect(request):
    """
    validates user token,
    saves user credentials into db
    redirects you to 'viz/' (viz/views.viz)
    """
    # Make sure that the request is from who we think it is
    if not xsrfutil.validate_token(settings.SECRET_KEY,
                                   request.GET.get('state').encode('utf8'),
                                   request.user.id):
        return HttpResponseBadRequest()

    code = request.GET.get('code')
    error = request.GET.get('error')

    if code:
        flow = get_flow(request)
        credentials = flow.step2_exchange(code)

        request.session['creds'] = credentials.to_json()
        email = credentials.id_token.get("email")
        user = User.objects.get(email=email)

        # Since we've oauth2'd the user, we should set the backend appropriately
        # This is usually done by the authenticate() method.
        user.backend = 'django.contrib.auth.backends.ModelBackend'

        # Refresh token is needed for renewing google api access token
        if credentials.refresh_token:
            user.refresh_token = credentials.refresh_token
        user.save()

        storage = DjangoORMStorage(CredentialsModel, 'id', user, 'credentials')
        storage.put(credentials)

        # Register that the user has successfully logged in
        auth_login(request, user)

        return redirect('viz')

    elif code is None and error:
        return HttpResponse(str(error))
    else:
        return HttpResponseBadRequest()
Exemple #31
0
    def get(self, request):
        # raise
        user = None
        if not request.user.is_anonymous():
            user = request.user

        if not xsrfutil.validate_token(
            settings.GOOGLE_OAUTH2_CLIENT_SECRET,
            request.GET['state'].encode('UTF-8'),
            request.user
            ):

            return  HttpResponseBadRequest()

        credentials = FLOW.step2_exchange(request.GET)

        http = credentials.authorize(httplib2.Http())

        service_plus = discovery.build('plus', 'v1', http=http)

        person = service_plus.people().get(userId='me').execute()

        email = person ['emails'][0]['value']
        user, created = User.objects.get_or_create(username=email, email=email)
        user.is_active = True
        user.save()
        login(request, user)
        storage = DjangoORMStorage(CredentialsModel, 'id', user, 'credential')

        if storage.get() is None:
            storage.put(credentials)

        return HttpResponseRedirect('/')





        # first_name = person['name']['givenName']
        # last_name = person['name']['familyName']
        # user_image_url = person['image']['url']
        # user_language = person['language']
        # user_id = person['id']
Exemple #32
0
def registration(request):
    form = SignUpForm()
    flow = OAuth2WebServerFlow(*musicmanager.oauth)
    auth_uri = flow.step1_get_authorize_url()
    args = {'form': form, 'auth_uri': auth_uri}
    if request.method == 'POST':
        form = SignUpForm(request.POST)
        if form.is_valid():
            credential = flow.step2_exchange(
                form.cleaned_data.get('oauth_code'))
            user = form.save()
            user.refresh_from_db()
            storage = Storage(Profile, 'user', user, 'google_oauth')
            storage.put(credential)
            raw_password = form.cleaned_data.get('password1')
            user = authenticate(username=user.username, password=raw_password)
            login(request, user)
            return redirect('index')
        args.update({'form': form})
    return render(request, 'core/register.html', args)
Exemple #33
0
def auth_return(request):
    get_state = bytes(request.GET.get('state'), 'utf8')
    if not xsrfutil.validate_token(settings.SECRET_KEY, get_state,
                                   request.user):
        return HttpResponseBadRequest()
    credential = FLOW.step2_exchange(request.GET.get('code'))
    storage = DjangoORMStorage(CredentialsModel, 'id', request.user, 'credential')
    storage.put(credential)
    http = httplib2.Http()
    http = credential.authorize(http)
    service = build('plus', 'v1', http=http)
    people_resource = service.people()
    people_document = people_resource.get(userId='me').execute()
    print(people_document)
    status = True
    #print('ID:' + people_document['id'])
    #print("Display name: " + people_document['displayName'])
    #print("Image URL: " + people_document['image']['url'])
    print("access_token: %s" % credential.access_token)
    #return HttpResponseRedirect("/")
    return render(request, 'index.html', {'status': status, 'people_document': people_document})
Exemple #34
0
def auth_return(request):
    """
    Step 2 of Google OAuth 2.0 flow.
    """
    if 'state' not in request.GET:
        return redirect('gauth_index')

    if not xsrfutil.validate_token(settings.SECRET_KEY,
                                   str(request.GET['state']),
                                   request.user):
        return HttpResponseBadRequest()

    FLOW = DjangoORMStorage(FlowModel, 'id', request.user, 'flow').get()
    if FLOW is None:
        return redirect('gauth_index')

    credential = FLOW.step2_exchange(request.GET)
    cred_storage = DjangoORMStorage(CredentialsModel, 'id', request.user, 'credential')
    cred_storage.put(credential)

    return redirect(request.session.get('next_view', '/'))
Exemple #35
0
def auth_return(request):
    """
    Step 2 of Google OAuth 2.0 flow.
    """
    if 'state' not in request.GET:
        return redirect('gauth_index')

    if not xsrfutil.validate_token(settings.SECRET_KEY,
                                   str(request.GET['state']), request.user):
        return HttpResponseBadRequest()

    FLOW = DjangoORMStorage(FlowModel, 'id', request.user, 'flow').get()
    if FLOW is None:
        return redirect('gauth_index')

    credential = FLOW.step2_exchange(request.GET)
    cred_storage = DjangoORMStorage(CredentialsModel, 'id', request.user,
                                    'credential')
    cred_storage.put(credential)

    return redirect(request.session.get('next_view', '/'))
Exemple #36
0
def config_access (request):
    credential = flow.step2_exchange(request.REQUEST.get('code'))
    storage = Storage(models.CredentialsModel, 'id', request.user, 'credential')
    storage.put(credential)
    return redirect(reverse('config_view'))
Exemple #37
0
    def post(self, request, *args, **kwargs):
        """
        Process the POST data sent via AJAX after user clicks on the sign-in button.
        """
        # retrive the one-time  Google generated code after user granted permission to the app.
        code = request.POST.get("code", None)
        print("code:" + code)
        #print(request.session['test'])
        # Make sure the request session is still intact and hasn't been tempered with.
        if not xsrfutil.validate_token(settings.SECRET_KEY, str(request.session['state']), None):
            return HttpResponseBadRequest()

        # if there is no one-time Google generated code then return
        if code is None:
            return HttpResponse ("No Code")

        # Exchange the one-time Google generated code for an AccessToken and RefreshToken.
        # Remember that RefreshToken is only generated once during the initial granting of
        # permission by the user.
        try:
            oauth_flow = flow_from_clientsecrets('blog/client_secrets.json', scope="")
            oauth_flow.redirect_uri = 'postmessage'
            credentials = oauth_flow.step2_exchange(code)
        except FlowExchangeError as e:
            return HttpResponse("Failed to upgrade the authorization code. 401 %s" % e)

        commenter, created = Commenter.objects.get_or_create(email=credentials.id_token['email'], defaults={'plus_id': credentials.id_token['sub']})

        request.session['cid'] = commenter.pk

        # retrieve the credentials object from the database based on the user's email
        gstorage = Storage(GoogleCredentialsModel, 'commenter', commenter, 'credential')

        # if the credentials object does not exist or is invalid then store it
        if gstorage.get() is None or credentials.invalid == True:
            gstorage.put(credentials)

        # if the commenter did not exist before, then save his/her basic profile
        if created:
            SERVICE = build('plus', 'v1')
            http = httplib2.Http()
            http = credentials.authorize(http)

            google_request = SERVICE.people().get(userId='me')
            result = google_request.execute(http=http)
            try:
                commenter.given_name = result['name']['givenName'] if ('name' in result and 'givenName' in result['name']) else None
                commenter.family_name = result['name']['familyName'] if ('name' in result and 'familyName' in result['name']) else None
                commenter.display_name = result['displayName'] if 'displayName' in result else None
                commenter.is_plus_user = result['isPlusUser'] if 'isPlusUser' in result else None
                commenter.gender = result['gender'] if 'gender' in result else None
                commenter.image_url = result['image']['url'] if ('image' in result and 'url' in result['image']) else None
                commenter.language = result['language'] if 'language' in result else None
                commenter.birthday = result['birthday'] if 'birthday' in result else None
                commenter.age_range_min = result['ageRange']['min'] if ('ageRange' in result and 'min' in result['ageRange']) else None
                commenter.age_range_max = result['ageRange']['max'] if ('ageRange' in result and 'max' in result['ageRange']) else None
                commenter.save()
            except Commenter.DoesNotExist as e:
                print(e)

        #return HttpResponse(json.dumps(credentials.to_json()))
        return HttpResponse(json.dumps({"commenter_id": commenter.pk}))