Example #1
0
 def google_auth(self,request,response,badResponse,*args,**kwargs):
     # pdb.set_trace()
     auth_code = json.loads(request.body.decode('utf-8'))['auth_code']
     # try:
     credentials = google_client.credentials_from_clientsecrets_and_code(
         settings.CLIENT_SECRET_FILE,
         # ['https://www.googleapis.com/plus/v1/people/me'],
         ["https://www.googleapis.com/auth/plus.me","https://www.googleapis.com/auth/userinfo.profile"], #Important: Use different scopes to use different google apis
         auth_code)
     http_auth = credentials.authorize(httplib2.Http())
     user_service = discovery.build('oauth2', 'v1', http=http_auth)
     userinfo = user_service.userinfo().get().execute()
     gsm_user_util = GSMUsersUtils(params={'email':userinfo['email'],'first_name':userinfo['given_name'],'last_name':userinfo['family_name']})
     gsm_usr_obj = gsm_user_util.findOrCreate()
     if not gsm_usr_obj.verified:
         gsm_usr_obj.verified = True
         gsm_usr_obj.save(update_fields=['verified'])
     stoken = SessionTokenUtils(gsm_user=gsm_usr_obj.id)
     vtoken = VerificationTokenUtils(gsm_user=gsm_usr_obj.id)
     vtoken.expireToken()
     res = {}
     res['sessiontoken'] = stoken.token.__dict__[stoken.token_name]
     # res['user'] = JSONRenderer().render(GSMUsersSerializer(gsm_usr_obj).data)
     res['user'] = GSMUsersSerializer(gsm_usr_obj).data
     response.write("%s"%(json.dumps(res)))
     return response
Example #2
0
    def post(self, request, format=None):
        code = request.data.get('code')
        credentials = client.credentials_from_clientsecrets_and_code(
            settings.CLIENT_SECRET_FILE, ['profile', 'email'], code)
        google_id = credentials.id_token.get('sub')
        username = credentials.id_token.get('email')
        full_name = credentials.id_token.get('name')
        avatar = credentials.id_token.get('picture')
        try:
            user = User.objects.get(profile__google_id=google_id)
            token, created = Token.objects.get_or_create(user=user)
            return Response({'token': token.key}, status=status.HTTP_200_OK)
        except:
            pass

        try:
            User.objects.get(username=username)
            return Response(
                {'login_error': 'There was an account with this username'},
                status=status.HTTP_400_BAD_REQUEST)
        except:
            pass

        user = User.objects.create_user(username=username)
        profile = Profile(full_name=full_name,
                          avatar=avatar,
                          google_id=google_id,
                          password_set=False,
                          user=user)
        profile.save()
        token, created = Token.objects.get_or_create(user=user)
        return Response({'token': token.key}, status=status.HTTP_201_CREATED)
Example #3
0
File: ui.py Project: rjw57/bitsbox
def export_google_sheet_do_export():
    spreadsheet_id = request.values.get('spreadsheet_id')
    name = request.values.get('name')
    code = request.values.get('code')

    if code is None:
        raise InvalidUsage('no code specified')

    # Exchange auth code for access token
    credentials = client.credentials_from_clientsecrets_and_code(
        current_app.config.get('GOOGLE_CLIENT_SECRET_FILE'),
        ['https://www.googleapis.com/auth/spreadsheets', 'profile'], code)

    http_auth = credentials.authorize(httplib2.Http())
    sheet_service = discovery.build('sheets', 'v4', http=http_auth)

    if spreadsheet_id is None or spreadsheet_id == '':
        # No spreadsheet id specified -> create one
        if name is None or name == '':
            raise InvalidUsage('no name specified for spreadsheet')
        response = sheet_service.spreadsheets().create(body={
            'properties': {
                'title': name
            }
        }).execute()

        spreadsheet_id = response['spreadsheetId']

    print('************ SSID: ', spreadsheet_id)

    return jsonify(response={'spreadsheetId': spreadsheet_id})
Example #4
0
def storeauthcode():
    # If this request does not have `X-Requested-With` header, this could be a CSRF
    if not request.headers.get('X-Requested-With'):
        # abort(403)
        return json.dumps({'error': "error"})
    auth_code = request.data
    # Set path to the Web application client_secret_*.json file you downloaded from the
    # Google API Console: https://console.developers.google.com/apis/credentials
    CLIENT_SECRET_FILE = 'client_secrets.json'

    # Exchange auth code for access token, refresh token, and ID token
    credentials = client.credentials_from_clientsecrets_and_code(
        CLIENT_SECRET_FILE,
        ['https://www.googleapis.com/auth/drive.appdata', 'profile', 'email'],
        auth_code)

    # Call Google API
    http_auth = credentials.authorize(httplib2.Http())
    # drive_service = discovery.build('drive', 'v3', http=http_auth)
    # appfolder = drive_service.files().get(fileId='appfolder').execute()

    # Get profile info from ID token
    userid = credentials.id_token['sub']
    email = credentials.id_token['email']
    return json.dumps({'user': userid, 'email': email})
Example #5
0
    def post(request):

        credentials = client.credentials_from_clientsecrets_and_code(
            os.path.join(settings.BASE_DIR, 'Tutorials', 'secret_file.json'), [
                'https://www.googleapis.com/auth/calendar',
                'https://www.googleapis.com/auth/classroom.courses.readonly',
                'https://www.googleapis.com/auth/classroom.profile.photos',
                'https://www.googleapis.com/auth/classroom.announcements',
                'https://www.googleapis.com/auth/classroom.coursework.students',
                'https://www.googleapis.com/auth/userinfo.email',
                'https://www.googleapis.com/auth/userinfo.profile',
                'https://www.googleapis.com/auth/classroom.rosters'
            ], request.data['code'])
        account, created = User.objects.get_or_create(
            email=credentials.id_token['email'],
            username=credentials.id_token['email'])
        account.username = account.id
        token, created = Token.objects.get_or_create(user=account)
        token = token.key
        cred, _ = CredentialModel.objects.get_or_create(user=account)
        cred.token = credentials.refresh_token
        cred.refresh_token = credentials.refresh_token
        cred.token_uri = credentials.token_uri
        cred.client_id = credentials.client_id
        cred.client_secret = credentials.client_secret
        cred.save()

        return Response({
            'token': token,
            'created': created
        },
                        status=status.HTTP_202_ACCEPTED)
