A small cookie (Cookie) Story - Part II

Part I introduces the basic registration process, simply talk about the next logon process and the emergence of Cookie

Log in to achieve a small function

When you type in the input box browser localhost:8080/sign_intime, initiates GETa request to visitsign_in.html

if (path === '/sign_up' && method === 'GET') {
  let string = fs.readFileSync('./sign_up.html', 'utf8')
  response.statusCode = 200
  response.setHeader('Content-Type', 'text/html;charset=utf-8')
  response.write(string)
  response.end()
}

CSS layout and the layout is basically the same article, omitted the table ~

Information than the user's information inside the database matches

Part of the routine is still, after obtaining user formdata, analyze data, and inside the database comparison

var users = fs.readFileSync('./db/users', 'utf8')
try {
    users = JSON.parse(users) //[] JSON也支持数组
} catch (exception) {
    users = []
}

let found 
for (let i = 0; i < users.length; i++) {
if (users[i].email === email && users[i].password === password) {
  found = true
  break
  }
}
if (found) {
  response.setHeader('Set-Cookie', `sign_in_email=${email};HTTPOnly`)
  response.statusCode = 200
} else {
  response.statusCode = 401
}

The difference is the introduction of a header, that is today's hero - Cookie

In fact, this and similar situations usually the Internet, sometimes we visit some of the shopping site, and not logged in, but you add things in the cart inside, when you come back after shopping and found inside the shopping cart have your records help you to do this thing also cookie.

Because the HTTP protocol is stateless, that is, the server does not know what to do once on the user, which seriously hampered the interactive Web applications implementation. In a typical online shopping scenario, a user browse a few pages, bought a box of biscuits and two bottles of drink. The final checkout, due to the stateless nature of HTTP, not by means of an additional server in the end user does not know what to buy, so Cookie is used to bypass one of the stateless nature of "additional means" of HTTP. Cookies server can be set or read the information contained in, thereby maintaining the user with the server session state) in.

Set head

As can be seen, when you initiate in sign_in GETrequest and set up Set-Cookieafter other homologous pages, they will bring Cookie, will also be able to ensure that when homologous website initiates a request to the server, the server can understand that you already are the logged-on user, and the difference between those pages did not get off the cookie.

Cookie's entry

Why write in a cookie inside HttpOnlyit, as this may prevent some cattle people use JSto modify the content of Cookie.

  • If you do not write this, you can use jsthe modified

js modify cookie

He wrote HttpOnlyafter can not be modified

Can not be modified

_ga is valid

This is Chrome's features for analyzing the cookie

The role of each part is detailed here

Cookie features

Through the above example, we can summarize a few important features

  1. Server via Set-Cookie response header Cookie
  2. After the browser to get Cookie, Cookie should be put on every request
  3. Cookie server reads the user's login information to know (email)

Of course, there are several issues that need to answer.

  1. Cookie which exist
    in the hard disk of a file inside
  2. Cookie will be tampered with users?
    Yes, that is to say it is not safe.

Unsafe

  1. Cookie Expiration do?

The default period of about 20 minutes, different browsers policy
backend can force set period

Set-Cookie: <cookie-name>=<cookie-value>; Expires=<date>
Set-Cookie: <cookie-name>=<cookie-value>; Max-Age=<non-zero-digit>

Specific Grammar Set-Cookie

After the user logs show different Home

Now that you have successfully logged in, should jump to the home page, and displays the appropriate interface.

$.post('/sign_in', hash)
.then((response) => {
  window.location.href = '/'
}, 
(request) => {
  alert('邮箱与密码不匹配')
  }
)

Home information should then make the appropriate changes based on user information

let cookies = request.headers.cookie.split('; ') //['email=..@..', 'a=1']
let hash = {}
cookies.forEach((cookie) => {
  let parts = cookie.split('=')
  let key = parts[0]
  let value = parts[1]
  hash[key] = value
})
let email = hash.sign_in_email
let users = fs.readFileSync('./db/users', 'utf8')
users = JSON.parse(users)
let foundUser
for (let i = 0; i < users.length; i++) {
  if (users[i].email === email) {
    foundUser = users[i]
    break
  }
}
if (foundUser) {
  string = string.replace('email', foundUser.email)
} else {
  string = string.replace('恭喜,email你已成功登录', '没有该用户')
}

Here code logic Part basically the same, the only difference in that the first line of code

let cookies = request.headers.cookie.split('; ') //['email=..@..', 'a=1']

Why use characters to split them up, because there can be multiple cookie

Multiple cookie

Cookie's two roles

Generally common action has the following two:

  1. Identify the user's identity. When the user A to access localhost:8080time, server A will give a unique id=00A(this is the cookie), when the user A accesses localhost:8080when other pages, will take the unique id. When the user B to access localhost:8080time, the server found that he did not have any identification, I will give him a unique id=00B, cookie so the server can help distinguish who is who.
  2. Record your browsing history. The most common requirement is that you visit this shopping site, you add to cart the stuff inside will be in a few days, and will not suddenly disappear. A user, for example, to taobao.combuy something, add a kettle, a millet phone to the cart inside, then the server can rewrite the above you make it specific cookie "id = 00A; cart = A1, A2 ," that means you inside the shopping cart to buy two things. You think of it a few days, to see inside the shopping cart, kettle, millet phone still inside. Your browser does not delete the cookie stored on your hard disk.

A figure below summarizes the process of registration Login

Login registration process

Then you can engage in a practice Others, like what session LocalStorage...... ( @ o @ ) wow ~

Code link sign_in.html

server.js

Guess you like

Origin www.cnblogs.com/baimeishaoxia/p/12033149.html