Example #1
0
var associateLoginId = module.exports.associateLoginId = function(ctx, loginId, userId, callback) {
    var validator = new Validator();
    _validateLoginIdForPersistence(validator, loginId);
    validator.check(null, {'code': 401, 'msg': 'You must be authenticated to associate a login id to a user.'}).isLoggedInUser(ctx);
    validator.check(userId, {'code': 400, 'msg': 'Must specify a user id'}).notEmpty();

    if (validator.hasErrors()) {
        return callback(validator.getFirstError());
    }

    var isAdmin = ctx.user().isAdmin(loginId.tenantAlias);
    var isTargetUser = (ctx.user().id === userId);

    if (!isAdmin && !isTargetUser) {
        // only admin and the user themself can associate a login id to the account
        return callback({'code': 401, 'msg': 'You cannot associate a login id to a user other than your own.'});
    }

    _getUserIdFromLoginId(loginId, function(err, existingUserIdMapping) {
        if (err) {
            return callback(err);
        } else if (existingUserIdMapping && !isAdmin) {
            // only admin can re-associate a login id to another user
            return callback({'code': 401, 'msg': 'Login ID is already associated to a user.'});
        }

        // verify we don't assign 2 ids of the same provider to a user
        _getUserLoginIds(userId, function(err, loginIds) {
            if (err) {
                return callback(err);
            } else if (loginIds[loginId.provider]) {
                return  callback({'code': 400, 'msg': 'User already has a login id of type ' + loginId.provider});
            }

            // ensure that the target user exists
            PrincipalsAPI.getUser(ctx, userId, function(err, user) {
                if (err) {
                    return callback(err);
                }

                if (!user) {
                    return callback({'code': 404, 'msg': 'User does not exist.'});
                }

                _associateLoginId(loginId, userId, function(err) {
                    if (err) {
                        callback(err);
                    } else {
                        log(ctx).info({
                            loginId: {
                                tenantAlias: loginId.tenantAlias,
                                provider: loginId.provider,
                                externalId: loginId.externalId
                            },
                            userId: userId
                        }, 'Mapped login id to user account.');
                        callback();
                    }
                });
            });
        });
    });
};
Example #2
0
function doAddMenu (req, res) {
	function complete(menu) {
		menu.name = req.body.name;
		menu.nameLowercase = req.body.name.toLowerCase();
		menu.priced = req.body.priced;
		menu.price = req.body.price;
		menu.description = req.body.description;
		menu.createdBy = req.user._id;
		
		// Courses
		menu.courses = [];
		var courses = req.body.courses;
		async.each(courses, function(course, cb) {
			var saveCourse = function (c) {
				c.name = course.name;
				c.nameLowercase = c.name.toLowerCase();
				c.priced = course.priced;
				c.price = course.price;
				c.createdBy = req.user._id
				
				menu.courses.push(c._id);
				
				c.items = [];
				if (!course.items || course.items.length == 0) {
					c.save();
					cb(null)
				} else {
					// Course Items
					async.each(course.items, function(item, cb2) {
						c.items.push(item._id)
						cb2(null)
					}, function() {
						c.save();
						cb(null)
					})
				}
			}
			
			if (course._id) {
				models.Course.findById(course._id, function(err, c) {
					if (err) {
						throw err;
					}
				
					if (!c) {
						saveCourse(new models.Course())
					} else {
						saveCourse(c)
					}
				})
			} else {
				saveCourse(new models.Course())
			}
		}, function() {
			menu.save()
			
			var menus = res.locals.restaurant.menus;
			var found = false;
			for(var i = 0; i < menus.length; i++) {
				if (menu._id.equals(menus[i]._id)) {
					found = true;
					break;
				}
			}
			
			if (!found) {
				res.locals.restaurant.menus.push(menu._id);
				res.locals.restaurant.save()
			}
			
			res.send({
				message: "Menu Saved!",
				_id: menu._id
			})
		})
	}
	
	var v = new Validator;
	var errors = [];
	var message = "";
	
	v.error = function(msg) {
		errors.push(msg)
		if (message.length > 0)
			message += ", "+msg;
		else
			message = msg
	}
	
	v.check(req.body.name, 'Menu Must Have a Name').notEmpty();
	req.body.priced = sanitize(req.body.priced).toBoolean();
	
	if (errors.length == 0) {
		try {
			models.Menu.findById(req.body._id, function(err, menu) {
				if (err || !menu) {
					complete(new models.Menu())
				} else {
					complete(menu)
				}
			})
		} catch (e) {
			complete(new models.Menu())
		}
	}
	else {
		res.send(400, {
			message: message
		})
	}
}
 req.check = function(param, fail_msg) {
   return validator.check(this.param(param), fail_msg);
 };
