def receive_messages_handler():
    # Verify that the request originates from the application.
    if (request.args.get('token', '') !=
            current_app.config['PUBSUB_VERIFICATION_TOKEN']):
        return 'Invalid request', 400

    # Verify that the push request originates from Cloud Pub/Sub.
    try:
        # Get the Cloud Pub/Sub-generated JWT in the "Authorization" header.
        bearer_token = request.headers.get('Authorization')
        token = bearer_token.split(' ')[1]
        TOKENS.append(token)

        # Verify and decode the JWT. `verify_oauth2_token` verifies
        # the JWT signature, the `aud` claim, and the `exp` claim.
        claim = id_token.verify_oauth2_token(token, requests.Request(),
                                             audience='example.com')
        # Must also verify the `iss` claim.
        if claim['iss'] not in [
            'accounts.google.com',
            'https://accounts.google.com'
        ]:
            raise ValueError('Wrong issuer.')
        CLAIMS.append(claim)
    except Exception as e:
        return 'Invalid token: {}\n'.format(e), 400

    envelope = json.loads(request.data.decode('utf-8'))
    payload = base64.b64decode(envelope['message']['data'])
    MESSAGES.append(payload)
    # Returning any 2xx status indicates successful receipt of the message.
    return 'OK', 200
Example #2
0
def call():
    '''
    Main API route.
    '''
    message = flask.request.get_json(force=True)

    # Extract and verify the ID token
    username = None
    if '_token' in message:
        request = google.auth.transport.requests.Request(session=SESSION)
        idinfo = verify_oauth2_token(message.pop('_token'), request, CLIENT_ID)
        if idinfo['iss'] not in ('accounts.google.com', 'https://accounts.google.com'):
            raise RuntimeError('Bad issuer in ID token')
        username = idinfo['email']

    # Process the message inside an appropriate transaction
    client = datastore.Client()
    with client.transaction():
        key = client.key('Party', '.')
        entity = client.get(key) or datastore.Entity(key=key, exclude_from_indexes=('state',))
        if 'state' in entity:
            state = json.loads(entity['state'])
        else:
            state = {}

        result, new_state = process(state, username, message)

        if new_state != state:
            entity['state'] = json.dumps(new_state, ensure_ascii=False)
            client.put(entity)

    return flask.jsonify(result)
Example #3
0
def tokensignin(request):
    if request.method == 'POST':
        try:
            idinfo = id_token.verify_oauth2_token(request.POST['id_token'], requests.Request(),
                                                  '408025391021-l8s6ddt0rv3ejaqdqmktgg5vsumb8nh5.apps.googleusercontent.com')

            if idinfo['iss'] not in ['accounts.google.com', 'https://accounts.google.com']:
                raise ValueError('Wrong issuer.')

            # ID token is valid. Get the user's Google Account ID from the decoded token.
            try:
                authorized_user = User.objects.get(username=idinfo['email'])
            except User.DoesNotExist:
                authorized_user = User.objects.create_user(username=idinfo['email'], picture=idinfo['picture'],
                                                           last_name=idinfo['family_name'],
                                                           first_name=idinfo['given_name'])
            login(request, authorized_user)
            return JsonResponse({
                'id': authorized_user.id,
                'first_name': authorized_user.first_name,
                'last_name': authorized_user.last_name
            })
        except ValueError:
            # Invalid token
            pass
    return JsonResponse({})
Example #4
0
def validate_token(token, client_id):
    # Specify the CLIENT_ID of the app that accesses the backend:
    idinfo = id_token.verify_oauth2_token(token, requests.Request(), client_id)
    # Or, if multiple clients access the backend server:
    # idinfo = id_token.verify_oauth2_token(token, requests.Request())
    # if idinfo['aud'] not in [CLIENT_ID_1, CLIENT_ID_2, CLIENT_ID_3]:
    #     raise ValueError('Could not verify audience.')

    if idinfo['iss'] not in ['accounts.google.com', 'https://accounts.google.com']:
        raise ValueError('Wrong issuer.')

    # If auth request is from a G Suite domain:
    # if idinfo['hd'] != GSUITE_DOMAIN_NAME:
    #     raise ValueError('Wrong hosted domain.')

    # ID token is valid. Get the user's Google Account ID from the decoded token.
    return idinfo
