Esempio n. 1
0
    def authenticate(self, token=None):
        try:
            idinfo = client.verify_id_token(token, settings.CLIENT_ID)
            # If multiple clients access the backend server:
            if idinfo['iss'] not in [
                    'accounts.google.com', 'https://accounts.google.com'
            ]:
                raise crypt.AppIdentityError("Wrong issuer.")
                return None
            '''
            if idinfo['aud'] not in [ANDROID_CLIENT_ID, IOS_CLIENT_ID, WEB_CLIENT_ID]:
                raise crypt.AppIdentityError("Unrecognized client.")
            if idinfo['hd'] != APPS_DOMAIN_NAME:
                raise crypt.AppIdentityError("Wrong hosted domain.")
            '''
        except crypt.AppIdentityError:
            # Invalid token
            raise crypt.AppIdentityError("Invalid token.")
            return None
        userid = idinfo['sub']
        print(idinfo.items())

        try:
            user = User.objects.get(username=userid)
        except User.DoesNotExist:
            user = User(username=userid,
                        email=idinfo['email'],
                        first_name=idinfo['given_name'],
                        last_name=idinfo['family_name'])
            user.set_unusable_password()
            user.save()
            student = Student(user=user)
            student.save()
        return user
Esempio n. 2
0
def sign_in():
    """Authenticate a user with Google sign in"""

    try:
        token = request.form['idtoken']
    except KeyError:
        return 'No idtoken provided', 401

    try:
        idinfo = client.verify_id_token(token, KEYS['OAUTH_CLIENT_ID'])

        if idinfo['aud'] != KEYS['OAUTH_CLIENT_ID']:
            raise crypt.AppIdentityError('Unrecognized client.')

        if idinfo['iss'] not in [
                'accounts.google.com', 'https://accounts.google.com'
        ]:
            raise crypt.AppIdentityError('Wrong issuer.')
    except ValueError:
        url = "https://www.googleapis.com/oauth2/v3/tokeninfo?id_token={}".format(
            token)
        req = urllib2.Request(url)
        response = urllib2.urlopen(url=req, timeout=30)
        res = response.read()
        idinfo = json.loads(res)
    except crypt.AppIdentityError, e:
        return 'Did not successfully authenticate'
Esempio n. 3
0
def remove():
  if request.method == 'GET':
    return redirect(url_for('index'))
  elif request.method == 'POST':
    token = request.json['idtoken']
    row = request.json['id']
    try:
      idinfo = client.verify_id_token(token, CLIENT_ID)

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

      if idinfo['aud'] != CLIENT_ID:
          raise crypt.AppIdentityError("Wrong Client.")

      admin_email = idinfo['email']

      if admin_email not in ADMIN:
        return "Not Admin", 200

      query = CheckIn.query.filter(CheckIn.id == row).first()

      db.session.delete(query)
      db.session.commit()

      return "Removed: " + str(id), 200
    except crypt.AppIdentityError:
      # Invalid token
      return "OAuth Identity Error", 200

    return redirect(url_for('index'))
Esempio n. 4
0
def verify_token(token_string):
    """Verify the given Google auth token string & return the 'sub' portion
    as stated in the docs. See: https://goo.gl/MIKN9X

    Returns None upon failure.

    """
    token = None
    valid_accounts = ['accounts.google.com', 'https://accounts.google.com']

    try:
        idinfo = client.verify_id_token(token_string, settings.GOOGLE_OAUTH_CLIENT_ID)

        # If multiple clients access the backend server:
        if idinfo['aud'] not in CLIENT_IDS:
            raise crypt.AppIdentityError("Unrecognized client.")

        if idinfo['iss'] not in valid_accounts:
            raise crypt.AppIdentityError("Wrong issuer.")

        # Save the portion we want to keep.
        token = idinfo['sub']

    except crypt.AppIdentityError:  # Invalid token
        token = None

    return token