Example #4
0
 isValidGroup: function (group) {
   var validator = new Validator();
   validator.check(group.id, 'Name ist ein Pflichtfeld.').notEmpty();
   validator.check(group.id, 'Name muss mindestens 2 und höchstens 20 Zeichen enthalten.').len(2, 20);
   validator.check(group.id, 'Name darf nur Buchstaben, Zahlen, Bindestrich und Unterstrich enthalten.').regex(/^[\w-äöüß]+$/i);
   validator.check(group.emailPrefix, 'Präfix für E-Mails ist ein Pflichtfeld.').notEmpty();
   validator.check(group.emailPrefix, 'Präfix für E-Mails muss mindestens 5 und höchstens 15 Zeichen enthalten.').len(5, 15);
   validator.check(group.emailPrefix, 'Präfix für E-Mails darf nur Zahlen, Buchstaben, Leerzeichen und Bindestriche enthalten.').regex(/^[a-z0-9 -]+$/i);
   validator.check(group.longName, 'Titel ist ein Pflichtfeld.').notEmpty();
   validator.check(group.description, 'Beschreibung ist ein Pflichtfeld.').notEmpty();
   validator.check(group.type, 'Gruppenart ist ein Pflichtfeld.').notEmpty();
   return validator.getErrors();
 },
Example #5
0
exports.isEmail = function(email) {
    return !!validator.check(email).isEmail();
};
Example #6
0
var db = null
  , ObjectID = require('mongodb').ObjectID
  , bcrypt = require('bcrypt')
  , tasks = require('./tasks')
  , Validator = require('validator').Validator
  , validator = new Validator();

Validator.prototype.error = function (msg) {
  this._errorsDictionary = this._errorsDictionary || {};
  this._errorsDictionary[this.errorDictionary.param] = this.errorDictionary;
  return this;
}

Validator.prototype.getErrors = function () {
  return this._errorsDictionary;
}

validator.getErrors();

/**
 * validate users
 *
 * @param object user
 */