Example #6
0
def gconnect():
    """Callback Function For Google Login"""
    if request.args.get('state') != session['state']:
        response = make_response(json.dumps('Invalid state parameter.'), 401)
        response.headers['Content-Type'] = 'application/json'
        return response

    if not request.headers.get('X-Requested-With'):
        abort(403)

    code = request.data

    CLIENT_SECRET_FILE = 'client_secrets.json'

    credentials = client.credentials_from_clientsecrets_and_code(
        CLIENT_SECRET_FILE, ['profile', 'email'], code)

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

    session['name'] = credentials.id_token['name']
    session['email'] = credentials.id_token['email']
    user_id = getUserID(session['email'])
    if not user_id:
        user_id = createUser(session)
    session['uid'] = user_id
    print session.get('access_token')
    output = ''
    output += '<h1>Welcome, '
    output += session['name']
    output += '!</h1>'
    flash("you are now logged in as %s" % session['name'])
    return output
Example #7
0
def oauth2callback(request):
    auth_code = request.GET['code']
    print auth_code
    credentials = client.credentials_from_clientsecrets_and_code(
        settings.CLIENT_SECRET_FILE,
        ['https://www.googleapis.com/auth/drive', 'profile', 'email'],
        auth_code,
        redirect_uri=settings.HOST_ADDR + '/oauth2callback')
    # credentials = flow.step2_exchange(auth_code)
    print credentials.id_token
    email = credentials.id_token['email']
    guser_id = credentials.id_token['sub']
    print credentials.id_token
    username = email.split('@')[0]
    try:
        user = User.objects.get(email=email)
    except:
        user = User(username=username, email=email)
        user.save()

    googleuser, created = GoogleUser.objects.get_or_create(user=user)
    googleuser.access_token = credentials.access_token
    googleuser.refresh_token = credentials.refresh_token
    googleuser.guser_id = guser_id
    googleuser.save()
    login(request, user)
    state = request.GET.get('state')
    if state:
        param = state
    else:
        param = ''
    redirect_uri = '/?' + param
    return HttpResponseRedirect(redirect_uri)
Example #8
0
    def verify_cridentials(self, request):
        """
        https://developers.google.com/api-client-library/python/start/get_started
        https://developers.google.com/+/web/api/rest/oauth
        https://developers.google.com/+/web/api/rest/latest/people/get
        """
        if not request.params.get('code'):
            return

        if not request.headers.get('X-Requested-With'):
            raise LoginProviderException('X-Requested-With required for google login')

        credentials = client.credentials_from_clientsecrets_and_code(
            self.client_secret_file,
            ['profile', 'email'],
            request.params.get('code'),
        )

        # Google API's
        # https://developers.google.com/api-client-library/python/apis/
        # Google API Explorer - Reference
        # https://developers.google.com/apis-explorer/#p/people/v1/people.people.get?resourceName=people%252Fme&personFields=photos%252Cnames%252CemailAddresses&_h=11&
        people_service = build('people', 'v1', http=credentials.authorize(httplib2.Http()))
        profile = people_service.people().get(resourceName='people/me', personFields='photos,names,emailAddresses').execute()

        return ProviderToken(self.name, profile['names'][0]['metadata']['source']['id'], profile)
Example #9
0
def google_login(request):
    """
    1. Receive google token from google's signin callback.
    2. Get token's email & get/create a user against it.
    3. Mark the user as logged in.
    """
    # Exchange auth code for access token, refresh token, and ID token
    auth_code = request.POST['authCode']

    credentials = client.credentials_from_clientsecrets_and_code(
        settings.CLIENT_SECRET_FILE,
        ['https://www.googleapis.com/auth/drive', 'profile', 'email'],
        auth_code)
    email = credentials.id_token['email']
    guser_id = credentials.id_token['sub']
    username = email.split('@')[0]
    try:
        user = User.objects.get(email=email)
    except:
        user = User(username=username, email=email)
        user.save()

    googleuser, created = GoogleUser.objects.get_or_create(user=user)
    googleuser.access_token = credentials.access_token
    googleuser.refresh_token = credentials.refresh_token
    googleuser.guser_id = guser_id
    googleuser.save()
    login(request, user)
    return JsonResponse({"success": True})
def googSignIn():
    """ This is the function to handle Google Sign-In """
    if not request.headers.get('X-Requested-With'):
        abort(403)
    CLIENT_SECRET = 'client_secret.json'

    auth_code = request.data

    credentials = client.credentials_from_clientsecrets_and_code(
        CLIENT_SECRET,
        ['https://www.googleapis.com/auth/drive.appdata', 'profile', 'email'],
        auth_code)

    credentials.authorize(httplib2.Http())

    email = credentials.id_token['email']
    user = db.query(User).filter_by(email=email).first()

    if not user:
        name = credentials.id_token['name']
        password = generate_password_hash(credentials.id_token['sub'])
        newUser = User(name=name, email=email, password=password)
        db.add(newUser)
        db.commit()
        newuser = db.query(User).filter_by(email=email).first()
        session['user_id'] = newuser.id
    else:
        session['user_id'] = user.id
    return redirect(url_for('displayCategories'))