Esempio n. 5
0
def checkin():
  if request.method == 'GET':
    return redirect(url_for('index'))
  elif request.method == 'POST':
    location = request.json['location']
    token = request.json['idtoken']

    try:
      idinfo = client.verify_id_token(token, CLIENT_ID)

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

      if idinfo['aud'] != CLIENT_ID:
          raise crypt.AppIdentityError("Wrong Client.")

      name = idinfo['name']
      email = idinfo['email']

      u = CheckIn(name, email, location)
      db.session.add(u)
      db.session.commit()


      return "Name: " + name + ", Email: " + email, 200
    except crypt.AppIdentityError:
      # Invalid token
      return "OAuth Identity Error", 200

    return redirect(url_for('index'))
Esempio n. 6
0
  def SecurityCheck(self, func, request, *args, **kwargs):
    """Check if access should be allowed for the request."""

    try:
      auth_header = request.headers.get("Authorization", "")
      if not auth_header.startswith(self.BEARER_PREFIX):
        raise crypt.AppIdentityError("JWT token is missing.")

      token = auth_header[len(self.BEARER_PREFIX):]

      auth_domain = config.CONFIG["AdminUI.firebase_auth_domain"]
      project_id = auth_domain.split(".")[0]

      idinfo = client.verify_id_token(token, project_id, cert_uri=self.CERT_URI)

      if idinfo["iss"] != self.SECURE_TOKEN_PREFIX + project_id:
        raise crypt.AppIdentityError("Wrong issuer.")

      request.user = idinfo["email"]
    except crypt.AppIdentityError as e:
      # For a homepage, just do a pass-through, otherwise JS code responsible
      # for the Firebase auth won't ever get executed. This approach is safe,
      # because wsgiapp.HttpRequest object will raise on any attempt to
      # access uninitialized HttpRequest.user attribute.
      if request.path != "/":
        return self.AuthError("JWT token validation failed: %s" % e)

    return func(request, *args, **kwargs)
Esempio n. 7
0
def _validate_gapi_token(token):
    import api_helper
    idinfo = client.verify_id_token(token, api_helper.API_CLIENT_ID)
    now = anticsrf.microtime()

    for key in ["exp", "iat"]:
        idinfo[key] *= (10**6)  # to microseconds from seconds

    # print("idinfo:", idinfo)
    if idinfo["iss"] not in [
            "accounts.google.com", "https://accounts.google.com"
    ]:
        raise crypt.AppIdentityError("Token has wrong issuer: {}".format(
            idinfo["iss"]))

    elif ((not DEV_VARS["no_check_timestamp"]) and (idinfo["iat"] >= now)
          or (idinfo["exp"] <= now)):
        raise client.AccessTokenCredentialsError(
            "Token has expired or invalid timestamps: issued-at {} expires {}".
            format(idinfo["iat"], idinfo["exp"]))

    elif idinfo["aud"] != api_helper.API_CLIENT_ID:
        # or idinfo["azd"] != API_CLIENT_ID:
        raise crypt.AppIdentityError("Token has wrong API token id")

    hd = None
    if "hd" in idinfo:
        hd = idinfo["hd"]

    idinfo["is_elevated"] = \
        api_helper.is_elevated_id(idinfo["email"], hd=hd)
    # print(idinfo)

    return idinfo
Esempio n. 8
0
def google_info_from_token(token):
    idinfo = client.verify_id_token(token, settings.GOOGLE_CLIENT_ID)
    if idinfo['aud'] != settings.GOOGLE_CLIENT_ID:
        raise crypt.AppIdentityError('aud dont match')
    if idinfo['iss'] not in [
            'accounts.google.com', 'https://accounts.google.com'
    ]:
        raise crypt.AppIdentityError("Wrong issuer.")
    return idinfo