function validate(user, create) {
  validator._errorsDictionary = false;

  if(user.email !== undefined || create) {
    validator.check(user.email, {
      'param': 'email',
      'msg': 'Please enter a valid email address'
Example #7
0
	.path('title').validate(function(title) {
		if (!title) return this.invalidate('title', 'Title cannot be blank.');
		if (!val.check(title).len(2)) this.invalidate('title', 'Title must be at least 2 characters.');
	}, null);
Example #8
0
	.path('passwordHash').validate(function() {
		var password = this._password;
		if (!password || !val.check(password).len(6)) {
			this.invalidate('password', 'Password must be at least 6 characters.');
		}
	}, null);
Example #9
0
	.path('email').validate(function(v) {
		if (!val.check(v).isEmail()) {
			this.invalidate('email', 'Doesn\'t look like a valid Email.');
		}
	}, null);
 validator: function(val, next) {
     next(Validator.check(val)[method].apply(Validator, args));
 },
Example #11
0
exports.loanOfficerIndex = function(req, res) {
  //grab all the unassigned clients and create excel of them so they can be assigned 

  var v = new Validator();

  v.check(req.params.lenderId, 'lenderId not Number').regex(/^[0-9a-fA-F]{24}$/);
  var errors = v.getErrors();
  if (errors.length == 0) {
    async.parallel([

    function(cb) {
      dbFun.newlyCreatedClients(function(err, results) {
        if (!err) {
          req.session.numUnassigned = results.numUnassigned;
          cb(null, results);
        } //end of !err if
        else {
          cb(err, null);
        } //end of !err else
      }); //end of newlyCreatedClients
    }, //end of first parallel function

    function(cb) {
      dbFun.GrabAllLO(function(err, results) {
        if (!err) {
          cb(null, results);
        } //end of !err if
        else {
          cb(err, null);
        } //end of !err else
      }); //end of GrabAllLO
    }, //end of second parallel function

    function(cb) {
      dbFun.getLOClients(req.params.lenderId, function(err, results) {
        if (!err) {
          cb(null, results);
        } //end of !err if
        else {
          cb(err, null);
        } //end of !err else
      }); //end of getLOClients
    } //end of third parallel function
    ], //end of third async functions to compute

    function(allErr, allResults) {
      if (!allErr) {
        //REMOVED
        res.render('loanofficer/loanOfficerIndex.jade', {
          title: 'loanOfficerIndex',
          message: 'Loan Officer page loaded correctly',
          clients: allResults[2].clients,
          allLO: allResults[1],
          numUnassigned: allResults[0].numUnassigned,
          currentClientId: null,
          privileges: allResults[2].privileges
        });
        // res.render('loanOfficerUnassigned', {title: 'lender', message: 'Loan Officer page loaded correctly', unassigned: allResults[0], clients: null, allLO: allResults[1], numUnassigned : allResults[0].numUnassigned});
      } //end of !allErr
      else {
        //REMOVED
        console.log('router: loanOfficerIndex: unassigned page failed to load');
        res.render('loanofficer/loanOfficerIndex.jade', {
          title: 'loanOfficerIndex',
          message: 'Something faild in the back end',
          clients: null,
          allLO: null,
          numUnassigned: null,
          currentClientId: null
        });
      } //end of !allErr
    } //end of totalerr function
    ); //end of asyncparallel
  } else {
    res.redirect(400, '/');

  } //end of errors
}; //end of loanOfficerIndex
Example #12
0
 var check = function (item, msg) {      
   return validator.check(item, msg);
 }
Example #13
0
utils.validator = function(item, method) {
  var res = Validator.check(item)[method].apply(Validator, [].slice.call(arguments, 2));
  return !(res===false || res._errors.length);
}
Example #14
0
var argv = require('optimist')
    .default('ip', '0.0.0.0')  // listen to all interfaces
    .default('port', '8888')
    .boolean('local_only')  // force --ip=127.0.0.1
    .boolean('mitm_proxy')  // for debug use; no access control
    .boolean('nolog')       // do not show network logs
    .boolean('production')  // pre-set configs for production server
    .argv
;
var colors = require('colors');


// check input parameters
var Validator = require('validator').Validator;
var vld = new Validator();
vld.error = function(msg) {
    console.error(msg.red);
    process.exit(1);
};
var sanitize = require('validator').sanitize;

vld.check(argv.ip, 'Invalid input for IP address.').isIP();
vld.check(argv.port, 'Invalid input for port number.').isNumeric();
if (argv.ext_ip) {  // custom IP/domain address in the PAC file, in case the proxy server is behind a router or firewall
    // vld.check(argv.ext_ip, 'Invalid input for external IP address.').isIP();
    if (argv.ext_ip !== sanitize(argv.ext_ip).escape()) {
        console.error('Invalid input for external IP/domain address.'.red);
        process.exit(1);
    }
}
Example #15
0
 return this.add(function(value) {
   return ValidatorPrototype[name].apply(externalValidator.check(value, message), args);
 });
exports.add = function(req,res){

    var serverKey = req.param("serverKey");
    var thisIsNotNullWhenUpdating = null;

    var v = new Validator();
    v.error = function(msg) {
        res.writeHead(500,{'content-type':'text/html'});
        res.end(msg);
        return;
    }

    if(req.param("update")!=null){

        console.log("updating endpoint "+req.param("update"));

        v.check(req.param("update"),"invalid key "+req.param("update")+" to update endpoint").notNull().isAlphanumeric();

        thisIsNotNullWhenUpdating = req.param("update");

    }else if(req.param("delete")!=null){

        console.log("deleting endpoint "+req.param("delete"));

        v.check(req.param("delete"),"invalid key "+req.param("delete")+" to delete endpoint").notNull().isAlphanumeric();

        endpoints.remove(req.param("delete"), function (err) {
            if (err) {
                res.end("could not delete "+err );
            }else{
                res.redirect('/servers/'+serverKey);
            }

        });

    }

    req.onValidationError(function (msg) {
        res.end(msg);
    });


    if(req.param("delete")==null){

        servers.getServerList(function(listOfServers){

            var existingServerKeys = [];
            for(var i=0; i<listOfServers.length; i++){
                existingServerKeys.push(listOfServers[i].key);
            }

            console.log("existingServerKeys-ho",existingServerKeys);

            req.assert('serverKey', 'invalid server key').notEmpty();
            req.assert('serverKey','server '+serverKey+' does not exist').isIn(existingServerKeys);
            //req.checkBody('path', 'invalid path').notEmpty().notContains("?").notContains("&");
            req.checkBody('defaultResponse', 'invalid defaultResponse').notEmpty();
            req.checkBody('enabled', 'invalid enabled status').notEmpty().isIn(['Enabled','Disabled']);
            req.checkBody('httpStatusCode','invalid HTTP status code').notEmpty().isNumeric();
            req.checkBody('contentType','invalid HTTP status code').notEmpty();
            req.checkBody('delay','invalid delay').notEmpty().isNumeric().min(0);


            if(req.validationErrors()==null){
                var newEndpoint = {
                    enabled:(req.body.enabled=="Enabled"?true:false),
                    path:req.body.path,
                    defaultResponse:req.body.defaultResponse,
                    serverKey:serverKey,
                    httpStatusCode:req.body.httpStatusCode,
                    contentType:req.body.contentType,
                    delay:req.body.delay
                };

                console.log("thisIsNotNullWhenUpdating "+thisIsNotNullWhenUpdating);

                endpoints.save(thisIsNotNullWhenUpdating,newEndpoint,function(err, key){
                    if (err) { throw err; }else{
                        console.log("created endpoint "+key);
                        res.redirect('/servers/'+serverKey);
                    }
                });
            }



        });

    }
}
Example #17
0
exports = module.exports = function(app, config) {

  var platform = config.platform;
  var asset = platform.asset;
  var assetHost = asset.subdomain + '.' + platform.host;
  var assetUrl = assetHost + asset.path;
  var accountAppString = platform.account + '/' + platform.app;
  var gaAccount = config.ga.account;
  var gaDomain = config.ga.domain;

  var jwtSimple = require('jwt-simple');
  var util = require('util');
  var crypto = require('crypto');
  var Validator = require('validator').Validator;
  var sanitize = require('validator').sanitize;

  var SendGrid = require('sendgrid');
  var twilio = require('twilio');

  var sendGrid;
  if (config.sendgrid.user && config.sendgrid.password) {
    sendGrid = new SendGrid(
      config.sendgrid.user,
      config.sendgrid.password,
      config.sendgrid.options
    );
  }

  var twilioClient;
  if (config.twilio.accountSid && config.twilio.auth_token) {
    twilioClient = new twilio.RestClient(
      config.twilio.accountSid,
      config.twilio.auth_token
    );
  }

  // Prevents throwing an exception
  Validator.prototype.error = function() {
    return false;
  };

  var validator = new Validator();

  app.get('/', function(req, res) {
    var sessionId = req.session.sessionId || null;
    var user = req.session.user;

    return res.render('homepage', {
      sessionId: sessionId,
      user: user
    });
  });

  app.get('/thankyou', function(req, res) {
    return res.render('thankyou');
  });

  app.get('/map/:session', authenticationValid, function(req, res) {
    var token = req.session.user.token;
    var sessionId = req.session.sessionId = req.params.session;

    var data = {
      platformHost: assetHost,
      platformAsset: assetUrl,
      platformConnect: platform.host + '/' + accountAppString,
      platformToken: token,
      sessionId: sessionId,
      gaAccount: gaAccount,
      gaDomain: gaDomain
    };

    return res.render('map', data);
  });

  app.get('/hiw-demo/:session/:user', function(req, res) {
    var name = req.params.user;
    var session = req.params.session;

    var validId = validator.check(session).is(/^(?:hiw-)?\d{5}$/);
    if (!validId) {
      return error(res, "Invalid sessionId");
    }

    // These are the only 2 valid user params, only used for how it works demo.
    if (name !== "User 1" && name !== "User 2") {
      return error(res, "Invalid demo user");
    }

    generateUid(name, function(uid, token) {
      var data = {
        platformHost: assetHost,
        platformAsset: assetUrl,
        platformConnect: platform.host + '/' + accountAppString,
        platformToken: token,
        sessionId: session,
        index: uid,
        gaAccount: gaAccount,
        gaDomain: gaDomain
      };

      return res.render('hiw-demo', data);
    });
  });

  app.post('/auth', function(req, res) {
    var displayName = sanitize(req.body.displayName).xss();

    generateUid(displayName, function(uid, token) {
      req.session.user = {
        name: displayName,
        uid: uid,
        token: token
      };

      if (!req.session.sessionId) {
        req.session.sessionId = randomNumber();
      }

      req.session.save(function() {
        res.redirect('/map/' + req.session.sessionId);
      });
    });
  });

  app.post('/invite/sms', authenticationValid, function(req, res) {
    if (!twilioClient) {
      res.statusCode = 500;
      return res.send('Twilio is not configured');
    }

    var sessionId = req.session.sessionId;

    var inviteUrl = req.protocol + '://' + req.host + '/map/' + sessionId;

    var number = req.body.number;
    var validNumber = validator.check(number).is(/^(?:\+\d)?\d{10}$/);
    if (!validNumber) {
      return error(res, "Invalid SMS number");
    }

    var username = sanitize(req.session.user.name).xss();

    var opts = {
      to: req.body.number,
      from: config.twilio.number,
      body: util.format(
          config.twilio.invite_body,
          username,
          inviteUrl
        )
    };

    twilioClient.sms.messages.create(opts, function(err) {
      if (err) {
        res.statusCode = 500;
        return res.send(err.message);
      }
      res.send('OK');
    });
  });

  app.post('/invite/email', authenticationValid, function(req, res) {
    if (!sendGrid) {
      res.statusCode = 500;
      return res.send('SendGrid is not configured');
    }

    var sessionId = req.session.sessionId;

    var inviteUrl = req.protocol + '://' + req.host + '/map/' + sessionId;

    var email = req.body.email;
    var validLen = validator.check(email).len(6, 64);
    var validEmail = validator.check(email).isEmail();
    if (!validLen || !validEmail) {
      return error(res, "Invalid email");
    }

    var username = sanitize(req.session.user.name).xss();

    sendGrid.send({
      to: email,
      from: config.sendgrid.from,
      subject: config.sendgrid.subject,
      html: util.format(
        config.sendgrid.invite_body,
        username,
        username,
        inviteUrl,
        username,
        username)
    }, function(success, message) {

      /* TODO: This is a little gross but success returns null on success, will submit a PR to fix */
      if (message.message !== 'success') {
        res.statusCode = 500;
        return res.send(message);
      }
      res.send(message);
    });
  });

  function error(res, msg) {
    res.statusCode = 400;
    res.send('Error: ' + msg);
  }

  function createJwt(name, uid) {
    var secret = new Buffer(config.platform.secret, 'base64');
    var claims = {
      iss: config.platform.iss,
      sub: ''+ uid, //TODO: When #629 is done this doesn't need to be a string.
      dn: name
    };

    return jwtSimple.encode(claims, secret);
  }

  function authenticationValid(req, res, next) {

    // validate the session param
    if (req.params.session) {
      var validId = validator.check(req.params.session).is(/^\d{5}$/);
      if (!validId) {
        return error(res, "Invalid sessionId");
      }
    }

    if (req.session.user && req.session.user.token) {
      return next();

    } else {
      req.session.sessionId = req.params.session;
      res.redirect('/');
    }
  }

  function randomNumber() {
    return Math.floor(Math.random() * 90000) + 10000;
  }

  function generateUid(name, cb) {
    crypto.randomBytes(20, function(err, buf) {
      var uid = buf.toString('hex');
      var token = createJwt(name, uid);

      cb(uid, token);
    });
  }
};
    endpoints.all(function (err, results) {
        var allEndpoints = [];
        var allEndpointKeys = [];
        var currentEndpointData = null;

        for (var key in results) {

            var i_endpoint = results[key]
            i_endpoint.key = key;

            allEndpoints[allEndpoints.length] = i_endpoint;
            allEndpointKeys[allEndpointKeys.length] = key;

            if(i_endpoint.key == endpointKey){
                serverKeyOfEndpoint = i_endpoint.serverKey;
                currentEndpointData = i_endpoint;
            }
        }

        //console.log("endps "+allEndpointKeys);

        req.assert('endpointKey', 'invalid endpoint key').notEmpty();
        req.assert('endpointKey','endpoint '+endpointKey+' does not exist').isIn(allEndpointKeys);
        v.check(serverKeyOfEndpoint,"invalid server key "+serverKeyOfEndpoint).isAlphanumeric().notEmpty();

        servers.getServerList(function (serverList) {

            v.check(serverList,"cannot get list of servers ").len(0);
            v.check(serverKeyOfEndpoint,"cannot find server "+serverKeyOfEndpoint).notNull();

            servers.getServer(serverKeyOfEndpoint,function(serverData){

                //console.log("endpoint "+util.inspect(endpoint));



                var params = currentEndpointData;

                var parsedJSON = null;

                try{
                    parsedJSON = JSON.parse(params.defaultResponse);
                }catch(e){
                    console.log("defaultresponse is not json");
                }

                if(parsedJSON){
                    params.defaultResponse = JSON.stringify(parsedJSON,null,4);
                }





                params.servers = serverList;
                params.server = {
                    key:serverData.key,
                        name:serverData.name
                };

                res.render('addEndpoint',params);

            });
        });
    });
Example #19
0
	.path('body').validate(function(body) {
		if (!body) return this.invalidate('body', 'Content cannot be blank.');
		if (!val.check(body).len(10)) this.invalidate('body', 'Content must be at least 10 characters.');
	}, null);
Example #20
0
  isValidForActivity: function (activityInput) {
    var validator = new Validator();
    var nonEmptyResourceNames = activityInput.resources ? _.compact(misc.toArray(activityInput.resources.names)) : [];
    var nonEmptyResourceLimits = activityInput.resources ? _.compact(misc.toArray(activityInput.resources.limits)) : [];

    validator.check(activityInput.url, 'URL ist ein Pflichtfeld.').notEmpty();
    validator.check(activityInput.title, 'Titel ist ein Pflichtfeld.').notEmpty();
    validator.check(activityInput.location, 'Veranstaltungsort ist ein Pflichtfeld.').notEmpty();
    validator.check(activityInput.startDate, 'Startdatum ist ein Pflichtfeld.').notEmpty();
    validator.check(activityInput.startTime, 'Startuhrzeit ist ein Pflichtfeld.').notEmpty();
    validator.check(activityInput.endDate, 'Endedatum ist ein Pflichtfeld.').notEmpty();
    validator.check(activityInput.endTime, 'Enduhrzeit ist ein Pflichtfeld.').notEmpty();
    _.each(nonEmptyResourceLimits, function (limit) { validator.check(limit, 'Die Ressourcenbeschränkungen dürfen nur aus Ziffern bestehen.').isInt(); });

    if (nonEmptyResourceNames.length === 0) {
      validator.error('Es muss mindestens eine Ressourcenbezeichnung angegeben werden.');
    }
    if (nonEmptyResourceNames.length !== _.uniq(nonEmptyResourceNames).length) {
      validator.error('Die Bezeichnungen der Ressourcen müssen eindeutig sein.');
    }

    var startUnix = fieldHelpers.parseToUnixUsingDefaultTimezone(activityInput.startDate, activityInput.startTime);
    var endUnix = fieldHelpers.parseToUnixUsingDefaultTimezone(activityInput.endDate, activityInput.endTime);

    if (startUnix >= endUnix) {
      validator.error('Start muss vor Ende liegen.');
    }

    return validator.getErrors();
  },
Example #21
0
 isValidMember: function (member) {
   var validator = new Validator();
   validator.check(member.nickname, 'Nickname ist ein Pflichtfeld.').notEmpty();
   validator.check(member.nickname, 'Nickname muss mindestens 2 Zeichen enthalten.').len(2);
   validator.check(member.firstname, 'Vorname ist ein Pflichtfeld.').notEmpty();
   validator.check(member.lastname, 'Nachname ist ein Pflichtfeld.').notEmpty();
   validator.check(member.email, 'E-Mail ist ein Pflichtfeld.').notEmpty();
   validator.check(member.email, 'E-Mail muss gültig sein.').isEmail();
   validator.check(member.location, 'Ort / Region ist ein Pflichtfeld.').notEmpty();
   validator.check(member.reference, 'Wie ich von... ist ein Pflichtfeld.').notEmpty();
   validator.check(member.profession, 'Beruf ist ein Pflichtfeld.').notEmpty();
   return validator.getErrors();
 },
Example #22
0
 _.each(nonEmptyResourceLimits, function (limit) { validator.check(limit, 'Die Ressourcenbeschränkungen dürfen nur aus Ziffern bestehen.').isInt(); });
Example #23
0
 isValidMessage: function (message) {
   var validator = new Validator();
   validator.check(message.subject, 'Subject ist ein Pflichtfeld.').notEmpty();
   validator.check(message.markdown, 'HTML-Text ist ein Pflichtfeld.').notEmpty();
   return validator.getErrors();
 }
Example #24
0
 $('#submit').on('click',function(){
   if($(this).hasClass('disabled')) return;
   /*
    * 信息验证
    * 1、域名不为空且符合规则
    * 2、端口可以为空
    * 3、文件至少一个且已上传成功,体现在这里就是files不为空
    * */
   var data={};
     data.domain=$.trim($('#domainAdd').val());
     data.port=$.trim($('#port').val());
     data.files=JSON.stringify(window.files);
     /*
      * files中的信息为:
      * {
      *   infAdd:'接口地址',
      *   filePath:'服务器暂存地址',
      *   fileId:上传队列中生成的每个文件的唯一ID
      * }
      * fileId需要传的唯一原因就是在后端存储数据库失败时要在前端做标识。因为文件已通过验证,数据库的出错概率较低,所以此时允许部分失败。
      * */
     var validator=new Validator({
       domain:{
         required:true,
         domain:true
       },
       port:{
         required:true,
         port:true
       },
       files:{
         defined:true,
         notEmptyArray:true
       }
     });
     validator.addValidation('domain',function(r){
       if(r){
         if(!(/^[a-zA-Z]{5,10}$/.test(this.value))){
           return {
             status:false,
             msg:'请输入正确的网站名称!'
           }
         }else{
           return {
             status:true
           }
         }
       }
     })
     validator.addValidation('notEmptyArray',function(r){
       if(r){
         if(this.value.length<1){
           return {
             status:false,
             msg:'文件不存在!'
           }
         }else{
           return {
             status:true
           }
         }
       }
     });
     validator.addValidation('defined',function(r){
       if(r){
         if(typeof this.value=='undefined'){
           return {
             status:false,
             msg:'文件不存在!'
           }
         }else{
           return {
             status:true
           }
         }
       }
     });
     var toValidate={
       domain:{
         value:data.domain,
         note:$('#note_domainAdd')
       },
       port:{
         value:data.port,
         note:$('#note_port')
       },
       files:{
         value:window.files,
         note:$('#note_files')
       }
     }
     if(!validator.validate(toValidate).passed) return;
   $('.loading').show();
   Promise.resolve($.ajax({
     url:'/Post/P/save',
     type:'post',
     data:data,
     dataType:'json'
   })).then(function(data){
     if(data.errno){
       var detail=data.data;
       for(var i=0;i<detail.length;i++){
         if(!detail[i].errdata){
           $('#'+detail[i].fileId).append('<td>&radic;</td>');
         }else{
           $('#'+detail[i].fileId).append('<td>&chi;</td>').attr('title','错误代码:'+detail[i].errdata.errno);
         }
       }
       $('#note').html('<b class="message_error"></b>'+data.errmsg).show();
     }else{
       $('#fileList tbody tr').append('<td>&radic;</td>');
       $('#note').html('<b class="message_success"></b>'+data.msg).show();
     }
     /*改变整个页面的上传状态tag*/
     lastUpload=true;
     $('.loading').hide();
   }).catch(function(err){
     alert('请求出错');
     lastUpload=true;
   })
 })