Want to write a series of articles, is to analyze an MVC architecture koA2 blog project, architecture design above, (dry article

1. Check whether the user name exists

routerAPI

Router. Post ('/isExist', async (CTX, Next) => {const {username} = ctx.request.body console.log(ctx.request.body); Body = await isExist(userName) // ctx.body= CTX})Copy the code

controller

async function isExist(userName) { const userInfo = await getUserInfo(userName) if (userInfo) { // { errno: 0, data: {... } } return new SuccessModel(userInfo) } else { // { errno: 10003, message: 'user name did not exist'} return new ErrorModel (registerUserNameNotExistInfo)}}Copy the code

server

@param {string} userName userName * @param {string} password password */ async function getUserInfo(userName, If (password) {object. assign(whereOpt,) {whereOpt, whereOpt, const whereOpt = {userName} } // query const result = await user. findOne({attributes: ['id', 'userName', 'nickName', 'picture', 'city'], where: WhereOpt}) if (result == null) {return result} const formatRes = const formatRes = formatUser(result.dataValues) return formatRes }Copy the code

model

// users const User = seq. Define (' User ', {userName: {type: STRING, allowNull: false, unique: True, comment: 'username, unique'}, password: {type: STRING, allowNull: false, comment: 'password'}, nickName: {type: STRING, allowNull: false, comment: 'nickname'}, gender: {type: DECIMAL, allowNull: false, defaultValue: 3, comment: }, picture: {type: STRING, comment: 'PIC'}, city: {type: STRING, comment: 'PIC'}})Copy the code

2. The user logs in

routerAPI

Post ('/login', async (CTX, next) => {const {userName, password } = ctx.request.body console.log('request-body:',ctx.request.body) ctx.body = await login(ctx, userName, password) })Copy the code

controller

async function login(ctx, userName, Const userInfo = await getUserInfo(userName, docrypto (password)) if (! UserInfo) {// Login failed return new ErrorModel(loginFailInfo)} // Login succeeded if (ctx.session.userInfo == null) { Ctx.session. userInfo = userInfo} return new SuccessModel()}Copy the code

server

/ / the userinfoCopy the code

model

/ / the user classCopy the code

utils

const crypto = require('crypto')
const { CRYPTO_SECRET_KEY } = require('.. /conf/secretKeys')
// Crypto_secret_key is a custom random value used to salt data encryption
/** * MD5 encryption *@param {string} The content clear * /
function _md5(content) {
    const md5 = crypto.createHash('md5')
    return md5.update(content).digest('hex')}/** * Encryption method *@param {string} The content clear * /
function doCrypto(content) {
  // MD5 encryption is not reversible by design, but I can't reverse the original value from the result, but it has been cracked;
  // You can add salt to crypto_secret_key for further protection
  // As long as the crypto_secret_key is not leaked, there is no problem
    const str = `password=${content}&key=${CRYPTO_SECRET_KEY}`
    return _md5(str)
}
Copy the code

Supplementary knowledge

1. Session and cookie

(1) Vividly understand the relationship between cookies and Session

1. The Session is saved on the server, and the Cookie is saved on the client.

2. Every time a user visits the site, it’s like visiting.

3. The user takes the cookie to the server home and knocks on the door.

4. The server asks who is it?

User: It’s me (cookie)!

6. Server: Let me confirm this.

7. After the server is confirmed, let the user enter the door.

(2) The response header of the actual website login request

1. This is the response header returned after a website login. It can be seen that the server requires the browser to set several Cookies. this

Is the source of Cookies, and the token is usually used as the user’s unique credential [login success, response header set-cookies, browser set Cookies]

2. When the browser requests this website again, the browser will put these Cookies in the request header and submit them to the server; The Cookies carry the SessionID information (token).

3. The server can find the corresponding user Session information based on the SessionID, and then determine the login status of the user.

4. If some variables in the Session setting the login status are valid, the user is logged in.

5. At this point, the server will return the web page content that can be viewed only after login, and the browser will parse it to see it.

6. When the Cookie is invalid or the Session has expired, we need to log in again to visit the website.

2.md5

The purpose of the Crypto module is to provide universal encryption and hashing algorithms. It’s not impossible to do this in pure JavaScript code, but it’s very slow. Nodejs implements these algorithms in C/C++ and exposes them as JavaScript interfaces through the CYPTO module, which is easy to use and fast to run.

MD5 is a common hash algorithm used to give arbitrary data a “signature.” This signature is usually represented as a hexadecimal string:

const crypto = require('crypto'); const hash = crypto.createHash('md5'); // Call update() as many times as you like: hash.update('Hello, world! '); hash.update('Hello, nodejs! '); console.log(hash.digest('hex')); // 7e1977739c748beac0c0fd14fd26a544Copy the code

The update() method defaults to utF-8 string encoding and can also be passed into buffers.

If you want to calculate SHA1, only need to change the ‘md5’ to ‘SHA1, can get the result of the SHA1 1 f32b9c9932c02227819a4151feed43e131aca40.

You can also use the more secure SHA256 and SHA512.

3. A little thought after MD5

The password in utils is encrypted and salted with the secret_key, md5 is encrypted irreversively, security is guaranteed

So if I have a requirement that my database get the encrypted password, is to be able to decrypt their own to see the original value, and to ensure security, then how to do

The following algorithm is symmetric encryption, should be able to achieve my requirement (? Very sleepy, too lazy to study, the big guy told me after seeing, don’t stay up late

! [](/Users/szuet/Library/Application Support/typora-user-images/image-20210617011145178.png)

This blog system is MVC architecture, view-Controller-server-model to show the code. Tonight, I met a problem that the password submitted by the user must be encrypted, but if I were the administrator, I would like to know the original value of the password before encryption. Then it can not be processed according to the MD5 +secrect value in the warehouse code with salt. I see that there is an AES encryption under the article, which seems to use the same key to encrypt and decrypt. Is this able to meet my needs as well as security? (What the fuck am I talking about, going to sleep)