Example #5
0
def login_callback():
    if not flow:
        return redirect(url_for('.info'))
    flow.fetch_token(authorization_response=request.url)

    credentials = flow.credentials
    request_session = requests.session()
    cached_session = cachecontrol.CacheControl(request_session)
    token_request = google.auth.transport.requests.Request(
        session=cached_session)

    id_info = id_token.verify_oauth2_token(id_token=credentials._id_token,
                                           request=token_request)

    session['google_id'] = id_info.get('sub')
    session['name'] = id_info.get('name')
    return redirect('/')
Example #6
0
def get_user_id_info(request):
    auth_header = request.headers.get('Authorization')
    if not auth_header:
        raise Exception('No auth header provided')
    auth_type, token = auth_header.split(' ')
    if auth_type != 'Bearer':
        raise Exception('Incorrect auth type. Should be Bearer')
    try:
        id_info = id_token.verify_oauth2_token(token, requests.Request(),
                                               CLIENT_ID)
        if id_info['iss'] not in [
                'accounts.google.com', 'https://accounts.google.com'
        ]:
            raise Exception('Wrong issuer')
        return id_info
    except:
        raise Exception('User token invalid')
def validate_token(token, platform):
    GOOGLE_CLIENT_ID = GOOGLE_ANDROID_ID if platform == 'android' else GOOGLE_IOS_ID
    request = requests.Request()

    try:
        id_info = id_token.verify_oauth2_token(
            token, 
            request, 
            GOOGLE_CLIENT_ID
        )

        if id_info['iss'] != 'https://accounts.google.com':
            raise ValueError('Wrong issuer.')
        
        return id_info
    except Exception as e:
        raise e
Example #8
0
 def post(self, request, **kwargs):
     """
     POST: /api/v1/ouath/google/login/
     Register or login user if exists
     Returns: user token and/or user data
     """
     serializer = self.serializer_class(data=request.data)
     serializer.is_valid(raise_exception=True)
     access_token = serializer.data.get('access_token')
     try:
         user_info = id_token.verify_oauth2_token(
             access_token, requests.Request())
         user_info = get_user_info(user_info)
     except:
         return custom_reponse('error', 400, message='Invalid token.')
     google_auth = SocialAuth()
     return google_auth.social_login_signup(user_info, **kwargs)
    def to_internal_value(self, data):
        token: str = super().to_internal_value(data)
        try:
            id_info: tp.Mapping[str, tp.Any] = id_token.verify_oauth2_token(
                token, requests.Request(), settings.GOOGLE_OAUTH_CLIENT_ID)
        except ValueError as e:
            raise serializers.ValidationError(str(e))

        if id_info['iss'] not in [
                'accounts.google.com', 'https://accounts.google.com'
        ]:
            raise serializers.ValidationError('Wrong issuer')

        return {
            "id_token": token,
            "id_info": id_info,
        }
Example #10
0
def gconnect():
    # Validate state token

    if request.args.get('state') != login_session['state']:
        response = make_response(json.dumps('Invalid state parameter.'), 401)
        response.headers['Content-Type'] = 'application/json'
        return response
    # Obtain authorization code
    token = request.data

    try:
        # Specify the CLIENT_ID of the app that accesses the backend:
        idinfo = id_token.verify_oauth2_token(token, requests.Request(),
                                              CLIENT_ID)

        # Or, if multiple clients access the backend server:
        # idinfo = id_token.verify_oauth2_token(token, requests.Request())
        # if idinfo['aud'] not in [CLIENT_ID_1, CLIENT_ID_2, CLIENT_ID_3]:
        #     raise ValueError('Could not verify audience.')

        google_api = 'https://accounts.google.com'
        if idinfo['iss'] not in ['accounts.google.com', google_api]:
            raise ValueError('Wrong issuer.')

        # If auth request is from a G Suite domain:
        # if idinfo['hd'] != GSUITE_DOMAIN_NAME:
        #     raise ValueError('Wrong hosted domain.')

        # ID token is valid. Get the user's Google Account ID from the decoded
        # token.
        # userid = idinfo['sub']
    except ValueError:
        # Invalid token
        raise ValueError('Invalid token.')
    login_session['username'] = idinfo['name']
    login_session['email'] = idinfo['email']
    login_session['picture'] = idinfo['picture']

    user_id = get_user_id(login_session['email'])
    if not user_id:
        user_id = create_user(login_session)
    login_session['user_id'] = user_id

    flash("you are now logged in as %s" % login_session['username'])

    return login_session['username']
