BVB Source Codes

parse-server Show AuthenticationAdapters.spec.js Source code

Return Download parse-server: download AuthenticationAdapters.spec.js Source code - Download parse-server Source code - Type:.js
  1. var request = require('request');
  2. var Config = require("../src/Config");
  3. var defaultColumns = require('../src/Controllers/SchemaController').defaultColumns;
  4. var authenticationLoader = require('../src/Adapters/Auth');
  5. var path = require('path');
  6.  
  7. describe('AuthenticationProviers', function() {
  8.   ["facebook", "github", "instagram", "google", "linkedin", "meetup", "twitter", "janrainengage", "janraincapture", "vkontakte"].map(function(providerName){
  9.     it("Should validate structure of " + providerName, (done) => {
  10.       var provider = require("../src/Adapters/Auth/" + providerName);
  11.       jequal(typeof provider.validateAuthData, "function");
  12.       jequal(typeof provider.validateAppId, "function");
  13.       const authDataPromise = provider.validateAuthData({}, {});
  14.       const validateAppIdPromise = provider.validateAppId("app", "key", {});
  15.       jequal(authDataPromise.constructor, Promise.prototype.constructor);
  16.       jequal(validateAppIdPromise.constructor, Promise.prototype.constructor);
  17.       authDataPromise.then(()=>{}, ()=>{});
  18.       validateAppIdPromise.then(()=>{}, ()=>{});
  19.       done();
  20.     });
  21.   });
  22.  
  23.   var getMockMyOauthProvider = function() {
  24.     return {
  25.       authData: {
  26.         id: "12345",
  27.         access_token: "12345",
  28.         expiration_date: new Date().toJSON(),
  29.       },
  30.       shouldError: false,
  31.       loggedOut: false,
  32.       synchronizedUserId: null,
  33.       synchronizedAuthToken: null,
  34.       synchronizedExpiration: null,
  35.  
  36.       authenticate: function(options) {
  37.         if (this.shouldError) {
  38.           options.error(this, "An error occurred");
  39.         } else if (this.shouldCancel) {
  40.           options.error(this, null);
  41.         } else {
  42.           options.success(this, this.authData);
  43.         }
  44.       },
  45.       restoreAuthentication: function(authData) {
  46.         if (!authData) {
  47.           this.synchronizedUserId = null;
  48.           this.synchronizedAuthToken = null;
  49.           this.synchronizedExpiration = null;
  50.           return true;
  51.         }
  52.         this.synchronizedUserId = authData.id;
  53.         this.synchronizedAuthToken = authData.access_token;
  54.         this.synchronizedExpiration = authData.expiration_date;
  55.         return true;
  56.       },
  57.       getAuthType: function() {
  58.         return "myoauth";
  59.       },
  60.       deauthenticate: function() {
  61.         this.loggedOut = true;
  62.         this.restoreAuthentication(null);
  63.       }
  64.     };
  65.   };
  66.  
  67.   Parse.User.extend({
  68.     extended: function() {
  69.       return true;
  70.     }
  71.   });
  72.  
  73.   var createOAuthUser = function(callback) {
  74.     var jsonBody = {
  75.       authData: {
  76.         myoauth: getMockMyOauthProvider().authData
  77.       }
  78.     };
  79.  
  80.     var options = {
  81.       headers: {'X-Parse-Application-Id': 'test',
  82.         'X-Parse-REST-API-Key': 'rest',
  83.         'X-Parse-Installation-Id': 'yolo',
  84.         'Content-Type': 'application/json' },
  85.       url: 'http://localhost:8378/1/users',
  86.       body: JSON.stringify(jsonBody)
  87.     };
  88.  
  89.     return request.post(options, callback);
  90.   }
  91.  
  92.   it("should create user with REST API", done => {
  93.     createOAuthUser((error, response, body) => {
  94.       expect(error).toBe(null);
  95.       var b = JSON.parse(body);
  96.       ok(b.sessionToken);
  97.       expect(b.objectId).not.toBeNull();
  98.       expect(b.objectId).not.toBeUndefined();
  99.       var sessionToken = b.sessionToken;
  100.       var q = new Parse.Query("_Session");
  101.       q.equalTo('sessionToken', sessionToken);
  102.       q.first({useMasterKey: true}).then((res) => {
  103.         if (!res) {
  104.           fail('should not fail fetching the session');
  105.           done();
  106.           return;
  107.         }
  108.         expect(res.get("installationId")).toEqual('yolo');
  109.         done();
  110.       }).fail(() => {
  111.         fail('should not fail fetching the session');
  112.         done();
  113.       })
  114.     });
  115.   });
  116.  
  117.   it("should only create a single user with REST API", (done) => {
  118.     var objectId;
  119.     createOAuthUser((error, response, body) => {
  120.       expect(error).toBe(null);
  121.       var b = JSON.parse(body);
  122.       expect(b.objectId).not.toBeNull();
  123.       expect(b.objectId).not.toBeUndefined();
  124.       objectId = b.objectId;
  125.  
  126.       createOAuthUser((error, response, body) => {
  127.         expect(error).toBe(null);
  128.         var b = JSON.parse(body);
  129.         expect(b.objectId).not.toBeNull();
  130.         expect(b.objectId).not.toBeUndefined();
  131.         expect(b.objectId).toBe(objectId);
  132.         done();
  133.       });
  134.     });
  135.   });
  136.  
  137.   it("unlink and link with custom provider", (done) => {
  138.     var provider = getMockMyOauthProvider();
  139.     Parse.User._registerAuthenticationProvider(provider);
  140.     Parse.User._logInWith("myoauth", {
  141.       success: function(model) {
  142.         ok(model instanceof Parse.User, "Model should be a Parse.User");
  143.         strictEqual(Parse.User.current(), model);
  144.         ok(model.extended(), "Should have used the subclass.");
  145.         strictEqual(provider.authData.id, provider.synchronizedUserId);
  146.         strictEqual(provider.authData.access_token, provider.synchronizedAuthToken);
  147.         strictEqual(provider.authData.expiration_date, provider.synchronizedExpiration);
  148.         ok(model._isLinked("myoauth"), "User should be linked to myoauth");
  149.  
  150.         model._unlinkFrom("myoauth", {
  151.           success: function(model) {
  152.  
  153.             ok(!model._isLinked("myoauth"),
  154.                "User should not be linked to myoauth");
  155.             ok(!provider.synchronizedUserId, "User id should be cleared");
  156.             ok(!provider.synchronizedAuthToken, "Auth token should be cleared");
  157.             ok(!provider.synchronizedExpiration,
  158.                "Expiration should be cleared");
  159.             // make sure the auth data is properly deleted
  160.             var config = new Config(Parse.applicationId);
  161.             config.database.adapter.find('_User', {
  162.               fields: Object.assign({}, defaultColumns._Default, defaultColumns._Installation),
  163.             }, { objectId: model.id }, {})
  164.             .then(res => {
  165.               expect(res.length).toBe(1);
  166.               expect(res[0]._auth_data_myoauth).toBeUndefined();
  167.               expect(res[0]._auth_data_myoauth).not.toBeNull();
  168.  
  169.               model._linkWith("myoauth", {
  170.                 success: function(model) {
  171.                   ok(provider.synchronizedUserId, "User id should have a value");
  172.                   ok(provider.synchronizedAuthToken,
  173.                      "Auth token should have a value");
  174.                   ok(provider.synchronizedExpiration,
  175.                      "Expiration should have a value");
  176.                   ok(model._isLinked("myoauth"),
  177.                      "User should be linked to myoauth");
  178.                   done();
  179.                 },
  180.                 error: function() {
  181.                   ok(false, "linking again should succeed");
  182.                   done();
  183.                 }
  184.               });
  185.             });
  186.           },
  187.           error: function() {
  188.             ok(false, "unlinking should succeed");
  189.             done();
  190.           }
  191.         });
  192.       },
  193.       error: function() {
  194.         ok(false, "linking should have worked");
  195.         done();
  196.       }
  197.     });
  198.   });
  199.  
  200.   function validateValidator(validator) {
  201.     expect(typeof validator).toBe('function');
  202.   }
  203.  
  204.   function validateAuthenticationHandler(authenticatonHandler) {
  205.     expect(authenticatonHandler).not.toBeUndefined();
  206.     expect(typeof authenticatonHandler.getValidatorForProvider).toBe('function');
  207.     expect(typeof authenticatonHandler.getValidatorForProvider).toBe('function');
  208.   }
  209.  
  210.   function validateAuthenticationAdapter(authAdapter) {
  211.     expect(authAdapter).not.toBeUndefined();
  212.     if (!authAdapter) { return; }
  213.     expect(typeof authAdapter.validateAuthData).toBe('function');
  214.     expect(typeof authAdapter.validateAppId).toBe('function');
  215.   }
  216.  
  217.   it('properly loads custom adapter', (done) => {
  218.     var validAuthData = {
  219.       id: 'hello',
  220.       token: 'world'
  221.     }
  222.     const adapter = {
  223.       validateAppId: function() {
  224.         return Promise.resolve();
  225.       },
  226.       validateAuthData: function(authData) {
  227.         if (authData.id == validAuthData.id && authData.token == validAuthData.token) {
  228.           return Promise.resolve();
  229.         }
  230.         return Promise.reject();
  231.       }
  232.     };
  233.  
  234.     const authDataSpy = spyOn(adapter, 'validateAuthData').and.callThrough();
  235.     const appIdSpy = spyOn(adapter, 'validateAppId').and.callThrough();
  236.  
  237.     const authenticationHandler = authenticationLoader({
  238.       customAuthentication: adapter
  239.     });
  240.  
  241.     validateAuthenticationHandler(authenticationHandler);
  242.     const validator = authenticationHandler.getValidatorForProvider('customAuthentication');
  243.     validateValidator(validator);
  244.  
  245.     validator(validAuthData).then(() => {
  246.       expect(authDataSpy).toHaveBeenCalled();
  247.       // AppIds are not provided in the adapter, should not be called
  248.       expect(appIdSpy).not.toHaveBeenCalled();
  249.       done();
  250.     }, (err) => {
  251.       jfail(err);
  252.       done();
  253.     })
  254.   });
  255.  
  256.   it('properly loads custom adapter module object', (done) => {
  257.     const authenticationHandler = authenticationLoader({
  258.       customAuthentication: path.resolve('./spec/support/CustomAuth.js')
  259.     });
  260.  
  261.     validateAuthenticationHandler(authenticationHandler);
  262.     const validator = authenticationHandler.getValidatorForProvider('customAuthentication');
  263.     validateValidator(validator);
  264.  
  265.     validator({
  266.       token: 'my-token'
  267.     }).then(() => {
  268.       done();
  269.     }, (err) => {
  270.       jfail(err);
  271.       done();
  272.     })
  273.   });
  274.  
  275.   it('properly loads custom adapter module object', (done) => {
  276.     const authenticationHandler = authenticationLoader({
  277.       customAuthentication: { module: path.resolve('./spec/support/CustomAuthFunction.js'), options: { token: 'valid-token' }}
  278.     });
  279.  
  280.     validateAuthenticationHandler(authenticationHandler);
  281.     const validator = authenticationHandler.getValidatorForProvider('customAuthentication');
  282.     validateValidator(validator);
  283.  
  284.     validator({
  285.       token: 'valid-token'
  286.     }).then(() => {
  287.       done();
  288.     }, (err) => {
  289.       jfail(err);
  290.       done();
  291.     })
  292.   });
  293.  
  294.   it('properly loads a default adapter with options', () => {
  295.     const options = {
  296.       facebook: {
  297.         appIds: ['a', 'b']
  298.       }
  299.     };
  300.     const { adapter, appIds, providerOptions } = authenticationLoader.loadAuthAdapter('facebook', options);
  301.     validateAuthenticationAdapter(adapter);
  302.     expect(appIds).toEqual(['a', 'b']);
  303.     expect(providerOptions).toEqual(options.facebook);
  304.   });
  305.  
  306.   it('properly loads a custom adapter with options', () => {
  307.     const options = {
  308.       custom: {
  309.         validateAppId: () => {},
  310.         validateAuthData: () => {},
  311.         appIds: ['a', 'b']
  312.       }
  313.     };
  314.     const { adapter, appIds, providerOptions } = authenticationLoader.loadAuthAdapter('custom', options);
  315.     validateAuthenticationAdapter(adapter);
  316.     expect(appIds).toEqual(['a', 'b']);
  317.     expect(providerOptions).toEqual(options.custom);
  318.   });
  319. });
  320.  
