限制 Google 登录到 Meteor 中的 .edu 帐户

Limit Google Sign-In to .edu accounts in Meteor

我正在尝试将我的 Google + 登录按钮限制为仅允许 @something.edu 帐户登录。我该怎么做。到目前为止,这是我的代码:

Template.googleLogin.events({
    'click #gLogin': function(event) {
        Meteor.loginWithGoogle({}, function(err){
            if (err) {
                throw new Meteor.Error("Google login didn't work!");
            }
            else {
                Router.go('/home')
            }


        });
    }
})

Template.primaryLayout.events({
    'click #gLogout': function(event) {
        Meteor.logout(function(err){
            if (err) {
                throw new Meteor.Error("Hmm looks like your logout failed. ");
            }
            else {
                Router.go('/')
            }
        })
    }
})

您可以使用 Accounts.config 完成此操作(在根目录中,因此它在客户端和服务器上运行)

Accounts.config({ restrictCreationByEmailDomain: 'something.edu' })

如果您需要更自定义的东西,您可以用一种方法替换 something.edu 如果您需要细化您的要求,即对于任何 .edu 域:

Accounts.config({ restrictCreationByEmailDomain: function(address) {
        return new RegExp('\.edu$', 'i')).test(address)
    }
});

帐户包允许通过以下方式配置帐户创建域:

Accounts.config({
  restrictCreationByEmailDomain: 'something.edu' 
})

但是在google的情况下这有一些限制:

  1. 这只是客户端,只允许登录表单获得适当的样式以表示域的徽标等。但是可以通过制作 google oauth 登录 url 很容易地克服它手工
  2. 如果您需要配置额外的选项,例如允许多个域或一个域和一些外部用户(可能是第三方承包商或软件公司的支持等),这将不起作用。在 accounts-google 的情况下,程序包检查 restrictCreationByEmailDomain 是否是一个字符串,如果它是一个函数,它就丢弃它。

因此,为了能够正确安全地使用此类功能,您需要使用官方Accounts.validateNewUser回调:

Accounts.validateNewUser(function(newUser) {
  var newUserEmail = newUser.services.google.email;
  if (!newUserEmail) throw new Meteor.Error(403,'You need a valid email address to sign up.');
  if (!checkEmailAgainstAllowed(newUserEmail)) throw new Meteor.Error(403,'You need an accepted organization email address to sign up.');
  return true;
});

var checkEmailAgainstAllowed = function(email) {
  var allowedDomains = ['something.edu'];
  var allowedEmails = ['someone@example.com'];
  var domain = email.replace(/.*@/,'').toLowerCase();
  return _.contains(allowedEmails, email) || _.contains(allowedDomains, domain);
};

如果您想格外小心,您也可以对 Accounts.validateLoginAttemptAccounts.onCreateUser 回调实施相同的操作。