CareChat: Build a chat app in minutes!
In this post, we will show you how to build a simple chat app quickly with Firebase and AngularJS.
What is CareChat?
It’s a communication channel suited for customer service type use case — allows Customer Service representative to chat with Customers (but Customers can’t talk among themselves). The demo app has two roles, User and Administrator. User represents Customer while Admin represents Customer Service Representative.
Technology Stack
AngularJS: Is an awesome open-source JavaScript framework to create Single Page Application. It does a great job in maintaining client-side scripts in a structured manner and it also reduces the load on server thereby improving the user experience.
Firebase: Firebase powers app’s back-end, including data storage, user authentication, static hosting, and more. Firebase frees up the developer to focus on creating extraordinary user experiences as Firebase does the heavy lifting on the back-end.
Before proceeding further, take a look at a simple chat app which can be used in different use cases such as Customer Care or for Doctor-Patient communication.
Demo: CareChat
Source Code: Github
Libraries Required:
Yeoman (optional): Web scaffolding tool for constructing web apps.
AngularJS: JavaScript framework – can be used from CDN or downloaded and added to project.
Firebase Javascript: Javascript API – can be used from CDN or downloaded and added to project.
AngularFire Plugin: AngularJS binding for Firebase – add it as bower dependency
- Create Yeoman App based on Angular generator & add Firebase and AngularFire bower component
After creating Yeoman application with “yo angular care-chat” add Firebase and AngularFire as JS dependencies.1bower install angularfire --save-dev - Set up Firebase app environment at Firebase.com
Login to Firebase.com site with valid credential & create an APP. Enable authentication from “Login & Auth” tab & check “Enable Email & Password Authentication” checkbox.Configure the Firebase rules so that customers can’t see each other butCustomer Service representative can. Also,Customer Service representative is the only one who should be able to talk to various customers. Firebase rules are at-most important configuration for security requirement. To configure the rules, move to manage section and navigate to “Security & Rules” tab.
Copy below JSON and paste them in Firebase
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
{ "rules": { ".read":true, "users":{ ".read":"auth != null", "$uid":{ ".read":"auth != null && auth.uid == $uid", ".write":"auth != null && auth.uid == $uid" } }, "chats":{ "$id": { ".read": "auth != null && root.child('channels').child($id).val().contains(auth.uid)", ".write": "auth != null && root.child('channels').child($id).val().contains(auth.uid)" } }, "channels":{ ".read":"auth != null", "$cid":{ ".read":"auth != null && data.val().contains(auth.uid)", ".write":"auth != null" } } } } |
For more information on Firebase rules, visit https://www.firebase.com/docs/security/guide/
- AngularJS code to interact with Firebase server Inject “firebase” as Angular dependency in your app.js file — your app.js file should contain this code.
1var app = angular.module('chatDemo',['firebase']);1234567891011121314angular.module('chatDemo').controller('MainCtrl',function($scope,$firebaseAuth, $firebaseObject, $firebaseArray){//…….//…….//Replace with a your app url that you have in firebase//account. (Please create a firebase account in case you don't have it)var FIREBASE_APP_URL = 'chatdemo-firebaseio.com' //your app urlvar firebaseRef = new Firebase(FIREBASE_APP_URL);//firebase provides authentication feature through FirebaseAuth module//create firebase auth object using angular $firebaseAuth service contained in//firebase module$scope.authObj = $firebaseAuth(firebaseRef);});12345678910var user = {email: userDetails.email,password: userDetails.password};$scope.authObj.$createUser(user).then(function (userData) {//on success take necessary action to inform user about status}).catch(function (error) {//error});12345678$scope.authObj.$authWithPassword({email: "doctor@carechat.com",password: "doctor123"}).then(function(authData) {console.log("Logged in as:", authData.uid);}).catch(function(error) {console.error("Authentication failed:", error);});12345678var user = {name:"doctor",email:"doctor@carechat.com",age:34,phone: 9876-xxx-xxx,address: "Flat 1A,Society X, Street Y, City Z (US)"};firebaseRef.child("users").child(authData.uid).set(user);
Create channels to start chat sessions between users. A channel indicates a chat session (In our app patients or customers can’t chat with each other while doctors or customer care representative can chat with everyone). To create channel we have created a schema of channel collection. i.e our channel consist of combination of doctor uid and user uid.
1234channels = {firebase_generate_id1:"uid1,uid2",firebase_generate_id2:"uid1,uid2"};123456789101112131415161718$firebaseObject(firebaseRef.child("channels")).$loaded(function(channels){//success$scope.channels = channels;},function(error){//errorconsole.log(error.message);});//above code we should perform in resolve state with angular promises to get more stability//Fetch that chats for channel xevSD8xzz7advar chatRef = new Firebase('chatdemo-firebaseio.com/chats/xevSD8xzz7ad');$firebaseArray(chatRef).$loaded(function (chats) {//success$scope.chats = chats;}, function (error) {//errorconsole.log(error.message);});123456var chat = {sid:'uid1', //sender uid or logged in user uid (doctor's uid in our case)message:'Hi, how can I help you' , //message typed by doctorread:false //we set read flag to false initially, will set to true if patient reads it.};$scope.chats.$add(chat);