Integration of Ionic and Phonegap enables the incorporation of an offline database system with secure authorization

After creating a simple app using the ionic framework and integrating Firebase for database storage, I realized that offline capabilities were limited. While Firebase worked well for user authentication and data access rules, it didn't provide full offline storage in javascript. A recommendation to use CouchDB/PouchDB for offline storage and sync with a remote server seemed promising, but then I encountered an issue with user authorization.

I needed a solution that would offer offline database capabilities, authorization with Google, remote database syncing after authorization, and hassle-free hosting on a reliable server. The goal was to have guest users store data locally, while authenticated users had their data accessible on both local and remote databases for cross-device usage.

With the aim of finding a hosting service compatible with Ionic/AngularJS/Cordova that supported a remote and local database with synchronization, I began my search.

Answer №1

Why avoid MongoDB when it easily integrates with Express/Node.js through the npm mongoose? It's a popular and efficient way to store data, similar to firebase. For instance:

const Express = require('express'),
app = Express.router();
app.route('/api/auth/signup').post(users.signup);

An Example Schema:

const mongoose = require('mongoose'),
  Schema = mongoose.Schema

const UserSchema = new Schema({
  firstName: {
    type: String,
    trim: true,
    default: '',
    required: 'Please fill in your first name'//message given if you fail to provide the required field.
  },
  lastName: {
    type: String,
    trim: true,
    default: '',
    required: 'Please fill in your last name'
  },
  displayName: {
    type: String,
    trim: true
  },
  email: {
    type: String,
    unique: 'Email already exists. Sign In?',
    lowercase: true,
    trim: true,
    default: '',
    validate: [validateLocalStrategyEmail, 'Please fill a valid email address'],//create a custom Email Validation strategy
    required: 'Please enter a valid business Email'
  },
});

A Sample Controller:

exports.signup = function (req, res) {
  // For security reasons, we remove the roles from the req.body object
  delete req.body.roles;

  // Initialize user and add missing fields
  const user = new User(req.body);
  user.provider = 'local';
  user.displayName = user.firstName + ' ' + user.lastName;

  // Save the user details
  user.save(function (err) {
    if (err) {
      return res.status(400).send({
        message: errorHandler.getErrorMessage(err)
      });
    } else {
      // Remove sensitive data before login
      user.password = undefined;
      user.salt = undefined;

      const jwtToken = authentication.signToken(user);
      res.json({ user: user, token: jwtToken });
    }
  });
};

You can find similar examples on MEAN.js Github. However, make sure to utilize LocalStorage and JSON web tokens for your ionic app to ensure compatibility with iPad/iPhone devices.

Answer №2

A great solution is to utilize PouchDB, a tool that seamlessly integrates with local storage systems (perfect for ionic/cordova) and can easily synchronize data with a remote couchdb server using just a few lines of code:

var localDB = new PouchDB('mylocaldb');
var remoteDB = new PouchDB('http://localhost:5984/myremotedb');
localDB.sync(remoteDB);

The challenge comes when dealing with the remote server authentication. CouchDB supports oauth by default, but on a per-database basis, requiring the creation of a separate database for each user, which can be quite complex. Explore npmjs.com for more resources on CouchDB.

Alternatively, you can protect your CouchDB using a node server like Express, implementing authentication in Express before filtering requests through.

This task is not straightforward, and services like Firebase come at a cost once usage increases. If server-side development isn't your forte, consider simpler solutions like meteor or hoodie.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Steps to set up gapi-script authentication with next-auth in a Next.js application

I have encountered an issue while working on my open-source project that involves utilizing the Google Drive API. Can anyone guide me on how to set up gapi-script authentication using next-auth in a Next.js project? I have managed to implement authentica ...

Receiving the error message "Encountered SyntaxError: Unexpected token )" when using a custom directive

Encountering an issue with the customer directive of auto-complete, as I am receiving the error Uncaught SyntaxError: Unexpected token ). This error is displayed in the console of the chrome browser as VM80623:1 Uncaught SyntaxError: Unexpected token ). Cl ...

Can one monitor a Vuex module in real time?

I have a single module imported into the Vuex store: import date from './modules/date-select'; export default new Vuex.Store({ modules: {date}, }); Is it possible to "watch" for changes in the entire module within a component? For example: ...

Steps to making an overlapping sidebar with Bootstrap column

