Compare commits

...
15 Commits
Author SHA1 Message Date
Fosco Marotto ee8f85baef Merge pull request #1169 from ParsePlatform/fosco.222
Changelog and update to 2.2.2
2016-03-23 16:57:53 -08:00
Fosco Marotto 7a73d74869 Changelog and update to 2.2.2 2016-03-23 17:57:12 -07:00
Mengyan Wang 047c8e71ff Merge pull request #1168 from ParsePlatform/wangmengyan.fix_gcm_payload
Add pushId back to GCM payload
2016-03-23 17:47:07 -07:00
wangmengyan95 cbd1b878b9 Add pushId back to GCM payload 2016-03-23 17:39:27 -07:00
Drew 24146753b9 Merge pull request #1166 from ParsePlatform/flovilmart.MoveParseServer
moves ParseServer to it's own file
2016-03-23 16:45:31 -07:00
Florent Vilmart ea211e658f moves ParseServer to it's own file 2016-03-23 19:05:56 -04:00
Florent Vilmart 16b6ec4879 Merge pull request #1153 from ParsePlatform/flovilmart.fixBrokenParseServerClass
Mounts createLiveQueryServer, fix babel induced problem
2016-03-23 12:49:41 -04:00
Florent Vilmart ddb76a8650 Mounts createLiveQueryServer, fix babel induced problem 2016-03-23 09:19:09 -04:00
Florent Vilmart f5fdedfbc7 Merge pull request #1138 from ParsePlatform/flovilmart.bootstrap
Adds bootstrap.sh
2016-03-23 07:52:17 -04:00
Florent Vilmart 3ce634bd82 Merge pull request #1142 from ParsePlatform/flovilmart.fixes1136
do not override username
2016-03-23 07:52:04 -04:00
Florent Vilmart b30805b47b do not override username 2016-03-22 21:17:53 -04:00
Fosco Marotto 0e662190b3 Merge pull request #1139 from ParsePlatform/drew-gross-patch-2
Update README.md - remove deploy buttons - replace with community links
2016-03-22 16:55:30 -08:00
Drew 7d6f359434 Update README.md 2016-03-22 17:17:37 -07:00
Florent Vilmart 0a4cc606c6 Adds curl test command 2016-03-22 20:10:13 -04:00
Florent Vilmart b7a723fa7e Adds bootstrap.sh 2016-03-22 18:59:41 -04:00
11 changed files with 562 additions and 320 deletions
+9
View File
@@ -1,5 +1,14 @@
## Parse Server Changelog
### 2.2.2 (3/23/2016)
* Important Fix: Mounts createLiveQueryServer, fix babel induced problem [\#1153](https://github.com/ParsePlatform/parse-server/pull/1153) (flovilmart)
* Move ParseServer to it's own file [\#1166](https://github.com/ParsePlatform/parse-server/pull/1166) (flovilmart)
* Update README.md - remove deploy buttons - replace with community links [\#1139](https://github.com/ParsePlatform/parse-server/pull/1139) (drew-gross)
* Adds bootstrap.sh [\#1138](https://github.com/ParsePlatform/parse-server/pull/1138) (flovilmart)
* Fix: Do not override username [\#1142](https://github.com/ParsePlatform/parse-server/pull/1142) (flovilmart)
* Fix: Add pushId back to GCM payload [\#1168](https://github.com/ParsePlatform/parse-server/pull/1168) (wangmengyan95)
### 2.2.1 (3/22/2016)
* New: Add FileSystemAdapter file adapter [\#1098](https://github.com/ParsePlatform/parse-server/pull/1098) (dtsolis)
+9 -2
View File
@@ -102,9 +102,16 @@ Once you have a better understanding of how the project works, please refer to t
### Parse Server Sample Application
We have provided a basic [Node.js application](https://github.com/ParsePlatform/parse-server-example) that uses the Parse Server module on Express and can be easily deployed using any of the following buttons:
We have provided a basic [Node.js application](https://github.com/ParsePlatform/parse-server-example) that uses the Parse Server module on Express and can be easily deployed to various infrastructure providers:
<a title="Deploy to AWS" href="https://console.aws.amazon.com/elasticbeanstalk/home?region=us-west-2#/newApplication?applicationName=ParseServer&solutionStackName=Node.js&tierName=WebServer&sourceBundleUrl=https://s3.amazonaws.com/elasticbeanstalk-samples-us-east-1/eb-parse-server-sample/parse-server-example.zip" target="_blank"><img src="http://d0.awsstatic.com/product-marketing/Elastic%20Beanstalk/deploy-to-aws.png" height="32"></a> <a title="Deploy to Heroku" href="https://heroku.com/deploy?template=https://github.com/parseplatform/parse-server-example" target="_blank"><img src="https://www.herokucdn.com/deploy/button.png"></a> <a title="Deploy to Azure" href="https://azuredeploy.net/?repository=https://github.com/parseplatform/parse-server-example" target="_blank"><img src="http://azuredeploy.net/deploybutton.png"></a>
* [Heroku and mLab](https://github.com/ParsePlatform/parse-server/wiki/Deploying-Parse-Server#deploying-to-heroku-and-mLab)
* [AWS and Elastic Beanstalk](http://mobile.awsblog.com/post/TxCD57GZLM2JR/How-to-set-up-Parse-Server-on-AWS-using-AWS-Elastic-Beanstalk)
* [Digital Ocean](https://www.digitalocean.com/community/tutorials/how-to-run-parse-server-on-ubuntu-14-04)
* [NodeChef](https://nodechef.com/blog/post/6/migrate-from-parse-to-nodechef%E2%80%99s-managed-parse-server)
* [Google App Engine](https://medium.com/@justinbeckwith/deploying-parse-server-to-google-app-engine-6bc0b7451d50)
* [Microsoft Azure](https://azure.microsoft.com/en-us/blog/azure-welcomes-parse-developers/)
* [Pivotal Web Services](https://github.com/cf-platform-eng/pws-parse-server)
* [Back4app](http://blog.back4app.com/2016/03/01/quick-wizard-migration/)
### Parse Server + Express
Executable
+163
View File
@@ -0,0 +1,163 @@
#!/bin/sh
RED='\033[0;31m'
GREEN='\033[0;32m'
NC='\033[0m'
BOLD='\033[1m'
CHECK="${GREEN}\xE2\x9C\x93${NC}"
DEFAULT_MONGODB_URI='mongodb://localhost:127.0.0.1:27017/parse'
confirm() {
DEFAULT=$1;
shift
printf "$@"
read -r YN
if [ "$YN" = "" ] && [ "$DEFAULT" = 'N' ]; then
exit 1
elif [ "$YN" != "" ] && [ "$YN" != "y" ] && [ "$YN" != "Y" ]; then
echo 'Bye Bye!'
exit 1
fi
}
genstring() {
local l=$1
[ "$l" == "" ] && l=40
LC_ALL=C tr -dc A-Za-z0-9 < /dev/urandom | head -c ${l}
}
check_node() {
node=`which node 2>&1`
ret=$?
if [ $ret -eq 0 ] && [ -x "$node" ]; then
echo "${CHECK} node:" $(node -v)
(exit 0)
else
echo "parse-server cannot be installed without Node.js." >&2
exit 1
fi
}
check_npm() {
npm=`which npm 2>&1`
ret=$?
if [ $ret -eq 0 ] && [ -x "$npm" ]; then
echo "${CHECK} npm:" $(npm -v)
(exit 0)
else
echo "parse-server cannot be installed without npm." >&2
exit 1
fi
}
echo ''
echo 'This will setup parse-server in the current directory'
confirm 'Y' 'Do you want to continue? (Y/n): '
check_node
check_npm
echo "Setting up parse-server in $PWD"
if [ -f './package.json' ]; then
echo "\n${RED}package.json exists${NC}"
confirm 'N' "Do you want to continue? \n${RED}this will erase your configuration${NC} (y/N): "
fi
if [ -f 'config.json' ]; then
echo "\n${RED}config.json exists${NC}"
confirm 'N' "Do you want to continue? \n${RED}this will erase your configuration${NC} (y/N): "
fi
APP_NAME=''
i=0
while [ "$APP_NAME" = "" ]
do
[[ $i != 0 ]] && printf "${RED}An application name is required!${NC}\n"
printf 'Enter your Application Name: '
read -r APP_NAME
i=$(($i+1))
done
printf 'Enter your appId (leave empty to generate): '
read -r APP_ID
[[ $APP_ID = '' ]] && APP_ID=$(genstring) && printf "\n$APP_ID\n\n"
printf 'Enter your masterKey (leave empty to generate): '
read -r MASTER_KEY
[[ $MASTER_KEY = '' ]] && MASTER_KEY=$(genstring) && printf "\n$MASTER_KEY\n\n"
printf "Enter your mongodbURI (%s): " $DEFAULT_MONGODB_URI
read -r MONGODB_URI
[[ $MONGODB_URI = '' ]] && MONGODB_URI="$DEFAULT_MONGODB_URI"
cat > ./config.json << EOF
{
"appId": "$APP_ID",
"masterKey": "$MASTER_KEY",
"appName": "$APP_NAME",
"cloud": "./cloud/main",
"mongodbURI": "$MONGODB_URI"
}
EOF
echo "${CHECK} Created config.json"
# Make a proper npm app name
NPM_APP_NAME=$(echo "$APP_NAME" | tr '[:upper:]' '[:lower:]' | tr ' ' '-')
cat > ./package.json << EOF
{
"name": "$NPM_APP_NAME",
"scripts": {
"start": "parse-server ./config.json"
},
"dependencies": {
"parse-server": "^2.0.0"
}
}
EOF
echo "${CHECK} Created package.json"
if [ -d "./cloud/" ]; then
echo "${CHECK} cloud/ exists"
else
mkdir -p ./cloud
echo "${CHECK} Created cloud/"
fi
if [ -e "./cloud/main.js" ]; then
echo "${CHECK} cloud/main.js exists"
else
echo "${CHECK} Created cloud/main.js"
cat > ./cloud/main.js << EOF
// Cloud Code entry point
EOF
fi
if [ -d "./public/" ]; then
echo "${CHECK} public/ exists"
else
mkdir -p ./public
echo "${CHECK} Created public/"
fi
echo "\n${CHECK} running npm install\n"
npm install
CURL_CMD=$(cat << EOF
curl -X POST -H 'X-Parse-Application-Id: ${APP_ID}' \\
-H 'Content-Type: application/json' \\
-d '{"foo":"bar"}' http://localhost:1337/parse/classes/TestObject
EOF)
echo "\n${CHECK} Happy Parsing!\n\n"
echo "${CHECK} Make sure you have ${BOLD}mongo${NC} listening on ${BOLD}${MONGODB_URI}${NC}"
echo "${CHECK} start parse-server by running ${BOLD}npm start${NC}"
echo "${CHECK} Test your setup with:\n\n${CURL_CMD}\n"
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "parse-server",
"version": "2.2.1",
"version": "2.2.2",
"description": "An express module providing a Parse-compatible API server",
"main": "lib/index.js",
"repository": {
+12 -4
View File
@@ -23,15 +23,17 @@ describe('GCM', () => {
var data = {
'alert': 'alert'
};
var pushId = 'pushId';
var timeStamp = 1454538822113;
var timeStampISOStr = new Date(timeStamp).toISOString();
var payload = GCM.generateGCMPayload(data, timeStamp);
var payload = GCM.generateGCMPayload(data, pushId, timeStamp);
expect(payload.priority).toEqual('normal');
expect(payload.timeToLive).toEqual(undefined);
var dataFromPayload = payload.data;
expect(dataFromPayload.time).toEqual(timeStampISOStr);
expect(dataFromPayload['push_id']).toEqual(pushId);
var dataFromUser = JSON.parse(dataFromPayload.data);
expect(dataFromUser).toEqual(data);
done();
@@ -42,16 +44,18 @@ describe('GCM', () => {
var data = {
'alert': 'alert'
};
var pushId = 'pushId';
var timeStamp = 1454538822113;
var timeStampISOStr = new Date(timeStamp).toISOString();
var expirationTime = 1454538922113
var payload = GCM.generateGCMPayload(data, timeStamp, expirationTime);
var payload = GCM.generateGCMPayload(data, pushId, timeStamp, expirationTime);
expect(payload.priority).toEqual('normal');
expect(payload.timeToLive).toEqual(Math.floor((expirationTime - timeStamp) / 1000));
var dataFromPayload = payload.data;
expect(dataFromPayload.time).toEqual(timeStampISOStr);
expect(dataFromPayload['push_id']).toEqual(pushId);
var dataFromUser = JSON.parse(dataFromPayload.data);
expect(dataFromUser).toEqual(data);
done();
@@ -62,16 +66,18 @@ describe('GCM', () => {
var data = {
'alert': 'alert'
};
var pushId = 'pushId';
var timeStamp = 1454538822113;
var timeStampISOStr = new Date(timeStamp).toISOString();
var expirationTime = 1454538822112;
var payload = GCM.generateGCMPayload(data, timeStamp, expirationTime);
var payload = GCM.generateGCMPayload(data, pushId, timeStamp, expirationTime);
expect(payload.priority).toEqual('normal');
expect(payload.timeToLive).toEqual(0);
var dataFromPayload = payload.data;
expect(dataFromPayload.time).toEqual(timeStampISOStr);
expect(dataFromPayload['push_id']).toEqual(pushId);
var dataFromUser = JSON.parse(dataFromPayload.data);
expect(dataFromUser).toEqual(data);
done();
@@ -82,17 +88,19 @@ describe('GCM', () => {
var data = {
'alert': 'alert'
};
var pushId = 'pushId';
var timeStamp = 1454538822113;
var timeStampISOStr = new Date(timeStamp).toISOString();
var expirationTime = 2454538822113;
var payload = GCM.generateGCMPayload(data, timeStamp, expirationTime);
var payload = GCM.generateGCMPayload(data, pushId, timeStamp, expirationTime);
expect(payload.priority).toEqual('normal');
// Four week in second
expect(payload.timeToLive).toEqual(4 * 7 * 24 * 60 * 60);
var dataFromPayload = payload.data;
expect(dataFromPayload.time).toEqual(timeStampISOStr);
expect(dataFromPayload['push_id']).toEqual(pushId);
var dataFromUser = JSON.parse(dataFromPayload.data);
expect(dataFromUser).toEqual(data);
done();
+40 -1
View File
@@ -146,7 +146,46 @@ describe('rest create', () => {
done();
});
});
it('handles anonymous user signup and upgrade to new user', (done) => {
var data1 = {
authData: {
anonymous: {
id: '00000000-0000-0000-0000-000000000001'
}
}
};
var updatedData = {
authData: { anonymous: null },
username: 'hello',
password: 'world'
}
var username1;
var objectId;
rest.create(config, auth.nobody(config), '_User', data1)
.then((r) => {
expect(typeof r.response.objectId).toEqual('string');
expect(typeof r.response.createdAt).toEqual('string');
expect(typeof r.response.sessionToken).toEqual('string');
objectId = r.response.objectId;
return auth.getAuthForSessionToken({config, sessionToken: r.response.sessionToken })
}).then((sessionAuth) => {
return rest.update(config, sessionAuth, '_User', objectId, updatedData);
}).then((r) => {
return Parse.User.logOut().then(() => {
return Parse.User.logIn('hello', 'world');
})
}).then((r) => {
expect(r.id).toEqual(objectId);
expect(r.get('username')).toEqual('hello');
done();
}).catch((err) => {
fail('should not fail')
done();
})
});
it('handles no anonymous users config', (done) => {
var NoAnnonConfig = Object.assign({}, config);
NoAnnonConfig.authDataManager.setEnableAnonymousUsers(false);
+8
View File
@@ -228,4 +228,12 @@ describe('server', () => {
done();
})
});
it('has createLiveQueryServer', done => {
// original implementation through the factory
expect(typeof ParseServer.ParseServer.createLiveQueryServer).toEqual('function');
// For import calls
expect(typeof ParseServer.default.createLiveQueryServer).toEqual('function');
done();
});
});
+5 -2
View File
@@ -22,6 +22,7 @@ function GCM(args) {
* @returns {Object} A promise which is resolved after we get results from gcm
*/
GCM.prototype.send = function(data, devices) {
let pushId = cryptoUtils.newObjectId();
// Make a new array
devices = new Array(...devices);
let timestamp = Date.now();
@@ -52,7 +53,8 @@ GCM.prototype.send = function(data, devices) {
expirationTime = data['expiration_time'];
}
// Generate gcm payload
let gcmPayload = generateGCMPayload(data.data, timestamp, expirationTime);
// PushId is not a formal field of GCM, but Parse Android SDK uses this field to deduplicate push notifications
let gcmPayload = generateGCMPayload(data.data, pushId, timestamp, expirationTime);
// Make and send gcm request
let message = new gcm.Message(gcmPayload);
@@ -107,9 +109,10 @@ GCM.prototype.send = function(data, devices) {
* @param {Number|undefined} expirationTime A number whose format is the Unix Epoch or undefined
* @returns {Object} A promise which is resolved after we get results from gcm
*/
function generateGCMPayload(coreData, timeStamp, expirationTime) {
function generateGCMPayload(coreData, pushId, timeStamp, expirationTime) {
let payloadData = {
'time': new Date(timeStamp).toISOString(),
'push_id': pushId,
'data': JSON.stringify(coreData)
}
let payload = {
+284
View File
@@ -0,0 +1,284 @@
// ParseServer - open-source compatible API Server for Parse apps
import 'babel-polyfill';
var batch = require('./batch'),
bodyParser = require('body-parser'),
DatabaseAdapter = require('./DatabaseAdapter'),
express = require('express'),
middlewares = require('./middlewares'),
multer = require('multer'),
Parse = require('parse/node').Parse,
authDataManager = require('./authDataManager');
//import passwordReset from './passwordReset';
import cache from './cache';
import Config from './Config';
import parseServerPackage from '../package.json';
import ParsePushAdapter from './Adapters/Push/ParsePushAdapter';
import PromiseRouter from './PromiseRouter';
import requiredParameter from './requiredParameter';
import { AnalyticsRouter } from './Routers/AnalyticsRouter';
import { ClassesRouter } from './Routers/ClassesRouter';
import { FeaturesRouter } from './Routers/FeaturesRouter';
import { FileLoggerAdapter } from './Adapters/Logger/FileLoggerAdapter';
import { FilesController } from './Controllers/FilesController';
import { FilesRouter } from './Routers/FilesRouter';
import { FunctionsRouter } from './Routers/FunctionsRouter';
import { GCSAdapter } from './Adapters/Files/GCSAdapter';
import { GlobalConfigRouter } from './Routers/GlobalConfigRouter';
import { GridStoreAdapter } from './Adapters/Files/GridStoreAdapter';
import { HooksController } from './Controllers/HooksController';
import { HooksRouter } from './Routers/HooksRouter';
import { IAPValidationRouter } from './Routers/IAPValidationRouter';
import { InstallationsRouter } from './Routers/InstallationsRouter';
import { loadAdapter } from './Adapters/AdapterLoader';
import { LiveQueryController } from './Controllers/LiveQueryController';
import { LoggerController } from './Controllers/LoggerController';
import { LogsRouter } from './Routers/LogsRouter';
import { ParseLiveQueryServer } from './LiveQuery/ParseLiveQueryServer';
import { PublicAPIRouter } from './Routers/PublicAPIRouter';
import { PushController } from './Controllers/PushController';
import { PushRouter } from './Routers/PushRouter';
import { randomString } from './cryptoUtils';
import { RolesRouter } from './Routers/RolesRouter';
import { S3Adapter } from './Adapters/Files/S3Adapter';
import { SchemasRouter } from './Routers/SchemasRouter';
import { SessionsRouter } from './Routers/SessionsRouter';
import { setFeature } from './features';
import { UserController } from './Controllers/UserController';
import { UsersRouter } from './Routers/UsersRouter';
import { FileSystemAdapter } from './Adapters/Files/FileSystemAdapter';
// Mutate the Parse object to add the Cloud Code handlers
addParseCloud();
// ParseServer works like a constructor of an express app.
// The args that we understand are:
// "databaseAdapter": a class like DatabaseController providing create, find,
// update, and delete
// "filesAdapter": a class like GridStoreAdapter providing create, get,
// and delete
// "loggerAdapter": a class like FileLoggerAdapter providing info, error,
// and query
// "databaseURI": a uri like mongodb://localhost:27017/dbname to tell us
// what database this Parse API connects to.
// "cloud": relative location to cloud code to require, or a function
// that is given an instance of Parse as a parameter. Use this instance of Parse
// to register your cloud code hooks and functions.
// "appId": the application id to host
// "masterKey": the master key for requests to this app
// "facebookAppIds": an array of valid Facebook Application IDs, required
// if using Facebook login
// "collectionPrefix": optional prefix for database collection names
// "fileKey": optional key from Parse dashboard for supporting older files
// hosted by Parse
// "clientKey": optional key from Parse dashboard
// "dotNetKey": optional key from Parse dashboard
// "restAPIKey": optional key from Parse dashboard
// "javascriptKey": optional key from Parse dashboard
// "push": optional key from configure push
class ParseServer {
constructor({
appId = requiredParameter('You must provide an appId!'),
masterKey = requiredParameter('You must provide a masterKey!'),
appName,
databaseAdapter,
filesAdapter,
push,
loggerAdapter,
databaseURI = DatabaseAdapter.defaultDatabaseURI,
databaseOptions,
cloud,
collectionPrefix = '',
clientKey,
javascriptKey,
dotNetKey,
restAPIKey,
fileKey = 'invalid-file-key',
facebookAppIds = [],
enableAnonymousUsers = true,
allowClientClassCreation = true,
oauth = {},
serverURL = requiredParameter('You must provide a serverURL!'),
maxUploadSize = '20mb',
verifyUserEmails = false,
emailAdapter,
publicServerURL,
customPages = {
invalidLink: undefined,
verifyEmailSuccess: undefined,
choosePassword: undefined,
passwordResetSuccess: undefined
},
liveQuery = {}
}) {
setFeature('serverVersion', parseServerPackage.version);
// Initialize the node client SDK automatically
Parse.initialize(appId, javascriptKey || 'unused', masterKey);
Parse.serverURL = serverURL;
if (databaseAdapter) {
DatabaseAdapter.setAdapter(databaseAdapter);
}
if (databaseOptions) {
DatabaseAdapter.setAppDatabaseOptions(appId, databaseOptions);
}
if (databaseURI) {
DatabaseAdapter.setAppDatabaseURI(appId, databaseURI);
}
if (cloud) {
addParseCloud();
if (typeof cloud === 'function') {
cloud(Parse)
} else if (typeof cloud === 'string') {
require(cloud);
} else {
throw "argument 'cloud' must either be a string or a function";
}
}
const filesControllerAdapter = loadAdapter(filesAdapter, () => {
return new GridStoreAdapter(databaseURI);
});
// Pass the push options too as it works with the default
const pushControllerAdapter = loadAdapter(push && push.adapter, ParsePushAdapter, push);
const loggerControllerAdapter = loadAdapter(loggerAdapter, FileLoggerAdapter);
const emailControllerAdapter = loadAdapter(emailAdapter);
// We pass the options and the base class for the adatper,
// Note that passing an instance would work too
const filesController = new FilesController(filesControllerAdapter, appId);
const pushController = new PushController(pushControllerAdapter, appId);
const loggerController = new LoggerController(loggerControllerAdapter, appId);
const hooksController = new HooksController(appId, collectionPrefix);
const userController = new UserController(emailControllerAdapter, appId, { verifyUserEmails });
const liveQueryController = new LiveQueryController(liveQuery);
cache.apps.set(appId, {
masterKey: masterKey,
serverURL: serverURL,
collectionPrefix: collectionPrefix,
clientKey: clientKey,
javascriptKey: javascriptKey,
dotNetKey: dotNetKey,
restAPIKey: restAPIKey,
fileKey: fileKey,
facebookAppIds: facebookAppIds,
filesController: filesController,
pushController: pushController,
loggerController: loggerController,
hooksController: hooksController,
userController: userController,
verifyUserEmails: verifyUserEmails,
allowClientClassCreation: allowClientClassCreation,
authDataManager: authDataManager(oauth, enableAnonymousUsers),
appName: appName,
publicServerURL: publicServerURL,
customPages: customPages,
maxUploadSize: maxUploadSize,
liveQueryController: liveQueryController
});
// To maintain compatibility. TODO: Remove in some version that breaks backwards compatability
if (process.env.FACEBOOK_APP_ID) {
cache.apps.get(appId)['facebookAppIds'].push(process.env.FACEBOOK_APP_ID);
}
Config.validate(cache.apps.get(appId));
this.config = cache.apps.get(appId);
hooksController.load();
}
get app() {
return ParseServer.app(this.config);
}
static app({maxUploadSize = '20mb'}) {
// This app serves the Parse API directly.
// It's the equivalent of https://api.parse.com/1 in the hosted Parse API.
var api = express();
//api.use("/apps", express.static(__dirname + "/public"));
// File handling needs to be before default middlewares are applied
api.use('/', middlewares.allowCrossDomain, new FilesRouter().getExpressRouter({
maxUploadSize: maxUploadSize
}));
api.use('/', bodyParser.urlencoded({extended: false}), new PublicAPIRouter().expressApp());
// TODO: separate this from the regular ParseServer object
if (process.env.TESTING == 1) {
api.use('/', require('./testing-routes').router);
}
api.use(bodyParser.json({ 'type': '*/*' , limit: maxUploadSize }));
api.use(middlewares.allowCrossDomain);
api.use(middlewares.allowMethodOverride);
api.use(middlewares.handleParseHeaders);
let routers = [
new ClassesRouter(),
new UsersRouter(),
new SessionsRouter(),
new RolesRouter(),
new AnalyticsRouter(),
new InstallationsRouter(),
new FunctionsRouter(),
new SchemasRouter(),
new PushRouter(),
new LogsRouter(),
new IAPValidationRouter(),
new FeaturesRouter(),
];
if (process.env.PARSE_EXPERIMENTAL_CONFIG_ENABLED || process.env.TESTING) {
routers.push(new GlobalConfigRouter());
}
if (process.env.PARSE_EXPERIMENTAL_HOOKS_ENABLED || process.env.TESTING) {
routers.push(new HooksRouter());
}
let routes = routers.reduce((memo, router) => {
return memo.concat(router.routes);
}, []);
let appRouter = new PromiseRouter(routes);
batch.mountOnto(appRouter);
api.use(appRouter.expressApp());
api.use(middlewares.handleParseErrors);
//This causes tests to spew some useless warnings, so disable in test
if (!process.env.TESTING) {
process.on('uncaughtException', (err) => {
if ( err.code === "EADDRINUSE" ) { // user-friendly message for this common error
console.log(`Unable to listen on port ${err.port}. The port is already in use.`);
process.exit(0);
} else {
throw err;
}
});
}
return api;
}
static createLiveQueryServer(httpServer, config) {
return new ParseLiveQueryServer(httpServer, config);
}
}
function addParseCloud() {
const ParseCloud = require("./cloud-code/Parse.Cloud");
Object.assign(Parse.Cloud, ParseCloud);
global.Parse = Parse;
}
export default ParseServer;
+19 -19
View File
@@ -281,26 +281,26 @@ RestWrite.prototype.handleAuthData = function(authData) {
this.storage['authProvider'] = Object.keys(authData).join(',');
if (results.length == 0) {
this.data.username = cryptoUtils.newToken();
} else if (!this.query) {
// Login with auth data
// Short circuit
delete results[0].password;
// need to set the objectId first otherwise location has trailing undefined
this.data.objectId = results[0].objectId;
this.response = {
response: results[0],
location: this.location()
};
} else if (this.query && this.query.objectId) {
// Trying to update auth data but users
// are different
if (results[0].objectId !== this.query.objectId) {
throw new Parse.Error(Parse.Error.ACCOUNT_ALREADY_LINKED,
'this auth is already used');
if (results.length > 0) {
if (!this.query) {
// Login with auth data
// Short circuit
delete results[0].password;
// need to set the objectId first otherwise location has trailing undefined
this.data.objectId = results[0].objectId;
this.response = {
response: results[0],
location: this.location()
};
} else if (this.query && this.query.objectId) {
// Trying to update auth data but users
// are different
if (results[0].objectId !== this.query.objectId) {
throw new Parse.Error(Parse.Error.ACCOUNT_ALREADY_LINKED,
'this auth is already used');
}
}
}
}
return Promise.resolve();
});
}
+12 -291
View File
@@ -1,294 +1,15 @@
// ParseServer - open-source compatible API Server for Parse apps
import ParseServer from './ParseServer'
import { GCSAdapter } from './Adapters/Files/GCSAdapter';
import { S3Adapter } from './Adapters/Files/S3Adapter';
import { FileSystemAdapter } from './Adapters/Files/FileSystemAdapter';
import 'babel-polyfill';
var batch = require('./batch'),
bodyParser = require('body-parser'),
DatabaseAdapter = require('./DatabaseAdapter'),
express = require('express'),
middlewares = require('./middlewares'),
multer = require('multer'),
Parse = require('parse/node').Parse,
authDataManager = require('./authDataManager');
//import passwordReset from './passwordReset';
import cache from './cache';
import Config from './Config';
import parseServerPackage from '../package.json';
import ParsePushAdapter from './Adapters/Push/ParsePushAdapter';
import PromiseRouter from './PromiseRouter';
import requiredParameter from './requiredParameter';
import { AnalyticsRouter } from './Routers/AnalyticsRouter';
import { ClassesRouter } from './Routers/ClassesRouter';
import { FeaturesRouter } from './Routers/FeaturesRouter';
import { FileLoggerAdapter } from './Adapters/Logger/FileLoggerAdapter';
import { FilesController } from './Controllers/FilesController';
import { FilesRouter } from './Routers/FilesRouter';
import { FunctionsRouter } from './Routers/FunctionsRouter';
import { GCSAdapter } from './Adapters/Files/GCSAdapter';
import { GlobalConfigRouter } from './Routers/GlobalConfigRouter';
import { GridStoreAdapter } from './Adapters/Files/GridStoreAdapter';
import { HooksController } from './Controllers/HooksController';
import { HooksRouter } from './Routers/HooksRouter';
import { IAPValidationRouter } from './Routers/IAPValidationRouter';
import { InstallationsRouter } from './Routers/InstallationsRouter';
import { loadAdapter } from './Adapters/AdapterLoader';
import { LiveQueryController } from './Controllers/LiveQueryController';
import { LoggerController } from './Controllers/LoggerController';
import { LogsRouter } from './Routers/LogsRouter';
import { ParseLiveQueryServer } from './LiveQuery/ParseLiveQueryServer';
import { PublicAPIRouter } from './Routers/PublicAPIRouter';
import { PushController } from './Controllers/PushController';
import { PushRouter } from './Routers/PushRouter';
import { randomString } from './cryptoUtils';
import { RolesRouter } from './Routers/RolesRouter';
import { S3Adapter } from './Adapters/Files/S3Adapter';
import { SchemasRouter } from './Routers/SchemasRouter';
import { SessionsRouter } from './Routers/SessionsRouter';
import { setFeature } from './features';
import { UserController } from './Controllers/UserController';
import { UsersRouter } from './Routers/UsersRouter';
import { FileSystemAdapter } from './Adapters/Files/FileSystemAdapter';
// Mutate the Parse object to add the Cloud Code handlers
addParseCloud();
// ParseServer works like a constructor of an express app.
// The args that we understand are:
// "databaseAdapter": a class like DatabaseController providing create, find,
// update, and delete
// "filesAdapter": a class like GridStoreAdapter providing create, get,
// and delete
// "loggerAdapter": a class like FileLoggerAdapter providing info, error,
// and query
// "databaseURI": a uri like mongodb://localhost:27017/dbname to tell us
// what database this Parse API connects to.
// "cloud": relative location to cloud code to require, or a function
// that is given an instance of Parse as a parameter. Use this instance of Parse
// to register your cloud code hooks and functions.
// "appId": the application id to host
// "masterKey": the master key for requests to this app
// "facebookAppIds": an array of valid Facebook Application IDs, required
// if using Facebook login
// "collectionPrefix": optional prefix for database collection names
// "fileKey": optional key from Parse dashboard for supporting older files
// hosted by Parse
// "clientKey": optional key from Parse dashboard
// "dotNetKey": optional key from Parse dashboard
// "restAPIKey": optional key from Parse dashboard
// "javascriptKey": optional key from Parse dashboard
// "push": optional key from configure push
export default class ParseServer {
constructor({
appId = requiredParameter('You must provide an appId!'),
masterKey = requiredParameter('You must provide a masterKey!'),
appName,
databaseAdapter,
filesAdapter,
push,
loggerAdapter,
databaseURI = DatabaseAdapter.defaultDatabaseURI,
databaseOptions,
cloud,
collectionPrefix = '',
clientKey,
javascriptKey,
dotNetKey,
restAPIKey,
fileKey = 'invalid-file-key',
facebookAppIds = [],
enableAnonymousUsers = true,
allowClientClassCreation = true,
oauth = {},
serverURL = requiredParameter('You must provide a serverURL!'),
maxUploadSize = '20mb',
verifyUserEmails = false,
emailAdapter,
publicServerURL,
customPages = {
invalidLink: undefined,
verifyEmailSuccess: undefined,
choosePassword: undefined,
passwordResetSuccess: undefined
},
liveQuery = {}
}) {
setFeature('serverVersion', parseServerPackage.version);
// Initialize the node client SDK automatically
Parse.initialize(appId, javascriptKey || 'unused', masterKey);
Parse.serverURL = serverURL;
if (databaseAdapter) {
DatabaseAdapter.setAdapter(databaseAdapter);
}
if (databaseOptions) {
DatabaseAdapter.setAppDatabaseOptions(appId, databaseOptions);
}
if (databaseURI) {
DatabaseAdapter.setAppDatabaseURI(appId, databaseURI);
}
if (cloud) {
addParseCloud();
if (typeof cloud === 'function') {
cloud(Parse)
} else if (typeof cloud === 'string') {
require(cloud);
} else {
throw "argument 'cloud' must either be a string or a function";
}
}
const filesControllerAdapter = loadAdapter(filesAdapter, () => {
return new GridStoreAdapter(databaseURI);
});
// Pass the push options too as it works with the default
const pushControllerAdapter = loadAdapter(push && push.adapter, ParsePushAdapter, push);
const loggerControllerAdapter = loadAdapter(loggerAdapter, FileLoggerAdapter);
const emailControllerAdapter = loadAdapter(emailAdapter);
// We pass the options and the base class for the adatper,
// Note that passing an instance would work too
const filesController = new FilesController(filesControllerAdapter, appId);
const pushController = new PushController(pushControllerAdapter, appId);
const loggerController = new LoggerController(loggerControllerAdapter, appId);
const hooksController = new HooksController(appId, collectionPrefix);
const userController = new UserController(emailControllerAdapter, appId, { verifyUserEmails });
const liveQueryController = new LiveQueryController(liveQuery);
cache.apps.set(appId, {
masterKey: masterKey,
serverURL: serverURL,
collectionPrefix: collectionPrefix,
clientKey: clientKey,
javascriptKey: javascriptKey,
dotNetKey: dotNetKey,
restAPIKey: restAPIKey,
fileKey: fileKey,
facebookAppIds: facebookAppIds,
filesController: filesController,
pushController: pushController,
loggerController: loggerController,
hooksController: hooksController,
userController: userController,
verifyUserEmails: verifyUserEmails,
allowClientClassCreation: allowClientClassCreation,
authDataManager: authDataManager(oauth, enableAnonymousUsers),
appName: appName,
publicServerURL: publicServerURL,
customPages: customPages,
maxUploadSize: maxUploadSize,
liveQueryController: liveQueryController
});
// To maintain compatibility. TODO: Remove in some version that breaks backwards compatability
if (process.env.FACEBOOK_APP_ID) {
cache.apps.get(appId)['facebookAppIds'].push(process.env.FACEBOOK_APP_ID);
}
Config.validate(cache.apps.get(appId));
this.config = cache.apps.get(appId);
hooksController.load();
}
get app() {
return ParseServer.app(this.config);
}
static app({maxUploadSize = '20mb'}) {
// This app serves the Parse API directly.
// It's the equivalent of https://api.parse.com/1 in the hosted Parse API.
var api = express();
//api.use("/apps", express.static(__dirname + "/public"));
// File handling needs to be before default middlewares are applied
api.use('/', middlewares.allowCrossDomain, new FilesRouter().getExpressRouter({
maxUploadSize: maxUploadSize
}));
api.use('/', bodyParser.urlencoded({extended: false}), new PublicAPIRouter().expressApp());
// TODO: separate this from the regular ParseServer object
if (process.env.TESTING == 1) {
api.use('/', require('./testing-routes').router);
}
api.use(bodyParser.json({ 'type': '*/*' , limit: maxUploadSize }));
api.use(middlewares.allowCrossDomain);
api.use(middlewares.allowMethodOverride);
api.use(middlewares.handleParseHeaders);
let routers = [
new ClassesRouter(),
new UsersRouter(),
new SessionsRouter(),
new RolesRouter(),
new AnalyticsRouter(),
new InstallationsRouter(),
new FunctionsRouter(),
new SchemasRouter(),
new PushRouter(),
new LogsRouter(),
new IAPValidationRouter(),
new FeaturesRouter(),
];
if (process.env.PARSE_EXPERIMENTAL_CONFIG_ENABLED || process.env.TESTING) {
routers.push(new GlobalConfigRouter());
}
if (process.env.PARSE_EXPERIMENTAL_HOOKS_ENABLED || process.env.TESTING) {
routers.push(new HooksRouter());
}
let routes = routers.reduce((memo, router) => {
return memo.concat(router.routes);
}, []);
let appRouter = new PromiseRouter(routes);
batch.mountOnto(appRouter);
api.use(appRouter.expressApp());
api.use(middlewares.handleParseErrors);
//This causes tests to spew some useless warnings, so disable in test
if (!process.env.TESTING) {
process.on('uncaughtException', (err) => {
if ( err.code === "EADDRINUSE" ) { // user-friendly message for this common error
console.log(`Unable to listen on port ${err.port}. The port is already in use.`);
process.exit(0);
} else {
throw err;
}
});
}
return api;
}
static ParseServer(options) {
let server = new ParseServer(options);
return server.app;
}
static createLiveQueryServer(httpServer, config) {
return new ParseLiveQueryServer(httpServer, config);
}
// Factory function
let _ParseServer = function(options) {
let server = new ParseServer(options);
return server.app;
}
// Mount the create liveQueryServer
_ParseServer.createLiveQueryServer = ParseServer.createLiveQueryServer;
function addParseCloud() {
const ParseCloud = require("./cloud-code/Parse.Cloud");
Object.assign(Parse.Cloud, ParseCloud);
global.Parse = Parse;
}
let runServer = function(options) {
return ParseServer.ParseServer(options);
}
export { S3Adapter, GCSAdapter, FileSystemAdapter };
export { runServer as ParseServer };
export default ParseServer;
export { S3Adapter, GCSAdapter, FileSystemAdapter, _ParseServer as ParseServer };