<commit_before>var express = require('express');
var app = express();
var fs = require('fs');
var rootPath = __dirname.replace('/web', '');
var staticServer = require('serve-static');
var compression = require('compression');
var multer = require('multer');
var bodyParser = require('body-parser');
var methodOverride = require('method-override');
var cookieParser = require('cookie-parser');
var cookieSession = require('cookie-session');
var config = require('../config');
var passport = require('passport');
var PassportStrategy = require('passport-local').Strategy;
var Datastore = require('nedb');
var membersDbFilePath = config.dataPath + '/members.db';
var signer = require('jws');
var Persistence = require('../boundaries/persistence')(config);
var Member = require('../profile/entities/member');
var Ejs = require('ejs');
var Https = require('https');
var Http = require('http');
var QueryString = require('querystring');
var XmlToJson = require('xml2js');
var uploadsFolder = rootPath + '/uploads/';
var imagesFolder = rootPath + '/uploads/images/';
var members = [];
var webDataFolder = rootPath + '/web/data';
var membersFolder = webDataFolder + '/members';
var pagesFolder = webDataFolder + '/pages';
var httpImageRoot = "/uploads/images/";
var Moment = require('moment');

function Resource(obj){
	this.layout = 'default';
	this.title = config.site.title;
	this.js = [];
	this.css = [];
	this.header = {};
	this.user = null;
	this.status = {code: 200, description: 'Ok'};
	this.posts = [];
	this.author = "<NAME>";
	this.description = "profiles app";
	for(var key in obj) this[key] = obj[key];
}
var represent = require('represent').Represent({
	themeRoot: rootPath + '/web/themes/' + config.theme
	, appPath: rootPath + '/web'
});
function createFolderIfDoesntExist(folder){
	if(!fs.existsSync(folder)){
		fs.mkdirSync(folder);
	}
}
createFolderIfDoesntExist(config.dataPath);
createFolderIfDoesntExist(webDataFolder);
createFolderIfDoesntExist(uploadsFolder);
createFolderIfDoesntExist(imagesFolder);
createFolderIfDoesntExist(membersFolder);
createFolderIfDoesntExist(pagesFolder);
express.response.represent = require('./withRepresent')(represent, config);
app.use(compression());
app.use("/public", staticServer(represent.themeRoot));
app.use("/uploads", staticServer(rootPath + '/uploads/'));
app.set("views", rootPath + "/themes/default/templates");
app.set("view engine", function(view, options, fn){ return fn(view, options);});
app.use(cookieParser());
app.use(multer({dest: './uploads/'}));
app.use(bodyParser.urlencoded({ extended: true }));
app.use(methodOverride(function(req, res){
	if(req.body._method) return req.body._method;
	return req.method;
}));
app.use(cookieSession({ keys: [config.cookie.key, ':blah:'], secret: config.cookie.secret}));
app.use(passport.initialize());
app.use(passport.session());

passport.serializeUser(function(member, done) {
	var signature = signer.sign({
		header: {alg: 'HS256'}
		, payload: member.username
		, secret: config.secret
	});
	done(null, signature);
});
passport.deserializeUser(function deserializeUser(token, done) {
	var decodedSignature = signer.decode(token);
	if(!decodedSignature) return done(null, null);
	Persistence.member.findOne({username: decodedSignature.payload}, function(err, member) {
		if(err) console.log(err);
		done(err, member);
	});
});
var Authentication = (function(){
	var self = {
		login: function(username, password, callback){
			var body = QueryString.stringify({callingProgram: 'dtcprofiles', j_username: username, j_password: password, j_storenumber: 9100});
			var request = Https.request({hostname: 'hdapps.homedepot.com'
				, port: '443'
				, path: '/MYTHDPassport/rs/identity/auth'
				, method: 'POST'
				, headers: {
		          'Content-Type': 'application/x-www-form-urlencoded'
				  , 'Content-Length': body.length
		    	}
			}, function(response){
				response.setEncoding('utf8');
				response.on('data', function (chunk) {				
					XmlToJson.parseString(chunk, function(err, identity){
						if(err) return callback(err);
						if(identity.Auth.Error){
							//console.log(identity.Auth.Error[0]);
							return callback(null, null, {message: identity.Auth.Error[0]});
						}
						return callback(null, new Member({username: username}));
					});
				});
			});
			request.write(body);
			request.end();
		}
	};
	return self;
})();

passport.use(new PassportStrategy(
	function(username, password, done) {
		Authentication.login(username, password, function(err, member, response){
			if(err) return done(err);
			if(member !== null){
				Persistence.member.findOne({username: username}, function(err, member){
					if(err) return done(err);
					if(member) return done(null, member);
					var member = new Member({
						username: username
						, background: ''
						, name: username
						, avatar: ''
						, page: ''
						, active: (new Date()).getTime()
					});
					client.send(new Commands.AddMember(member));
					done(null, member);
				});
			}else{
				done(null, null, response);
			}
		});
	}
));
function Folder(files){
	this.files = files;
}
Folder.prototype = {
	canEdit: function(user){
		return user !== null;
	}
};
Folder.isValid = function(fileName){
	if(fileName === null) return false;
	if(fileName.length > 30) return false;
	return /^\w+(\.\w+)?$/.test(fileName);
};

function Page(name, contents){
	this.name = name.replace(/\.\w+$/, '');
	this.contents = contents;
}