Esempio n. 9
0
def markhere():
  if request.method == 'GET':
    return redirect(url_for('index'))
  elif request.method == 'POST':
    email = request.json['email']
    token = request.json['idtoken']
    week = request.json['week']

    try:
      idinfo = client.verify_id_token(token, CLIENT_ID)

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

      if idinfo['aud'] != CLIENT_ID:
          raise crypt.AppIdentityError("Wrong Client.")

      admin_email = idinfo['email']

      if admin_email not in ADMIN:
        return "Not Admin", 200

      name = PEOPLE[email]
      location = HALL

      date_arr = WEEKS[week].split("-")
      date = datetime(int(date_arr[0]), int(date_arr[1]), int(date_arr[2]), tzinfo=pst)
      delta = timedelta(days=1)

      dayQs = CheckIn.query.filter(CheckIn.time > date).filter(CheckIn.time < date + delta).all()

      admin_checks = []

      for q in dayQs:
        if q.email in ADMIN:
          admin_checks.append(q)

        if q.email == email:
          db.session.delete(q)

      if len(admin_checks) <= 0:
        return "Needs Admin Check Ins", 200

      for check in admin_checks:
        time = check.time
        u = CheckIn(name, email, location, time)
        db.session.add(u)

      db.session.commit()


      return "Name: " + name + ", Email: " + email, 200
    except crypt.AppIdentityError:
      # Invalid token
      return "OAuth Identity Error", 200

    return redirect(url_for('index'))
Esempio n. 10
0
def _verify_google_id_token(request):
    if "google_id_token" not in request.POST:
        raise crypt.AppIdentityError("google_id_token missing.")
    token = request.POST.get("google_id_token", None)

    idinfo = client.verify_id_token(token, django_settings.GOOGLE_CLIENT_ID)
    if idinfo["iss"] not in ["accounts.google.com", "https://accounts.google.com"]:
        raise crypt.AppIdentityError("Invalid issuer.")

    return token, idinfo
Esempio n. 11
0
def tokenGoogle():
    id_token = request.form['idtoken']

    try:
        idinfo = client.verify_id_token(id_token, CLIENT_ID)
        if idinfo['aud'] not in [CLIENT_ID]:
            raise crypt.AppIdentityError("Unrecognized client.")
        if idinfo['iss'] not in [
                'accounts.google.com', 'https://accounts.google.com'
        ]:
            raise crypt.AppIdentityError("Wrong issuer.")
        '''if idinfo['hd'] != APPS_DOMAIN_NAME:
                        raise crypt.AppIdentityError("Wrong hosted domain.")'''

    except crypt.AppIdentityError:
        print "Invalid Token"

    picture = "/static/assets/img/user.png"

    url = '/dashboard'
    connection = r.connect(host='localhost', port=28015)
    count = r.db('taggem').table('user').filter({
        'user_id': idinfo['email']
    }).count().run(connection)

    try:
        picture = idinfo['picture']
    except:
        picture = "/static/assets/img/user.png"

    if count > 0:
        print id_token
        print "User exist"
    else:
        print dir(idinfo)
        new_user = user_save(user_id=idinfo['email'],
                             connection=connection,
                             full_name=idinfo['name'],
                             profile_url=picture)
        new_user.save_to_db()

        print("New user created in database")

    session['logged_user_ID'] = idinfo['email']

    session['profile'] = picture
    session['email'] = idinfo['email']
    t = list(
        r.db('taggem').table('user').filter({
            'user_id': session['email']
        }).run(connection))
    session['id'] = t
    session['name'] = idinfo['name']
    return url