I'm trying to set up a sidebar in Bootstrap that overlaps with a column. The goal is for the sidebar to appear when a button is clicked and disappear when the close button x is clicked. Despite using a Bootstrap row and column layout, I encountered is ...

Importing Audio Using AJAX in HTML

My music playlist allows me to click on an image of a song and open the media player using AJAX. Here is my HTML code: <div class="container "> <div class="row center"> @foreach($singles as $single) <div class="col-m ...

The EJS template in an Express.js (Node.js) application is not updating to show recent modifications

I'm currently developing a node.js application that serves an index.ejs page through a route named index.js. var express = require('express'); var router = express.Router(); /* GET home page. */ router.get('/', function(req, res) ...

The validity of the return statement in the ajax code is malfunctioning

Currently, I am in the process of validating duplicate email addresses from a database. Initially, I validate the email format, then check the email length and finally verify the email with the database using ajax. However, the return true or return false ...

What is the method for referencing an AngularJS Template within a JavaScript file that is supplied by a Grails plugin?

My Grails application utilizes multiple Grails Plugins that are also needed by other Grails apps beyond my own. Within a Resources Bundle in one of the Grails Plugins, I originally had this defined: (note: I have since switched to the Asset Pipeline) mod ...

What is the best way to utilize ajax for uploading both a text field and a file simultaneously?

I am currently new to AJAX and working on implementing a form that uploads a name and a file to a PHP file for processing and insertion into a database using mysqli. While the PHP file works, I am facing issues with the AJAX code. I have tried implementati ...

Using Angular's filter service within a controller

Just starting out so please be kind!! Encountering an issue with Angular 1.3 while using a Stateful Filter within a controller. In brief, when utilizing the $filter('custom')(data) method instead of the {{ data | custom }} method - and the cust ...

Instructions for sending a PNG or JPEG image in binary format from a React app to a Node.js server

I am in the process of transferring a file from a react web app to a node.js server. To begin, I have an HTML input of type file where users can upload their files. Once a user uploads a file, a post request is triggered to my Node.js server. Within my N ...

Adjust the size of an event in the Angular Full Calendar with Chronofy, while utilizing constraints to control the drag and drop functionality

I'm currently in the process of developing an availability calendar for scheduling meetings during open times. If a time slot is unavailable, users should not be able to place an event there. While I have successfully implemented this feature, I am ...

An array of tooltips linked to specific areas on an image using

Hello, I have created an imagemap with area polygons that display tooltips when the mouse hovers over them. Additionally, there is a legend at the bottom of the image map. My goal is to show the tooltip on the specific polygon area when the mouse is hove ...

Exploring SQL connections and their attributes across multiple Excel sheets using VBA

I have recently inherited several complex Excel workbooks that contain multiple worksheets and various SQL data connections. These workbooks come with different settings such as password protection, connection files, and automatic data refresh upon opening ...

Unexpectedly, nextJS is facing difficulties resolving components

I've encountered an issue while working on my website in NextJS. It suddenly started showing an error message about being unable to resolve multiple elements: https://i.sstatic.net/fQf1rf6t.png Here are a few things that I attempted, but unfortunately ...

Can anyone explain why I am having trouble loading JavaScript files into a different HTML file?

Currently, I am developing an electron application. In my index.html file, I have successfully loaded JavaScript files in the head tag and can access the JS functions without any problems. Now, I have created a separate browser window with another HTML fi ...

Is there a way to verify if a user navigated to a specific route or URL using the back button?

What is the best way to implement functionality that triggers when a user returns to a previously visited page in their browsing history? ...

Is there a live password verification tool available?

Currently, I am conducting some initial research for my school's IT department as a student employee. The students at our institution are required to change their passwords every six months, but many of them struggle with the various password regulati ...

What is the best way to ensure that two objects collide with one another?

Issue Description I am currently working on implementing collision detection for two objects. The goal is to determine if the objects are intersecting by calculating their bounding boxes with Box3 and using the .intersectsBox() function to obtain a boolea ...

Tips for successfully retrieving a boolean value from an ASP.Net JavaScript AJAX request using a C# method

Query: Is there a way to call a C# function from JavaScript code on an .aspx webpage to get authentication results based on a username and password? Here is the JavaScript AJAX POST request I am currently using: $.ajax({ type: "POST", ...