Example #1
0
exports.createUser = function (req, res, next) {


    var user = new User();
    user.email =  req.body.email;
    user.password = req.body.password;
    user.username = req.body.username;

    if(tools.isEmpty(user.email)||tools.isEmpty(user.password)){
        return res.json(Results.ERR_PARAM_ERR);
    }

    user.password = md5(user.password);


    var ep = new EventProxy();
    ep.all('checkEmail','checkUsername', function () {
        user.save(function (err, user) {

            if (err)
                res.json({result:false,err:err});
            else
                res.json({
                    result: true,
                    id: user.id
                });
        });
    });

    ep.fail(function (err) {
        res.json({
            result: false,
            err: err
        });
    });

    User.findOne({
        email: user.email
    }, function (err, item) {
        if (item != null) {
            ep.emit("error", 'ERR_EXISTED_EMAIL');
        } else {
            ep.emit('checkEmail');
        }
    });
    
    User.findOne({
        username: user.username
    }, function (err, item) {
        if (item != null) {
            ep.emit("error", 'ERR_EXISTED_NAME');
        } else {
            ep.emit('checkUsername');
        }
    });
    
};
Example #2
0
  User.getUserByName(user_name, function(err, user) {
    if (!user) {
      res.render('notify/notify', {
        error: '这个用户不存在。'
      });
      return;
    }

    var render = function(topics, relation, pages) {
      user.friendly_create_at = Util.format_date(user.create_at, true);
      res.render('user/replies', {
        user: user,
        topics: topics,
        relation: relation,
        current_page: page,
        pages: pages
      });
    };

    var proxy = new EventProxy();
    proxy.assign('topics', 'relation', 'pages', render);
    proxy.fail(next);

    Reply.getRepliesByAuthorId(user._id, proxy.done(function(replies) {
      // 获取所有有评论的主题
      var topic_ids = [];
      for (var i = 0; i < replies.length; i++) {
        if (topic_ids.indexOf(replies[i].topic_id.toString()) < 0) {
          topic_ids.push(replies[i].topic_id);
        }
      }
      var query = {
        '_id': {
          '$in': topic_ids
        }
      };
      var opt = {
        skip: (page - 1) * limit,
        limit: limit,
        sort: [
          ['create_at', 'desc']
        ]
      };
      Topic.getTopicsByQuery(query, opt, proxy.done('topics'));

      Topic.getCountByQuery(query, proxy.done(function(all_topics_count) {
        var pages = Math.ceil(all_topics_count / limit);
        proxy.emit('pages', pages);
      }));
    }));

    if (!req.session.user) {
      proxy.emit('relation', null);
    } else {
      Relation.getRelation(req.session.user._id, user._id, proxy.done('relation'));
    }
  });