Esempio n. 12
0
def verifyToken():
    payload = request.get_json()

    if payload is None:
        abort(400)

    try:
        idinfo = client.verify_id_token(payload['token'], creds.CLIENT_ID)

        if idinfo['aud'] != creds.ANDROID_CLIENT_ID:
            raise crypt.AppIdentityError("Unrecognized client.")

        if idinfo['iss'] not in [
                'accounts.google.com', 'https://accounts.google.com'
        ]:
            raise crypt.AppIdentityError("Wrong issuer.")
    except crypt.AppIdentityError:
        abort(500)

    accId = idinfo['sub']
    res, status = cntrl.getUser(ent.User, ent.Account, accId)

    #if new user
    if status == 204:
        payload = {
            'account': idinfo['sub'],
            'email': idinfo['email'],
            'fname': idinfo['given_name'],
            'lname': idinfo['family_name']
        }
        res, status = cntrl.addUser(payload)
    #if returning user
    elif status == 200:
        res, status = {
            'message':
            'Signed in as ' + idinfo['given_name'] + ' ' +
            idinfo['family_name'],
            'email':
            idinfo['email'],
            'fname':
            idinfo['given_name'],
            'lname':
            idinfo['family_name'],
            'account':
            idinfo['sub'],
            'user':
            res['user']
        }, 200

    res = jsonify(res)
    res.headers['Status'] = status

    return res
Esempio n. 13
0
def gconnect():
    # Validate state token
    if request.args.get('state') != session['state']:
        response = make_response(json.dumps('Invalid state parameter.'), 401)
        response.headers['Content-Type'] = 'application/json'
        return response

    code = request.data

    try:
        idinfo = client.verify_id_token(code, WEB_CLIENT_ID)
        # If multiple clients access the backend server:
        if idinfo['aud'] not in [WEB_CLIENT_ID]:
            raise crypt.AppIdentityError("Unrecognized client.")
        if idinfo['iss'] not in [
                'accounts.google.com', 'https://accounts.google.com'
        ]:
            raise crypt.AppIdentityError("Wrong issuer.")
    except crypt.AppIdentityError as e:
        response = make_response(json.dumps(e.message), 401)
        response.headers['Content-Type'] = 'application/json'
        return response

    gplus_id = idinfo['sub']
    stored_gplus_id = session.get('gplus_id')

    if gplus_id == stored_gplus_id:
        response = make_response(
            json.dumps('Current user is already connected.'), 200)
        response.headers['Content-Type'] = 'application/json'
        return response

    # set session variables

    session['auth_type'] = 'gplus'
    session['username'] = idinfo['name']
    session['picture'] = idinfo['picture']
    session['email'] = idinfo['email']

    # see if user exists, if it doesn't make a new one
    user_id = get_user_id(idinfo["email"])
    print user_id
    if not user_id:
        user_id = create_user(session)

    session['user_id'] = user_id

    # response to be shown
    output = '<h3>Welcome, {}!</h3><img src="{}" class="google-img">'.format(
        session['username'], session['picture'])
    flash("You are now logged in as {}".format(session['username']))
    return output
Esempio n. 14
0
 def validate_g_token(self, id_token):  # validate on sign in and submit
     try:
         idinfo = client.verify_id_token(id_token, CLIENT_ID)
         if idinfo["aud"] not in [CLIENT_ID]:
             raise crypt.AppIdentityError("Unrecognized client.")
         if idinfo["iss"] not in [
                 "accounts.google.com", "https://accounts.google.com"
         ]:
             raise crypt.AppIdentityError("Wrong issuer.")
         # if idinfo['hd'] != #APPS_DOMAIN_NAME:
         #     raise crypt.AppIdentityError("Wrong hosted domain.")
         return idinfo
     except crypt.AppIdentityError:
         pass  # Invalid token
Esempio n. 15
0
 def verify_user(self, token, user_id):
     try:
         idinfo = client.verify_id_token(token, user_id)
         # If multiple clients access the backend server:
         if idinfo['aud'] is not ANDROID_CLIENT_ID:
             raise crypt.AppIdentityError("Unrecognized client.")
         if idinfo['iss'] not in [
                 'accounts.google.com', 'https://accounts.google.com'
         ]:
             raise crypt.AppIdentityError("Wrong issuer.")
         if idinfo['hd'] != "com.attender":
             raise crypt.AppIdentityError("Wrong hosted domain.")
     except crypt.AppIdentityError:
         userid = idinfo['sub']
