[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 ...
随机推荐
- WebForms简介
http://www.w3school.com.cn/aspnet/aspnet_intro.asp ASP.NET 是下一代 ASP,不是 ASP 的更新版本. https://docs.micro ...
- Process Monitor —— 程序(文件和注册表)监控
下载地址:Process Monitor v3.33 通过追踪 Process Monitor 的日志,我们可以确认某程序的行为:
- 【Linux】JDK+Eclipse 搭建C/C++开发环境
注:本文所提供的参考示例是在CentOS Linux环境下的安装,不保证适用于其他版本的Linux系统. · 安装前的注意事项 编译源代码是需要对应的代码编译工具的,本文中安装的Eclipse只 ...
- 由安装两块网卡的linux系统中引起网络不通想到的
由安装两块网卡的linux系统中引起网络不通想到的 一天,小王突然急匆匆的来找我,他说:"我在机子上刚装的redhat怎么老也ping不通服务器,我网卡的驱动都安装了,ping 自己的两块网 ...
- WISP > Client+AP > WDS 的区别
最直白易懂的分别:WISP > Client+AP > WDS WISP,真正万能,兼容任何厂牌的上级AP,毋须设置上级AP,不受上级AP的信道影响,自由DHCP,所带机器或设备的IP,上 ...
- RocketMQ 就是耗内存
http://blog.csdn.net/loongshawn/article/details/51086876 https://rocketmq.incubator.apache.org/docs/ ...
- cogs 1396. wwww
1396. wwww ☆ 输入文件:wwww.in 输出文件:wwww.out 简单对比时间限制:1 s 内存限制:256 MB [题目描述] 对于一个递归函数w(a,b,c) 如果 ...
- xgboost参数调优的几个地方
tree ensemble里面最重要就是防止过拟合. min_child_weight是叶子节点中样本个数乘上二阶导数后的加和,用来控制分裂后叶子节点中的样本个数.样本个数过少,容易过拟合. su ...
- [Python] Manage Dependencies with Python Virtual Environments
Virtual Environments ensure that dependencies from one Python application don’t overwrite the depend ...
- MySQL架构组成之逻辑模块组成
MySQL 能够看成是二层架构 第一层SQL Layer.包含权限推断.sql 解析.运行计划优化,query cache 的处理等等. 第二层存储引擎层(Storage Engine Lay ...