STDIO Training

32 bundles
2 filesa month ago
4

Demo Auth

models/auth.js

01112131415161718191101111121131141151161171181191201211221231241251const mongoose = require("mongoose");
const bcrypt = require("bcryptjs");

var userSchema = new mongoose.Schema({
  username: {
    type: String,
    required: [true, "username cannot blank"]
  },
  password: {
    type: String,
    required: [true, "password cannot blank"]
  },
  createdAt: {
    type: Number,
    default: null
  }
});

//Encrypt password using brcypt
userSchema.pre("save", async function(next) {
  const salt = await bcrypt.genSalt(10);
  this.password = await bcrypt.hash(this.password, salt);
});

export default mongoose.model("user", userSchema);

services/user.js

01112131415161718191101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421import User from "../models/user";
const bcrypt = require("bcryptjs");
var jwt = require("jwt-simple");
var secret = "aaaa";

class UserService {
  async signup(data) {
    const user = await User.create({ ...data, createdAt: new Date() });
    return user;
  }

  async login(username, password) {
    try {
      const user = await User.findOne({ username });
      console.log(user);
      if (!user) {
        return {
          error: "Username is not exist!",
          success: false,
          code: 401
        };
      }
      // Check if password matches
      const isMatch = await bcrypt.compare(password, user.password);
      console.log(isMatch);
      if (!isMatch) {
        return {
          error: "Invalid credentials",
          success: false,
          code: 401
        };
      }
      const token = jwt.encode({ _id: user._id }, secret);
      console.log(token);
      return { token, success: true, code: 200 };
    } catch (err) {
      return { err, code: 400, success: false };
    }
  }
}

export default new UserService();