HEX
Server: Microsoft-IIS/8.5
System: Windows NT YDAWBH120 6.3 build 9600 (Windows Server 2012 R2 Standard Edition) AMD64
User: tentjecom_web (0)
PHP: 7.4.14
Disabled: NONE
Upload Files
File: D:/HostingSpaces/RImmers2/portal.photomenu.nl/wwwroot/controllers/default.js
const validator = require('validator');
const site_maintanance = false;

exports.install = function () {
    F.route('/', index);
	F.route('/restaurant-edit', indexRestaurants);
	F.route('/menu-edit', indexMenus);
	F.route('/share-edit', indexShares);
    F.route('/login', login, ['get']);
    F.route('/login', loginProcess, ['post']);
    F.route('/reset-password', resetPassword, ['get']);
    F.route('/reset-password', sendPasswordReset, ['post']);
	F.route('/tips', tips, ['get', 'authorize']);
    F.route('/logout', logout, ['get', 'authorize']);    
	//F.route('/restaurant-web', webRestaurants);
};


function index() {
    const self = this;
    if (self.repository.type === 'restaurant') {
        //after inlog restaurant directly go to the menu
		F.model('restaurant').load(self.repository.currentRestaurant).then(restaurant => {
            this.res.redirect(`/menus/${self.repository.currentRestaurant}/${restaurant.Menu}`);
        })
    } else {
        this.res.redirect('/restaurants');
    }
};

function indexRestaurants() {
    const self = this;
    if (self.repository.type === 'restaurant') {
		F.model('restaurant').load(self.repository.currentRestaurant).then(restaurant => {
            this.res.redirect(`/restaurants/edit/${self.repository.currentRestaurant}`);
        })
    } else {
        this.res.redirect('/restaurants');
    }
};

function indexMenus() {
    const self = this;
    if (self.repository.type === 'restaurant') {
		F.model('restaurant').load(self.repository.currentRestaurant).then(restaurant => {
            this.res.redirect(`/menus/${self.repository.currentRestaurant}/${restaurant.Menu}`);
        })
    } else {
        this.res.redirect('/menus');
    }
};

function indexShares() {
    const self = this;
    if (self.repository.type === 'restaurant') {
		F.model('restaurant').load(self.repository.currentRestaurant).then(restaurant => {
            this.res.redirect(`/sharesHistory/${self.repository.currentRestaurant}`);
        })
    } else {
        this.res.redirect('/sharesHistory');
    }
};

function sendEmail(fromaddress,toaddress,txtsubject,txthtml,bodytext) {
  var nodemailer = require('nodemailer');
  var smtpTransport = require('nodemailer-smtp-transport');
  var transporter = nodemailer.createTransport(smtpTransport({
   host: 'localhost',
   port: 25   
  }));
   
   transporter.sendMail({
   from: fromaddress,
   to: toaddress,
   subject: txtsubject,
   html: txthtml,
   text: bodytext
  }).catch(err => {
        console.log(err);
  });
//  console.log('sendEmail successfull');
}

function resetPassword() {
    var self = this;
    self.layout(false);
    self.view('reset-password', {
        error: false
    });
}

function tips() {
    var self = this;
    self.layout('/layouts/protected');
    self.view('/tips/index', {
        error: false
    });
}

function sendPasswordReset() {
    var self = this;
    var params = {};
    self.layout(false);
    if (!validator.isEmail(self.body['E-mail'])) {
        self.view('reset-password', {
            error: true,
            message: "Invalid email address."
        });
    } else {
        F.firebaseAuth().sendPasswordResetEmail(self.body['E-mail']).then(() => {
            self.view('reset-password-confirmation', {});
        }).catch(err => {
            self.view('reset-password', {
                error: true,
                message: "User with this e-mail doesn't exist."
            });
        })
    }

};

