Skip to main content

Create Google Drive App to View and Upload Files Using OAuth 2.0 and Flask





For authentication and authorization processes, we can use OAuth 2.0 framework. It is an industry standard authorization protocol. This is a direct authentication pattern. So users can login using their other public profiles. No need to register and enter password. Because of that, this is often called the password anti-pattern.

How Aouth works?




When web application redirects a browser to a Google URLauthorization sequence begins; the URL includes query parameters that indicate the type of access being requested. Google manages the user authentication and session selection. The result is an authorization code, which the application can exchange for an access token and a refresh token [6].

Your application sends a token request to the Google Authorization Server, receives an authorization code,
exchanges the code for a token, and uses the token to call a Google API endpoint.
The application should store the refresh token for future use and use the access token to access a Google API. Once the access token expires, the application uses the refresh token to obtain a new one[6].

Here, we are creating a web application to  login to google using AOuth 2.0 ,view files from google drive and upload files to google drive.

1. Create / Register google app










  • Enter project name and continue


  • Click on "Enable services and APIs" button and enable google drive api
  • Then, Add credentials for the project




  • create OAuth client ID using below values







  • Download the json file and rename it as client_id.json

2. Create web application
  • Install following dependancies

pip install flask google-api-python-client
pip install oauth2client
  • Create home page  to do the OAuth authentication on behalf of the logged in user.

 get_credentials()- checks the local access token file credentials
 fetch() -that displays the list of all root folders ,files and documents

In here if the user is not logged in browser redirect to google login page by calling the below function. Otherwise, using authorized code, app loads google drive files from the authorized user account.

  • callback function


If the user is not loged in , application calls this function. Then using google app client id key and secret key application sends request to login, then server pass the authorized token values.
  • file upload function

# upload file to google drive@app.route('/uploads', methods=['GET', 'POST'])
def upload():
    credentials = get_credentials()
    http = credentials.authorize(httplib2.Http())
    service = discovery.build('drive', 'v3', http=http)

    if request.method == 'POST':
        # check if the post request has the file part        
if 'file' not in request.files:

            print('no file part')
            return redirect(request.url)
        file = request.files['file']

        # if user does not select file, browser also submit a empty part
 without filename

        if file.filename == '':

            print('no selected file')
            return redirect(request.url)
        if file:
            filename = file.filename
            print(filename)

            #set write access to upload folder            os.chmod(UPLOAD_FOLDER, 0o777)
            os.access('files', os.W_OK)  # Check for write access            os.access('files', os.R_OK)

            #save file in upload folder            file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))

            #get file path            filepath=os.path.join(app.config['UPLOAD_FOLDER'], filename)

            #set file meta data            file_metadata = {'name': filename}

            #set upload file mime type            media = MediaFileUpload(filepath, mimetype='image/png')
            file = service.files().create(body=file_metadata,
media_body=media,fields='id').execute()
            print ('File ID: %s' % file.get('id'))

    return render_template('success.html')



3.Output




4. Resources




Comments

Popular posts from this blog

Advantages of using REST API

  Representational State Transfer is an architectural style that defines a set of constraints and properties based on HTTP. ● Uniform interface ● Stateless ● Cacheable ● Client-Server ● Layered System 1. Uniform interface-   to transfer data, the REST system applies specific actions (POST, GET, PUT and DELETE) on the resources, provided they are identified with a URI. This makes it easier to obtain a uniform interface that systematizes the process with the information. 2. Stateless -  REST APIs are stateless, meaning that calls can be made independently of one another, and each call contains all of the data necessary to complete itself successfully. 3. Cacheble -    Because a stateless API can increase request overhead by handling large loads of incoming and outbound calls, a REST API should be designed to encourage the storage of cacheable data. 4. Layerd System-  REST APIs have different layers of their architecture working together to build a hierar

Node js and Java Script

open-source JavaScript run-time environment executes JavaScript code server-side       JavaScript is a programming language.        Node . js  is an environment allowing  JavaScript  code to run on the server side and not in a browser. It is based on Chrome's V8 Engine, which runs on Google Chrome. Java script engines runs the JavaScript from the web pages. Firefox                -      Spidermonkey Safari                  -      JavaScriptCore Chrome              -           V8   Node js based on v8 engine.  Node Js  is Easy to learn has Freedom in building apps helps to write both backend and front end of web app using js