Example #11
0
def googlesignin():
    auth_code = Utils.getParam(request.form, 'data', '')
    if not auth_code:
        return ''
    client_secret_file = '/etc/ostrich_conf/google_client_secret.json'
    credentials = client.credentials_from_clientsecrets_and_code(
        client_secret_file, ['profile', 'email'], auth_code)
    http_auth = credentials.authorize(httplib2.Http())
    users_service = discovery.build('oauth2', 'v2', http=http_auth)
    user_document = users_service.userinfo().get().execute()

    #TODO check consistencies b/w session and user cache
    #from app import cache
    #cache_key = credentials.id_token['sub']
    #user = cache.get(cache_key)
    user = session.get('_user', None)
    if not user:
        user_data = {
            'username': user_document['email'],
            'name': user_document['name'],
            'email': user_document['email'],
            'google_id': credentials.id_token['sub'],
            'picture': user_document['picture'],
            'source': 'web'
        }

        user = User.createUser(user_data)
        WebUtils.storeUserSession(user,
                                  client=Utils.getParam(request.form,
                                                        'client',
                                                        default=None))
        user = session['_user']

    visible_user_data = {'user': user}
    return jsonify(data=visible_user_data)
def store_auth_code():
    req = request.get_data()
    CLIENT_SECRET_FILE = 'credentials.json'
    credentials = client.credentials_from_clientsecrets_and_code(
        CLIENT_SECRET_FILE, [
            'https://www.googleapis.com/auth/calendar',
            'https://www.googleapis.com/auth/calendar.events'
        ], req)

    airtable_url = "https://api.airtable.com/v0/app4l7uUwpnOQedPM/google-credentials"
    api_key = "keyOrtPlDobjLtiaJ"
    cred = json.loads(credentials.to_json())
    response = {
        'records': [{
            'fields': {
                'googleid': cred['id_token']['sub'],
                'credential': json.dumps(cred)
            }
        }]
    }
    headers = {
        'Authorization': 'Bearer ' + api_key,
        'Content-Type': 'application/json'
    }
    airtable_response = requests.post(airtable_url,
                                      data=json.dumps(response),
                                      headers=headers)
    print(airtable_response.status_code)
    print(airtable_response.text)
    return req
Example #13
0
def login_callback():
    if not request.headers.get('X-Requested-With'):
        return json.dumps({'success': False}), 403, {'ContentType': 'application/json'}

    content_type = request.headers.get("Content-Type")
    auth_code = request.stream if content_type == "application/octet-stream" else request.get_data()
    CLIENT_SECRET_FILE = 'website/static/secret/BCVS_client_secret.json'

    # Exchange auth code for access token, refresh token, and ID token
    credentials = client.credentials_from_clientsecrets_and_code(
        CLIENT_SECRET_FILE,
        ['profile', 'email'],
        auth_code)
    print(credentials.id_token)

    # Get profile info from ID token
    session['authenticated'] = True
    session['userid'] = credentials.id_token['sub']
    session['fname'] = credentials.id_token['given_name']
    try:
        session['lname'] = credentials.id_token['family_name']
    except KeyError:
        session['lname'] = " "
    session['email'] = credentials.id_token['email']
    return json.dumps({'success': True}), 200, {'ContentType': 'application/json'}
Example #14
0
    def check_credentials(self, user_uid):
        google_token_db = "google"

        # If length is less than 60, auth code given
        # Convert auth code to credential
        cred = firebase.database().child("users").child(user_uid).child(
            "tokens").child(google_token_db).get().val()
        if (len(cred) < 60):
            credentials = client.credentials_from_clientsecrets_and_code(
                filename=CLIENT_SECRET_FILE,
                scope=['https://www.googleapis.com/auth/gmail.readonly'],
                code=cred,
                redirect_uri=flask.url_for('oauthhandler', _external=True))
            print(credentials.to_json())
            firebase.database().child("users").child(user_uid).child(
                "tokens").update({google_token_db: credentials.to_json()})
        else:
            # Create credentials from credentials json
            credentials = client.Credentials.new_from_json(
                json.loads(json.dumps(cred)))

        # Refresh token if expired
        if credentials.access_token_expired:
            credentials.refresh(httplib2.Http())
            firebase.database().child("users").child(user_uid).child(
                "tokens").update({google_token_db: credentials.to_json()})

        self.credentials = credentials
Example #15
0
def get_user_access_token_google():
    global credentials
    print(request.data)
    auth_code = str(request.data).split("\'")[1]
    print(auth_code)
    CLIENT_SECRET_FILE = 'client_secret_1070969009500-4674ntngjh3dvlbcvoer0r4c7hao04dh.apps.googleusercontent.com.json'

    # Exchange auth code for access token, refresh token, and ID token
    credentials = client.credentials_from_clientsecrets_and_code(
        CLIENT_SECRET_FILE,
        ['https://www.googleapis.com/auth/drive.appdata', 'profile', 'email'],
        auth_code)

    # Call Google API
    http = httplib2.Http()
    http_auth = credentials.authorize(http)
    resp, content = http.request(
        'https://www.googleapis.com/language/translate/v2/?q=voiture&target=en&source=fr'
    )
    print(resp.status)
    print(content.decode('utf-8'))

    # # Get profile info from ID token
    userid = credentials.id_token['sub']
    email = credentials.id_token['email']
    session['email'] = email
    session['userid'] = userid
    # session['credentials'] = jsonpickle.dumps(credentials)
    # if not 'credentials' in session:
    #   print("Credentials not saved to session")
    # session.modified = True
    print(userid)
    print(email)
    return jsonify(email=email)
Example #16
0
def google_connect():
    """The google sign in route which will be used to sign in the User into the application"""

    if not request.headers.get('X-Requested-With'):
        abort(403)

    auth_code = request.data
    site_root = path.realpath(path.dirname(__file__)) + '/../'

    client_secret_file = path.join(site_root, 'static', 'client_secret.json')

    credentials = client.credentials_from_clientsecrets_and_code(
        client_secret_file,
        ['https://www.googleapis.com/auth/drive.appdata', 'profile', 'email'],
        auth_code)

    email = credentials.id_token['email']

    try:
        result = users.get_by_email(email=email)
        token = result.token
    except NoResultFound:
        token = b64encode(urandom(100)).decode('utf-8')
        new_user = User(email=email, token=token)
        users.add(new_user)
        unit_of_work.save()

    response = make_response(redirect(request.referrer))
    response.set_cookie('token', token)
    return response