Example #3
0
exports.signUp = function(req, res, next) {
	var ep = new EventProxy();		

	ep.on('sign_up_error', function(errcode, message) {
		var rdata = {
			errcode: errcode,
			message: message
		};
		res.json(rdata);
		
	});
	ep.fail(next);

	var account    = validator.trim(req.body.account).toLowerCase();
	var email      = validator.trim(req.body.email);
	var nick_name  = validator.trim(req.body.nick_name); 
	var password   = validator.trim(req.body.password);
	var rePassword = validator.trim(req.body.rePassword);

	if ( [account, email, nick_name, password, rePassword].some(function(item) { return item === '' }) ) {
		return ep.emit('sign_up_error', 422, '信息填写不完整');
	}

	if (!validator.isEmail(email))
    	return ep.emit('sign_up_error', 422, '邮箱不合法');

  	if ( password !== rePassword )
	    return ep.emit('sign_up_error', 422, '两次密码输入不一致。');

	var query = {
		'$or': [
			{account : account},
			{email   : email}
		]
	};

	User.getUsersByQuery(query, {}, function(err, user) {		
		if ( err )
			return next(err);

		if ( user.length )
			return ep.emit('sign_up_error', 422, '登录名或者邮箱被占用');

	    tools.bhash(password, function (err, passhash) {
		    User.newAndSave(account, passhash, email, nick_name, function (err) {
    	    	if (err)
          			return next(err);

          		var rdata = {
          			errcode: 0,
          			message: '注册成功'
          		};
          		res.json(rdata);
      		});
      	});
	});
}
Example #4
0
exports.login = function (req, res, next) {
  var loginname = validator.trim(req.body.name).toLowerCase();
  var pass      = validator.trim(req.body.pass);
  var ep        = new eventproxy();

  ep.fail(next);

  if (!loginname || !pass) {
    res.status(422);
    return res.render('sign/signin', { error: '信息不完整。' });
  }

  var getUser;
  if (loginname.indexOf('@') !== -1) {
    getUser = User.getUserByMail;
  } else {
    getUser = User.getUserByLoginName;
  }

  ep.on('login_error', function (login_error) {
    res.status(403);
    res.render('sign/signin', { error: '用户名或密码错误' });
  });

  getUser(loginname, function (err, user) {
    if (err) {
      return next(err);
    }
    if (!user) {
      return ep.emit('login_error');
    }
    var passhash = user.pass;
    tools.bcompare(pass, passhash, ep.done(function (bool) {
      if (!bool) {
        return ep.emit('login_error');
      }
      if (!user.active) {
        // 重新发送激活邮件
        mail.sendActiveMail(user.email, utility.md5(user.email + passhash + config.session_secret), user.loginname);
        res.status(403);
        return res.render('sign/signin', { error: '此帐号还没有被激活,激活链接已发送到 ' + user.email + ' 邮箱,请查收。' });
      }
      // store session cookie
      authMiddleWare.gen_session(user, res);
      //check at some page just jump to home page
      var refer = req.session._loginReferer || '/';
      for (var i = 0, len = notJump.length; i !== len; ++i) {
        if (refer.indexOf(notJump[i]) >= 0) {
          refer = '/';
          break;
        }
      }
      res.redirect(refer);
    }));
  });
};
Example #5
0
var show = function (req, res, next) {
  var topicId  = String(req.params.id);

  var mdrender = req.query.mdrender === 'false' ? false : true;
  var ep       = new eventproxy();

  if (!validator.isMongoId(topicId)) {
    res.status(422);
    return res.send({
      error_msg: 'not valid topic id',
    });
  }

  ep.fail(next);

  TopicProxy.getFullTopic(topicId, ep.done(function (msg, topic, author, replies) {
    if (!topic) {
      return res.send({error_msg: 'topic_id `' + topicId + '` is not exists.'});
    }
    topic = _.pick(topic, ['id', 'author_id', 'tab', 'content', 'title', 'last_reply_at',
      'good', 'top', 'reply_count', 'visit_count', 'create_at', 'author']);

    if (mdrender) {
      topic.content = renderHelper.markdown(at.linkUsers(topic.content));
    }
    topic.author = _.pick(author, ['loginname', 'avatar_url']);

    topic.replies = replies.map(function (reply) {
      if (mdrender) {
        reply.content = renderHelper.markdown(at.linkUsers(reply.content));
      }
      reply.author = _.pick(reply.author, ['loginname', 'avatar_url']);
      reply =  _.pick(reply, ['id', 'author', 'content', 'ups', 'create_at', 'reply_id']);
      reply.reply_id = reply.reply_id || null;
      return reply;
    });

    ep.emit('full_topic', topic)
  }));


  if (!req.user) {
    ep.emitLater('is_collect', null)
  } else {
    TopicCollect.getTopicCollect(req.user._id, topicId, ep.done('is_collect'))
  }

  ep.all('full_topic', 'is_collect', function (full_topic, is_collect) {
    full_topic.is_collect = !!is_collect;

    res.send({data: full_topic});
  })



};
Example #6
0
File: qun.js Project: fluagen/ownc
exports.join = function(req, res, next) {

    var qid = req.params.qid;
    var code = req.params.code;
    var user = req.session.user;
    var ep = new EventProxy();
    var alerts = [];
    if (user.alerts) {
        alerts = user.alerts;
    }
    ep.fail(next);
    ep.all('invitation', 'qun', function(invitation, qun) {
        if (!invitation || !qun) {
            alerts.push({
                text: '邀请码已被使用或已过期',
                type: 'alert-warning'
            });
            user.alerts = alerts;
            return res.redirect('/');
        }
        if (tools.is_member(qun.members, user)) {

            alerts.push({
                text: '你已经是群内成员,不可重复加入',
                type: 'alert-warning'
            });
            user.alerts = alerts;

            return res.redirect('/qun/' + qid);

        }
        invitation.remove();
        qun.members.push({
            'id': user.loginid,
            'type': 2
        });
        qun.save();

        alerts.push({
            text: '你成功加入了 ' + qun.name,
            type: 'alert-warning'
        });
        user.alerts = alerts;

        return res.redirect('/qun/' + qid);
    });

    Invitation.findOne({
        code: code,
        qun_id: qid
    }, ep.done('invitation'));

    Qun.findOne({
        id: qid
    }, ep.done('qun'));
};
Example #7
0
  User.getUserByLoginName(user_name, function (err, user) {
    if (err) {
      return next(err);
    }
    if (!user) {
      res.render404('这个用户不存在。');
      return;
    }

    var render = function (recent_topics, recent_replies) {
      user.url = (function () {
        if (user.url && user.url.indexOf('http') !== 0) {
          return 'http://' + user.url;
        }
        return user.url;
      })();
      // 如果用户没有激活,那么管理员可以帮忙激活
      var token = '';
      if (!user.active && req.session.user && req.session.user.is_admin) {
        token = utility.md5(user.email + user.pass + config.session_secret);
      }
      res.render('user/index', {
        user: user,
        recent_topics: recent_topics,
        recent_replies: recent_replies,
        token: token,
        pageTitle: util.format('@%s 的个人主页', user.loginname),
      });
    };

    var proxy = new EventProxy();
    proxy.assign('recent_topics', 'recent_replies', render);
    proxy.fail(next);

    var query = {author_id: user._id};
    var opt = {limit: 5, sort: '-create_at'};
    Topic.getTopicsByQuery(query, opt, proxy.done('recent_topics'));

    Reply.getRepliesByAuthorId(user._id, {limit: 20, sort: '-create_at'},
      proxy.done(function (replies) {

        var topic_ids = replies.map(function (reply) {
          return reply.topic_id.toString()
        })
        topic_ids = _.uniq(topic_ids).slice(0, 5); //  只显示最近5条

        var query = {_id: {'$in': topic_ids}};
        var opt = {};
        Topic.getTopicsByQuery(query, opt, proxy.done('recent_replies', function (recent_replies) {
          recent_replies = _.sortBy(recent_replies, function (topic) {
            return topic_ids.indexOf(topic._id.toString())
          })
          return recent_replies;
        }));
      }));
  });
