Niels Vanwingh
Niels Vanwingh

Reputation: 604

OAuth2 Authorization Code Grant Flow Node.js mixed with Client-Side

I am performing OAuth2 authentication against the Fitbit API. This all using the Authorization Code Grant Flow. So first getting the auth code, being redirected to my application, then exchanging this for the access token and getting data with this token.

Starting off at the homePage on the "post_request.html" page, pushing the "fitbit" button, the user is redirected to the Authorization EndPoint of Fitbit. I am using Node.js to build a localserver to host the application and to be able to redirect without any problem..

My HTML file is the following, with inline script..

<!DOCTYPE html>
<html lang = "en">  <!–– language check you can perform ––>

    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1";>                                                             <!–– necessary to make the website responsive, zoom level to 1 ––>
        <title>API Fitbit OAuth2</title>
        <meta name="description" content="Planner for Trail Running">                                                                     <!–– this part will be used in SEM, result of content strategy workshops ––>
        <meta name="author" content="Niels">                                                                         <!–– make sure this refers to the right css sheet ––>
    </head>

    <body>

        <button onclick="fitbitAuth()">Fitbit</button>

        <!-- action = route, method = method -->
        <form action="/" method="POST" id="form">
            <h3>Email Address:</h3>
            <input type="email">
            <br>
            <h3>Password:</h3>
            <input type="password">     
            <br>
            <br>
            <button type="submit">Send Request</button>   
        </form>

    <script>
            // run this script upon landing back on the page with the authorization code 
            var url_terug = window.location.search;
            var auth_code = url_terug.substr(6);
            console.log(auth_code);

            // get the authorization code out of the response 
            // execute a POST request with the right parameters 
            // get the access token out of the JSON response 
            // execute a GET request on the API endpoint 
            // handle the data 

            // upon clicking fitbit button, starting off the oauth2 authentication 
            function fitbitAuth() {

                window.location.href = 'https://www.fitbit.com/oauth2/authorize?client_id=MYCLIENTID&response_type=code&scope=activity&redirect_uri=http://localhost:3000/fitbit&prompt=consent';

            }

        </script>

    </body>
    </html>

My question is on the Node.js side.. I am quite new to Node.. How can I add proper error handling to the page in the method "app.get(/fitbit)"?

// PROJECT making a POST request 
const express = require("express");
const app = express();
const filesys = require("fs");
const path = require("path");
// body parser module parses form data into server
const body_parse = require("body-parser");

// middleware
app.use('/public', express.static(path.join(__dirname, 'static')));
// allows us to parse url encoded forms 
app.use(body_parse.urlencoded({extended: false}));

// using readstream with chunks in buffer with security on the path 
app.get("/fitbit", (req, res) => {

    const readStream = filesys.createReadStream(path.join(__dirname,'static','post_request.html'));
    res.writeHead(200, {'Content-type' : 'text/html'});
    readStream.pipe(res);

});

// bodyparser parses data and adds to the body of the request 
app.get("/", (req, res, err) => {

    const readStream = filesys.createReadStream(path.join(__dirname,'static','post_request.html'));
    res.writeHead(200, {'Content-type' : 'text/html'});
    readStream.pipe(res);

});

app.listen(3000);

Upvotes: 0

Views: 618

Answers (1)

Aaron Meese
Aaron Meese

Reputation: 2223

This page describing basic error handling in Express might be helpful to you. It's hard to give any more specific information because we do not know what type of errors you anticipate getting.

If you mean specifically with createReadStream, the methods discussed here might be helpful to you:

readStream = filesys.createReadStream(path.join(__dirname,'static','post_request.html'));
readStream.on('error', function(){ /*handle error*/ });
res.writeHead(200, {'Content-type' : 'text/html'});
readStream.pipe(res);

Upvotes: 1

Related Questions