/selfbits-angular-sdk

SDK for Selfbits Backend-as-a-Service

Primary LanguageJavaScriptMIT LicenseMIT

selfbits-angular-sdk

This package allows you to easily integrate the Selfbits Backend-as-Service into your Angular based project. Please note that you MUST have a Selfbits BaaS Account and an active Project to use the service. Check out http://baas.selfbits.org for more info.

Selfbits Backend-as-Service allows you to skip backend development and focus on what's most important for you: your user-experience.

Features

  • $sbAuth - Handles Social & Basic Auth for you
  • $sbDatabase - Puts a ready-to use database integration at your fingertips
  • $sbPush - Allows to easily use Push Notifications in your App
  • $sbFile - Allows to easily use file storage in your App

Installation

# Bower
bower install selfbits-angular-sdk

Include the script:

<script src="bower_components/dist/selfbits-angular.min.js"></script>

Usage

Step 1: App Module

angular.module('MyApp', ['selfbitsAngular'])
    .config(function($sbApiProvider) {
        /* Your App Domain */
        $sbApiProvider.domain = 'YourSbAppDomain';
        /* Your Selfbits App ID */
        $sbApiProvider.appId = 'yourSbAppId';
        /* OPTIONAL: your Selfbits App Secret
           NOTE: on public clients we highly recommend to set Allowed Origins in your Selfbits BaaS Project Dashboard instead of using the Secret
        */
        $sbApiProvider.appSecret = 'yourSbAppSecret';
    })

Step 2: Controller

Note: this example uses vm syntax. Using $scope is just fine.

angular.module('MyApp')
    .controller(function($sbApi, $sbDatabase) {
        var vm = this;
        vm.login = function (user) {
            $sbApi.login(user).then(function() {
                 // DO SOMETHING AFTER LOGIN
                });
        }
        vm.signup = function (user) {
            $sbApi.signup(user).then(function() {
                 // DO SOMETHING AFTER SIGNUP
                });
        }
    })

API Reference

$sbAuth

$sbAuth.login(user)

Sign in using email and password:

Parameters

Param Type Details
user Object JavaScript object containing user information

Returns

  • response the HTTP response object from the server

Usage

var user = {
    email: 'abc@def.de',
    password: 'mypassword'
}

$sbAuth.login(user)
  .then(function(response) {
    // Redirect user here after a successful log in.
  })
  .catch(function(response) {
    // Handle errors here, such as displaying a notification
    // for invalid email and/or password.
  });

$sbAuth.signup(user)

Sign up using email and password. You have to make sure to make neccessary sanity checks (e.g. password repeat, password strength).

Parameters

Param Type Details
user Object JavaScript object containing user information

Returns

  • response the HTTP response object from the server

Usage

var user = {
    email: 'abc@def.de',
    password: 'mypassword'
}

$sbAuth.signup(user)
  .then(function(response) {
    // Redirect user here after a successful log in.
  })
  .catch(function(response) {
    // Handle errors here, such as displaying a notification
    // for invalid email and/or password.
  });

$sbAuth.social(provider)

Sign in OR up using social providers. Opens a popup window, that leads the user through the social auth flow.

Parameters

Param Type Details
provider String String with the Providername, e.g. 'facebook'

Returns

  • response the HTTP response object from the server

Usage

$sbAuth.social('facebook')
  .then(function(response) {
    // Redirect user here after a successful log in.
  })
  .catch(function(response) {
    // Handle errors here, such as displaying a notification
    // for invalid email and/or password.
  });

$sbAuth.unlink(provider)

Unlink social providers from a user profile.

Parameters

Param Type Details
provider String String with the Providername, e.g. 'facebook'

Returns

  • response the HTTP response object from the server

Usage

$sbAuth.unlink('facebook')
  .then(function(response) {
    // Do something
  })
  .catch(function(response) {
    // Handle errors here, such as displaying a notification
  });

$sbAuth.password(newPassword,[oldPassword])

Allows to update a users password or create one, if the user used social auth. You have to make sure to make necessary sanity checks for the new password (e.g. password repeat, password strength).

Parameters

Param Type Details
newPassword String The new password
oldPassword (optional) String The existing password (only required if a password already exists)