Example #8
0
var count = function (req, res, next) {
  var userId = req.user.id;

  var ep = new eventproxy();
  ep.fail(next);

  Message.getMessagesCount(userId, ep.done(function (count) {
    res.send({data: count});
  }));
};
Example #9
0
  it('fail should pass multi args', function () {
    var ep = new EventProxy();
    ep.fail(function (err, arg) {
      assert.equal(arguments.length, 2, 'fail handler should get two args');
      assert.equal(err, 'custom_error');
      assert.equal(arg, 200);
    });

    ep.emit('error', 'custom_error', 200);
  });
Example #10
0
function getAll(cityOrCode, callback){
    var ep = new EP();
    ep.all('seven', 'realtime', function(seven, realtime){
        callback(null, seven, realtime);
    });
    ep.fail(callback);

    getSeven(cityOrCode, ep.done('seven') );
    getRealtime(cityOrCode, ep.done('realtime') );
}
Example #11
0
 		[have_read, not_read].forEach(function (msgs, idx) {
 			var epfill = new EventProxy();
 			epfill.fail(next);
 			epfill.after('message_ready', msgs.length, function (docs) { 
 				ep.emit(idx === 0 ? 'have_read_msg' : 'not_read_msg', docs);
 			});
 			msgs.forEach(function (doc) {
 				MessageDao.getDetailMessageById(doc._id, epfill.group('message_ready'));
 			});
 		});
