The introduction

Blog front desk reconstruction finished, the next is the background part, the main function of the background is to publish, delete, modify the article, nature is not who can casually enter. In the vue project, I was in the global front guard of the Vue Router to determine whether the current user has cookies to determine whether it has the right to enter the background. One of the biggest differences between Nuxt and Vue is that instead of using the Vue Router, Nuxt uses a directory for page routing, so we lose the global front-guard. Nuxt does have a solution, but before that we need to understand the authentication principle.

The Cookie and Session

I believe that the front end of the students have long heard of these two names, but do not necessarily have a detailed understanding. As we all know, the HTTP protocol we use to browse the web is stateless, which means that every request you make is the same to the server and it has no way of remembering that it was sent by you. So we’re going to use cookies here.

A Cookie is a set of data that the browser stores on your hard drive, such as your user data, and carries it with it every time it sends a request to the server. The server will see who sent it. This process is called a Session

Session initiation is the concept of a period of time during which you interact with the site. In this cycle the server is trying to figure out who you are by storing cookies in the browser. However, because cookies stored locally are not secure and can be seen and changed by anyone, it is now more popular to identify users only by the unique user identifier (SessionID) stored in cookies, while user information is stored on the server side. So the concept of Session is kind of the parent or sibling of cookies

Nuxt authentication

Explained the basic principle of Nuxt authentication, we can know that authentication is in the user into the page when the local Cookie to judge, there is a set of cookies so that the user has logged in, put him in the past. Nothing? No, you sign me in, you jump to the login page. Understand this process to start the specific work.

The server side

On the server side we install koA-session using koA-session

NPM install koa-session NPM install koa-session-mongoose // Use mongodb to store session informationCopy the code

Then use this in the entry file

Renew: true, store: app.use(session({key: "***", // encryption key overwrite: true, // overwrite Cookie httpOnly: true, // with permission renew: true, store: new MongooseStore({ createIndexes: "appSessions", connection: mongoose, expires: 86400, // 1 day is the default name: "AppSession"}) // pass in an external store for session, I'm using mongodb}, app);Copy the code

Session (ctx.req.session) is not easy for users to get, so we move it a bit to ctx.req.session

  app.use((ctx) => {
    ctx.status = 200
    ctx.respond = false // Bypass Koa's built-in response handling
    ctx.req.session = ctx.session
    ctx.req.ctx = ctx // This might be useful later on, e.g. in nuxtServerInit or with nuxt-stash
      return new Promise((resolve, reject) => {
        ctx.res.on('close', resolve)
        ctx.res.on('finish', resolve)
        nuxt.render(ctx.req, ctx.res, promise => {
          // nuxt.render passes a rejected promise into callback on error.
          promise.then(resolve).catch(reject)
        })
      })
  })Copy the code

This is the login function, query whether the database and the corresponding user name and password, if there is, set a Cookie to the client to return a successful login

  static async login(ctx) {
    let { passwd, email } = ctx.request.body;
    let hasuser = await UserModel.findOne({ email: email, passwd: md(passwd) });

    if (!hasuser) {
      return ctx.error({});
    }
    else {
      let userid = hasuser._id;
      const { session } = ctx;
      session.userid = userid;
      return ctx.success({ data: { userid: userid } });
    }
  }Copy the code

The server setup is complete

Client (Nuxt)

In fact, the above steps are the same as in the Vue project, the main difference in Nuxt is the loss of the global front-guard, so where to determine whether there is a Cookie, not so quickly, Nuxt official nature of the solution, first look at the Nuxt life cycle

These are the nuxtServerInit and Middleware periods in the red box, so let’s look at the code

Export const actions = {// nuxtServerInit is called by nuxt.js before server-rendering every Page nuxtServerInit({commit}, {req}) {if (req.session && req.session.userid) {console.log(" user is logged in "); commit("SET_USER", req.session.userid); } }, export const mutations = { SET_USER(state, user) { state.authUser = user; }},Copy the code

The nuxtServerInit function in the Store Action module is the first one to run throughout the life cycle, and this is where we determine whether the current user has cookies in their browser, and if so, save them in a field in state. Sounds like a global front guard. It’s just a judgment call, it’s just a stamp on whether you’re logged in or not, where’s the block, don’t worry, it’s in the next flow middleware.

Open the Middleware folder (the Nuxt project comes with it) and create the auth.js file

// auth.js export default function ({ store, redirect }) { if (! store.state.authUser) { return redirect('/welcome') } }Copy the code

Check Vuex to see if you are logged in or not. If not, send you to the login page. Simple and straightforward, just reference the middleware in the page that requires authentication

export default {
    middleware: 'auth',
};Copy the code

conclusion

In this way, users who have not logged in will be redirected to the login page when they visit the background, which is a simple use of cookies. Due to the nature of the project, many functions of session are not used, such as storing user information on the server side. Basically what it does is it prevents people from accessing the background, very simple.

There will be a follow-up article

  • Koa-session source code analysis
  • Koa-session is used to store user information in mongodb

Stay tuned for

Welcome to my Blog