completed move to v1 API, made specific API request class, started plugging in API authorization methodology

pull/20/head
Ro 5 years ago
parent d329522091
commit f3339089ff

@ -1,115 +0,0 @@
import DateUtils from '../../utils/tools/DateUtils';
import StringUtils from '../../utils/tools/StringUtils';
import * as DataEvent from '../../utils/events/DataEvent';
import sanitize from 'sanitize-html';
import RightsManager, {
TASK_CREATE,
TASK_UPDATE,
OBJECT_POST
} from '../../utils/tools/RightsManager';
const express = require('express');
const router = express.Router();
const multer = require('multer');
const md = require('markdown-it')('commonmark');
const fs = require('fs-extra');
const dateUtils = new DateUtils();
const rightsManager = new RightsManager();
const uploadPath =
'./public/assets/images/blog/' +
dateUtils.getDate('year', new Date()) +
'/' +
dateUtils.getDate('month', new Date());
const Sequelize = require('sequelize');
const Op = Sequelize.Op;
const _ = require('lodash');
fs.ensureDir(uploadPath, () => {
//console.log(err) // => null
// dir has now been created, including the directory it is to be placed in
});
var storage = multer.diskStorage({
destination: function(req, file, cb) {
cb(null, uploadPath);
},
filename: function(req, file, cb) {
var splice = file.originalname.split(':');
cb(null, splice[0]);
}
});
var feature_upload = multer({
storage: storage
}).array('feature_image');
var post_upload = multer({
storage: storage
}).array('post_image');
//** SYNC POSTS */
router.post('/sync', (req, res) => {
let payload = req.body;
});
router.get('/json/:filter?', function(req, res) {
var filter = req.params.filter;
});
/***
POST IMAGE
*/
router.post('/add-post-image', function(req, res) {
//console.log(req.body);
if (!req.session.user)
return res.json({
message: 'You need to be logged in, champ.'
});
Models.User.findById(req.session.user.id).then(user => {
if (rightsManager.check(user.role, OBJECT_POST, TASK_CREATE)) {
post_upload(req, res, function(err) {
if (err) {
//console.log('Error in Saving Entry: ' + err);
res.json({
message: err
});
throw err;
} else {
var postImage = req.files[0].path;
return res.json({
message: DataEvent.POST_IMAGE_ADDED,
url: postImage.substr(7, postImage.length)
});
}
});
} else {
res.json({
message: "Nah. You can't do that. Talk to the admin, sport."
});
}
});
});
router.post('/add-feature-image', function(req, res) {
//console.log(req.body);
if (!req.session.user)
return res.json({
message: 'You need to be logged in, champ.'
});
Models.User.findById(req.session.user.id).then(user => {
if (rightsManager.check(user.role, OBJECT_POST, TASK_CREATE)) {
feature_upload(req, res, function(err) {
if (err) {
//console.log('Error in Saving Entry: ' + err);
res.json({
message: err
});
throw err;
} else {
var postImage = req.files[0].path;
return res.json({
message: DataEvent.FEATURE_IMAGE_ADDED,
url: postImage.substr(7, postImage.length)
});
}
});
} else {
res.json({
message: "Nah. You can't do that. Talk to the admin, sport."
});
}
});
});
module.exports = router;

