Stateful session management: Store session which associate with user, and store in the menory on server.

Sign Up:

app.route('/api/signup')
.post(createUser);
import {Request, Response} from 'express';
import {db} from './database'; import * as argon2 from 'argon2';
import {validatePassword} from './password-validation';
import {randomBytes} from './security.utils';
import {sessionStore} from './session-store'; export function createUser (req: Request, res: Response) {
const credentials = req.body; const errors = validatePassword(credentials.password); if (errors.length > 0) {
res.status(400).json({
errors
});
} else {
createUserAndSession(res, credentials);
}
} async function createUserAndSession(res, credentials) {
// Create a password digest
const passwordDigest = await argon2.hash(credentials.password);
// Save into db
const user = db.createUser(credentials.email, passwordDigest);
// create random session id
const sessionId = await randomBytes(32).then(bytes => bytes.toString('hex'));
// link sessionId with user
sessionStore.createSession(sessionId, user);
// set sessionid into cookie
res.cookie('SESSIONID', sessionId, {
httpOnly: true, // js cannot access cookie
secure: true // enable https only
});
// send back to UI
res.status(200).json({id: user.id, email: user.email});
}

Password validation:

import * as passwordValidator from 'password-validator';

// Create a schema
const schema = new passwordValidator(); // Add properties to it
schema
.is().min(7) // Minimum length 7
.has().uppercase() // Must have uppercase letters
.has().lowercase() // Must have lowercase letters
.has().digits() // Must have digits
.has().not().spaces() // Should not have spaces
.is().not().oneOf(['Passw0rd', 'Password123']); // Blacklist these values export function validatePassword(password: string) {
return schema.validate(password, {list: true});
}

Random bytes generator:

const util = require('util');
const crypto = require('crypto'); // convert a callback based code to promise based
export const randomBytes = util.promisify(
crypto.randomBytes
);

Session storage:

import {Session} from './session';
import {User} from '../src/app/model/user';
class SessionStore {
private sessions: {[key: string]: Session} = {}; createSession(sessionId: string, user: User) {
this.sessions[sessionId] = new Session(sessionId, user);
} findUserBySessionId(sessionId: string): User | undefined {
const session = this.sessions[sessionId];
return this.isSessionValid(sessionId) ? session.user : undefined;
} isSessionValid(sessionId: string): boolean {
const session = this.sessions[sessionId];
return session && session.isValid();
} destroySession(sessionId: string): void {
delete this.sessions[sessionId];
}
} // We want only global singleton
export const sessionStore = new SessionStore();

In menory database:

import * as _ from 'lodash';
import {LESSONS, USERS} from './database-data';
import {DbUser} from './db-user'; class InMemoryDatabase { userCounter = 0; createUser(email, passwordDigest) {
const id = ++this.userCounter;
const user: DbUser = {
id,
email,
passwordDigest
}; USERS[id] = user; return user;
} findUserByEmail(email: string): DbUser {
const users = _.values(USERS);
return _.find(users, user => user.email === email);
}
} export const db = new InMemoryDatabase();

Login:

app.route('/api/login')
.post(login);
import {Request, Response} from 'express';
import {db} from './database';
import {DbUser} from './db-user';
import * as argon2 from 'argon2';
import {randomBytes} from './security.utils';
import {sessionStore} from './session-store'; export function login(req: Request, res: Response) { const info = req.body;
const user = db.findUserByEmail(info.email); if (!user) {
res.sendStatus(403);
} else {
loginAndBuildResponse(info, user, res);
}
} async function loginAndBuildResponse(credentials: any, user: DbUser, res: Response) {
try {
const sessionId = await attemptLogin(credentials, user);
res.cookie('SESSIONID', sessionId, {httpOnly: true, secure: true});
res.status(200).json({id: user.id, email: user.email});
} catch (err) {
res.sendStatus(403);
}
} async function attemptLogin(info: any, user: DbUser) {
const isPasswordValid = await argon2.verify(user.passwordDigest, info.password); if (!isPasswordValid) {
throw new Error('Password Invalid');
} const sessionId = await randomBytes(32).then(bytes => bytes.toString('hex'));
sessionStore.createSession(sessionId, user); return sessionId;
}

