[Koa2 User registration, log in and check salt encryption

Encryption and decryption

 First introduce on the service end user name with the storage state code, we know the current end when registering a new user will enter the user name and password in the form and submit it to the server through the post request, the server then user name and password from in ctx.request.body out, stored into a database table. This table will usually be named users.

  The key is how the server stores the user name and password to the database. Direct deposit? Impossible, so too unsafe, dangerous situation never occurs all the user names and passwords sweeping in a table.

  Therefore, a better method is a process, the first server to encrypt the user's password salt, and then saved to the database.

  That password authentication it? Is receiving front-end input plaintext password, for comparison with the corresponding database encryption password, if correct, it means that the login is successful. Note: If someone get this encrypted password is useless. Methods of alignment of right and wrong because of the dead have been written on the server, can only be compared to the plaintext password and encryption password is consistent. If two identical receiving an encrypted password, the authentication is not passed.

  As for how than the plaintext password and encryption password, do not worry, encryption and decryption methods of production are paired together. bcryptjs is such a good tool for encryption and decryption. (Because the installation will complain bcrypt on the windows, no problem said to other systems, so instead install bcryptjs, its api and use exactly the same methods and bcrypt)

  I define two methods in a js module, an encrypted, a decryption. In the encryption algorithm, first we need to generate salt, called salt is first mixed with a number of random characters in the plain text password. Incoming larger the number, the more complex represents the mixed salt. Finally, generating an encrypted password hashSync method and return. The decryption method is even more simple, direct method calls compareSync packaged in plain text password and encryption password comparison.

  

User Registration

  The server routing module, exposing a register interface for receiving the front end of the registration information, the password salt encrypted and stored in the database.

const router = require("koa-router")();
const UserModel = require("../schema/user");
const Crypt = require("./crypt");
const jwt = require("jsonwebtoken");

// 新增一名用户
router.post("/register", async ctx => {
  const UserEntity = new UserModel(ctx.request.body);
  UserEntity.password = Crypt.encrypt(UserEntity.password);
  await UserEntity.save()
    .then(() => {
      ctx.body = {
        code: 200,
        msg: "register successfuly"
      };
    })
    .catch(() => {
      ctx.body = {
        code: 500,
        msg: "register failed"
      };
    });
});

(看一下我这段代码,有几个需要说明的地方:第一,我是通过userModel这一个模型的save方法将这条数据存入mongoDB数据库中,至于model、schema的概念问题,先不在这里赘述;第二:存储失败的原因可能是网络问题,服务端程序出错,但最大的可能还是因为我在userSchema里定义了用户名的不可重复性,也就是所谓的“该用户名已存在”)。

  为了阐述方便,这里将userModel的定义代码贴出来:

  

 

 

登录校验

  让我们回到服务端路由模块,看下怎样去完成一个登录校验。

  

// 登录校验
router.post("/login", async ctx => {
  const data = ctx.request.body;
  await UserModel.findOne({ account: data.account })
    .then(res => {
      const checkPassword = Crypt.decrypt(data.password, res.password);
      if (checkPassword) {
        const token = jwt.sign({ account: res.account }, "zhangnan", {
          expiresIn: "2h"
        });
        ctx.body = { code: 200, msg: "successfuly login", token: token };
      } else {
        ctx.body = { code: 500, msg: "wrong password" };
      }
    })
    .catch(() => {
      ctx.body = { code: 501, msg: "user does not exist" };
    });
});

  首先,我们根据用户输入的用户名去数据库查找用户信息,如果查不到,说明用户名不存在,这是第一层逻辑。

  如果查到了,则调用刚刚定义好的解密方法进行明文密码与加密密码比对,如错误,则告诉前端密码错误;如正确,则调用jwt的sign方法签发一个token给前端。签发的内容是用户名;后面前端再发来请求并携带这个token时,如果验证到token有效,那解析出来的用户名就是服务器判断前端请求身份的标识,它告诉服务器“我是xxx,且我处于已登录状态”。这是第二层逻辑。

  

 

Guess you like

Origin www.cnblogs.com/zhangnan35/p/11217978.html