Example #17
0
def credentials_using_auth_code(auth_code, scopes=None):
    if scopes is None:
        scopes = [
            'https://www.googleapis.com/auth/cloud-platform',
            'profile',
            'email',
            'https://www.googleapis.com/auth/admin.directory.group'
        ]

    # Fetch token from cached users
    cached_user_credentials = cached_users.get(auth_code, None)

    if cached_user_credentials is None:
        get_content_to_file("gcp-flask-api", "client_secret_creation_form.json")
        # Exchange auth code for access token, refresh token, and ID token
        credentials = client.credentials_from_clientsecrets_and_code(
            CLIENT_SECRET_FILE,
            scopes,
            auth_code)

        # Cache new user's token
        cached_users[auth_code] = credentials

    else:
        print('Returned from cached_user_credentials: {}'.format(
            cached_user_credentials))
        credentials = cached_user_credentials

    return credentials
Example #18
0
def gauth():
    db_session = start()
    # If this request does not have `X-Requested-With` header, this could be a CSRF
    if not request.headers.get('X-Requested-With'):
        abort(403)

    # Exchange auth code for access token, refresh token, and ID token
    auth_code = request.data
    credentials = client.credentials_from_clientsecrets_and_code(CLIENT_SECRET_FILE, ['profile', 'email'], auth_code)

    # Get profile info from ID token
    userid = credentials.id_token['sub']
    email = credentials.id_token['email']
    name = credentials.id_token['name']
    picture = credentials.id_token['picture']

    # Check if user already exists
    old_user = db_session.query(User).filter(User.email == email).first()

    if old_user is None:
        # create new user and login
        user = User(name=name, email=email, picture=picture)
        db_session.add(user)
        db_session.commit()
        login_user(user)
    else:
        # login the old user
        login_user(old_user)

    db_session.close()
    flash("Login Successful, Welcome {}".format(name))
    return redirect(url_for('home'))
    def test_exchange_code_and_cached_file_for_token(self):
        http = HttpMockSequence([({"status": "200"}, b'{ "access_token":"asdfghjkl"}')])
        cache_mock = CacheMock()
        load_and_cache("client_secrets.json", "some_secrets", cache_mock)

        credentials = credentials_from_clientsecrets_and_code(
            "some_secrets", self.scope, self.code, http=http, cache=cache_mock
        )
        self.assertEqual(credentials.access_token, "asdfghjkl")
    def post(self, request):
        SAMPLE_SPREADSHEET_ID = '1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms'
        SAMPLE_RANGE_NAME = 'Class Data!A2:E'
        #CLIENT_SECRET_FILE = os.path.join(os.path.dirname(__file__), '..', 'client_secrets.json'

        auth_code = "4/QgEWsHaVX2AHvgm_oFobYcvfHJFX4Kxmi9ELsOBDOTHlYndDlDnyGLwotzeQoV9R7xhZ058J82VsEUzwXoFfh3o"

        # Exchange auth code for access token, refresh token, and ID token
        credentials = client.credentials_from_clientsecrets_and_code(
            CLIENT_SECRET_FILE, [
                'https://www.googleapis.com/auth/drive.file',
                'https://www.googleapis.com/auth/spreadsheets.readonly'
            ], auth_code)

        # Call Google API
        ##http_auth = credentials.authorize(httplib2.Http())
        service = discovery.build('sheets', 'v4', credentials=credentials)

        sheet = service.spreadsheets()

        spreadsheet = {'properties': {'title': "sheet example ja"}}
        spreadsheet = sheet.create(body=spreadsheet,
                                   fields='spreadsheetId').execute()
        print('Spreadsheet ID: {0}'.format(spreadsheet.get('spreadsheetId')))

        auth_code = "4/PQELICMYJTtywERyDS8nkvp-xH3NKs7Qxuw4YeIZ-WscCBhVpifvX_ZQ02hvLt8j_tjROM_8wX74NPLK82dzB2I"
        scope = [
            'https://www.googleapis.com/auth/drive.file',
            'https://www.googleapis.com/auth/spreadsheets.readonly'
        ]

        credentials = client.credentials_from_clientsecrets_and_code(
            CLIENT_SECRET_FILE, scope, auth_code)

        service = discovery.build('sheets', 'v4', credentials=credentials)

        sheet = service.spreadsheets()

        spreadsheet = {'properties': {'title': "TEST SHEET API"}}
        spreadsheet = sheet.create(body=spreadsheet,
                                   fields='spreadsheetId').execute()
        print('Spreadsheet ID: {0}'.format(spreadsheet.get('spreadsheetId')))

        return Response({"detail": "Done"}, status=HTTP_200_OK)
Example #21
0
def get_credentials(authCode):
    if (session.get("credentials", None) == None
            or session.get('authCode', None) != authCode):
        session[
            'credentials'] = client.credentials_from_clientsecrets_and_code(
                CLIENT_SECRET_FILE, SCOPES, authCode,
                redirect_uri=redir).to_json()
        session['authCode'] = authCode

    return session['credentials']
Example #22
0
 def get_token_using_authorization_code(self, auth_code: str, scopes: list,
                                        redirect_uri: str) -> dict:
     secret = os.environ['GOOGLE_OAUTH_SECRET_FILE_PATH']
     try:
         credentials = client.credentials_from_clientsecrets_and_code(
             secret, scopes, auth_code, redirect_uri=redirect_uri)
         return self._tokens_output(credentials)
     except FlowExchangeError as e:
         raise exceptions.LoginFailureError(
             "Not able to sign in with given code", e)
    def test_exchange_code_and_file_for_token_fail(self):
        http = HttpMockSequence([({"status": "400"}, b'{"error":"invalid_request"}')])

        try:
            credentials = credentials_from_clientsecrets_and_code(
                datafile("client_secrets.json"), self.scope, self.code, http=http
            )
            self.fail("should raise exception if exchange doesn't get 200")
        except FlowExchangeError:
            pass