@ -1,203 +0,0 @@
import DateUtils from '../../utils/tools/DateUtils';
import * as DataEvent from '../../utils/events/DataEvent';
import RightsManager, {
TASK_CREATE,
TASK_UPDATE,
OBJECT_POST,
OBJECT_SETTINGS
} from '../../utils/tools/RightsManager';
const express = require('express');
const router = express.Router();
const multer = require('multer');
const fs = require('fs-extra');
const dateUtils = new DateUtils();
const rightsManager = new RightsManager();
const uploadPath =
'./public/assets/images/user/' +
dateUtils.getDate('year', new Date()) +
'/' +
dateUtils.getDate('month', new Date());
fs.ensureDir(uploadPath, () => {
//console.log(err) // => null
// dir has now been created, including the directory it is to be placed in
});
var storage = multer.diskStorage({
destination: function(req, file, cb) {
cb(null, uploadPath);
},
filename: function(req, file, cb) {
var splice = file.originalname.split(':');
cb(null, splice[0]);
}
});
var avatar_upload = multer({
storage: storage
}).array('avatar_upload');
var background_upload = multer({
storage: storage
}).array('background_upload');
//** SYNC POSTS */
router.post('/sync', (req, res) => {
let payload = req.body;
if (rightsManager.check(user.role, OBJECT_SETTINGS, TASK_UPDATE)) {
fs.readJson('config/site-settings.json')
.then(obj => {
if (user.hande != payload.handle || user.email != payload.email) {
user.update({
handle: payload.handle,
email: payload.email
})
.then(() => {
//console.log('UPDATED');
})
.catch(() => {
//console.log('ERR', err);
});
} else {
//console.log('USER NOT UPDATED');
}
obj.url = payload.url;
obj.title = payload.title;
obj.description = payload.descriptions;
obj.private = payload.private;
obj.theme = payload.theme;
obj.background = payload.background; //TODO: make this url relative
//mail stuff
obj.email.active = payload.mailSettings.activeProtocol;
obj.email.smtp.domain = payload.mailSettings.smtp.domain;
obj.email.smtp.email = payload.mailSettings.smtp.email;
obj.email.smtp.password = payload.mailSettings.smtp.password;
obj.email.mailgun.domain = payload.mailSettings.mailgun.domain;
obj.email.mailgun['api-key'] = payload.mailSettings.mailgun.key;
fs.writeJson('config/site-settings.json', obj)
.then(() => {
res.json({
message: DataEvent.SETTINGS_UPDATED
});
})
.catch(() => {
//console.error(err);
});
})
.catch(() => {
//console.error(err);
});
} else {
res.json({
message: "Nah. You can't do that. Talk to the admin, sport."
});
}
});
router.get('/nav', function(req, res) {
fs.readJson('config/site-settings.json')
.then(obj => {
fs.writeJson('config/site-settings.json', obj)
.then(() => {
res.json(obj.menu);
})
.catch(() => {
//console.error(err);
});
})
.catch(() => {
//console.error(err);
});
});
router.post('/nav-sync', (req, res) => {
let payload = req.body;
if (rightsManager.check(user.role, OBJECT_SETTINGS, TASK_UPDATE)) {
fs.readJson('config/site-settings.json')
.then(obj => {
obj.menu = payload;
fs.writeJson('config/site-settings.json', obj)
.then(() => {
res.json({
message: DataEvent.SETTINGS_UPDATED
});
})
.catch(() => {
//console.error(err);
});
})
.catch(() => {
//console.error(err);
});
} else {
res.json({
message: "Nah. You can't do that. Talk to the admin, sport."
});
}
});
/***
UPLOAD AVATAR
*/
router.post('/add-avatar', function(req, res) {
//console.log(req.body);
if (!req.session.user)
return res.json({
message: 'You need to be logged in, champ.'
});
if (rightsManager.check(user.role, OBJECT_POST, TASK_CREATE)) {
avatar_upload(req, res, function(err) {
if (err) {
res.json({
message: err
});
throw err;
} else {
var avatar = req.files[0].path;
user.update({
avatar: avatar.substr(7, avatar.length)
})
.then(updated => {
req.session.user = updated;
})
.catch(() => {
//console.log('ERR', err);
});
return res.json({
message: DataEvent.AVATAR_UPLOADED,
url: avatar.substr(7, avatar.length)
});
}
});
} else {
res.json({
message: "Nah. You can't do that. Talk to the admin, sport."
});
}
});
/***
UPLOAD FEATURE BACKGROUND
*/
router.post('/add-feature-background', function(req, res) {
//console.log(req.body);
if (!req.session.user)
return res.json({
message: 'You need to be logged in, champ.'
});
if (rightsManager.check(user.role, OBJECT_POST, TASK_CREATE)) {
background_upload(req, res, function(err) {
if (err) {
res.json({
message: err
});
throw err;
} else {
var bgImage = req.files[0].path;
return res.json({
message: DataEvent.SITE_BACKGROUND_UPLOADED,
url: bgImage.substr(7, bgImage.length)
});
}
});
} else {
res.json({
message: "Nah. You can't do that. Talk to the admin, sport."
});
}
});
module.exports = router;