function login() {
    var self = this;
    var cookie = self.cookie('xxxx');
    if (cookie && cookie.length >= 10) {
        var obj = F.decrypt(cookie, 'user');
        var user = F.cache.read('user_' + obj.user);
        if (user) {            
			self.res.redirect('/');
        }
    }
    self.layout(false);
    if (site_maintanance) {
      self.view('maintanance', {
        error: false
      });
    }
  else{
    self.view('login', {
        error: false
    });
  }
};

function loginProcess() {
    var self = this;
    self.layout(false);
	var strLogin  = self.body.login;
    F.firebaseAuth().signInWithEmailAndPassword(strLogin, self.body.password)
        .then(function (result) {
			var dtNow = new Date().format('dd-MM-yyyy HH:mm:ss');
			var user = F.firebaseAuth().currentUser;
	
			F.model('user').load(result.uid).then(function (snapshot) {
                const dbUser = snapshot.val();
                if (!dbUser.status) {
                    return self.view('login', {
                        login: self.body.login,
                        error: true
                    });
                }
                if (user && dbUser) {
// BEGIN email restaurants login 
					        if (self.body.login!='info@photomenu.nl' && self.body.login!='info@robertimmers.nl' && self.body.login!='robert.immers@gmail.com') {
					          F.model('restaurant').load(dbUser.restaurant).then(function (restaurant) {
					            var userfullname = restaurant.Name + ' | ' + dbUser.name + ' (' + dbUser.email + ')';
						          sendEmail('info@photomenu.nl','photomenushares@gmail.com','Portal login','user login : ' + userfullname,'user: login' + userfullname);
					          });
					        }
// END email restaurants login 		                    
				  user.role = dbUser.role;
                  user.restaurant = dbUser.restaurant;
				  user.hasStatistics = (dbUser.hasStatistics || dbUser.role == 'admin');
				  user.hasLunch = (dbUser.hasLunch || dbUser.role == 'admin');
				  user.hasAllergens = (dbUser.hasAllergens || dbUser.role == 'admin');
				  user.hasDrinks = (dbUser.hasDrinks || dbUser.role == 'admin');
				  
 				  var sessionTimeout = '1200 minutes';
                  self.cookie('xxxx', F.encrypt({
                      user: result.uid
                  }, 'user'), sessionTimeout);
                  F.cache.add('user_' + result.uid, user, sessionTimeout);
                  self.res.redirect('/');
                  F.model('user').update(result.uid, {
                      last_login: new Date().getTime()
                  });
                }
              else {
					sendEmail('info@photomenu.nl','photomenushares@gmail.com','Portal login failed','user login : ' + strLogin,'user: login' + strLogin);
					return self.view('login', {                        
					  login: self.body.login,
                      error: true
                    });
                   }
            })
        }).catch(function (err) {
            console.log(err);
			      sendEmail('info@photomenu.nl','photomenushares@gmail.com','Portal login error','error user login : ' + strLogin + ", " + err,'error user login: ' + strLogin + ", " + err);
            self.view('login', {
                login: self.body.login,
                error: true
            });
        });
};

function logout() {
    var self = this;
    var cookie = self.cookie('xxxx');
    var obj = F.decrypt(cookie, 'user');

//BEGIN sent email when restaurants logsout	
	F.model('user').load(obj.user).then(function (snapshot) {
    const current = snapshot.val();
	  var userfullname = current.name + ' (' + current.email + ')';
	  if (current.email!='info@photomenu.nl' && current.email!='info@robertimmers.nl' && current.email!='robert.immers@gmail.com') {	 
	    sendEmail('info@photomenu.nl','photomenushares@gmail.com','Portal logout','user: ' + userfullname,'user: ' + userfullname);
	  }
	});	
// END sent email 	
    F.firebaseAuth().signOut().then(function (res) {
        F.cache.add('user_' + obj.user, false, '-1 year');
        self.cookie('xxxx', '', new Date().add('-1 year'));
        self.res.redirect('/login');
    });
};