Esempio n. 16
0
def request_google_auth_service(client_id, token):
    idinfo = client.verify_id_token(token, client_id)
    if idinfo['aud'] not in GOOGLE_ACCEPT_CLIENT_IDS:
        raise crypt.AppIdentityError("Unrecognized client.")
    if idinfo['iss'] not in [
            'accounts.google.com', 'https://accounts.google.com'
    ]:
        raise crypt.AppIdentityError("Wrong issuer.")
    idinfo['uid'] = idinfo['sub']
    for (x, y) in (('name', 'username'), ('given_name', 'first_name'),
                   ('family_name', 'last_name')):
        idinfo[y] = idinfo[x] if x in idinfo else ''
    idinfo['provider'] = 'google-oauth2'
    # logger.debug('idinfo = {}'.format(idinfo))
    return idinfo
Esempio n. 17
0
def verify_token():
    """Verifies the identify of the user through their oauth token

    Returns a 200 HTTP response if the token is valid
    Returns a 401 HTTP response on error.
    """
    token = request.form.get('token')
    csrftoken = request.form.get('csrftoken')
    provider = request.form.get('provider')

    if csrftoken != session['csrf']:
        response = make_response(json.dumps('Invalid CSRF token.'), 401)
        response.headers['Content-Type'] = 'application/json'
        return response
    session['csrf'] = ''
    try:
        token_info = client.verify_id_token(
            token, config.oauth['google']['client_id'])
        if token_info['iss'] not in [
                'accounts.google.com', 'https://accounts.google.com'
        ]:
            raise crypt.AppIdentityError("Wrong issuer.")
        session['provider'] = 'google'
        session['name'] = token_info['name']
        session['email'] = token_info['email']
        user = User.by_email(token_info['email']) or User.create_user(session)
        session['user_id'] = user.id
        response = make_response(json.dumps('You have logged in.'), 200)
        response.headers['Content-Type'] = 'application/json'
        return response
    except crypt.AppIdentityError:
        response = make_response(json.dumps('Invalid token.'), 401)
        response.headers['Content-Type'] = 'application/json'
        return response
Esempio n. 18
0
def verify_google_id_token(id_token):
    """
    Verifies if id_token is a valid google account token
    :param id_token: 
    :return: None or sub
    """

    try:
        # id_info = client.verify_id_token(id_token, CLIENT_ID)

        # Or, if multiple clients access the backend server:
        id_info = client.verify_id_token(id_token, None)
        # if id_info['aud'] not in [CLIENT_ID_1, CLIENT_ID_2, CLIENT_ID_3]:
        #    raise crypt.AppIdentityError("Unrecognized client.")

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

            # If auth request is from a G Suite domain:
            # if idinfo['hd'] != GSUITE_DOMAIN_NAME:
            #    raise crypt.AppIdentityError("Wrong hosted domain.")
    except crypt.AppIdentityError:
        # Invalid token
        return None
    user_id = id_info['sub']
    return user_id
    def authenticate(self, token=None):
        try:
            idinfo = client.verify_id_token(token, settings.GOOGLE_CLIENT_ID)

            if idinfo['iss'] not in [
                    'accounts.google.com', 'https://accounts.google.com'
            ]:
                raise crypt.AppIdentityError("Wrong issuer.")
        except crypt.AppIdentityError:
            return None

        user = User.objects.filter(email=idinfo['email']).first()
        if not user:
            user = User.objects.create(username=idinfo['sub'],
                                       email=idinfo['email'])
            user.is_active = idinfo['email_verified']
            user.set_unusable_password()
            user.username_set = False
            user.save()
            user.profile.first_name = idinfo['given_name']
            user.profile.last_name = idinfo['family_name']
            user.profile.email_confirmed = idinfo['email_verified']
            user.profile.save()

        return user
