Back

How to build a public Streak integration: Building the Auth Flow

Aug 14, 20247 minute read

Hey there, fellow JavaScript enthusiast! Ready to dive into the world of Streak integrations? Today, we're going to tackle one of the most crucial parts of building a public integration: the authorization flow. Buckle up, because we're about to make your integration secure and user-friendly in no time!

Prerequisites

Before we jump in, make sure you've got:

  • Your favorite JavaScript environment set up
  • A Streak developer account with API credentials
  • A burning desire to create awesome integrations

Setting up the project

Let's kick things off by getting our project ready:

mkdir streak-integration && cd streak-integration npm init -y npm install express axios dotenv

Create an index.js file and let's get coding!

Understanding Streak's OAuth 2.0 flow

Streak uses OAuth 2.0, which is like a fancy handshake between your app and Streak. Here's the gist:

  1. Your app asks for permission
  2. User says "sure, go ahead"
  3. Streak gives you a special code
  4. You exchange that code for an access token
  5. You use that token to make API requests

Simple, right? Let's make it happen!

Implementing the authorization request

First, we need to send users to Streak's auth page. Here's how:

const express = require('express'); const app = express(); app.get('/auth', (req, res) => { const authUrl = `https://www.streak.com/api/v1/oauth/authorize?client_id=${process.env.CLIENT_ID}&redirect_uri=${encodeURIComponent(process.env.REDIRECT_URI)}&response_type=code`; res.redirect(authUrl); }); app.listen(3000, () => console.log('Server running on port 3000'));

Handling the callback

When the user grants permission, Streak will send them back to your redirect URI with a code. Let's catch that:

app.get('/callback', async (req, res) => { const { code } = req.query; // We'll use this code in the next step res.send('Authorization successful! You can close this window.'); });

Exchanging the code for access token

Now for the good stuff - let's get that access token:

const axios = require('axios'); async function getAccessToken(code) { const response = await axios.post('https://www.streak.com/api/v1/oauth/token', { client_id: process.env.CLIENT_ID, client_secret: process.env.CLIENT_SECRET, code, grant_type: 'authorization_code', redirect_uri: process.env.REDIRECT_URI }); return response.data.access_token; }

Refreshing the access token

Tokens don't last forever, so let's add a refresh mechanism:

async function refreshAccessToken(refreshToken) { const response = await axios.post('https://www.streak.com/api/v1/oauth/token', { client_id: process.env.CLIENT_ID, client_secret: process.env.CLIENT_SECRET, refresh_token: refreshToken, grant_type: 'refresh_token' }); return response.data.access_token; }

Securing the token storage

Remember, with great power comes great responsibility. Store those tokens securely! Consider using encryption or a secure database.

// This is just a simple example. In a real app, use proper secure storage! const tokens = new Map(); function storeTokens(userId, accessToken, refreshToken) { tokens.set(userId, { accessToken, refreshToken }); }

Making authenticated requests to Streak API

Now you're ready to rock the Streak API:

async function makeStreakRequest(userId, endpoint) { const { accessToken } = tokens.get(userId); try { const response = await axios.get(`https://www.streak.com/api/v1/${endpoint}`, { headers: { Authorization: `Bearer ${accessToken}` } }); return response.data; } catch (error) { if (error.response && error.response.status === 401) { // Token expired, refresh and try again const newAccessToken = await refreshAccessToken(tokens.get(userId).refreshToken); storeTokens(userId, newAccessToken, tokens.get(userId).refreshToken); return makeStreakRequest(userId, endpoint); } throw error; } }

Error handling and edge cases

Always be prepared for things to go sideways. Handle errors gracefully and give users helpful feedback.

Testing the auth flow

Take your integration for a spin! Try authorizing, making requests, and even intentionally expiring tokens to test your refresh logic.

Conclusion

And there you have it! You've just built a rock-solid auth flow for your Streak integration. From here, the sky's the limit. Go forth and create amazing things with the Streak API!

Remember, this is just the beginning. Keep exploring, keep coding, and most importantly, keep having fun with it. Happy integrating!