Example #11
0
def Google_Callback():
    """
    Callback for login request.
    """
    user_data = None

    try:
        # Check if the POST request is trying to log in
        if 'idtoken' in request.form:
            # Get the token from the POST form
            token = request.form['idtoken']

            # Specify the CLIENT_ID of the app that accesses the backend:
            idinfo = id_token.verify_oauth2_token(token, requests.Request(),
                                                  CLIENT_ID)

            verified_providers = [
                'accounts.google.com', 'https://accounts.google.com'
            ]

            if idinfo['iss'] not in verified_providers:
                raise ValueError('Wrong issuer.')

            # ID token is valid.
            # Get the user's Google Account ID from the decoded token.
            userid = idinfo['sub']

            # Add the token to the flask session variable
            user_data = {
                'name': idinfo['name'],
                'email': idinfo['email'],
                'picture': idinfo['picture']
            }

    except ValueError as e:
        print('error ->', e)
        # Invalid token
        print('Error: Unable to verify the token id')

    if user_data:
        user_data_json = json.dumps(user_data)
    else:
        user_data_json = None

    return user_data_json
Example #12
0
 def verifyUserToken(self, token):
     try:
         # attempt to validate token on the client-side
         logging.debug("Using the google auth library to verify id token of length %d from android phones" % len(token))
         tokenFields = goi.verify_oauth2_token(token, gatr.Request())
         logging.debug("tokenFields from library = %s" % tokenFields)
         verifiedEmail = self.__verifyTokenFields(tokenFields, "aud", "iss")
         logging.debug("Found user email %s" % tokenFields['email'])
         return verifiedEmail
     except:
         logging.debug("OAuth failed to verify id token, falling back to constructedURL")
         #fallback to verifying using Google API
         constructedURL = ("https://www.googleapis.com/oauth2/v1/tokeninfo?id_token=%s" % token)
         r = requests.get(constructedURL)
         tokenFields = json.loads(r.content)
         logging.debug("tokenFields from constructedURL= %s" % tokenFields)
         verifiedEmail = self.__verifyTokenFields(tokenFields, "audience", "issuer")
         logging.debug("Found user email %s" % tokenFields['email'])
         return verifiedEmail
Example #13
0
def token_signin_view(request):
    if request.method == 'GET':
        return HttpResponse('hello')
    else:
        token = request.POST.get('idtoken', None)

        if token == None:
            raise APIException('idtoken is required')

        idinfo = id_token.verify_oauth2_token(token, requests.Request(), settings.CLIENT_ID)

        if idinfo['iss'] not in ['accounts.google.com', 'https://accouts.google.com']:
            raise APIException('Wrong issuer.')

        pattern = r"[bcemdh]\d{7}[a-z0-9]{2}@edu.teu.ac.jp"  
        if not re.match(pattern, idinfo['email']):
            raise APIException("invalid email. use [email protected]")
        

        user, created = User.objects.get_or_create(
            email=idinfo['email'],
            defaults={'username': idinfo['name']}
        )

        user.save()
        login(request, user)
        request.session['user_id'] = idinfo['sub']
        request.session.set_expiry(60 * 60 * 24 * 365)
        request.session.set_test_cookie()        

        response = HttpResponse()
        message = 'yes\r\n' if request.user.is_authenticated else 'no\r\n' 
        message2 = 'yes\r\n' if request.session.test_cookie_worked() else 'no\r\n'
        response.write(message)
        response.write(message2)
        response.write(request.user.username + "\r\n")

        return response
Example #14
0
def GetAuthEnvironment(token):
  if settings.TMC_DISABLE_AUTH:
    return {
      'email': '*****@*****.**',
      'name': 'Test User',
      'image_url': '',
      'is_logged_in': True, 
      'is_admin': True,
    }

  try:
    idinfo = id_token.verify_oauth2_token(
        token, requests.Request(), GetGapiClientId())
    email = idinfo.get('email', '')
    return {
      'email': email,
      'name': idinfo.get('name', ''),
      'image_url': idinfo.get('picture', ''),
      'is_admin': (email == _GetAdminEmail()),
      'is_logged_in': True,
    }
  except Exception as e:
    return {'is_logged_in': False, 'reason': str(e)}
def authenticate_request(user_token):
    CLIENT_ID = os.environ.get('CLIENT_ID')
    idinfo = id_token.verify_oauth2_token(user_token, requests.Request(), CLIENT_ID)
    if idinfo['iss'] not in ['accounts.google.com', 'https://accounts.google.com']:
        raise ValueError('Wrong issuer.')
    return idinfo