jormungandr-bite/src/api/endpoints/app/create.js

129 lines
2.8 KiB
JavaScript
Raw Normal View History

2016-12-28 15:49:51 -07:00
'use strict';
/**
* Module dependencies
*/
import rndstr from 'rndstr';
import App from '../../models/app';
import serialize from '../../serializers/app';
2017-01-06 02:33:03 -07:00
/**
* @swagger
* /app/create:
* post:
* summary: Create an application
* parameters:
* - $ref: "#/parameters/AccessToken"
* -
* name: name_id
* description: Application unique name
* in: formData
* required: true
* type: string
* -
* name: name
* description: Application name
* in: formData
* required: true
* type: string
* -
* name: description
* description: Application description
* in: formData
* required: true
* type: string
* -
* name: permission
* description: Permissions that application has
* in: formData
* required: true
* type: array
* items:
* type: string
* collectionFormat: csv
* -
* name: callback_url
* description: URL called back after authentication
* in: formData
* required: false
* type: string
2017-03-01 01:37:01 -07:00
*
2017-01-06 02:33:03 -07:00
* responses:
* 200:
* description: Created application's information
* schema:
* $ref: "#/definitions/Application"
2017-03-01 01:37:01 -07:00
*
2017-01-06 02:33:03 -07:00
* default:
* description: Failed
* schema:
* $ref: "#/definitions/Error"
*/
2016-12-28 15:49:51 -07:00
/**
* Create an app
*
2017-03-01 01:37:01 -07:00
* @param {any} params
* @param {any} user
* @return {Promise<any>}
2016-12-28 15:49:51 -07:00
*/
module.exports = async (params, user) =>
new Promise(async (res, rej) =>
{
// Get 'name_id' parameter
const nameId = params.name_id;
2017-03-01 06:33:54 -07:00
if (nameId == null) {
2016-12-28 15:49:51 -07:00
return rej('name_id is required');
2017-03-01 06:33:54 -07:00
} else if (typeof nameId != 'string') {
return rej('name_id must be a string');
2016-12-28 15:49:51 -07:00
}
// Validate name_id
if (!/^[a-zA-Z0-9\-]{3,30}$/.test(nameId)) {
return rej('invalid name_id');
}
// Get 'name' parameter
const name = params.name;
if (name == null || name == '') {
return rej('name is required');
}
// Get 'description' parameter
const description = params.description;
if (description == null || description == '') {
return rej('description is required');
}
// Get 'permission' parameter
const permission = params.permission;
if (permission == null || permission == '') {
return rej('permission is required');
}
// Get 'callback_url' parameter
let callback = params.callback_url;
if (callback === '') {
callback = null;
}
// Generate secret
const secret = rndstr('a-zA-Z0-9', 32);
// Create account
2017-01-20 01:38:05 -07:00
const app = await App.insert({
2016-12-28 15:49:51 -07:00
created_at: new Date(),
user_id: user._id,
name: name,
name_id: nameId,
name_id_lower: nameId.toLowerCase(),
description: description,
permission: permission.split(','),
callback_url: callback,
secret: secret
});
// Response
res(await serialize(app));
});