S
S
Sergey Burduzha2021-07-05 10:50:46
User identification
Sergey Burduzha, 2021-07-05 10:50:46

Where can I find an example of how nuxt auth works?

Good afternoon.
I can't figure out how nuxt auth works.

On the site there is a video instruction https://auth.nuxtjs.org/ , only the author does not tell everything.
I can't understand how it works.

submitForm() {
      this.loading = true;
      this.$refs.ruleForm.validate(async valid => {
        if (valid) {
          try {
            const data = {
              login: this.ruleForm.login,
              password: this.ruleForm.password
            };
            const response = await this.$auth.loginWith("local", data);
            console.log(response, "response");
            this.loading = false;

            // this.$message.success("User was logged in");
            // this.$router.push("/admin");
          } catch (error) {
            console.log(error, "error from login vue");
            this.loading = false;
          }
        } else {
          this.loading = false;
          console.log("error submit!!");
          return false;
        }
      });
    }


proxy: { "/api/": process.env.BASE_URL },
  auth: {
    strategies: {
      local: {
        token: {
          property: "token",
          global: true
          // required: true,
          // type: 'Bearer'
        },
        user: {
          property: "user"
          // autoFetch: true
        },
        endpoints: {
          login: { url: "/api/auth/login", method: "post" },
          logout: { url: "/api/auth/logout", method: "post" },
          user: { url: "/api/auth/user", method: "get" }
        }
      }
    }
  },


When I call the this.$auth.loginWith("local", data) method, on the server side, should I accept data and forms, write to the database, and return the token back?
Or do I need to create this action for these actions myself.

Why couldn't the whole process be shown? Not everyone is that smart.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Sergey Burduzha, 2021-07-05
@serii81

I'm done with authorization. Works with both local storage and cookies. "
nuxt.config.js

axios: { proxy: true },
  proxy: { "/api/": process.env.BASE_URL + "/" },
  auth: {
    strategies: {
      local: {
        token: {
          property: "token",
          global: true
          // required: true,
          // type: 'Bearer'
        },
        user: {
          property: "user",
          autoFetch: false
        },
        endpoints: {
          login: { url: "/api/login", method: "post" },
          logout: { url: "/api/auth/logout", method: "post" },
          user: { url: "/api/auth/user", method: "get" }
        }
      }
    }
  },

auth routes
const { Router } = require("express");
const router = Router();
const {
  login,
  register,
  user,
  logout
} = require("./../controllers/auth.controller");

router.post("/api/login", login);
router.post("/api/auth/register", register);
router.get("/api/auth/user", user);
router.post("/api/auth/logout", logout);

module.exports = router;

auth controllers
const User = require("./../models").User;
const Sequelize = require("sequelize");
const Op = Sequelize.Op;
const bcrypt = require("bcrypt-nodejs");
const jwt = require("jsonwebtoken");

module.exports.login = async (req, res) => {
  const login = req.body.login;
  const password = req.body.password;

  try {
    const candidate = await User.findOne({
      where: {
        login: {
          [Op.eq]: login
        }
      }
    });
    if (candidate) {
      if (bcrypt.compareSync(password, candidate.password)) {
        const token = jwt.sign(
          {
            user: candidate.login,
            userId: candidate.id
          },
          process.env.JWT,
          { expiresIn: "2h" }
        );

        res
          .status(200)
          .json({ status: 1, message: "You are logged in", token });
      } else {
        res.status(200).json({ status: 0, message: "User not found" });
      }
    } else {
      res.status(200).json({ status: 0, message: "User not found" });
    }
  } catch (error) {
    throw error;
    return res.status(500).json(error);
  }
};

module.exports.register = async (req, res) => {
  const { login, password } = req.body.data;
  try {
    const candidate = await User.findOne({
      where: {
        login: {
          [Op.eq]: login
        }
      }
    });
    if (candidate) {
      res.status(200).json({ status: 0, message: "User exists" });
    } else {
      const salt = bcrypt.genSaltSync(10);
      await User.create({
        login: login,
        password: bcrypt.hashSync(password, salt)
      });
      res.status(200).json({ status: 1, message: "User was created" });
    }
  } catch (error) {
    throw error;
    return res.status(500).json(error);
  }
};

module.exports.user = async (req, res) => {
  const token = req.headers["authorization"];
  const newToken = token.replace("Bearer ", "");
  if (token) {
    jwt.verify(newToken, process.env.JWT, (error, decode) => {
      if (error) {
        res.status(403).json({ status: 0, message: "invalid token", error });
      } else {
        res.status(200).json({ status: 1, user: decode.user });
      }
    });
  } else {
    res.status(500).json({ status: 0, message: "Please, send a token" });
  }
};

module.exports.logout = (req, res) => {
  res.status(200).json({ status: 1, message: "You are logged in", token: "" });
};

logout
methods: {
    logout() {
      this.$auth.logout();
    }
  }

Login
submitForm() {
      this.loading = true;
      this.$refs.ruleForm.validate(async valid => {
        if (valid) {
          try {
            const data = {
              login: this.ruleForm.login,
              password: this.ruleForm.password
            };
            const response = await this.$auth.loginWith("local", {
              data: this.ruleForm
            });

            this.loading = false;

            if (response.data.status === 1) {
              this.$message.success(response.data.message);
              window.location.href = process.env.baseUrl;
            } else {
              this.$message.warning(response.data.message);
            }
          } catch (error) {
            this.loading = false;
          }
        } else {
          this.loading = false;
          console.log("error submit!!");
          return false;
        }
      });
    }

V
Vadim, 2021-07-05
@vadimeo

This video helped me
https://www.youtube.com/watch?v=zzUpO8tXoaw

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question