Example #12
0
router.get('/fail', function (req, res) {
    var ep = new EventProxy();
    ep.fail(function (err) {
        res.send(`failed, error is ${err}`);
    });

    setTimeout(function (error) {
        ep.emit('error', error);
    }, 1000, '1000 error');
});
Example #13
0
function ringGroupsList(req, res, next) {
  var ep = new EventProxy();
  ep.all('rgsData', function(rgsData) {
    res.json(util.parseJSON(rgsData)).end();
  });
  ep.fail(function(err, errMsg) {
    res.json({err_code:'500', msg:err.msg || errMsg }).end();
  });
  apiRingGroups.ringGroupsList(req.query, util.done('rgsData', ep, 'ringGroupsList ERROR'));
}
Example #14
0
exports.login = function (req, res, next) {
  var loginname = validator.trim(req.body.name).toLowerCase();
  var pass = validator.trim(req.body.pass);
  var ep = new eventproxy();
  ep.fail(next);

  if (!loginname || !pass) {
    res.status(422);
    return res.render('sign/signin', { error: ' Incomplete information 。' });
  }

  var getUser;
  if (loginname.indexOf('@') !== -1) {
    getUser = User.getUserByMail;
  } else {
    getUser = User.getUserByLoginName;
  }

  ep.on('login_error', function (login_error) {
    res.status(403);
    res.render('sign/signin', { error: ' User name or password error ' });
  });

  getUser(loginname, function (err, user) {
    if (err) {
      return next(err);
    }
    if (!user) {
      return ep.emit('login_error');
    }
    var passhash = user.pass;
    tools.bcompare(pass, passhash, ep.done(function (bool) {
      if (!bool) {
        return ep.emit('login_error');
      }
      if (!user.active) {
        //  Again  Send activation email 
        mail.sendActiveMail(user.email, utility.md5(user.email + passhash + config.session_secret), user.loginname);
        res.status(403);
        return res.render('sign/signin', { error: ' This account has not been activated , Activation link has been sent to  ' + user.email + '  Mailbox , Please check 。' });
      }
      // store session cookie
      authMiddleWare.gen_session(user, res);
      //check at some page just jump to home page
      var refer = req.session._loginReferer || '/';
      for (var i = 0, len = notJump.length; i !== len; ++i) {
        if (refer.indexOf(notJump[i]) >= 0) {
          refer = '/';
          break;
        }
      }
      res.redirect(refer);
    }));
  });
};
Example #15
0
// 管理首页(默认是吐槽管理)
function index(req, res, next){
    if( !util.checkAdmin(res, '无权限') ) return;

    var ep = new EventProxy(),
        page = parseInt(req.query.page) || 1,
        limit = config.limit,
        opt = {skip: (page - 1) * limit, limit: limit, sort: [['_id', 'desc']]};

    ep.all('topicList', 'totalCount', 'totalTopicNum', function(topicList, totalCount, totalTopicNum){
        var pagination = util.pagination(page, totalCount);
        res.render('admin/index', {
            title: '后台管理 - '+ config.name,
            config: config,
            topics: topicList,
            pagination: pagination,
            total: totalTopicNum,
            layout: 'admin/admin_layout'
        });
    });
    ep.fail(next);

    topicProxy.getMainTopic('', opt, ep.done(function(topicList){
        var topicLen = topicList.length, arr = [];
        for(var i = 0; i < topicLen; i++){
            if(!topicList[i].replyTo){
                arr.push(topicList[i]);
            }
        };

        // 如果用户设置了昵称,则优先显示昵称
        // 将昵称与头像附加到主题对象
        ep.after('toAll', arr.length, function(){
            ep.emit('topicList', arr);
        });

        // 获取当前主题的作者昵称与头像
        arr.forEach(function(cur){
            userProxy.getOneUserInfo({_id : cur.author_id}, 'name nickName head', ep.done(function(user){
                var nickName = user.nickName, time = cur.create_time;

                cur.author_nickName = nickName ? nickName : user.name;
                cur.head = user.head ? user.head : config.nopic;
                cur.create_time = new Date(time).format('MM月dd日 hh:mm');

                ep.emit('toAll');
            }));
        });
    }));

    // 取得总页数
    topicProxy.getTopicCount(ep.done(function(totalCount){
        ep.emit('totalCount', Math.ceil(totalCount / limit));
        ep.emit('totalTopicNum', totalCount);
    }));
};
Example #16
0
exports.addProfile = function(req, res, next) {
	var ep = new EventProxy();

	ep.fail(next);
	ep.on('add_profile_error', function(errcode, message) {
		var rdata = {
			errcode: errcode,
			message: message
		};
		res.json(rdata);
	});

	var userid     = req.session.user._id;

	var avatar     = req.body.avatar;
	var profile    = req.body.profile;
	var experience = req.body.experience;   		
	var hobby      = req.body.hobby;
	var hate       = req.body.hate
	var thinking   = req.body.thinking;
	var education  = req.body.education;

	if ( !avatar || !profile )
		return ep.emit('update_profile_error', 422, '请输入头像和简介');

	if ( [experience, hobby, hate, thinking, education].some(function(item) {return !Array.isArray(item)}) )
		return ep.emit('update_profile_error', 422, 'experience,hobby,hate,thinking必须是数组');

	User.getUserById(userid, ep.done(function(user) {
		if ( !user )
			return ep.emit('update_profile_error', 422, '用户不存在');

		if ( req.session.user.role !== 'manager' && user._id !== userid )
				return ep.emit('del_note_book_error', 403, '没有权限');

		ep.emit('user_check', user);
	}));

	ep.on('user_check', function() {
		Profile.getProfileByUserId(user._id, ep.done(function(profile) {
			if ( profile )
				return ep.emit('update_profile_error', 422, '该用户的profile已经存在');

			Profile.newAndSave(userid, avatar, profile, experience, hobby, hate, thinking, education, ep.done(function() {
				profile.save(ep.done(function() {
					var rdata = {
						errcode: 0,
						message: '创建成功'
					};
					res.json(data);
				}));
			}));
		}));
	});
}
Example #17
0
/**
 * 校验文件是否可以删除
 * @param  {[type]}   user     [description]
 * @param  {[type]}   file     [description]
 * @param  {Function} callback [description]
 * @return {[type]}            [description]
 */
