[Node] Stateful Session Management for login, logout and signup
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的更多相关文章
- Spring Security笔记:自定义Login/Logout Filter、AuthenticationProvider、AuthenticationToken
在前面的学习中,配置文件中的<http>...</http>都是采用的auto-config="true"这种自动配置模式,根据Spring Securit ...
- login/logout切换
1. 前端按钮 <img border="0" width="18" height="18" src="<%=base ...
- YII session存储 调用login方法
当要进行用户的session存储的时候,可以调用里面的login方法进行存储
- node express session
在express4.0版本以上,需要单独增加session模块:express-session:https://www.npmjs.com/package/express-session 具体做法是, ...
- node中session存储与销毁,及session的生命周期
1.首先在使用session之前需要先配置session的过期时间等,在入口文件app.js中 app.use(express.session({ cookie: { maxAge: config.g ...
- session management
The session does not created until the HttpServletRequest.getSession() method is called.
- Use Spring transaction to simplify Hibernate session management
Spring对Hibernate有很好的支持 DataSource ->SessionFactory-> HibernateTranscationManagerHibernate中通 ...
- node中session的管理
请看这个博客: http://spartan1.iteye.com/blog/1729148 我自己的理解 session俗称会话. 第一次访问服务器的时候由服务器创建,相当于一个cookie(就 ...
- Apache Shiro Session Management
https://shiro.apache.org/session-management.html#session-management https://shiro.apache.org/session ...
随机推荐
- Ubuntu 安装软件和centos 对比命令
之前都是使用Redhat 或者Centos 等rpm的linux ,开始使用ubuntu 很不习惯 1. 安装命令Centos : yum install httpd ...
- P1328 生活大爆炸版石头剪刀布
题目描述 石头剪刀布是常见的猜拳游戏:石头胜剪刀,剪刀胜布,布胜石头.如果两个人出拳一样,则不分胜负.在<生活大爆炸>第二季第8 集中出现了一种石头剪刀布的升级版游戏. 升级版游戏在传统的 ...
- 携手互联网企业10巨头设VC基金
包括小米科技.盛大集团.人人网.掌趣科技.游族网络.龙图游戏.蓝港互动.37游戏.星辉互动娱乐.博雅互动等10家知名互联网企业作为出资人(LP)的优格创投基金近日正式成立. 众所周知,伴随着移动互联网 ...
- 【js基础】判断是否是合法邮箱地址(正则表达式的应用)
2019-01-21 09:11:21 <!DOCTYPE html> <html> <head> <meta charset="utf-8&quo ...
- or in 、Object.keys()以及Object.getOwnPropertyNames有什么区别?
or in .Object.keys()以及Object.getOwnPropertyNames的区别 var obj= Object.create(parent, { b: { value: 2, ...
- CodeForcesGym 100502G Outing
Outing Time Limit: 1000ms Memory Limit: 524288KB This problem will be judged on CodeForcesGym. Origi ...
- UVA 11642 Fire!
Fire! Time Limit: 1000ms Memory Limit: 131072KB This problem will be judged on UVA. Original ID: 116 ...
- WMI获取进程CPU占用率
Monitor % Process CPU Usage (specific process) http://www.tek-tips.com/viewthread.cfm?qid=395765 for ...
- 开创学习的四核时代-iTOP-4412开发板开源硬件平台
iTOP-4412开发板如今比較热门的开发板.笔者最近入了一套. 也推荐给初学ARM的朋友学习,4412开发板搭载三星Exynos四核处理器,配备1GB内存,4GB固态硬盘EMMC存储,兼具高速读取与 ...
- Java Swing设置主窗体位置居中方法
01.第一种方法 int windowWidth = frame.getWidth(); //获得窗体宽 int windowHeight = frame.getHeight(); //获得窗体高 ...