Example #24
0
def gconnect():
    # If this request does not have `X-Requested-With` header, this could be a
    # CSRF
    if not request.headers.get("X-Requested-With"):
        response = make_response(json.dumps("Not authorized!"), 403)
        response.headers["Content-Type"] = "application/json"
        return response

    # Set path to the Web application client_secret_*.json file you downloaded
    # from the Google API Console:
    # https://console.developers.google.com/apis/credentials
    CLIENT_SECRET_FILE = "/var/www/catalogapp/client_secrets.json"

    auth_code = request.data
    # Exchange auth code for access token, refresh token, and ID token
    credentials = client.credentials_from_clientsecrets_and_code(
        CLIENT_SECRET_FILE,
        ["https://www.googleapis.com/auth/drive.appdata", "profile", "email"],
        auth_code,
    )

    # Call Google API http_auth = credentials.authorize(httplib2.Http())
    # drive_service = discovery.build('drive', 'v3', http=http_auth)
    # appfolder = drive_service.files().get(fileId='appfolder').execute()
    guser_id = credentials.id_token["sub"]
    stored_access_token = login_session.get("access_token")
    stored_guser_id = login_session.get("user_id")
    if stored_access_token is not None and guser_id == stored_guser_id:
        response = make_response(
            json.dumps("Current user is already connected."), 200)
        response.headers["Content-Type"] = "application/json"
        return response

    print(str(credentials.id_token))
    # Store the access token in the session for later use.
    login_session["access_token"] = credentials.access_token
    login_session["user_id"] = guser_id
    login_session["username"] = credentials.id_token["name"]
    login_session["picture"] = credentials.id_token["picture"]
    login_session["email"] = credentials.id_token["email"]

    try:
        db.session.query(User).filter_by(id=guser_id).one()
    except BaseException:
        newUser = User(
            id=login_session["user_id"],
            name=login_session["username"],
            email=login_session["email"],
            group="google",
        )
        print("Adding user " + guser_id + " in database")
        db.session.add(newUser)
        db.session.commit()

    return "You have logged in!"
def googleConnect():

    # check if the STATE is the same server/client. this is needed to control any malicious javascript
    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


# prevent CSRF attacks
    if not request.headers.get('X-Requested-With'):
        response = make_response(json.dumps('aborted for security reason.'),
                                 403)
        response.headers['Content-Type'] = 'application/json'
        return response

    auth_code = request.data

    # Exchange auth code for access token, refresh token, and ID token
    credentials = client.credentials_from_clientsecrets_and_code(
        CLIENT_SECRETS_FILE, SCOPES, auth_code)

    # pprint(credentials.to_json())

    # Call Google API
    # http_auth = credentials.authorize(httplib2.Http())
    # service = googleapiclient.discovery.build('oauth2', 'v3', credentials=credentials)

    # Get profile info from ID token

    #login_session['userid'] = credentials.id_token['sub']
    login_session['username'] = credentials.id_token['name']
    login_session['email'] = credentials.id_token['email']
    picture_url = credentials.id_token['picture']
    ## Save image on server ##
    urllib.request.urlretrieve(
        picture_url,
        "static/cache/images/" + login_session['username'] + ".jpg")
    login_session['picture'] = "static/cache/images/" + \
        login_session['username']+".jpg"
    login_session['provider'] = 'google'

    # check if the user is already on the Database

    user_id = getUserIdDB(login_session['email'])

    if user_id == 'None':
        user_id = createUserDB(login_session)

    login_session['user_id'] = user_id

    flash('You are now connected ad %s' % login_session['username'])

    return redirect(url_for('showRestaurants'))
Example #26
0
 def test_exchange_code_and_file_for_token(self):
     http = HttpMockSequence([
         ({
             'status': '200'
         }, """{ "access_token":"asdfghjkl",
    "expires_in":3600 }"""),
     ])
     credentials = credentials_from_clientsecrets_and_code(
         datafile('client_secrets.json'), self.scope, self.code, http=http)
     self.assertEquals(credentials.access_token, 'asdfghjkl')
     self.assertNotEqual(None, credentials.token_expiry)
  def test_exchange_code_and_cached_file_for_token(self):
    http = HttpMockSequence([
      ({'status': '200'}, '{ "access_token":"asdfghjkl"}'),
      ])
    cache_mock = CacheMock()
    load_and_cache('client_secrets.json', 'some_secrets', cache_mock)

    credentials = credentials_from_clientsecrets_and_code(
        'some_secrets', self.scope,
        self.code, http=http, cache=cache_mock)
    self.assertEquals(credentials.access_token, 'asdfghjkl')
 def test_exchange_code_and_file_for_token(self):
   http = HttpMockSequence([
     ({'status': '200'},
     """{ "access_token":"asdfghjkl",
      "expires_in":3600 }"""),
   ])
   credentials = credentials_from_clientsecrets_and_code(
                           datafile('client_secrets.json'), self.scope,
                           self.code, http=http)
   self.assertEquals(credentials.access_token, 'asdfghjkl')
   self.assertNotEqual(None, credentials.token_expiry)
Example #29
0
  def test_exchange_code_and_cached_file_for_token(self):
    http = HttpMockSequence([
      ({'status': '200'}, b'{ "access_token":"asdfghjkl"}'),
      ])
    cache_mock = CacheMock()
    load_and_cache('client_secrets.json', 'some_secrets', cache_mock)

    credentials = credentials_from_clientsecrets_and_code(
        'some_secrets', self.scope,
        self.code, http=http, cache=cache_mock)
    self.assertEqual(credentials.access_token, 'asdfghjkl')
Example #30
0
  def test_exchange_code_and_file_for_token_fail(self):
    http = HttpMockSequence([
      ({'status': '400'}, b'{"error":"invalid_request"}'),
      ])

    try:
      credentials = credentials_from_clientsecrets_and_code(
                            datafile('client_secrets.json'), self.scope,
                            self.code, http=http)
      self.fail('should raise exception if exchange doesn\'t get 200')
    except FlowExchangeError:
      pass