@ -5,6 +5,7 @@ const bCrypt = require('bcrypt-nodejs');
const jwt = require('jsonwebtoken');
const fs = require('fs-extra');
const _ = require('lodash');
//const crypto = require('crypto'); // for setting up new accounts
/**
* Get Auth Status
@ -19,6 +20,25 @@ router.get('/', function(req, res) {
res.status(200).send(decoded);
});
});
/**
* Get Auth Status
*/
router.get('/status', function(req, res) {
if (req.session.user) {
let session = req.session;
res.json({
type: DataEvent.API_REQUEST_GOOD,
message: 'Auth is Good',
token: session.token
});
} else {
res.json({
type: DataEvent.API_REQUEST_LAME,
message: 'NOT AUTHORIZED'
});
}
});
/**
* Login Member and return token
*/
@ -33,7 +53,7 @@ router.post('/login', function(req, res) {
});
}
let token = jwt.sign({ id: found.id }, 'super-secret-string', {
let token = jwt.sign({ id: found.id }, found.key, {
expiresIn: 86400 // expires in 24 hours
});

@ -5,6 +5,7 @@ const router = express.Router();
const multer = require('multer');
const fs = require('fs-extra');
const moment = require('moment');
const jwt = require('jsonwebtoken');
const book = new Book();
const uploadPath =
'./public/assets/images/blog/' + moment().format('YYYY') + '/' + moment().format('MM');
@ -41,6 +42,17 @@ router.get('/', (req, res) => {
Update Page
*/
router.post('/write/:task?', feature_upload, (req, res) => {
/**
if (req.session.user) {
var member = req.session.user;
jwt.verify(req.session.token, member.key, function(err, decoded) {
if (err) {
console('NOPE', err);
}
console.log('YUP', decoded);
});
}
*/
var feature = '';
if (req.files.length > 0) {
var path = req.files[0].path;

@ -12,9 +12,9 @@ router.get('/', function(req, res) {
result.sort((a, b) => parseFloat(b.metadata.id) - parseFloat(a.metadata.id));
let pageData = [];
if (req.session.user) {
pageData = { title: settings.title, status: true, pages: result };
pageData = { title: settings.global.title, status: true, pages: result };
} else {
pageData = { title: settings.title, status: false, pages: result };
pageData = { title: settings.global.title, status: false, pages: result };
}
res.render('index', pageData);

@ -1,9 +1,11 @@
import DataUtils, { REQUEST_TYPE_POST, CONTENT_TYPE_JSON } from './utils/DataUtils';
import ApiUtils, { REQUEST_TYPE_POST, CONTENT_TYPE_JSON } from './utils/APIUtils';
import DataUitls from './utils/DataUtils';
import * as DataEvent from './events/DataEvent';
import DashManager from './controllers/DashManager';
import Notfications from './ui/Notifications';
const data = new DataUtils();
const api = new ApiUtils();
const data = new DataUitls();
const notify = new Notfications();
export default class Base {
@ -33,7 +35,7 @@ export default class Base {
e.stopPropagation();
e.preventDefault();
let authForm = data.formDataToJSON(document.getElementById('login'));
data.request(
api.request(
'/api/v1/auth/login',
DataEvent.AUTH_STATUS,
REQUEST_TYPE_POST,

@ -1,6 +1,6 @@
import DataUtils, { REQUEST_TYPE_POST, CONTENT_TYPE_JSON } from '../../../src/com/utils/DataUtils';
import ApiUtils, { REQUEST_TYPE_POST, CONTENT_TYPE_JSON } from '../../../src/com/utils/APIUtils';
import * as DataEvent from '../../../src/com/events/DataEvent';
const utils = new DataUtils();
const api = new ApiUtils();
export default class NavActions {
//--------------------------
// constructor
@ -21,14 +21,13 @@ export default class NavActions {
});
}
return new Promise(function(resolve, reject) {
utils
.request(
'/api/v1/settings/nav-sync',
DataEvent.SETTINGS_UPDATED,
REQUEST_TYPE_POST,
CONTENT_TYPE_JSON,
navData
)
api.request(
'/api/v1/settings/nav-sync',
DataEvent.API_SETTINGS_WRITE,
REQUEST_TYPE_POST,
CONTENT_TYPE_JSON,
navData
)
.then(response => {
resolve(response);
})

@ -1,13 +1,12 @@
import DataUtils, { REQUEST_TYPE_POST, CONTENT_TYPE_JSON } from '../utils/DataUtils';
import ApiUtils, { REQUEST_TYPE_POST, CONTENT_TYPE_JSON } from '../utils/APIUtils';
import StringUtils from '../utils/StringUtils';
import * as DataEvent from '../events/DataEvent';
const api = new ApiUtils();
export default class PostActions {
//--------------------------
// constructor
//--------------------------
constructor() {
this.dataUtils = new DataUtils();
}
constructor() {}
//--------------------------
// methods
//--------------------------
@ -84,9 +83,7 @@ export default class PostActions {
});
}
updateNav(add, id, post) {
var self = this;
this.dataUtils
.request('/api/settings/nav', DataEvent.SETTINGS_LOADED)
api.request('/api/settings/nav', DataEvent.SETTINGS_LOADED)
.then(response => {
let menu = JSON.parse(response.request['response']);
let item = {
@ -104,14 +101,13 @@ export default class PostActions {
}
}
}
self.dataUtils
.request(
'/api/settings/nav-sync',
DataEvent.SETTINGS_UPDATED,
REQUEST_TYPE_POST,
CONTENT_TYPE_JSON,
menu
)
api.request(
'/api/settings/nav-sync',
DataEvent.API_SETTINGS_WRITE,
REQUEST_TYPE_POST,
CONTENT_TYPE_JSON,
menu
)
.then(() => {
//console.log(response);
})

@ -1,6 +1,6 @@
import DataUtils, { REQUEST_TYPE_POST, CONTENT_TYPE_JSON } from '../../../src/com/utils/DataUtils';
import ApiUtils, { REQUEST_TYPE_POST, CONTENT_TYPE_JSON } from '../../../src/com/utils/APIUtils';
import * as DataEvent from '../../../src/com/events/DataEvent';
const utils = new DataUtils();
const api = new ApiUtils();
export default class SettingsActions {
//--------------------------
// constructor
@ -61,14 +61,13 @@ export default class SettingsActions {
}
};
return new Promise(function(resolve, reject) {
utils
.request(
'/api/v1/settings/sync',
DataEvent.SETTINGS_UPDATED,
REQUEST_TYPE_POST,
CONTENT_TYPE_JSON,
settingsData
)
api.request(
'/api/v1/settings/sync',
DataEvent.SETTINGS_UPDATED,
REQUEST_TYPE_POST,
CONTENT_TYPE_JSON,
settingsData
)
.then(response => {
//console.log("RESPONSE", response)
resolve(response);

@ -1,12 +1,12 @@
//TOOLS
import DataUtils, { REQUEST_TYPE_POST, CONTENT_TYPE_FORM } from '../utils/DataUtils';
import ApiUtils, { REQUEST_TYPE_POST, CONTENT_TYPE_FORM } from '../utils/APIUtils';
import * as DataEvent from '../events/DataEvent';
import PageActions from '../actions/PageActions';
import * as EditorEvent from '../events/EditorEvent';
import TinyDatePicker from 'tiny-date-picker';
import TextEditor from '../ui/TextEditor';
import Notfications from '../ui/Notifications';
const data = new DataUtils();
const api = new ApiUtils();
const notify = new Notfications();
export default class PostEditor {
//--------------------------
@ -17,6 +17,7 @@ export default class PostEditor {
this.urlPieces = document.URL.split('/');
this.post = [];
this.postID = null;
api.authStatus();
if (document.getElementById('post-edit-index').getAttribute('data-index')) {
this.postID = document.getElementById('post-edit-index').getAttribute('data-index');
}
@ -125,7 +126,7 @@ export default class PostEditor {
.collectInfo(document.getElementById('featured-image-upload').files[0])
.then(page => {
data.request(
api.request(
apiUrl,
DataEvent.API_PAGE_WRITE,
REQUEST_TYPE_POST,
@ -213,7 +214,7 @@ export default class PostEditor {
}
handleImageUpload(type, files) {
let url = '/api/v1/page/add-post-image';
let eventType = DataEvent.POST_IMAGE_ADDED;
let eventType = DataEvent.API_IMAGES_UPLOAD;
let self = this;
var imageData = new FormData();
for (var i = 0; i < files.length; i++) {
@ -224,7 +225,7 @@ export default class PostEditor {
}
imageData.append('post_image', file, file.name);
}
data.request(url, eventType, REQUEST_TYPE_POST, CONTENT_TYPE_FORM, imageData)
api.request(url, eventType, REQUEST_TYPE_POST, CONTENT_TYPE_FORM, imageData)
.then(response => {
let r = JSON.parse(response.request['response']);
if (r.type == DataEvent.POST_IMAGE_ADDED)

@ -1,9 +1,9 @@
import SettingsActions from '../actions/SettingsActions';
import DataUtils, { REQUEST_TYPE_POST, CONTENT_TYPE_FORM } from '../../../src/com/utils/DataUtils';
import ApiUtils, { REQUEST_TYPE_POST, CONTENT_TYPE_FORM } from '../../../src/com/utils/APIUtils';
import * as DataEvent from '../../../src/com/events/DataEvent';
import Mailer from '../actions/Mailer';
import Notifications from '../ui/Notifications';
const utils = new DataUtils();
const api = new ApiUtils();
const notify = new Notifications();
const mailer = new Mailer();
export default class SettingsIndex {
@ -138,7 +138,7 @@ export default class SettingsIndex {
}
handleImageUpload(type, files) {
let url = '';
let eventType = '';
let eventType = DataEvent.API_IMAGES_UPLOAD;
type == 'avatar-upload'
? (url = '/api/v1/settings/add-avatar')
: (url = '/api/v1/settings/add-feature-background');
@ -153,8 +153,7 @@ export default class SettingsIndex {
? imageData.append('avatar_upload', file, file.name)
: imageData.append('background_upload', file, file.name);
}
utils
.request(url, eventType, REQUEST_TYPE_POST, CONTENT_TYPE_FORM, imageData)
api.request(url, eventType, REQUEST_TYPE_POST, CONTENT_TYPE_FORM, imageData)
.then(response => {
let r = JSON.parse(response.request['response']);
if (r.type == DataEvent.AVATAR_UPLOADED) {

@ -1,5 +1,7 @@
export const REQUEST_GOOD = 'requestGood';
export const REQUEST_LAME = 'requestLame';
export const API_REQUEST_GOOD = 'apiUseNotAuthorized';
export const API_REQUEST_LAME = 'apiUseAuthorized';
export const IMG_REQUEST_GOOD = 'imgRequestGood';
export const IMG_REQUEST_LAME = 'imgRequestLame';
export const SETTINGS_LOADED = 'settingsLoaded';
@ -13,7 +15,10 @@ export const SETTINGS_UPDATED = 'settingsUpdated';
export const MENU_UPDATED = 'menuUpdated';
export const AVATAR_UPLOADED = 'avatarUploaded';
export const SITE_BACKGROUND_UPLOADED = 'siteBackgroundUploaded';
export const UPLOAD_PROGRESS = 'uploadProgress';
export const API_PAGE_WRITE = 'writingItDown';
export const API_SETTINGS_WRITE = 'savingSettings';
export const API_IMAGES_UPLOAD = 'uploadProfileImages';
class DataEvent {
//--------------------------
// methods

@ -0,0 +1,77 @@
export const REQUEST_TYPE_POST = 'POST';
export const REQUEST_TYPE_GET = 'GET';
export const REQUEST_TYPE_PUT = 'PUT';
export const REQUEST_TYPE_DELETE = 'DELETE';
export const CONTENT_TYPE_JSON = 'json';
export const CONTENT_TYPE_FORM = 'x-www-form-urlencoded';
import * as DataEvent from '../events/DataEvent';
export default class APIUtils {
//--------------------------
// constructor
//--------------------------
constructor() {
this.percentComplete = 0;
this.token = null;
}
//--------------------------
// methods
//--------------------------
authStatus() {
this.request('/api/v1/auth/status').then(r => {
let response = JSON.parse(r.request['response']);
if (response.type === DataEvent.API_REQUEST_GOOD) {
this.token = response.token;
} else {
//don't set token
}
});
}
request(
requestURL,
eventType,
requestType = REQUEST_TYPE_GET,
contentType = CONTENT_TYPE_JSON,
requestData = null
) {
var self = this;
return new Promise(function(resolve, reject) {
var request = new XMLHttpRequest();
request.upload.onprogress = self.handleLoadProgress;
request.open(requestType, requestURL, true);
request.onload = () => {
if (request.status == 200) {
resolve({
request,
eventType
});
} else {
reject({
request,
eventType
});
}
};
if (requestType == REQUEST_TYPE_PUT || requestType == REQUEST_TYPE_POST) {
switch (contentType) {
case CONTENT_TYPE_JSON:
request.setRequestHeader('Content-type', 'application/' + contentType);
request.send(JSON.stringify(requestData));
break;
case CONTENT_TYPE_FORM:
request.send(requestData);
break;
}
} else {
request.send();
}
});
}
//--------------------------
// event handlers
//--------------------------
handleLoadProgress(e) {
this.percentComplete = Math.ceil((e.loaded / e.total) * 100);
//this.emitEvent(DataEvent.UPLOAD_PROGRESS);
}
}

@ -1,60 +1,12 @@
export const REQUEST_TYPE_POST = 'POST';
export const REQUEST_TYPE_GET = 'GET';
export const REQUEST_TYPE_PUT = 'PUT';
export const REQUEST_TYPE_DELETE = 'DELETE';
export const CONTENT_TYPE_JSON = 'json';
export const CONTENT_TYPE_FORM = 'x-www-form-urlencoded';
import EventEmitter from '../events/EventEmitter';
export default class DataUtils extends EventEmitter {
export default class DataUtils {
//--------------------------
// constructor
//--------------------------
constructor() {
super();
}
constructor() {}
//--------------------------
// methods
//--------------------------
request(
requestURL,
eventType,
requestType = REQUEST_TYPE_GET,
contentType = CONTENT_TYPE_JSON,
requestData = null
) {
var self = this;
return new Promise(function(resolve, reject) {
var request = new XMLHttpRequest();
request.upload.onprogress = self.handleLoadProgress;
request.open(requestType, requestURL, true);
request.onload = () => {
if (request.status == 200) {
resolve({
request,
eventType
});
} else {
reject({
request,
eventType
});
}
};
if (requestType == REQUEST_TYPE_PUT || requestType == REQUEST_TYPE_POST) {
switch (contentType) {
case CONTENT_TYPE_JSON:
request.setRequestHeader('Content-type', 'application/' + contentType);
request.send(JSON.stringify(requestData));
break;
case CONTENT_TYPE_FORM:
request.send(requestData);
break;
}
} else {
request.send();
}
});
}
imgLoad(url) {
'use strict';
// Create new promise with the Promise() constructor;
@ -137,7 +89,4 @@ export default class DataUtils extends EventEmitter {
//--------------------------
// event handlers
//--------------------------
handleLoadProgress(e) {
//var percentComplete = Math.ceil((e.loaded / e.total) * 100);
}
}

Loading…
Cancel
Save