Logout:

app.route('/api/logout')
.post(logout);
import {Response, Request} from 'express';
import {sessionStore} from './session-store'; export const logout = (req: Request, res: Response) => {
console.log(req.cookies['SESSIONID']);
const sessionId = req.cookies['SESSIONID'];
sessionStore.destroySession(sessionId);
res.clearCookie('SESSIONID');
res.sendStatus(200);
};

[Node] Stateful Session Management for login, logout and signup的更多相关文章

  1. Spring Security笔记:自定义Login/Logout Filter、AuthenticationProvider、AuthenticationToken

    在前面的学习中,配置文件中的<http>...</http>都是采用的auto-config="true"这种自动配置模式,根据Spring Securit ...

  2. login/logout切换

    1. 前端按钮 <img border="0" width="18" height="18" src="<%=base ...

  3. YII session存储 调用login方法

    当要进行用户的session存储的时候,可以调用里面的login方法进行存储

  4. node express session

    在express4.0版本以上,需要单独增加session模块:express-session:https://www.npmjs.com/package/express-session 具体做法是, ...

  5. node中session存储与销毁,及session的生命周期

    1.首先在使用session之前需要先配置session的过期时间等,在入口文件app.js中 app.use(express.session({ cookie: { maxAge: config.g ...

  6. session management

    The session does not created until the HttpServletRequest.getSession() method is called.

  7. Use Spring transaction to simplify Hibernate session management

    Spring对Hibernate有很好的支持    DataSource ->SessionFactory-> HibernateTranscationManagerHibernate中通 ...

  8. node中session的管理

    请看这个博客:   http://spartan1.iteye.com/blog/1729148 我自己的理解 session俗称会话. 第一次访问服务器的时候由服务器创建,相当于一个cookie(就 ...

  9. Apache Shiro Session Management

    https://shiro.apache.org/session-management.html#session-management https://shiro.apache.org/session ...

随机推荐

  1. Task Scheduler

    https://technet.microsoft.com/en-us/library/cc748993(v=ws.11).aspx#BKMK_winui If Task Scheduler is n ...

  2. Mybatis传多个参数(推荐)

    Dao层的函数方法 int deleteMsgById(@Param("name") String name,@Param("id") String id); ...

  3. Gym - 100625J Jailbreak 最短路+搜索

    http://codeforces.com/gym/100625/attachments/download/3213/2013-benelux-algorithm-programming-contes ...

  4. C# Aspose.Cells 使用汇总

    Workbook workbook = new Workbook(); //工作簿 Worksheet sheet = workbook.Worksheets[0]; //工作表 Cells cell ...

  5. XFCE 桌面环境美化,fedora27系统

    一.添加RPM Fusion源,安装方法这里就不说了以前的文章里写过. 二.安装XFCE 主题管理器 xfce-theme-manager [root@Fedora ~]# dnf install x ...

  6. VBA 字符串操作(基础篇)

    转自:http://blog.csdn.net/jyh_jack/article/details/2315345 mid(字符串,从第几个开始,长度) 在[字符串]中[从第几个开始]取出[长度个字符串 ...

  7. vue.js中compted与model的区别

    在p便签内写的{{reversemessage}}方法,若js里对应的函数为computed则不需要加上括号 若js里对应的函数为model则应该将{{reversemessage}}改为{{reve ...

  8. CS224d lecture 9札记

    欢迎转载.转载注明出处: http://blog.csdn.net/neighborhoodguo/article/details/47193885 近期几课的内容不是非常难.还有我的理解能力有所提高 ...

  9. 4.2.2 MINUS

    4.2.2 MINUS正在更新内容,请稍后

  10. 从头认识java-13.12 超类通配符

    这一章节我们来讨论一下超类通配符. 1.什么是超类通配符 在前一章节我们提到一种通配符,是使用<? extends XXX>来实现的,导致了后面的一系列问题,如今我们引入还有一种通配符-- ...