我应该如何使用身份验证实现我的mongoose userSchema?

时间:2016-08-30 02:10:31

标签: node.js authentication mongoose passport.js jwt

我尝试使用Node.js,Express创建一个 RESTful API ,并使用mongodb使用 mongoose ,所以如果这个问题听起来很傻,我很抱歉

API应允许学生 整理 信息。学生可以认证,从那里他可以添加学期,并且每个学期他都可以添加课程,每个课程他都可以添加注释等等......

例如:学生A:[第一学期:[课程A:[注释1],[注释2] ...],[课程B:[注释1],[注释2] ...]]

学生A 获取所有学期发送请求时,他应该只获取他的信息。

我将使用Passport.js的JWT。到目前为止,我有这个,但我需要添加集合:学期 - >课程 - >注释。

我应该将所有这些文件放在userSchema中吗?还是应该为每个文档创建单独的子文档?最好的方法是什么?

非常感谢!

var userSchema = new mongoose.Schema({ //Cria schema do usuario
    email: {
        type: String,
        unique: true,
        required: true
    },
    name: {
        type: String,
        required: true
    },
    hash: String //Senha criptografada com o salt
    salt: String //Utilizado para 'salgar' a senha
});

userSchema.methods.setPassword(password){
    this.salt = crypto.randomBytes(16).toString('hex');
    this.hash = crypto.pbkdf2Sync(password, this.salt, 1000, 64).toString('hex');
};

userSchema.methods.validatePassword(password){
    var hash = crypto.pbkdf2Sync(password, this.salt, 1000, 64).toString('hex');
    return hash == this.hash;
};

userSchema.methods.generateJwt(){
    var expiry = new Date();
    expiry.setDate(expiry.getDate() + 7);

    return jwt.sign({
        _id: this.id,
        email: this.email,
        name: this.name,
        exp: parseInt(expiry.getTime() / 1000),
    }, "MY_SECRET");
};

0 个答案:

没有答案
相关问题