Git Product home page Git Product logo

twilio-conversations-demo-react's Introduction

Conversations Demo Web Application Overview

SDK version of this demo app:

The latest available SDK version of this demo app:

Getting Started

Welcome to the Conversations Demo Web application. This application demonstrates a basic Conversations client application with the ability to create and join conversations, add other participants into the conversations and exchange messages.

What you'll need to get started:

Generating Access Tokens

Client apps need access tokens to authenticate and connect to the Conversations service as a user. These tokens should be generated by your backend server using your private Twilio API Keys. If you already have a service that does this, skip to setting the token service URL.

For testing purposes, you can quickly set up a Twilio Serverless Functions to generate access tokens. Note that this is not a production ready implementation.

Generating Access Tokens with Twilio Functions

  1. Create a Twilio Functions Service from the console and add a new function using the Add+ button.
  2. Set the function path name to /token-service
  3. Set the function visibility to Public.
  4. Insert the following code:
// If you do not want to pay for other people using your Twilio service for their benefit,
// generate user and password pairs different from what is presented here
let users = {
    user00: "", !!! SET NON-EMPTY PASSWORD AND REMOVE THIS NOTE, THIS GENERATOR WILL NOT WORK WITH EMPTY PASSWORD !!!
    user01: ""  !!! SET NON-EMPTY PASSWORD AND REMOVE THIS NOTE, THIS GENERATOR WILL NOT WORK WITH EMPTY PASSWORD !!!
};

let response = new Twilio.Response();
let headers = {
    'Access-Control-Allow-Origin': '*',
  };

exports.handler = function(context, event, callback) {
    response.setHeaders(headers);
    if (!event.identity || !event.password) {
        response.setStatusCode(401);
        response.setBody("No credentials");
        callback(null, response);
        return;
    }

    if (users[event.identity] != event.password) {
        response.setStatusCode(401);
        response.setBody("Wrong credentials");
        callback(null, response);
        return;
    }
    
    let AccessToken = Twilio.jwt.AccessToken;
    let token = new AccessToken(
      context.ACCOUNT_SID,
      context.TWILIO_API_KEY_SID,
      context.TWILIO_API_KEY_SECRET, {
        identity: event.identity,
        ttl: 3600
      });

    let grant = new AccessToken.ChatGrant({ serviceSid: context.SERVICE_SID });
    if(context.PUSH_CREDENTIAL_SID) {
      // Optional: without it, no push notifications will be sent
      grant.pushCredentialSid = context.PUSH_CREDENTIAL_SID; 
    }
    token.addGrant(grant);
    response.setStatusCode(200);
    response.setBody(token.toJwt());

    callback(null, response);
};
  1. Save the function.
  2. Open the Environment Variables tab from the Settings section and:
    • Check the "Add my Twilio Credentials (ACCOUNT_SID) and (AUTH_TOKEN) to ENV" box, so that you get ACCOUNT_SID automatically.
    • Add SERVICE_SID
      • Open Conversations Services
      • Copy the SID for Default Conversations Service, or the service you want to set up.
    • Add TWILIO_API_KEY_SID and TWILIO_API_KEY_SECRET. Create API Keys in the console.
    • Optionally add PUSH_CREDENTIAL_SID, for more info see Setting up Push Notifications
  3. Copy URL from the "kebab" three dot menu next to it and and use it as REACT_APP_ACCESS_TOKEN_SERVICE_URL .env variable below.
  4. Click Deploy All.

Set the Token Service URL

If you don't have your own .env, rename this repo's .env.example file to .env. Set the value of REACT_APP_ACCESS_TOKEN_SERVICE_URL to point to a valid Access Token server. If you used Twilio Functions for generating tokens, get the value from Copy URL in step 7 above.

REACT_APP_ACCESS_TOKEN_SERVICE_URL=http://example.com/token-service/

NOTE: No need for quotes around the URL, they will be added automatically.

This demo app expects your access token server to provide a valid token for valid credentials by URL:

$REACT_APP_ACCESS_TOKEN_SERVICE_URL?identity=<USER_PROVIDED_USERNAME>&password=<USER_PROVIDED_PASSWORD>

And return HTTP 401 in case of invalid credentials.

Setting up Push Notifications

This demo app uses Firebase for processing notifications. This setup is optional. Note: Support may be limited for some browswers.

Set up Firebase

  1. Create a Firebase project
  2. Go to the Project Settings
  3. Got to the Cloud Messaging and enable Cloud Messaging API (Legacy) through the "kebab" menu besides it.
  4. Note or copy the Server Key token for creating push credentials.

Create Push Credential

Create a push credential to add a push grant to our access token.

  1. Go to the Credentials section of the console.
  2. Create a new FCM Push Credential and set the Firebase Cloud Message Server Key Token as the FCM Secret.
  3. Note or copy the CREDENTIAL SID to set as PUSH_CREDENTIAL_SID env variable in your token creation Function.

Create Firebase App set config

From the Firebase Project Settings General tab, add a web app to get the firebaseConfig, it should look like this:

var firebaseConfig = {
  apiKey: "sample__key12345678901234567890",
  authDomain: "convo-demo-app-internal.firebaseapp.com",
  projectId: "convo-demo-app-internal",
  storageBucket: "convo-demo-app-internal.appspot.com",
  messagingSenderId: "1234567890",
  appId: "1:1234567890:web:1234abcd",
  measurementId: "EXAMPLE_ID"
};

Note: Firebase API Keys aren't like Twilio API keys and don't need to be kept secret.

Replace this project's firebase-config.example in the public folder with a firebase-config.js containing your specific config.

Enable Push Notification in Conversations Service

Select your conversations service, navigate to the Push Notifications section, and check the Push notifications enabled boxes for the push notifications you want.

Build

  • Run yarn to fetch project dependencies.
  • Run yarn build to fetch Twilio SDK files and build the application.

Run application

  • Run yarn to fetch project dependencies.
  • Run yarn start to run the application locally.

License

MIT

twilio-conversations-demo-react's People

Contributors

berkus avatar infiniterain avatar sveta-leonovets-twi avatar rusmonster avatar pavel-cherentsov avatar josethepm avatar yunuscanemre avatar sahibbajaj avatar nipel-crumple avatar baugistoms avatar omalinovkyi avatar ricardonunoalmeida avatar snyk-bot avatar gray-wind avatar malinovskiy-alex avatar rziehl-twilio avatar twilio-product-security avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.