GraphQL用户身份验证

时间:2018-11-06 03:40:08

标签: mongodb graphql

仅当用户名和密码与数据库中的内容匹配时,我才尝试查询用户并返回用户。当前,如果我使用用户名查询,无论密码是对还是错,无论如何我都会得到响应。 (请阅读下面的上下文)这是我的graphql模式:

signInUser: {
  type: UserType,
  args: {
    username: { type: new GraphQLNonNull(GraphQLString) },
    password: { type: new GraphQLNonNull(GraphQLString) }
  },
  resolve(parent, args) {
    return User.findOne({ username: args.username }, (err, user) => {
      if (bcrypt.compareSync(args.password, user.password)) {
        return user;
      } else {
        return null;
      }
    });
  }
}

这是我的UserType模式:

const UserType = new GraphQLObjectType({
  name: 'User',
  fields: () => ({
    id: { type: GraphQLID },
    username: { type: GraphQLString },
    posts: {
      type: new GraphQLList(PostType),
      resolve(parent, args) {
        // Matches posts based on username
        // return _.filter(posts, { name: parent.name });
        console.log(parent.name);
        return Post.find({ name: parent.name });
      }
    }
  })
});

我的MongoDB模式:

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const userSchema = new Schema({
  username: String,
  password: String
});

module.exports = mongoose.model('User', userSchema);
// model = collection in database

我应该使用JWT吗?我也无法确定如何在知道用户已在应用程序的客户端登录的情况下处理该问题。我在想这种方式,如果此查询返回空,则可以认为登录失败,否则将用户ID存储到localStorage中并在任何时候使用它。其他方法的建议将不胜感激!

0 个答案:

没有答案