function verifyDelete(user, file, callback){

    // 普通用户只能删除自己的; 管理员可以删除所有; 部门和小组管理员可以删除所有

    var msg = 'not auth to delete this file, fileId: ' + file._id;
    var hasAuth = true;

    var ep = new EventProxy();
    ep.fail(callback);

    if(user._id.toString() === file.creator.oid.toString()){

        // 自己创建的文件
        user.__role |= config.ROLE_FILE_CREATOR;
        hasAuth = true;

    }

    mFolder.getFolder({ _id: file.folder.oid }, ep.doneLater('getFolder'));

    ep.on('getFolder', function(folder){

        if(!folder){
            return callback('no folder contain this file, fileId: ' + file._id, ERR.NOT_FOUND);
        }

        file.__folder = folder;

        verifyFolder(user, folder, ep.done('verifyFolder'));

    });

    ep.on('verifyFolder', function(folder){

        if(folder.__archived){
            return callback('can\'t delete an archived file', ERR.UNMODIFABLE);
        }

        if(folder.__editable && (user.__role & config.ROLE_FOLDER_MANAGER)){

            // 管理员和小组/部门管理员和文件夹创建者
            hasAuth = true;
        }
        
        file.__user_role = user.__role;

        if(hasAuth){
            return callback(null);
        }
        return callback(msg, ERR.NOT_AUTH);

    });

}
Example #18
0
exports.create = function (req, res, next) {
    var dish_name = validator.trim(req.body.dish_name);
    dish_name = validator.escape(dish_name);
    var dish_price = validator.trim(req.body.dish_price);
    dish_price = Number(dish_price);
    var user_id = req.session.user._id;
    var ispack = req.body.ispack;
    
    if (ispack === 'on') {
        ispack = true;
    } else {
        ispack = false;
    }
    // 验证(前端页面使用了bootStrapValidator插件验证,这里其实不需要)
    var editError;
    if (dish_name === '') {
        editError = '菜名不能是空的。';
    } else if (dish_name.length < 2 || dish_name.length > 40) {
        editError = '菜名字数太多或太少(2~8个字符)。';
    } else if (dish_price < 0) {
        editError = '价格不能小于0。';
    }
    // END 验证

    if (editError) {
        res.status(422);
        return res.render('index', {
            edit_error: editError,
            dish_name: dish_name,
            dish_price: dish_price,
            ispack: ispack,
            user_id: user_id
        });
    }
    var ep=new EventProxy();
    ep.fail(next);
    //保存订单
    OrderProxy.newAndSave(dish_name, dish_price, ispack, user_id, function (err, order) {
        if (err) {
            return next(err);
        }
        ep.emit('order_saved');
    });
    //更新用户积分
    UserProxy.getUserById(user_id,ep.done(function(user){
       user.score+=2;
       user.save();
       ep.emit('score_saved');
    }));
    //跳转
    ep.all('order_saved','score_saved',function(order){
         res.redirect('/orders');
    });
};
Example #19
0
exports.login = function(req, res, next) {
    var loginName = validator.trim(req.body.name).toLowerCase();
    var pass = validator.trim(req.body.pass).toLowerCase();
    var ep = new eventproxy();
    
    ep.fail(next);
    ep.on('login_error', function(login_error) {
        res.status(403);
        res.render('sign/signin', { error: '用户名或密码错误'});
    })
    
    if(!loginName || !pass) {
        res.status(422);
        return res.render('sign/signin', { error: '信息不完整'});
    }
    
    //根据用户名或邮箱获取用户
    var getUser;
    if(loginName.indexOf('@') !== -1) {
        getUser = User.getUserByMail;
    } else {
        getUser = User.getUserByLoginName;
    }
    
    getUser(loginName, function(err, user) {
        if(err) return next(err);
        if(!user) {
            return ep.emit('login_error');
        }
        
        //验证密码
        var passhash = user.pass;
        tools.bcompare(pass, passhash, ep.done(function(bool) {
            if(!bool) return ep.emit('login_error');
            
            //账号未激活,应该提示用户去激活
            if(!user.active) {
                console.log('该用户未激活');
            }
            
            //保存 session、cookie
            authMiddleWare.gen_session(user, req, res);
            //登录成功后的跳转地址
            var refer = (req.session && req.session._loginReferer) || '/';
            if(notJump.some(function(item) {
                return refer.indexOf(item) >= 0;
            })) {
                refer = '/';
            }
            
            res.redirect(refer);
        }));
    });
}
Example #20
0
        topic.save(function (err) {
          if (err) {
            return next(err);
          }

          var proxy = new EventProxy();
          var render = function () {
            res.redirect('/topic/' + topic._id);
          };
          proxy.assign('tags_removed_done', 'tags_saved_done', render);
          proxy.fail(next);

          // 删除topic_tag
          var tags_removed_done = function () {
            proxy.emit('tags_removed_done');
          };
          TopicTag.getTopicTagByTopicId(topic._id, function (err, docs) {
            if (docs.length === 0) {
              proxy.emit('tags_removed_done');
            } else {
              proxy.after('tag_removed', docs.length, tags_removed_done);
              // delete topic tags
              docs.forEach(function (doc) {
                doc.remove(proxy.done(function () {
                  Tag.getTagById(doc.tag_id, proxy.done(function (tag) {
                    proxy.emit('tag_removed');
                    tag.topic_count -= 1;
                    tag.save();
                  }));
                }));
              });
            }
          });
          // 保存topic_tag
          var tags_saved_done = function () {
            proxy.emit('tags_saved_done');
          };
          //话题可以没有标签
          if (topic_tags.length === 0) {
            proxy.emit('tags_saved_done');
          } else {
            proxy.after('tag_saved', topic_tags.length, tags_saved_done);
            //save topic tags
            topic_tags.forEach(function (tag) {
              TopicTag.newAndSave(topic._id, tag, proxy.done('tag_saved'));
              Tag.getTagById(tag, proxy.done(function (tag) {
                tag.topic_count += 1;
                tag.save();
              }));
            });
          }
          //发送at消息
          at.sendMessageToMentionUsers(content, topic._id, req.session.user._id);
        });