Esempio n. 20
0
def login():
    # To verify using ID Token and send access, refresh tokens

    content=request.get_json(force=True)
    token=content['idToken']
    print(token)

    try:
        idinfo = client.verify_id_token(token, CLIENT_ID)
        if idinfo['iss'] not in ['accounts.google.com', 'https://accounts.google.com']:
            raise crypt.AppIdentityError("Wrong issuer.")
    except crypt.AppIdentityError:
        #Invalid ID token
        return 'fail'

    print(idinfo['sub'])

    #Create refresh and access token
    refreshKey=random.getrandbits(32);
    secs=int(time.time())
    refreshToken = jwt.encode({'refreshSecret': refreshKey}, SIGNING_SECRET_KEY, algorithm='HS256')
    accessToken = jwt.encode( {'userID': idinfo['sub'],'iat':secs,'exp':secs+3000}, SIGNING_SECRET_KEY, algorithm='HS256')
    print('refreshtoken')
    print(refreshToken)
    #New User
    if not user_datastore.find_user(userID=idinfo['sub']):
        user_datastore.create_user(email=idinfo['email'], picture=idinfo['picture'], userID=idinfo['sub'], name=idinfo['name'], refreshSecret=refreshKey)
        print('new user created')
        return refreshToken
    #Existing User
    else :
        user=user_datastore.find_user(userID=idinfo['sub'])
        refreshKey=user.refreshSecret
        print(refreshKey)
        return jwt.encode({'refreshSecret': refreshKey}, SIGNING_SECRET_KEY, algorithm='HS256')
Esempio n. 21
0
def login(request):
	template = loader.get_template('search/afterlogin.html')
	if request.method=='POST':
		
		token=request.POST.get('idtoken','deftok77')
		CLIENT_ID='535075582690-pianvlpvq9lm07lbv71dh5fdgklvoe8n.apps.googleusercontent.com'
		try:
			idinfo = client.verify_id_token(token, CLIENT_ID)

    # Or, if multiple clients access the backend server:
    #idinfo = client.verify_id_token(token, None)
    #if idinfo['aud'] not in [CLIENT_ID_1, CLIENT_ID_2, CLIENT_ID_3]:
    #    raise crypt.AppIdentityError("Unrecognized client.")
			if idinfo['iss'] not in ['accounts.google.com', 'https://accounts.google.com']:
				raise crypt.AppIdentityError("Wrong issuer.")
			user = User.objects.create_user('luis')
			user.save()
    # If auth request is from a G Suite domain:
    #if idinfo['hd'] != GSUITE_DOMAIN_NAME:
    #    raise crypt.AppIdentityError("Wrong hosted domain.")
		except crypt.AppIdentityError:
			print("ivalid token")
		#nothing here
		# Invalid token
		user2 = User.objects.create_user('mike12')
		user2.save()
		userid=idinfo['sub']
		user3 = User.objectes.create_user(userid)
		user3.save()		
		context={'userid':userid}
		return HttpResponse(template.render(context,request))
Esempio n. 22
0
    def authenticate_credentials(self, token):
        User = get_user_model()

        _token = self.request.session.get('token')
        email = self.request.session.get('email')

        if token != _token:
            try:
                idinfo = client.verify_id_token(token,
                                                settings.GOOGLE_CLIENT_ID)
                auth_domains = [
                    'accounts.google.com', 'https://accounts.google.com'
                ]
                if idinfo['iss'] not in auth_domains:
                    raise crypt.AppIdentityError("Wrong issuer.")

                email = idinfo['email']
            except crypt.AppIdentityError:
                raise AuthenticationFailed('Invalid token.')

        try:
            user = User.objects.get(username=email)
            self.request.session['token'] = token
            self.request.session['email'] = email
            return (user, token)
        except User.DoesNotExist:
            raise AuthenticationFailed('User does not exist.')