Example #31
0
    def store_credentials_from_web(self, auth_code):

        credentials = client.credentials_from_clientsecrets_and_code(
            self._config['client_secret']['web'],
            self._config['scopes'],
            auth_code)

        store = file.Storage(self.cred_path())

        with open(self.cred_path(),'w') as ofh:
            ofh.write(credentials.to_json())
        self._credentials = credentials
def login(request):
    auth_code = request.POST['auth_code']

    client_secrets_file = "client_secret.json"
    scopes = ["https://www.googleapis.com/auth/youtube.readonly"]

    credentials = client.credentials_from_clientsecrets_and_code(
        client_secrets_file,
        scopes,
        auth_code)

    request.session['sessionCookie'] = credentials
    return HttpResponse('200')
Example #33
0
def gconnect():
    '''Google sigin metohd
    (Receive auth_code by HTTPS POST)'''

    #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'
        print 'failed to get state'
        return response
    # Obtain authorization code
    auth_code = request.data

    # If this request does not have `X-Requested-With` header, this could be a CSRF
    if not request.headers.get('X-Requested-With'):
        app.abort(403)

    # Set path to the Web application client_secret_*.json file you downloaded from the
    # Google API Console: https://console.developers.google.com/apis/credentials
    clientSecretFile = 'client_secret.json'

    # Exchange auth code for access token, refresh token, and ID token
    credentials = client.credentials_from_clientsecrets_and_code(
        clientSecretFile,
        ['https://www.googleapis.com/auth/drive.appdata', 'profile', 'email'],
        auth_code)

    userinfo_url = "https://www.googleapis.com/oauth2/v1/userinfo"
    params = {'access_token': credentials.access_token, 'alt': 'json'}
    answer = requests.get(userinfo_url, params=params)

    data = answer.json()
    login_session['credentials'] = credentials

    # Get profile info from ID token
    login_session['userid'] = credentials.id_token['sub']
    login_session['email'] = credentials.id_token['email']
    login_session['username'] = data['name']
    login_session['picture'] = data['picture']

    user = GetUserID(login_session['email'])
    if user is None:
        CreateUser(login_session)
    else:
        print user

    flash("you are now logged in as %s" % login_session['username'])
    print "signed in %s" % login_session['username']
    response = make_response(json.dumps("Logged in"), 200)
    response.headers['Content-Type'] = 'application/json'
    return response
Example #34
0
def storeauthcode():

    # If this request does not have `X-Requested-With` header,
    # this could be a CSRF

    if not request.headers.get('X-Requested-With'):
        abort(403)

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

    auth_code = request.data

    # Set path to the Web application client_secret_*.json file
    # you downloaded from the
    # Google API Console:
    # https://console.developers.google.com/apis/credentials

    CLIENT_SECRET_FILE = 'client_secret.json'

    # Exchange auth code for access token, refresh token, and ID token
    url_cred_retrieve = 'https://www.googleapis.com/auth/drive.appdata'

    credentials = credentials_from_clientsecrets_and_code(
        CLIENT_SECRET_FILE, [url_cred_retrieve, 'profile', 'email'], auth_code)

    # Get profile info from ID token

    login_session['access_token'] = credentials.access_token
    login_session['name'] = credentials.id_token['name']
    login_session['email'] = credentials.id_token['email']

    # See if a user exists, if it doesn't make a new one
    userId = getUserID(login_session['email'])
    if userId is None:
        userId = createUser(login_session)

    user = getUserInfo(userId)

    print('User logged in: \n' + '\t  Name: ' + user.name + '\n' +
          '\tE-mail: ' + user.email + '\n')

    response = make_response(json.dumps('OAuth code stored.'), 200)
    response.headers['Content-Type'] = 'application/json'
    return response
Example #35
0
def make_query():
    if request.method == "POST":
        if not request.headers.get('X-Requested-With'):
            Response(
                """
               Necessary Header: X-Requested-With header not present
                """,
                status=403,
            )

        r = request.get_json()
        auth_code = r['response']['code']
        query = r['query']
        if auth_code:
            # Exchange auth code for access token, refresh token, and ID token
            credentials = client.credentials_from_clientsecrets_and_code(
                CLIENT_SECRET_FILE, [
                    'https://www.googleapis.com/auth/drive',
                    'https://www.googleapis.com/auth/spreadsheets',
                    'https://www.googleapis.com/auth/documents', 'profile',
                    'email'
                ], auth_code)

            # Call Google API
            http_auth = credentials.authorize(httplib2.Http())

            sheet_service = build('sheets', 'v4',
                                  credentials=credentials).spreadsheets()
            drive_service = build('drive', 'v3', http=http_auth)
            doc_service = build('docs', 'v1',
                                credentials=credentials).documents()
            try:
                res = debug(drive_service, doc_service, sheet_service,
                            query['query'])
            except HttpError as e:
                return Response(e._get_reason(), e.resp.status)
            except Exception as e:
                return Response("Unknown server-side error", 400)
            return Response(res)

        elif query:
            return Response('Your query request will not be performed due to '
                            'an authorization error. Please contact the '
                            'developer.')
        else:
            return Response('There has been an unspecified authorization '
                            'error, please contact the developer')

    else:
        return redirect('/')
 def test_exchange_code_and_file_for_token(self):
     http = HttpMockSequence(
         [
             (
                 {"status": "200"},
                 b"""{ "access_token":"asdfghjkl",
    "expires_in":3600 }""",
             )
         ]
     )
     credentials = credentials_from_clientsecrets_and_code(
         datafile("client_secrets.json"), self.scope, self.code, http=http
     )
     self.assertEqual(credentials.access_token, "asdfghjkl")
     self.assertNotEqual(None, credentials.token_expiry)