Example #21
0
  function install_user_single(filename, callback) {
    var count = 0, startStudentId = 0;
    var accounts = [];
    util.lineSplit('src/data/' + filename + '.csv', function(line) {
      var userdata = line.split(',');
      if (userdata && userdata.length >= 2) {
        var studentid_ = parseInt(userdata[0]);
        if (userdata[1] && studentid_ > 0) {
          if (startStudentId === 0) {
            startStudentId = studentid_;
          }

          var objuser = {
            studentId: studentid_,
            name: userdata[1],
            password: functions.password_hash(studentid_.toString()),
            accounttype: constdata.account_type.STUDENT
          };

          accounts.push(objuser);

          count++;
        }
      }
    });

    var events = ['accounts', 'pages'];
    var ep = new EventProxy();
    ep.all(events, function (accounts, pages) {
      callback();
    });

    ep.fail(function (err) {
      callback(err);
    });

    ep.after('page', accounts.length, function (list) {
      ep.emit('pages', list);
    });

    ep.after('account', accounts.length, function (list) {
      for (var i = 0; i < list.length; i++) {
        UserPageProxy.newAndSave(list[i]._id, 3, false, list[i].name, '', '', '',
          ep.group('page'));
      }
      ep.emit('accounts', list);
    });

    for (var i = 0; i < accounts.length; i++) {
      UserAccountProxy.newAndSave(accounts[i].studentId, accounts[i].name, accounts[i].accounttype, '',
        accounts[i].password, '', false,
        ep.group('account'));
    }
  }