Esempio n. 23
0
def signin():
    """ This function handles the signin process """
    if request.method == 'POST':
        token = request.form['id_token']

        try:
            idinfo = client.verify_id_token(
                token, '1072405718300-7kdr08dkvn4hkg' +
                'ceimh4c7p679rbsmol.apps.goog' + 'leusercontent.com')

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

        except crypt.AppIdentityError:
            return 'Error AppIdentityError'

        userid = idinfo['sub']
        username = idinfo['name']
        user_exists = db_get('SELECT id, name FROM users WHERE' + ' id = ? ',
                             [userid])

        if not user_exists:
            db_insert('INSERT INTO users VALUES (?, ?)', [(username, userid)])
            user_exists = db_get(
                'SELECT id, name FROM users WHERE' + ' id = ? ', [userid])

        user = User(user_exists[0][0], user_exists[0][1])
        login_user(user)

    return redirect(url_for('landing_page'))
Esempio n. 24
0
def google_auth():
    try:
        data = json.loads(request.data.decode())
        idinfo = client.verify_id_token(
            data['data'],
            '192085420693-gnet8a4sjhn89ll6ejjho1tudv3l2oaa.apps.googleusercontent.com'
        )
        if idinfo['iss'] not in [
                'accounts.google.com', 'https://accounts.google.com'
        ]:
            raise crypt.AppIdentityError("Wrong issuer.")
        else:
            userid = idinfo['sub']
            registered_user = User.query.filter_by(
                email=idinfo['email']).first()
            if not registered_user:
                user = User(email=idinfo['email'])
                db.session.add(user)
                db.session.commit()
                registered_user = User.query.filter_by(
                    email=idinfo['email']).first()

            return login_registered_user(registered_user)

    except crypt.AppIdentityError:
        return json.dumps({'message': 'Invalid token'}), 400
Esempio n. 25
0
def validate_user_id(userId):
    # (Receive token by HTTPS POST)
    if userId == -1:
        print('USER ID ENTERED AS -1')
        return -1

    try:
        idinfo = client.verify_id_token(userId, CLIENT_ID)

        # Or, if multiple clients access the backend server:
        # idinfo = client.verify_id_token(token, None)
        # if idinfo['aud'] not in [CLIENT_ID_1, CLIENT_ID_2, CLIENT_ID_3]:
        #    raise crypt.AppIdentityError("Unrecognized client.")

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

            # If auth request is from a G Suite domain:
            # if idinfo['hd'] != GSUITE_DOMAIN_NAME:
            #    raise crypt.AppIdentityError("Wrong hosted domain.")
    except crypt.AppIdentityError:
        print('USER ID PARSED TO -1')
        return -1

    return idinfo['sub']
Esempio n. 26
0
def gconnect():
    """Endpoint that authenticates user."""
    try:
        idinfo = client.verify_id_token(
            request.data, '1014623565180-lm2sl4gftjv5r8jhgikg0ti9lcldol8c'
            '.apps.googleusercontent.com')

        if idinfo['iss'] not in [
                'accounts.google.com', 'https://accounts.google.com'
        ]:
            raise crypt.AppIdentityError("Wrong issuer.")
    except crypt.AppIdentityError:
        return (jsonify({
            'data': 'Invalid authentication issuer',
            'error': '401'
        }), 401)

    user = get_user(idinfo['email'])

    if user is None:
        user = add_user(idinfo['email'], idinfo['name'])

        if user is None:
            return (jsonify({'data': 'Internal Error', 'error': '500'}), 500)

    login_session['userid'] = user.id

    return Response({
        'user_id': user.id,
        'user_name': idinfo['name'],
        'user_picture': idinfo['picture']
    })