Example #37
0
def gSignIn():
    # Verify that the state token sent from the login
    # page is the same as the state token stored in
    # login_session
    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

    # Store google authorization code and use it
    # to get user credentials
    auth_code = request.data
    credentials = client.credentials_from_clientsecrets_and_code(
        CLIENT_SECRET_FILE,
        ['profile', 'email'],
        auth_code
    )

    # Get user info from google with stored credentials
    userinfo_url = "https://www.googleapis.com/oauth2/v1/userinfo"
    params = {'access_token': credentials.access_token, 'alt': 'json'}
    answer = requests.get(userinfo_url, params=params)
    data = json.loads(answer.text)

    # Get user info from returned data and store in login_session
    login_session['username'] = data['name']
    login_session['email'] = data['email']
    login_session['picture'] = data['picture']

    # Get user id from database
    # If None returned, add new user to datbase
    # from data stored in login_session
    user_id = getUserId(login_session['email'])
    if not user_id:
        user_id = createUser(login_session)
    login_session['user_id'] = user_id

    # Formats output to be returned as 'result' in login.html
    output = ''
    output += '<h2>Welcome, '
    output += login_session['username']
    output += '!</h2>'
    output += '<img src="'
    output += login_session['picture']
    output += '" style="width: 100px; height: 100px; border-radius: 100%;">'

    return output
Example #38
0
    def token(self):
    #----------------------------------------------------------------------
        # (Receive auth_code by HTTPS POST)
        auth_code = request.data

        # If this request does not have `X-Requested-With` header, this could be a CSRF
        if not request.headers.get('X-Requested-With'):
            abort(403)

        # Exchange auth code for access token, refresh token, and ID token
        credentials = client.credentials_from_clientsecrets_and_code(
            self.client_secrets_file,
            self.scopes,
            auth_code)

        # Get profile info from ID token
        user_id = credentials.id_token['sub']
        email = credentials.id_token['email']

        authorized = False
        if user_id:
            credfile = os.path.join(self.credfolder, user_id)
            storage = Storage(credfile)
            # do the new credentials not have a refresh token? do we already have credentials? 
            # if so, just update the access token and expiry from new credentials into stored and resave
            storedcred = storage.get()
            if not credentials.refresh_token and storedcred:
                storedcred.access_token = credentials.access_token
                storedcred.token_expiry = credentials.token_expiry
                credentials = storedcred
            credentials.set_store(storage)
            storage.put(credentials)
            session['_ga_google_user_id'] = user_id
            session['_ga_google_email'] = email
            # refresh
            http = httplib2.Http()
            credentials.refresh(http)

            # take care of login specifics
            authorized = self.logincallback(email)

        if self.logdebug: self.logdebug( 'oauth2callback() session = {}'.format(session) )

        return jsonify( {'authorized':authorized, 'redirect':url_for(self.startendpoint)} )
def gconnect():
    state_token = request.args.get('state')
    if state_token != login_session['state']:
        return json_response('Invalid State Parameter', 401)
    auth_code = request.data
    print('auth_code %s' % str(auth_code))

    # Exchange auth code for access token, refresh token, and ID token
    credentials = client.credentials_from_clientsecrets_and_code(
        CLIENT_SECRET_FILE,
        ['profile', 'email'],
        auth_code)

    # Store the access token in the session for later use.
    login_session['credentials'] = credentials.to_json()
    google_id = credentials.id_token['sub']
    login_session['google_id'] = google_id

    # Call Google API
    http = credentials.authorize(httplib2.Http())
    service = build('plus', 'v1', http=http)
    people_resource = service.people()
    people_document = people_resource.get(userId='me').execute()

    # Get profile info from ID token
    name = people_document['displayName']
    email = credentials.id_token['email']
    picture_url = people_document['image']['url']

    # Get the user
    user = getUserByGoogleId(login_session['google_id'])

    # Create the user if they don't exist in our system yet
    if not user:
        user = createUser(google_id, name, email, picture_url)

    # Load their data into the session
    login_session['username'] = name
    login_session['email'] = email
    login_session['picture'] = picture_url

    flash('Logged in as %s' % name)
    return redirect('/')
Example #40
0
def googleLogin():
	# Verify state token
	if request.args.get('google_state_token') != \
			login_session['google_state_token']:
		return makeJSONResponse('Invalid state token', 401)
	authorizationCode = request.data

	# Get credentials
	CLIENT_SECRET_FILE = getGoogleClientSecret()
	try:
		credentials = client.credentials_from_clientsecrets_and_code(
			CLIENT_SECRET_FILE,
				['https://www.googleapis.com/auth/drive.appdata', 
				'profile', 'email'],
    authorizationCode)
	except client.FlowExchangeError:
		return makeJSONResponse('Failed to exchange authorization code', 401)
	http_auth = credentials.authorize(httplib2.Http())
	drive_service = discovery.build('drive', 'v3', http=http_auth)
	appfolder = drive_service.files().get(fileId='appfolder').execute

	# Get user info
	oauth_id = credentials.id_token['sub']
	email = credentials.id_token['email']
	url = 'https://www.googleapis.com/oauth2/v1/userinfo?alt=json&access_token=%s' \
		% credentials.access_token
	response = requests.get(url)
	data = json.loads(response.text)
	name = data['name']

	# Check if user already exists
	matchingUser = session.query(User).filter(User.oauth_id == oauth_id) \
		.first()
	if matchingUser is None:
		newUser = User(oauth_id = oauth_id, name = name, email = email)
		session.add(newUser)
		session.commit()
		login_session['user_id'] = newUser.id
	else:
		login_session['user_id'] = matchingUser.id
	login_session['login_type'] = 'google'
	login_session['google_access_token'] = credentials.access_token
	return makeJSONResponse('Logged in through Google', 200)