downloadAuthenticationAdapters.spec.js Source code - Download parse-server Source code
Related Source Codes/Software:
react-boilerplate - 2017-06-07
webtorrent - Streaming torrent client for the web ... 2017-06-06
machine-learning-for-software-engineers - A complete daily plan for studying to become a mac... 2017-06-06
upterm - A terminal emulator for the 21st century. 2017-06-06
lottie-android - Render After Effects animations natively on Androi... 2017-06-07
AsyncDisplayKit - Smooth asynchronous user interfaces for iOS apps. ... 2017-06-07
ionicons - The premium icon font for Ionic ... 2017-06-07
storybook - 2017-06-07
prettier - Prettier is an opinionated JavaScript formatter. ... 2017-06-08
CRYENGINE - CRYENGINE is a powerful real-time game development... 2017-06-11
postal - 2017-06-11
reactide - Reactide is the first dedicated IDE for React web ... 2017-06-11
rkt - rkt is a pod-native container engine for Linux. It... 2017-06-11
uWebSockets - Tiny WebSockets https://for... 2017-06-11
realworld - TodoMVC for the RealWorld - Exemplary fullstack Me... 2017-06-11
goreplay - GoReplay is an open-source tool for capturing and ... 2017-06-10
pyenv - Simple Python version management 2017-06-10
redux-saga - An alternative side effect model for Redux apps ... 2017-06-10
angular-starter - 2017-06-10

 Back to top