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. Lesson 2 Building your first web page: Part 3

    Time to build your first HTML page by hand I could go on with more theory and send half of you to sl ...

  2. 85.explicit作用

    #include <iostream> using namespace std; class myclass { public: int num; public: explicit myc ...

  3. 请求由tomcat转到servlet的临界点

    >>>>>>>>>>>>>>>>>>>>>>>>> ...

  4. BFS(广度优先搜索)

    Catch That Cow Farmer John has been informed of the location of a fugitive cow and wants to catch he ...

  5. 小试VS 2017 开发Python Django项目过程一

    一.新建项目python ->django web 项目 (选择带bootstrap风格与twwriter)项目名称iepiececomputing (ie计件计算)跳出窗体 -> 添加虚 ...

  6. jquery点击弹框外层关闭弹框

    $(document).bind("click",function(e){            if($( e.target ).closest(".game-cont ...

  7. 【CS Round #37 (Div. 2 only) B】Group Split

    [Link]:https://csacademy.com/contest/round-37/task/group-split/ [Description] 让你把一个数分成两个数a.b的和; (a,b ...

  8. 洛谷 P2558 [AHOI2002]网络传输

    P2558 [AHOI2002]网络传输 题目描述 在计算机网络中所有数据都是以二进制形式来传输的. 但是在进行较大数据的传输时,直接使用该数的二进制形式加以传输则往往传输的位数过多. 譬如要传输 1 ...

  9. Codeforces 164 D Minimum Diameter

    题目链接~~> 做题感悟:越来越感觉CF的题非常好,非常有深度. 解题思路: 这题须要注意 k 的大小.由于 k 仅仅有 30 个,终于形成的点的直径一定是某个确定的值,所以我们能够枚举这个值. ...

  10. Swift之 vm10虚拟机安装Mac OS X10.10教程

    VM10装Mac OS X 10.9.3及更新到Mac OS X 10.10,让你的windows也能玩Swift .   近期WWDC放出终极大招--新的编程语言Swift(雨燕),导致一大波程序猿 ...