Example #41
0
    def action(self, action, d):
        base = "http://localhost:8080" if tools.on_dev_server() else BASE
        if action == 'login':
            scope = "email profile"
            flow = User.get_auth_flow(scope=scope)
            flow.params['access_type'] = 'offline'
            flow.params['include_granted_scopes'] = 'true'
            auth_uri = flow.step1_get_authorize_url(state=scope)
            self.json_out({'auth_uri': auth_uri}, success=True, debug=True)

        elif action == 'oauth2callback':

            error = self.request.get('error')
            code = self.request.get('code')
            scope = self.request.get('scope')
            state_scopes = self.request.get('state')

            if code:
                CLIENT_SECRET_FILE = os.path.join(os.path.dirname(__file__), 'client_secrets.json')

                credentials = client.credentials_from_clientsecrets_and_code(
                    CLIENT_SECRET_FILE,
                    scope.split(' '),
                    code,
                    redirect_uri=base + "/api/auth/oauth2callback")
                user = self.user
                if not user:
                    email = credentials.id_token['email']
                    user = User.GetByEmail(email)
                    if not user:
                        # Create account
                        user = User.Create(email=email)

                if user:
                    user.save_credentials(credentials)
                    user.put()
                    self.session['user'] = user
            elif error:
                logging.error(error)


            self.redirect("/app/settings")
Example #42
0
def code():
    # If session doesn't include `id`, the user is not signed in
    if 'id' not in session:
        return make_response('Not authenticated', 401)

    user_id = session.get('id', None)

    # POST should include `code`
    code = request.form.get('code', '')
    # Exchange the `code` with credential information
    credentials = client.credentials_from_clientsecrets_and_code(
        'client_secrets.json', scope='', code=code)

    # If the credential is `None`
    if credentials is None:
        # Means it failed to obtain the credential object
        return make_response('Invalid authorization code.', 401)

    # Extract user id from `id_token`'s content
    sub = credentials.id_token['sub']

    # If the requesting user id doesn't match with the signed-in user id
    if user_id != sub:
        # Reject
        return make_response("User doesn't match", 401)

    # Obtain Datastore entry by user id
    store = CredentialStore.get_by_id(sub)

    # If the store is `None`, the user hasn't previously signed-in
    if store is None:
        return make_response('Authorization before authentication.', 401)
        # You could optionally authenticate if it makes sense.
        # Just chose not to do so here because Google recommendation is
        # to separate AuthN and AuthZ.

    # Serialize the credential object and save
    store.credentials = credentials.to_json()
    store.put()

    return make_response('', 200)
Example #43
0
def code_auth(code):
    credentials = credentials_from_clientsecrets_and_code(
        'client_secrets.json', SCOPES, code)
    storage = Storage('credentials_file')
    storage.put(credentials)
    print credentials.to_json()
Example #44
0
def gconnect():
    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
    code = request.data
    try:
        # oauth_flow = flow_from_clientsecrets('client_secret.json',
        #     scope='')
        # oauth_flow.redirect_uri = 'postmessage'
        # # Exchange one time one time secret from client to get access code fpr servver
        # credentials = oauth_flow.step2_exchange(code)
        credentials = client.credentials_from_clientsecrets_and_code(
        'client_secret.json',
        ['https://www.googleapis.com/auth/drive.appdata', 'profile', 'email'],
        code)
    except FlowExchangeError:
        response = make_response(json.dumps('Failed to upgrade the authorization code'),
            401)
        response.headers['Content-Type'] = 'application/json'
        return response
    # Check that access token is valid
    # access_token = credentials.access_token
    # url = ('https://www.googleapis.com/oauth2/v1/tokeninfo?accesstoken=%s'
    #     % access_token)
    # h = httplib2.Http()
    # rb = h.request(url,'GET')[1].decode('latin1')
    # result = json.loads(rb)
    # # If there was an error in the access token info, abort.
    # if result.get('error') is not None:
    #     response = make_response(json.dumps(result.get('error')), 500)
    #     response.headers['Content-Type'] = 'application/json'
    http_auth = credentials.authorize(httplib2.Http())
    # Verify tht the access token is ised fpr yje intended client
    gplus_id = credentials.id_token['sub']
    # if result['user_id'] != gplus_id:
    #     response = make_response(
    #         json.dumps("Token's user ID doesnt match given USER ID"), 401
    #     )
    #     response.headers['Content-Type'] = 'application/json'
    #     return response
    # Check to see if user is already logged in
    stored_credentials = login_session.get('credentials')
    stored_gplus_id = login_session.get('gplus_id')
    if (stored_credentials is not None 
        and gplus_id == stored_gplus_id):
        response = make_response(json.dumps('Current user is already connected.'),
                        200)
        response.headers['Content-Type'] = 'application/json'

    # Store the access toen in the session for later use
    login_session['credentials'] = credentials.access_token
    login_session['gplus_id'] = gplus_id

    # Get User info
    userinfo_url = 'https://www.googleapis.com/oauth2/v1/userinfo'
    params = {"access_token": credentials.access_token, 'alt':'json'}
    answer = requests.get(userinfo_url, params=params)
    data = json.loads(answer.text)
    login_session['username'] = data['name']
    login_session['picture'] = data['picture']
    login_session['email'] = data['email']

    

    output = """
    <h1> Welcome, %(username)s</h1>
    <img src="%(picture)s" style="width:300px; height:300px; border-radius:150px">
    """ % {"username": login_session['username'], "picture": login_session['picture']}
    flash("You are now logged in as %s" % login_session["username"])
    user_id = getUserId(login_session['email'])
    if not user_id:
        user_id = createUser(login_session)
    login_session['user_id'] = user_id
    return output
Example #45
0
LIENT_SECRET_FILE

from apiclient import discovery
import httplib2
from oauth2client import client
import os


auth_code = "nLLIpv_yDHecvUC_uzrR2rw02MYS3Ly3jeeKECW878s"
CLIENT_SECRET_FILE = str(os.getcwd()) + "/client_secret.json" 

credentials = client.credentials_from_clientsecrets_and_code(
    CLIENT_SECRET_FILE,
    ['https://www.googleapis.com/auth/gmail.readonly'],
    auth_code)


#http = credentials.authorize(httplib2.Http())
#gmail_service = discovery.build('gmail', 'v1', http=http)