Returns

  • response the HTTP response object from the server

Usage

$sbAuth.password('oldPassword', 'newPassword')
  .then(function(response) {
    // Do something
  })
  .catch(function(response) {
    // Handle errors here, such as displaying a notification
  });

$sbAuth.logout()

Logs out the current user, removing the Token and the UserId from localStorage.

Usage

$sbAuth.logout();

$sbAuth.getUserId()

Returns the ID of the logged-in user for use e.g. in database querys.

Usage

$sbAuth.getUserId();

$sbDatabase

$sbDatabase.table(tableName)

Select a table/collection you previously defined in the Admin Dashboard to run operations on it.

Parameters

Param Type Details
tableName String Name of the table/collection you want to query

Returns

  • $resource an Angular HTTP $resource object

Usage

Angulars $resource is a powerful to manipulate data in the database in a REST-Style manner. Our API offers the get save update and delete methods to retrieve and edit data in a specific table. In addition you can use sophisticated Mogoose Querys to retrieve exactly the data you need. Please read the linked docs to get a deeper understanding, as covering all the mechanics here is not possible. Despite, we provide a few examples to demonstrate what's possible.

// Select the active database and bind the resource object to a variable
var todo = $sbDatabase.table('todo');

// retrieve all todos and bind them to the $scope
$scope.myTodos = todo.get();

// retrieve single todo by id and bind it to $scope
$scope.singleTodo = todo.get({_id:"57879806aeb310dc651899ef"});

// retrieve all todos and bind them to the $scope
// but this time also request meta data and deep-linked objects
$scope.myTodos = todo.get({ meta: true, deep: true});

// retrieve all todos and bind them to the $scope
// but this time apply a mongoose filter and
// sort descending (-) by occupation and ascending (+) by _id
$scope.myTodos = todo.get({
  filter: {
      occupation: 'host',
      age: {
          $gt: 17,
          $lt: 66
      },
      likes: {
          $in: ['vaporizing', 'talking']
      }
    },
  sort: '-occupation +_id'  
});

// save a todo object to the database
var newTodo = {
    title: 'Buy Milk',
    description: 'Please get fresh milk from Wholefoods'
}
todo.save(newTodo);

// use custom error and result handling
var newTodo = {
    title: 'Buy Milk',
    description: 'Please get fresh milk from Wholefoods'
}
todo.save(newTodo, function(res){
  //do something with the response
}, function(err) {
  //handle an error
});

$sbFile

$sbFile.get(params)

Get metadata of an uploaded file that contains a temporary download link.

Parameters

Param Type required default Details
params Object true JavaScript object
params.fileId String true The ID of the file you want to get
params.expiresInSeconds Number false 900 The time to live of the shareable temporary download url

Returns

  • response the file metadata object containing url and expiresAt from the server

Usage

var params = {
  fileId: 'YOUR-FILE-ID',
  expiresInSeconds: 60
}

$sbFile.get(params)
  .then(function(response) {
      // do something with file metadata response
      var downloadLink = response.url;
      // use download link as long as it is valid
  })
  .catch(function(err) {
      // Handle errors here, such as displaying a notification
  })
 };

$sbFile.upload(params)

Upload a file to the authenticated user's file store. Unified function that initiates, executes and verifies the upload.

Parameters

Param Type required default Details
params Object true JavaScript object containing upload information
params.file File true The file you want to upload
params.filePath String false params.file.name The destination path where you want to put the file. This path is prefixed by <PROJECT-ID>/<USER-ID>/
params.permissionScope String false user The permission scope: 'user' = only the uploading user can access the file. '*': Every authenticated user can access the file with its fileId.

Returns

  • response the file metadata object from the server

Usage

var f = new File(["plain text file content"], "filename.txt", {
  type: "text/plain",
  lastModified: new Date()
})
var params = {
  file: f,
  filePath: 'myFile.txt'
}
$sbFile.upload(params)
  .then(function(response) {
      // do something with file metadata response
  })
  .catch(function(err) {
      // Handle errors here, such as displaying a notification
  })
 };

License

Copyright (c) 2016 Selfbits GmbH

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.