Example #22
0
var accesstoken = function (req, res, next) {
  var ep = new eventproxy();
  ep.fail(next);

  res.send({
    success: true,
    loginname: req.user.loginname,
    avatar_url: req.user.avatar_url,
    id: req.user.id
  });
};
Example #23
0
exports.showAdmin = function(req, res, next) {
    var proxy = new EventProxy();
    proxy.fail(next);

    var user_limit = config.admin_list_user_count;
    User.getUsersByQuery({}, {limit:user_limit}, proxy.done('users', function(users){ return users; })); 

    var topic_limit = config.admin_list_topic_count;
    Topic.getTopicsByQuery({} ,{limit:topic_limit}, proxy.done('topics', function(topics){ return topics; }));

    proxy.all('topics', 'users', function(topics, users) {
        res.render('admin/index',{
            topics: topics,
            users: users,
            user_current_page: 1,
            user_pages:1
        });
    });
    proxy.fail(next);
}
Example #24
0
module.exports.showMessage = function(req, res, next) {
	var messageId = req.query.id;
	var ep = new eventproxy();
	ep.fail(next);

	Message.getMessageById(messageId, ep.done(function(message) {
		res.render('blog/admin/message/detail', {
			title: '留言详细信息',
			message: message
		});
	}));
};
Example #25
0
File: sign.js Project: 3Q-/myapp
exports.login = function(req, res, next){
    var email = validator.trim(req.body.email).toLowerCase();
    var password = validator.trim(req.body.password);
    var ep = new eve();
    ep.fail(next);
    ep.on('l_err', function(msg){
        res.status(422); 
        log.error(msg);
        res.message(msg);
        render(req, res, 'login', {
            title: '用户登录',
            email: email,
            password: password
        });
    });
    if (!validator.isEmail(email)) {
        return ep.emit('l_err', email+'邮箱不合法。');
    }
    if (!validator.isLength(password, 8)) {
        return ep.emit('l_err', '请输入8位或8位以上密码!');
    }

    User.getUserByEmail(email, function(err, user){
        if(err){
            log.error('--------- '+ email +' 登陆的时候查找该邮箱数据库报错 ------------');
            return next(err);
        }
        if(!user){
            return ep.emit('l_err', '该账户不存在');
        }

        tools.bcompare(password, user.salt, function (err, hash) {
            if(err){
                log.error('登陆时密码hash的时候报错');
                return ep.emit('l_err', '程序问题 登陆不了密码不对赶紧处理');
            }
            if(hash === user.password){
                var refer = req.session._loginReferer || '/', i, len;
                for (i = 0, len = notJump.length; i !== len; ++i) {
                    if (refer.indexOf(notJump[i]) >= 0) {
                        refer = '/';
                        break;
                    }
                }
                req.session.user = user;
                log.debug(user.email+'登陆成功!!!!');
                res.redirect(refer);
            }else{
                return ep.emit('l_err', email+'输入密码不正确');
            }
        });
    });
};
Example #26
0
exports.count = function(req, res, next) {
    var ep = new eventproxy();
    ep.fail(next);

    proxy.dictProxy.getCount(
        ep.done(function (count) {
            res.send(util.sendOKJSON({
                count: count
            }));
        })
    );
};
Example #27
0
exports.login = function(req, res, next) {
    var loginname = validator.trim(req.body.username).toLowerCase();
    var password = validator.trim(req.body.password);
    var ep = new eventproxy();
    ep.fail(next);

    if (!loginname || !password) {
        res.status(422);
        res.render('login', {error: '信息不完整。'});
        return;
    }
    
    var getUser = null;
    if (loginname.indexOf('@') !== -1) {
        getUser = User.getUserByMail;
    } else {
        getUser = User.getUserByLoginName;
    }

    ep.on('login_error', function(login_error) {
        res.status(403);
        res.render('login', { error: '用户名或密码错误'});
    });

    ep.on('login_error_user_not_exist', function(login_error) {
        res.status(403);
        res.render('login', { error: '用户不存在'});
    });
    getUser(loginname, function(err, user) {
        if (err) {
            return next(err);
        }
        if (!user) {
            return ep.emit('login_error_user_not_exist');
        }
        var passhash = user.password;
        tools.bcompare(password, passhash, ep.done(function(bool) {
            if (!bool) {
                return ep.emit('login_error');
            }
            if (!user.active) {
                // 重新发送激活邮件
                mail.sendActiveMail(user.email, utility.md5(user.email + passhash + config.session_secret), user.loginname);
                res.status(403);
                return res.render('login', { error: '此帐号还没有被激活,激活链接已发送到 ' + user.email + ' 邮箱,请查收。' , title: 'website login'});
            }
            // store session cookie
            authMiddleWare.gen_session(user, res);
            //check at some page just jump to home page
            res.redirect('/');
        }));
    });
};
Example #28
0
        before(function(done){
            var ep = new eventproxy();
            ep.fail(done);

            ep.all('mockLevel1', function (Level1) {
                mockLevel1 = Level1;

                done();
            });

            support.createUserWithRoleAndArea(1, 0, ep.done('mockLevel1'));
        });
