{"size": 1800, "ext": "js", "max_stars_repo_path": "routes/controller/createPost.js", "max_stars_repo_name": "babylondublin/Babylon2", "max_stars_repo_stars_event_min_datetime": "2017-08-14T08:57:53.000Z", "max_stars_repo_stars_event_max_datetime": "2017-08-31T09:19:48.000Z", "max_issues_repo_path": "routes/controller/createPost.js", "max_issues_repo_name": "babylondublin/Babylon2", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "routes/controller/createPost.js", "max_forks_repo_name": "babylondublin/Babylon2", "max_forks_repo_forks_event_min_datetime": "2017-07-03T02:51:23.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-24T21:39:42.000Z"}
{"max_stars_count": 2, "max_issues_count": null, "max_forks_count": 10, "avg_line_length": 25.0, "max_line_length": 153, "alphanum_fraction": 0.6383333333}
var keystone = require('keystone'),
	Post = keystone.list('Post'),
	PostTag = keystone.list('PostTag');


exports = module.exports = function(req, res) {
	
	var view = new keystone.View(req, res),
		locals = res.locals;

	//if not admin or jurnalist
	if(!locals.user.isAdmin && !locals.user.isJournalist) res.redirect('/');

	//if no Session
	if(!req.session.country){
		return res.redirect('/news');
	};
	
	locals.section = 'me';
	locals.page.title = 'Create a Post - Babylon';

	// Load PostTags
	view.on('init', function(next) {
		PostTag.model.find()
		.sort('name')		
		.exec(function(err, tagsList) {
			if (err) res.err(err);
			locals.tags = tagsList;
			next();
		});
	});

	view.on('post', { action: 'create-post' }, function(next) {
		
		var session = req.session.country._id;
		// handle form
		var newPost = new Post.model({
				author: locals.user.id,
				publishedDate: new Date(),
				country: session
			}),

			updater = newPost.getUpdateHandler(req, res, {
				errorMessage: 'There was an error creating your new Post:'
			});
		
		// automatically publish posts by admin users
		if (locals.user.isAdmin || locals.user.isJournalist) {
			newPost.state = 'published';
		}
		
		updater.process(req.body, {
			flashErrors: true,
			logErrors: true,
			fields: 'title, tag, image, content.extended'
		}, function(err) {
			if (err) {
				locals.validationErrors = err.errors;
			} else {
				newPost.notifyAdmins();
				req.flash('success', 'Your post has been added' + ((newPost.state == 'draft') ? ' and will appear on the site once it\'s been approved' : '') + '.');
				return res.redirect('/news/post/' + newPost.slug);
			}
			next();
		});

	});
	var lang = (req.session.languageselected ? req.session.languageselected.key : 'en');	
	view.render(lang + '/site/createPost');
	
}
