Example #1
0
def youtube_required_info(code):
    """
    Obtains youtube channel id and email from code.

    Args:
        code: Google user agent code.
    Returns:
        Id of youtube channel and google email.
    Raises:
        GoogleAccessError
        ChannelNotFoundError
    """
    try:
        creds = credentials_from_code(CLIENT_ID, CLIENT_SECRET, SCOPES, code)
    except FlowExchangeError as exchange_error:
        raise GoogleAccessError(exchange_error)
    # then can use cache
    service = build(OAUTH_API, OAUTH_VERSION, credentials=creds)
    google_account = service.userinfo()
    service = build(YOUTUBE_API, YOUTUBE_VERSION, credentials=creds)
    channels = service.channels()
    try:
        email = google_account.get(fields='email').execute()['email']
        channel = channels.list(part='id', mine=True, fields='items/id')
        channel_id = channel.execute()['items'][0]['id']
    except (KeyError, IndexError, HttpAccessTokenRefreshError, HttpError,
            AccessTokenCredentialsError,) as api_error:
        raise GoogleAccessError(api_error)
    if not ChannelInfo(channel_id).is_exists():
        raise ChannelNotFoundError()
    return channel_id, email
Example #2
0
def authenticate():
  response_data = dict()
  code = request.data.decode('utf-8')

  csrf=request.args.get('_csrf_token', None) or abort(404)
  if csrf != session['_csrf_token']:
    return Response('Invalid state Parameter', status=401, content_type='application/json')

  if 'error' in request.args:
    return Response(json.dumps(dict(error=request.args['error'])),
          status=400,
          content_type='application/json')

  h = httplib2.Http()
  credentials = client.credentials_from_code(g.config['CLIENT_ID'],
        g.config['CLIENT_SECRET'],
        g.config['AUTH_SCOPE'],
        code,
        http=h)
  #pprint(credentials.refresh_token)
  h = credentials.authorize(http=h)

  service = discovery.build('plus', 'v1', http=h)
  person = None
  try:
    person = service.people().get(userId='me').execute()
  except client.AccessTokenRefreshError:
    return make_response('The credentials have been revoked or expired.',400)

  #pprint(person)
  try:
    user = User.objects.get(id=person['id'])
    # TODO: update if changed
    #pprint(user)
  except User.DoesNotExist:
    user = User(id=person['id'],
          given_name=person['name']['givenName'],
          family_name=person['name']['familyName'],
          display_name=person['displayName'],
          flags=dict(firstLogin=True))
    for email in person['emails']:
      if email['type'] == 'account':
        user.email = email['value']

  refresh_token = getattr(credentials, 'refresh_token', None)
  if refresh_token != None:
    user.refresh_token = refresh_token

  user.save()

  if user:
    #pprint(user.dict())
    login_user(user, redirect=False)

  # TODO: check for errors or something, respond with 400

  response = make_response(json.dumps(dict(user=user.dict()), 200))
  response.headers['Content-Type'] = 'application/json'
  return response
Example #3
0
def authcallback():
    code = request.args.get('code', None)
    if code:
        temp = credentials_from_code(CONFIG["client_id"], CONFIG["client_secret"], OAUTH_SCOPE, code, request.url_root + "authcallback")
        session["creds"] = temp.to_json()
        return redirect("/")
    else:
        return render_template("error.html", message=request.args.get("error", ""))
 def test_exchange_code_for_token(self):
     token = "asdfghjkl"
     payload = json.dumps({"access_token": token, "expires_in": 3600})
     http = HttpMockSequence([({"status": "200"}, payload.encode("utf-8"))])
     credentials = credentials_from_code(
         self.client_id, self.client_secret, self.scope, self.code, redirect_uri=self.redirect_uri, http=http
     )
     self.assertEqual(credentials.access_token, token)
     self.assertNotEqual(None, credentials.token_expiry)
    def test_exchange_code_for_token_fail(self):
        http = HttpMockSequence([({"status": "400"}, b'{"error":"invalid_request"}')])

        try:
            credentials = credentials_from_code(
                self.client_id, self.client_secret, self.scope, self.code, redirect_uri=self.redirect_uri, http=http
            )
            self.fail("should raise exception if exchange doesn't get 200")
        except FlowExchangeError:
            pass
 def test_exchange_code_for_token(self):
   token = 'asdfghjkl'
   payload =simplejson.dumps({'access_token': token, 'expires_in': 3600})
   http = HttpMockSequence([
     ({'status': '200'}, payload),
   ])
   credentials = credentials_from_code(self.client_id, self.client_secret,
       self.scope, self.code, redirect_uri=self.redirect_uri,
       http=http)
   self.assertEquals(credentials.access_token, token)
   self.assertNotEqual(None, credentials.token_expiry)
 def test_exchange_code_for_token(self):
   http = HttpMockSequence([
     ({'status': '200'},
     """{ "access_token":"asdfghjkl",
      "expires_in":3600 }"""),
   ])
   credentials = credentials_from_code(self.client_id, self.client_secret,
                                   self.scope, self.code, self.redirect_uri,
                                   http)
   self.assertEquals(credentials.access_token, 'asdfghjkl')
   self.assertNotEqual(None, credentials.token_expiry)
Example #8
0
def auth_with_google(request):
    code = request.GET.get('code', '')
    if code is not '':
        credentials = client.credentials_from_code(
            SsoConfig.google_client_id,
            SsoConfig.google_client_secret,
            'profile',
            code,
            redirect_uri='http://localhost:8000/callback/google'
        )
        return JsonResponse(credentials.id_token)
    else:
        return JsonResponse({'error': 'Error'})
  def create_user(self, code, id_token):
    self.logger.debug('creating user')
    cs = Util.get_client_secrets()
    credential = credentials_from_code(cs['client_id'], cs['client_secret'],
      'https://www.googleapis.com/auth/plus.me', code)
    google_user_info = self.get_google_user_info(credential)
    self.logger.debug('name: %s' % (google_user_info['name']))
    (user, created) = User.objects.get_or_create(username=str(id_token['sub']),
      first_name=google_user_info['name']['givenName'],
      last_name=google_user_info['name']['familyName'])

    storage = Storage(Solver_User_Info, 'user', user, 'credential')
    self.logger.debug('created storage')
    try:
      storage.put(credential)
      self.logger.debug('stored credential')
    except Exception as e:
      print(e)
    self.logger.debug('stored credntial')
    user.solver_user_info.google_id = id_token['sub']
    user.solver_user_info.save()
    self.logger.debug('added google id')
    return user