Example #29
0
exports.delete = function(req, res) {
    var params = req.parameter;

    var files = params.fileId;
    var group = params.groupId;

    var loginUser = req.loginUser;

    var ep = new EventProxy();

    ep.fail(function(err) {
        res.json({
            err: ERR.SERVER_ERROR,
            msg: err
        });
    });

    ep.after('delete', files.length, function() {
        res.json({
            err: ERR.SUCCESS
        });
    });

    var options = {
        groupId: group && group._id,
        updateUsed: true
    };

    files.forEach(function(file) {
        mFile.delete({
            _id: file._id
        }, options, ep.group('delete', function(result) {

            mLog.create({
                fromUser: loginUser,

                file: file,

                //操作类型 1: 上传, 2: 下载, 3: copy, 4: move, 5: modify
                //6: delete 7: 预览 8: 保存, 9: 分享给用户 10: 分享给小组, 
                //11: delete(移动到回收站) 12: 创建文件夹
                operateType: 6,

                srcFolderId: file.folder && file.folder.oid,

                fromGroupId: file.folder && file.folder.group && file.folder.group.oid

            });
            return result;
        }));
    });

};
Example #30
0
module.exports.deleteMessage = function(req, res, next) {
	logger.info('get deleting message id with: %j', req.params);

	var messageId = req.params.id;

	var ep = new eventproxy();
	ep.fail(next);

	Message.deleteMessageById(messageId, ep.done(function() {
		return res.redirect('/blog/admin/message/1/index?del=success');
	}));
};