app.get("/robots.txt", function(req, resp, next){
	resp.represent({
		view: 'robots/index'<commit_msg>handle empty page names upon intializing.<commit_after>var express = require('express');
var app = express();
var fs = require('fs');
var rootPath = __dirname.replace('/web', '');
var staticServer = require('serve-static');
var compression = require('compression');
var multer = require('multer');
var bodyParser = require('body-parser');
var methodOverride = require('method-override');
var cookieParser = require('cookie-parser');
var cookieSession = require('cookie-session');
var config = require('../config');
var passport = require('passport');
var PassportStrategy = require('passport-local').Strategy;
var Datastore = require('nedb');
var membersDbFilePath = config.dataPath + '/members.db';
var signer = require('jws');
var Persistence = require('../boundaries/persistence')(config);
var Member = require('../profile/entities/member');
var Ejs = require('ejs');
var Https = require('https');
var Http = require('http');
var QueryString = require('querystring');
var XmlToJson = require('xml2js');
var uploadsFolder = rootPath + '/uploads/';
var imagesFolder = rootPath + '/uploads/images/';
var members = [];
var webDataFolder = rootPath + '/web/data';
var membersFolder = webDataFolder + '/members';
var pagesFolder = webDataFolder + '/pages';
var httpImageRoot = "/uploads/images/";
var Moment = require('moment');

function Resource(obj){
	this.layout = 'default';
	this.title = config.site.title;
	this.js = [];
	this.css = [];
	this.header = {};
	this.user = null;
	this.status = {code: 200, description: 'Ok'};
	this.posts = [];
	this.author = "<NAME>";
	this.description = "profiles app";
	for(var key in obj) this[key] = obj[key];
}
var represent = require('represent').Represent({
	themeRoot: rootPath + '/web/themes/' + config.theme
	, appPath: rootPath + '/web'
});
function createFolderIfDoesntExist(folder){
	if(!fs.existsSync(folder)){
		fs.mkdirSync(folder);
	}
}
createFolderIfDoesntExist(config.dataPath);
createFolderIfDoesntExist(webDataFolder);
createFolderIfDoesntExist(uploadsFolder);
createFolderIfDoesntExist(imagesFolder);
createFolderIfDoesntExist(membersFolder);
createFolderIfDoesntExist(pagesFolder);
express.response.represent = require('./withRepresent')(represent, config);
app.use(compression());
app.use("/public", staticServer(represent.themeRoot));
app.use("/uploads", staticServer(rootPath + '/uploads/'));
app.set("views", rootPath + "/themes/default/templates");
app.set("view engine", function(view, options, fn){ return fn(view, options);});
app.use(cookieParser());
app.use(multer({dest: './uploads/'}));
app.use(bodyParser.urlencoded({ extended: true }));
app.use(methodOverride(function(req, res){
	if(req.body._method) return req.body._method;
	return req.method;
}));
app.use(cookieSession({ keys: [config.cookie.key, ':blah:'], secret: config.cookie.secret}));
app.use(passport.initialize());
app.use(passport.session());

passport.serializeUser(function(member, done) {
	var signature = signer.sign({
		header: {alg: 'HS256'}
		, payload: member.username
		, secret: config.secret
	});
	done(null, signature);
});
passport.deserializeUser(function deserializeUser(token, done) {
	var decodedSignature = signer.decode(token);
	if(!decodedSignature) return done(null, null);
	Persistence.member.findOne({username: decodedSignature.payload}, function(err, member) {
		if(err) console.log(err);
		done(err, member);
	});
});
var Authentication = (function(){
	var self = {
		login: function(username, password, callback){
			var body = QueryString.stringify({callingProgram: 'dtcprofiles', j_username: username, j_password: password, j_storenumber: 9100});
			var request = Https.request({hostname: 'hdapps.homedepot.com'
				, port: '443'
				, path: '/MYTHDPassport/rs/identity/auth'
				, method: 'POST'
				, headers: {
		          'Content-Type': 'application/x-www-form-urlencoded'
				  , 'Content-Length': body.length
		    	}
			}, function(response){
				response.setEncoding('utf8');
				response.on('data', function (chunk) {				
					XmlToJson.parseString(chunk, function(err, identity){
						if(err) return callback(err);
						if(identity.Auth.Error){
							//console.log(identity.Auth.Error[0]);
							return callback(null, null, {message: identity.Auth.Error[0]});
						}
						return callback(null, new Member({username: username}));
					});
				});
			});
			request.write(body);
			request.end();
		}
	};
	return self;
})();

passport.use(new PassportStrategy(
	function(username, password, done) {
		Authentication.login(username, password, function(err, member, response){
			if(err) return done(err);
			if(member !== null){
				Persistence.member.findOne({username: username}, function(err, member){
					if(err) return done(err);
					if(member) return done(null, member);
					var member = new Member({
						username: username
						, background: ''
						, name: username
						, avatar: ''
						, page: ''
						, active: (new Date()).getTime()
					});
					client.send(new Commands.AddMember(member));
					done(null, member);
				});
			}else{
				done(null, null, response);
			}
		});
	}
));
function Folder(files){
	this.files = files;
}
Folder.prototype = {
	canEdit: function(user){
		return user !== null;
	}
};
Folder.isValid = function(fileName){
	if(fileName === null) return false;
	if(fileName.length > 30) return false;
	return /^\w+(\.\w+)?$/.test(fileName);
};

function Page(name, contents){
	this.name = name ? name.replace(/\.\w+$/, '') : null;
	this.contents = contents;
}

app.get("/robots.txt", function(req, resp, next){
	resp.represent({
		view: 'robots/index'
{'fraction_non_alphanumeric': 0.17444164265129683, 'fraction_numerical': 0.003422190201729107, 'mean_word_length': 4.841662283008943, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 7, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 2}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '452298', 'n_tokens_mistral': 3856, 'n_tokens_neox': 3465, 'n_words': 740}