Esempio n. 27
0
def do_auth(better_data):
    pprint(better_data)
    CLIENT_ID = "711592045166-4o6ndv014o7l0jfq6dce74n3bh4l6o59.apps.googleusercontent.com"
    token = str(better_data['token'])
    try:
        idinfo = client.verify_id_token(token, CLIENT_ID)
        if idinfo['iss'] not in [
                'accounts.google.com', 'https://accounts.google.com'
        ]:
            raise crypt.AppIdentityError("Wrong issuer.")
            print("Wrong Issuer.")
        else:
            print("Beginning query for authen")
            # do we add a user ? i don't know. we could try
            usr = User.query.filter_by(uid=int(idinfo['sub']))
            pprint(usr)
            if usr is None or usr.count() < 0:
                print("User is not in count! Attemping to add")
                # add user
                u = User(int(idinfo['sub']), idinfo['family_name'],
                         idinfo['given_name'], idinfo['picture'])
                db.session.add(u)
                db.session.commit()
                return json.dumps({'type': 'auth', 'success': 1})
            else:
                print("User exists... now what?")
                return json.dumps({'type': 'auth', 'success': 1})
        return json.dumps({'type': 'auth', 'success': 0})
    except crypt.AppIdentityError:
        return json.dumps({'type': 'auth', 'success': 0})
Esempio n. 28
0
    def post(self):
        """Post method for GoogleLogin resource"""
        args = self.reqparse.parse_args()
        token = args['id_token']
        try:
            idinfo = client.verify_id_token(token, CLIENT_ID)

            # Or, if multiple clients access the backend server:
            # idinfo = client.verify_id_token(token, None)
            # if idinfo['aud'] not in [CLIENT_ID_1, CLIENT_ID_2, CLIENT_ID_3]:
            #    raise crypt.AppIdentityError("Unrecognized client.")

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

                # If auth request is from a G Suite domain:
                # if idinfo['hd'] != GSUITE_DOMAIN_NAME:
                #    raise crypt.AppIdentityError("Wrong hosted domain.")
        except crypt.AppIdentityError:
            # Invalid token
            pass
        else:
            userid = idinfo['sub']
            user, created = User.get_or_create(user_id=userid,
                                               user_type='google')
            return make_response(
                jsonify({
                    "message": "Login successful!",
                    "token": user.generate_auth_token().decode('ascii')
                }), 200)
Esempio n. 29
0
    def inner(requestHandler):
        headers = requestHandler.request.headers
        if "Authorization" in headers and headers["Authorization"].split(
        )[0] == "Bearer:":
            id_token = headers["Authorization"].split()[1]
        else:
            oauth_failed(requestHandler)
            return
        try:
            idinfo = client.verify_id_token(id_token, credentials.client_id)
            if idinfo["iss"] not in [
                    "accounts.google.com", "https://accounts.google.com"
            ]:
                raise crypt.AppIdentityError("Wrong issuer.")
        except crypt.AppIdentityError:
            oauth_failed(requestHandler)
            return

        current_time = int(time.time())
        if not (int(idinfo["iat"]) < current_time
                and current_time < int(idinfo["exp"])):
            oauth_failed(requestHandler)
            return

        userid = idinfo["sub"]

        logging.debug("Request authentication success")
        return http_handler_function(requestHandler)
Esempio n. 30
0
def decode(token):
    """Decodes the provided JWT into dictionaries.

    Parses the provided token and extracts its header values and claims.
    Note that this function does not perform any verification on the
    token content. Nor does it attempt to verify the token signature.
    Th only validation it performs is for the proper formatting/encoding
    of the JWT token, which is necessary to parse it. Simply use this
    function to unpack, and inspect the contents of a JWT.

    Args:
      token: A signed JWT token as a string.

    Returns:
      tuple: A 2-tuple where the first element is a dictionary of JWT headers,
          and the second element is a dictionary of payload claims.

    Raises:
      AppIdentityError: If the token is malformed or badly formatted
    """
    if token.count(b'.') != 2:
        raise crypt.AppIdentityError(('Wrong number of segments'
                                      ' in token: {0}').format(token))
    header, payload, _ = token.split(b'.')
    header_dict = json.loads(_urlsafe_b64decode(header).decode('utf-8'))
    payload_dict = json.loads(_urlsafe_b64decode(payload).decode('utf-8'))
    return (header_dict, payload_dict)