Move framework to lerna

This commit is contained in:
Jerko Steiner 2019-01-18 20:15:43 +01:00
parent e9a638cafe
commit 84fd213911
88 changed files with 12941 additions and 0 deletions

View File

@ -0,0 +1,62 @@
### ./Node.gitignore ###
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
# Runtime data
pids
*.pid
*.seed
*.pid.lock
# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov
# Coverage directory used by tools like istanbul
coverage
# nyc test coverage
.nyc_output
# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files)
.grunt
# Bower dependency directory (https://bower.io/)
bower_components
# node-waf configuration
.lock-wscript
# Compiled binary addons (https://nodejs.org/api/addons.html)
build/Release
# Dependency directories
node_modules/
jspm_packages/
# Typescript v1 declaration files
typings/
# Optional npm cache directory
.npm
# Optional eslint cache
.eslintcache
# Optional REPL history
.node_repl_history
# Output of 'npm pack'
*.tgz
# Yarn Integrity file
.yarn-integrity
# dotenv environment variables file
.env
build/
data/

View File

@ -0,0 +1,12 @@
declare namespace Application {
export interface User {
id: number
}
}
declare namespace Express {
export interface Request {
user?: Application.User
logInPromise(user: any): Promise<void>
}
}

View File

@ -0,0 +1,18 @@
server := src/server/index.ts
typeorm := ts-node ./node_modules/.bin/typeorm
orm:
typeorm $args
migration:
# typeorm migration:create -n $name
$typeorm migration:generate -n $name
migrate:
$typeorm migration:run
migrate-revert:
$typeorm migration:revert
start:
ts-node $server

View File

@ -0,0 +1 @@
- [ ] Try out styled-components

View File

@ -0,0 +1,25 @@
---
app:
name: Notify
baseUrl: http://localhost:3000/notify
session:
httpsOnly: false
secret:
- thisisasecret
name: notify.sid
cookie:
maxAge: 3600
db:
type: sqlite
database: data/data.db
synchronize: false
dropSchema: false
migrationsRun: false
logging: true
entities:
- src/server/entities/*.ts
migrations:
- src/server/migrations/*.ts
cli:
migrationsDir: src/server/migrations
entitiesDir: src/server/entities

View File

@ -0,0 +1 @@
---

View File

@ -0,0 +1,16 @@
module.exports = {
roots: [
'<rootDir>/src'
],
transform: {
'^.+\\.tsx?$': 'ts-jest'
},
testRegex: '(/__tests__/.*|\\.(test|spec))\\.tsx?$',
moduleFileExtensions: [
'ts',
'tsx',
'js',
'jsx'
],
setupFiles: ['<rootDir>/jest.setup.js']
}

View File

@ -0,0 +1,4 @@
if (!process.env.LOG) {
process.env.LOG = 'sql:warn'
}
// jest.mock('./src/server/database/namespace')

View File

@ -0,0 +1,2 @@
const config = require('config')
module.exports = JSON.parse(JSON.stringify(config.get('app.db')))

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,77 @@
{
"scripts": {
"test": "jest",
"lint": "tslint --project .",
"clean": "find src/ -type f -name '*.js' | xargs rm",
"watch": "npm-run-all -p '*:watch'",
"js:build": "browserify src/client/index.tsx -p [ tsify --project .] -g [ loose-envify purge --NODE_ENV production ] -v -o build/client.js",
"js:watch": "watchify src/client/index.tsx -p [tsify --project .] -v -d -o build/client.js",
"js:minify": "terser --ecma 5 --compress -o build/client.min.js --mangle -- build/client.js",
"start": "ts-node src/server/index.ts",
"start:watch": "nodemon --watch 'src/**/*.ts' --ignore 'src/**/*.test.ts' --exec ts-node src/server/index.ts",
"typeorm": "ts-node ./node_modules/.bin/typeorm"
},
"devDependencies": {
"@types/bcrypt": "^3.0.0",
"@types/body-parser": "^1.17.0",
"@types/cls-hooked": "^4.2.1",
"@types/config": "0.0.34",
"@types/csurf": "^1.9.35",
"@types/es6-shim": "^0.31.39",
"@types/express": "^4.16.0",
"@types/express-session": "^1.15.11",
"@types/http-errors": "^1.6.1",
"@types/jest": "^23.3.12",
"@types/node": "^10.12.18",
"@types/passport": "^1.0.0",
"@types/passport-local": "^1.0.33",
"@types/react": "^16.7.18",
"@types/react-dom": "^16.0.11",
"@types/react-redux": "^6.0.12",
"@types/shortid": "0.0.29",
"@types/std-mocks": "^1.0.0",
"@types/supertest": "^2.0.7",
"@types/uuid": "^3.4.4",
"browserify": "^16.2.3",
"buildfile": "^1.2.17",
"jest": "^23.6.0",
"loose-envify": "^1.4.0",
"nodemon": "^1.18.9",
"npm-run-all": "^4.1.5",
"std-mocks": "^1.0.1",
"supertest": "^3.3.0",
"terser": "^3.14.1",
"ts-jest": "^23.10.5",
"ts-node": "^7.0.1",
"tsify": "^4.0.1",
"tslint": "^5.12.0",
"typescript": "^3.2.2",
"typescript-tslint-plugin": "^0.2.1",
"watchify": "^3.11.0"
},
"dependencies": {
"bcrypt": "^3.0.3",
"body-parser": "^1.18.3",
"cls-hooked": "^4.2.2",
"config": "^3.0.1",
"csurf": "^1.9.0",
"email-validator": "^2.0.4",
"express": "^4.16.4",
"express-session": "^1.15.6",
"http-errors": "^1.7.1",
"js-yaml": "^3.12.1",
"passport": "^0.4.0",
"passport-google": "^0.3.0",
"passport-local": "^1.0.0",
"react": "^16.7.0",
"react-dom": "^16.7.0",
"react-redux": "^6.0.0",
"redux": "^4.0.1",
"reflect-metadata": "^0.1.12",
"shortid": "^2.2.14",
"sqlite3": "^4.0.4",
"typeorm": "^0.2.11",
"uuid": "^3.3.2",
"winston": "^3.1.0"
}
}

View File

@ -0,0 +1,46 @@
import React from 'react'
import {connect} from 'react-redux'
interface IComponentProps {
value: string
}
interface IStateProps {
value: string
}
export class Component
extends React.PureComponent<IComponentProps, IStateProps> {
constructor(props: IComponentProps) {
super(props)
this.state = {
value: props.value,
}
}
handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
this.setState({
value: e.target.value,
})
}
render() {
return (
<div>
<input
autoComplete='off'
type='text'
value={this.state.value}
onChange={this.handleChange}
/>
<div>{this.state.value}</div>
</div>
)
}
}
function mapStateToProps(state: any) {
return {
value: state.value,
}
}
export const CComponent = connect(mapStateToProps)(Component)

View File

@ -0,0 +1,25 @@
import ReactDOM from 'react-dom'
import React from 'react'
import {CComponent} from './components/Component'
import {Provider} from 'react-redux'
import {createStore} from './store'
const state = (window as any).__PRELOADED_STATE__
if (state) {
const store = createStore(state)
ReactDOM.hydrate(
<Provider store={store}>
<CComponent />
</Provider>,
document.body,
)
} else {
const store = createStore()
ReactDOM.render(
<Provider store={store}>
<CComponent />
</Provider>,
document.body,
)
}

View File

@ -0,0 +1,21 @@
export interface IState {
csrfToken: string
value: string
}
const defaultState: IState = {
csrfToken: '',
value: '',
}
export function value(state: IState = defaultState, action: any): IState {
switch (action && action.type) {
case 'VALUE_SET':
return {
...state,
value: action!.payload as string,
}
default:
return state || {value: ''}
}
}

View File

@ -0,0 +1,6 @@
import {createStore as create} from 'redux'
import {value, IState} from './reducers'
export function createStore(state?: IState) {
return create(value, state)
}

View File

@ -0,0 +1,36 @@
export interface IAPIDef {
'/auth/register': {
'post': {
body: {
username: string
password: string
}
}
}
'/auth/login': {
'post': {
body: {
username: string
password: string
}
}
}
'/auth/logout': {
'get': {}
},
'/users/password': {
'post': {
body: {
oldPassword: string
newPassword: string
}
}
}
'/users/profile': {
'get': {
response: {
id: number
}
}
}
}

View File

@ -0,0 +1,21 @@
export type IMethod = 'get'
| 'post'
| 'put'
| 'delete'
| 'patch'
| 'head'
| 'options'
export interface IRoutes {
// has to be any because otherwise TypeScript will start
// throwing error and interfaces without an index signature
// would not be usable
[route: string]: any
}
export interface IRoute {
params: any
query: any
body: any
response: any
}

View File

@ -0,0 +1,101 @@
import * as middleware from '../middleware'
import * as routes from '../routes'
import express from 'express'
import {AsyncRouter, TransactionalRouter} from '../router'
import {IApplication} from './IApplication'
import {IConfig} from './IConfig'
import {IDatabase} from '../database/IDatabase'
import {ILogger} from '../logger/ILogger'
import {IRoutes} from '../../common/REST'
import {ITransactionManager} from '../database/ITransactionManager'
import {IUserService, UserService} from '../services'
import {loggerFactory, LoggerFactory} from '../logger/LoggerFactory'
import {urlencoded, json} from 'body-parser'
export class Application implements IApplication {
readonly transactionManager: ITransactionManager
readonly server: express.Application
readonly userService: IUserService
readonly authenticator: middleware.Authenticator
readonly loggerFactory: LoggerFactory = loggerFactory
constructor(readonly config: IConfig, readonly database: IDatabase) {
this.transactionManager = database.transactionManager
this.userService = new UserService(this.transactionManager)
this.authenticator = new middleware.Authenticator(this.userService)
this.server = this.createServer()
}
protected getApiLogger(): ILogger {
return this.loggerFactory.getLogger('api')
}
protected createServer() {
const server = express()
server.set('trust proxy', 1)
server.disable('x-powered-by')
const router = express.Router()
this.configureMiddleware(router)
this.configureRouter(router)
server.use(this.config.app.context, router)
this.configureErrorHandling(server)
return server
}
protected configureMiddleware(router: express.Router) {
const {transactionManager} = this
const apiLogger = this.getApiLogger()
router.use('/app', urlencoded({ extended: false }))
router.use(new middleware.Session({
transactionManager,
baseUrl: this.config.app.baseUrl,
sessionName: this.config.app.session.name,
sessionSecret: this.config.app.session.secret,
}).handle)
router.use(middleware.csrf)
router.use(new middleware.Transaction(this.database.namespace).handle)
router.use(new middleware.RequestLogger(apiLogger).handle)
router.use(this.authenticator.handle)
}
protected configureRouter(router: express.Router) {
const apiLogger = this.getApiLogger()
router.use('/app', new routes.LoginRoutes(
this.userService,
this.authenticator,
this.createTransactionalRouter(),
).handle)
router.use('/app', routes.application)
router.use('/api', json())
router.use('/api', new routes.UserRoutes(
this.userService,
this.createTransactionalRouter(),
).handle)
router.use('/api', new middleware.ErrorApiHandler(apiLogger).handle)
}
protected configureErrorHandling(server: express.Application) {
const apiLogger = this.getApiLogger()
server.use(new middleware.ErrorPageHandler(apiLogger).handle)
}
createAsyncRouter<T extends IRoutes>(): AsyncRouter<T> {
return new AsyncRouter<T>()
}
createTransactionalRouter<T extends IRoutes>(): AsyncRouter<T> {
return new TransactionalRouter<T>(this.transactionManager)
}
}

View File

@ -0,0 +1,89 @@
import assert from 'assert'
import {AddressInfo} from 'net'
import {Application} from './Application'
import {Database} from '../database/Database'
import {IApplication} from './IApplication'
import {IBootstrap} from './IBootstrap'
import {IConfig} from './IConfig'
import {IDatabase} from '../database/IDatabase'
import {Server} from 'http'
import {SqlLogger, loggerFactory} from '../logger'
import {createNamespace, Namespace} from 'cls-hooked'
export class Bootstrap implements IBootstrap {
protected server?: Server
protected inUse: boolean = false
readonly application: IApplication
readonly database: IDatabase
constructor(
readonly config: IConfig,
protected readonly namespace: Namespace = createNamespace('application'),
protected readonly exit: (code: number) => void = process.exit,
) {
this.database = this.createDatabase()
this.application = this.createApplication(this.database)
}
protected createDatabase(): IDatabase {
const sqlLogger = new SqlLogger(loggerFactory.getLogger('sql'))
return new Database(this.namespace, sqlLogger, this.config.app.db)
}
protected createApplication(database: IDatabase): IApplication {
return new Application(this.config, database)
}
async listen(
port: number | string | undefined = process.env.PORT,
hostname?: string,
) {
try {
await this.start(port, hostname)
} catch (err) {
this.exit(1)
throw err
}
}
protected async start(
port: number | string | undefined = process.env.PORT,
hostname?: string,
): Promise<void> {
assert.ok(!this.inUse, 'Server already in use!')
this.inUse = true
await this.database.connect()
await new Promise((resolve, reject) => {
if (!port) {
this.server = this.application.server.listen(resolve)
return
} else if (typeof port === 'number' && hostname) {
this.server = this.application.server.listen(port, hostname, resolve)
} else {
this.server = this.application.server.listen(port, resolve)
}
})
const apiLogger = loggerFactory.getLogger('api')
if (hostname) {
apiLogger.info('Listening on %s %s', port, hostname)
} else {
apiLogger.info('Listening on %s', port)
}
}
getAddress(): AddressInfo | string {
return this.server!.address()
}
async close(): Promise<void> {
return new Promise((resolve, reject) => {
this.server!.close(resolve)
this.server = undefined
this.inUse = false
})
}
}

View File

@ -0,0 +1,12 @@
import express from 'express'
import {AsyncRouter} from '../router'
import {IRoutes} from '../../common/REST'
import {IDatabase} from '../database/IDatabase'
export interface IApplication {
readonly server: express.Application
readonly database: IDatabase
createAsyncRouter<T extends IRoutes>(): AsyncRouter<T>
createTransactionalRouter<T extends IRoutes>(): AsyncRouter<T>
}

View File

@ -0,0 +1,13 @@
import {AddressInfo} from 'net'
import {IApplication} from './IApplication'
import {IDatabase} from '../database/IDatabase'
import {IConfig} from './IConfig'
export interface IBootstrap {
readonly application: IApplication
readonly database: IDatabase
readonly config: IConfig
listen(port?: number | string, hostname?: string): Promise<void>
getAddress(): AddressInfo | string
close(): Promise<void>
}

View File

@ -0,0 +1,15 @@
import {UrlWithStringQuery} from 'url'
import {ConnectionOptions} from 'typeorm'
export interface IConfig {
readonly app: {
readonly name: string
readonly baseUrl: UrlWithStringQuery
readonly context: string
readonly session: {
readonly name: string
readonly secret: string | string[]
}
readonly db: ConnectionOptions
}
}

View File

@ -0,0 +1,3 @@
export * from './IApplication'
export * from './IConfig'
export * from './Application'

View File

@ -0,0 +1,18 @@
import cfg from 'config'
import {IConfig} from './application'
import URL from 'url'
const baseUrl = URL.parse(cfg.get('app.baseUrl'))
export const config: IConfig = {
app: {
name: cfg.get('app.name'),
baseUrl,
context: baseUrl.path!,
session: {
name: cfg.get('app.session.name'),
secret: cfg.get('app.session.secret'),
},
db: cfg.get('app.db'),
},
}

View File

@ -0,0 +1,40 @@
import {IDatabase} from './IDatabase'
import {Namespace} from 'cls-hooked'
import {TransactionManager} from './TransactionManager'
import {createConnection, Connection, ConnectionOptions, Logger} from 'typeorm'
export class Database implements IDatabase {
protected connection?: Connection
transactionManager: TransactionManager
constructor(
readonly namespace: Namespace,
protected readonly logger: Logger,
protected readonly options: ConnectionOptions,
) {
this.transactionManager = new TransactionManager(
namespace,
this.getConnection,
)
}
async connect(): Promise<Connection> {
this.connection = await createConnection({
...this.options,
logger: this.logger,
})
return this.connection
}
getConnection = (): Connection => {
if (!this.connection) {
throw new Error('Not connected! Did you call connect?')
}
return this.connection
}
async close() {
await this.getConnection().close()
}
}

View File

@ -0,0 +1,11 @@
import {Connection} from 'typeorm'
import {ITransactionManager} from './ITransactionManager'
import {Namespace} from 'cls-hooked'
export interface IDatabase {
namespace: Namespace
transactionManager: ITransactionManager
connect(): Promise<Connection>
getConnection(): Connection
close(): Promise<void>
}

View File

@ -0,0 +1,18 @@
import {
EntityManager,
EntitySchema,
ObjectType,
Repository,
} from 'typeorm'
export const ENTITY_MANAGER = 'ENTITY_MANAGER'
export interface ITransactionManager {
getEntityManager: () => EntityManager
getRepository: <Entity>(
target: ObjectType<Entity> | EntitySchema<Entity> | string,
) => Repository<Entity>
isInTransaction: () => boolean
doInTransaction: <T>(
fn: (entityManager: EntityManager) => Promise<T>) => Promise<T>
}

View File

@ -0,0 +1,59 @@
import {Namespace} from 'cls-hooked'
import {ENTITY_MANAGER, ITransactionManager} from './ITransactionManager'
import {
Connection,
EntityManager,
EntitySchema,
ObjectType,
Repository,
} from 'typeorm'
export type IConnectionGetter = () => Connection
export class TransactionManager implements ITransactionManager {
constructor(
readonly ns: Namespace,
readonly getConnection: IConnectionGetter,
) {}
getEntityManager = (): EntityManager => {
const entityManager = this.ns.get(ENTITY_MANAGER) as EntityManager
if (entityManager) {
return entityManager
}
return this.getConnection().manager
}
getRepository = <Entity>(
target: ObjectType<Entity> | EntitySchema<Entity> | string,
): Repository<Entity> => {
return this.getEntityManager().getRepository(target)
}
isInTransaction = (): boolean => {
return !!this.ns.get(ENTITY_MANAGER)
}
async doInTransaction<T>(fn: (entityManager: EntityManager) => Promise<T>) {
const alreadyInTransaction = this.isInTransaction()
if (alreadyInTransaction) {
return await fn(this.getEntityManager())
}
return this.getConnection().manager
.transaction(async entityManager => {
this.setEntityManager(entityManager)
try {
return await fn(entityManager)
} finally {
if (!alreadyInTransaction) {
this.setEntityManager(undefined)
}
}
})
}
protected setEntityManager(entityManager: EntityManager | undefined) {
this.ns.set(ENTITY_MANAGER, entityManager)
}
}

View File

@ -0,0 +1,103 @@
import {Database, ENTITY_MANAGER} from './'
import request from 'supertest'
import express, {Request, Response, NextFunction} from 'express'
import {createNamespace} from 'cls-hooked'
import {CORRELATION_ID, Transaction} from '../middleware'
import {config} from '../config'
import {SqlLogger, loggerFactory} from '../logger'
const ns = createNamespace('clsify-test')
const database = new Database(
ns,
new SqlLogger(loggerFactory.getLogger('sql')),
config.app.db,
)
describe('middleware/Transaction', () => {
const app = express()
const results: {[key: string]: string[]} = {}
function handler(req: Request, res: Response, next: NextFunction) {
results[req.params.id] = (results[req.params.id] || [])
results[req.params.id].push(ns.get(CORRELATION_ID))
setImmediate(next)
}
app.use(new Transaction(ns).handle)
app.use('/:id', handler)
app.use('/:id', handler)
app.use('/:id', handler)
app.use('/:id', handler)
app.get('/:id', (req, res) => res.end())
const size = 100
beforeEach(async () => {
const promises: Array<Promise<any>> = []
for (let i = 1; i <= size; i++) {
promises.push(request(app).get('/' + i))
}
await Promise.all(promises)
})
it('chains should have the same correlation ids', () => {
const allCorrelationIds = new Set()
const keys = Object.keys(results)
expect(keys.length).toEqual(size)
keys.forEach(key => {
const correlationIds = results[key]
expect(correlationIds.length).toEqual(4)
const id = correlationIds[0]
const allEqual = correlationIds.every(cId => cId === id)
expect(allEqual).toEqual(true)
allCorrelationIds.add(id)
})
expect(allCorrelationIds.size).toEqual(size)
})
})
describe('doInTransaction', () => {
let entityManager: any
const app = express()
app.use(new Transaction(ns).handle)
app.use('/', (req, res, next) => {
if (entityManager) {
ns.set(ENTITY_MANAGER, entityManager)
}
next()
})
app.get('/', (req, res, next) => {
const tm = database.transactionManager
tm.doInTransaction(async entMan => {
const em = tm.getEntityManager()
expect(em).toEqual(entMan)
res.json({inTransaction: !!em, alreadyIn: entityManager === em})
})
})
beforeEach(async () => {
entityManager = null
await database.connect()
})
afterEach(async () => {
await database.close()
})
it('opens a new transaction when no active transactions', async () => {
await request(app)
.get('/')
.expect(200)
.expect('{"inTransaction":true,"alreadyIn":false}')
})
it('starts a new transaction when already in a transaction', async () => {
entityManager = {}
await request(app)
.get('/')
.expect(200)
.expect('{"inTransaction":true,"alreadyIn":true}')
})
})

View File

@ -0,0 +1,4 @@
export * from './ITransactionManager'
export * from './TransactionManager'
export * from './IDatabase'
export * from './Database'

View File

@ -0,0 +1,22 @@
import {ISession} from '../session/ISession'
import {Column, Entity, PrimaryColumn, Index, ManyToOne} from 'typeorm'
import {User} from './User'
@Entity()
export class Session implements ISession {
@PrimaryColumn()
id!: string
@Index()
@Column()
expiredAt: number = Date.now()
@ManyToOne(type => User, user => user.sessions)
user?: User
@Column({ nullable: true })
userId!: number
@Column('text')
json = ''
}

View File

@ -0,0 +1,19 @@
import {Column, Entity, PrimaryGeneratedColumn, OneToMany} from 'typeorm'
import {UserEmail} from './UserEmail'
import {Session} from './Session'
@Entity()
export class User {
@PrimaryGeneratedColumn()
id!: number
@OneToMany(type => UserEmail, email => email.user)
emails!: UserEmail[]
// bcrypt encoded password
@Column({nullable: true, length: '60', select: false})
password?: string
@OneToMany(type => Session, session => session.user)
sessions!: Session[]
}

View File

@ -0,0 +1,17 @@
import {Column, Entity, PrimaryGeneratedColumn, ManyToOne} from 'typeorm'
import {User} from './User'
@Entity()
export class UserEmail {
@PrimaryGeneratedColumn()
id!: number
@Column({unique: true})
email!: string
@ManyToOne(type => User, user => user.emails)
user?: User
@Column()
userId?: number = undefined
}

View File

@ -0,0 +1,11 @@
if (!process.env.LOG) {
process.env.LOG = 'api,sql:warn'
}
import {config} from './config'
import {Bootstrap} from './application/Bootstrap'
export const bootstrap = new Bootstrap(config)
const port: string | number = process.env.PORT || 3000
bootstrap.listen(port)

View File

@ -0,0 +1,9 @@
type ILogFunction = (message: string, ...meta: any[]) => void
export interface ILogger {
error: ILogFunction
warn: ILogFunction
info: ILogFunction
debug: ILogFunction
verbose: ILogFunction
}

View File

@ -0,0 +1,5 @@
import {ILogger} from './ILogger'
export interface ILoggerFactory {
getLogger(name: string): ILogger
}

View File

@ -0,0 +1,105 @@
import {LoggerFactory, pad} from './LoggerFactory'
import stdMocks from 'std-mocks'
describe('LoggerFactory', () => {
let getLogger: typeof LoggerFactory.prototype.getLogger
beforeEach(() => {
getLogger = LoggerFactory.createFromEnv({
logs: 'test1:debug,-test3,t4,logtest5',
opts: '',
})
.getLogger
stdMocks.use();
// since winston uses console._stdout
(console as any)._stdout.write = process.stdout.write;
(console as any)._stderr.write = process.stderr.write
})
afterEach(() => {
stdMocks.restore();
(console as any)._stdout.write = process.stdout.write;
(console as any)._stderr.write = process.stderr.write
})
it('logs when enabled', () => {
const l1 = getLogger('test1')
const l2 = getLogger('test1')
const l3 = getLogger('test3')
const l4 = getLogger('t4')
const l5 = getLogger('logtest5')
const l6 = getLogger('logtest6')
expect(l1).toBe(l2)
expect(l2).not.toBe(l3)
l2.debug('test A')
l3.debug('test B')
l3.info('test C')
l4.info('test D')
l5.info('test E', { test: 5 })
l6.info('test')
// const output = stdMocks.flush()
// expect(output.stderr.length).toBe(0)
// expect(output.stdout.length).toBe(3)
// expect(output.stdout[0]).toMatch(/debug test1 test A\n$/)
// expect(output.stdout[1]).toMatch(/info {2}t4 {4}test D\n$/)
// expect(output.stdout[2]).toMatch(/info {2}logte test E\n$/)
})
describe('opts', () => {
const cases: {[key: string]: RegExp} = {
logstash: /"@message":"test"/,
color: /debug test1 test/,
json: /"message":"test"/,
}
Object.keys(cases).forEach(opt => {
describe(opt, () => {
it(`logs in ${opt} format`, () => {
getLogger = LoggerFactory.createFromEnv({
opts: opt,
logs: 'test1:debug',
}).getLogger
const l1 = getLogger('test1')
l1.debug('test')
// const output = stdMocks.flush()
// expect(output.stderr.length).toBe(0)
// expect(output.stdout.length).toBe(1)
// expect(output.stdout[0]).toMatch(cases[opt])
})
})
})
})
describe('create', () => {
it('creates a logger with defaults', () => {
LoggerFactory.createFromEnv()
})
it('logs all', () => {
const l = LoggerFactory.createFromEnv({ logs: '*' }).getLogger('test')
l.info('test123')
// const output = stdMocks.flush()
// expect(output.stderr.length).toBe(0)
// expect(output.stdout.length).toBe(1)
// expect(output.stdout[0]).toMatch(/info {2}test {2}test123\n$/)
})
})
describe('pad', () => {
it('pads space to right', () => {
expect(pad('test', 10, false)).toBe('test ')
expect(pad('test', 10, true)).toBe('test ')
})
it('does nothing when padding or trmming not needed', () => {
expect(pad('test', 4, false)).toBe('test')
expect(pad('test', 4, true)).toBe('test')
})
it('trims when trimming enabled and needed', () => {
expect(pad('test', 3, false)).toBe('test')
expect(pad('test', 3, true)).toBe('tes')
})
})
})

View File

@ -0,0 +1,138 @@
import {ILogger} from './ILogger'
import {ILoggerFactory} from './ILoggerFactory'
import {createLogger, format, transports} from 'winston'
// logging can be configured via environment variables, for example:
// `LOG='*:info,api:debug,-sql' node ...` sets all logs to info, api to debug,
// and disable all sql logs.
export function pad(text: string, n: number, trim: boolean) {
text = String(text)
if (text.length >= n) {
return trim ? text.substring(0, n) : text
}
while (text.length < n) {
text += ' '
}
return text
}
export type ILogLevel = 'error' | 'warn' | 'info' | 'debug' | 'verbose' | 'off'
export interface IEnabledLoggers {
readonly [key: string]: ILogLevel
}
export interface IParams {
readonly json: boolean
readonly color: boolean
readonly logstash: boolean,
}
export interface ILoggerOptions {
readonly enabledLoggers: IEnabledLoggers
readonly levelPad: number
readonly namePad: number
readonly params: IParams
}
export class LoggerFactory implements ILoggerFactory {
protected readonly defaultLogLevel: string
protected readonly loggers: {[key: string]: ILogger} = {}
getCorrelationId: () => string
static createFromEnv({
logs = process.env.LOG || '',
opts = process.env.LOG_OPTS || '',
} = {}) {
const enabledLoggers = logs.split(',').reduce((logConfig, log) => {
const [key, value] = log.split(':')
logConfig[key] = (value || 'info') as ILogLevel
return logConfig
}, {} as {[key: string]: ILogLevel})
const params = opts.split(',').reduce((o, key) => {
o[key] = true
return o
}, {} as {[key: string]: boolean})
return new this({
enabledLoggers,
levelPad: 5,
namePad: 5,
params: params as any as IParams,
})
}
constructor(readonly options: ILoggerOptions) {
this.defaultLogLevel = options.enabledLoggers['*'] || 'off'
this.getCorrelationId = () => ''
}
getLoggerLevel(name: string): ILogLevel {
const {enabledLoggers} = this.options
const disabled = !!enabledLoggers['-' + name]
if (disabled) {
return 'off'
}
return enabledLoggers[name] || this.defaultLogLevel
}
getLogger = (name: string): ILogger => {
if (this.loggers[name]) {
return this.loggers[name]
}
const {levelPad, namePad, params} = this.options
const addName = format((info, opts) => {
info.name = name
return info
})
const prettyFormat = format(info => {
info.message = info.timestamp + ' ' +
pad(info.level, levelPad, true) + ' ' +
pad(name, namePad, true) + ' ' +
this.getCorrelationId() + ' ' +
info.message
return info
})
const print = format.printf(info => {
return info.message
})
const formatters = [
addName(),
format.timestamp(),
format.splat(),
].filter(f => !!f)
if (params.logstash) {
formatters.push(format.logstash())
} else if (params.json) {
formatters.push(format.json())
} else if (params.color) {
formatters.push(prettyFormat())
formatters.push(format.colorize({ all: true }))
formatters.push(print)
} else {
formatters.push(prettyFormat())
formatters.push(print)
}
const logger = this.loggers[name] = createLogger({
format: format.combine.apply(format, formatters),
transports: [
new transports.Console({
handleExceptions: false,
level: this.getLoggerLevel(name),
}),
],
})
return logger
}
}
export const loggerFactory = LoggerFactory.createFromEnv()

View File

@ -0,0 +1,69 @@
import {ILogger} from './ILogger'
import {Logger, QueryRunner} from 'typeorm'
export class SqlLogger implements Logger {
constructor(protected readonly logger: ILogger) {}
logQuery(query: string, parameters?: any[], queryRunner?: QueryRunner): any {
if (parameters) {
this.logger.info('%s -- %s', query, parameters)
} else {
this.logger.info(query)
}
}
/**
* Logs query that is failed.
*/
logQueryError(
error: string,
query: string,
parameters?: any[],
queryRunner?: QueryRunner,
) {
if (parameters) {
this.logger.error('%s :: %s -- %s', error, query, parameters)
} else {
this.logger.error('%s :: %s', error, query)
}
}
/**
* Logs query that is slow.
*/
logQuerySlow(
time: number, query: string,
parameters?: any[],
queryRunner?: QueryRunner,
) {
if (parameters) {
this.logger.warn('Slow query: %d :: %s -- %s', time, query, parameters)
} else {
this.logger.warn('Slow query: %d :: %s', time, query)
}
}
/**
* Logs events from the schema build process.
*/
logSchemaBuild(message: string, queryRunner?: QueryRunner) {
this.logger.info(message)
}
/**
* Logs events from the migrations run process.
*/
logMigration(message: string, queryRunner?: QueryRunner) {
this.logger.info(message)
}
/**
* Perform logging using given logger, or by default to the console.
* Log has its own level and message.
*/
log(
level: 'log' | 'info' | 'warn',
message: any,
queryRunner?: QueryRunner,
) {
if (level === 'log') {
level = 'info'
}
this.logger[level]('%o', message)
}
}

View File

@ -0,0 +1,6 @@
export * from './LoggerFactory'
export * from './SQLLogger'
import {loggerFactory} from './LoggerFactory'
export const getLogger = loggerFactory.getLogger
export const apiLogger = getLogger('api')

View File

@ -0,0 +1,87 @@
import express, {Application} from 'express'
import request from 'supertest'
import {Authenticator} from './Authenticator'
import {ICredentials, IUserService} from '../services'
import {handlePromise} from './handlePromise'
import {urlencoded} from 'body-parser'
describe('passport.promise', () => {
let app: Application
let loginMiddleware: any
beforeEach(() => {
app = express()
const userService = new (class implements IUserService {
async createUser() {
return {id: 1}
}
async changePassword() {/* empty */}
async findOne(id: number) {
return {id}
}
async validateCredentials({username, password}: ICredentials) {
if (username === 'test' && password === 'pass') {
return {id: 1}
return
}
if (username === 'error') {
throw new Error('Test Error')
}
return undefined
}
})()
const authenticator = new Authenticator(userService)
app.use(urlencoded({ extended: false }))
app.use(authenticator.handle)
loginMiddleware = handlePromise(async (req, res, next) => {
const user = await authenticator.authenticate('local')(req, res, next)
if (!user) {
res.redirect('/failure')
return
}
await req.logInPromise(user)
res.redirect('/success')
})
})
describe('success', () => {
it('redirects to /success', async () => {
app.post('/login', loginMiddleware)
await request(app)
.post('/login')
.send('username=test&password=pass')
.expect(302)
.expect('location', '/success')
})
it('fails on error in authenticate', async () => {
app.post('/login', loginMiddleware)
await request(app)
.post('/login')
.send('username=error&password=pass')
.expect(500)
.expect(/Test Error/)
})
it('fails on error in logIn', async () => {
app.use((req, res, next) => {
req.logIn = jest.fn().mockImplementation((user, callback) => {
callback(new Error('2nd Error'))
})
next()
})
app.post('/login', loginMiddleware)
await request(app)
.post('/login')
.send('username=test&password=pass')
.expect(500)
.expect(/2nd Error/)
})
})
})

View File

@ -0,0 +1,88 @@
import {Authenticator as A, Passport} from 'passport'
import {IUserService} from '../services'
import {Strategy as LocalStrategy} from 'passport-local'
import {IHandler} from './IHandler'
import {IMiddleware} from './IMiddleware'
export class Authenticator implements IMiddleware {
protected readonly passport: A
readonly handle: IHandler[]
constructor(protected readonly userService: IUserService) {
this.passport = new Passport() as any
this.configurePassport()
this.configureStrategies()
this.handle = [
this.passport.initialize(),
this.passport.session(),
this.withLogInPromise,
]
}
withLogInPromise: IHandler = (req, res, next) => {
req.logInPromise = (user) => {
return new Promise((resolve, reject) => {
req.logIn(user, err => {
if (err) {
return reject(err)
}
resolve()
})
})
}
next()
}
protected serializeUser =
// TODO parametrize user type
(user: any, done: (err?: Error, userId?: number) => void) => {
done(undefined, user.id)
}
protected deserializeUser =
// TODO parametrize user type
(userId: number, done: (err?: Error, user?: any) => void) => {
this.userService.findOne(userId)
.then(user => done(undefined, user))
.catch(done)
}
protected configurePassport() {
this.passport.serializeUser(this.serializeUser)
this.passport.deserializeUser(this.deserializeUser)
}
protected configureStrategies() {
this.passport.use(new LocalStrategy({
passReqToCallback: false,
session: true,
}, this.validateCredentials))
}
protected validateCredentials = (
username: string,
password: string,
done: (err?: Error, user?: any) => void,
) => {
this.userService.validateCredentials({ username, password })
.then(user => done(undefined, user))
.catch(done)
}
authenticate(strategy: string | string[]): IHandler {
return (req, res, next) => {
return new Promise((resolve, reject) => {
this.passport.authenticate(strategy, (err: Error, user, info) => {
if (err) {
return reject(err)
}
resolve(user)
})(req, res, next)
})
}
}
}

View File

@ -0,0 +1,21 @@
import {IMiddleware} from './IMiddleware'
import {IErrorHandler} from './IErrorHandler'
import {ILogger} from '../logger/ILogger'
export class ErrorApiHandler implements IMiddleware {
constructor(readonly logger: ILogger) {}
handle: IErrorHandler = (err, req, res, next) => {
this.logger.error('An API error occurred: %s', err.stack)
const statusCode = this.getStatus(err)
res.status(statusCode)
res.end('An error occurred')
}
protected getStatus(err: Error): number {
if (typeof (err as any).status === 'number') {
return (err as any).status
}
return 500
}
}

View File

@ -0,0 +1,22 @@
import {IMiddleware} from './IMiddleware'
import {IErrorHandler} from './IErrorHandler'
import {ILogger} from '../logger/ILogger'
export class ErrorPageHandler implements IMiddleware {
constructor(readonly logger: ILogger) {}
handle: IErrorHandler = (err, req, res, next) => {
this.logger.error('An error occurred: %s', err.stack)
// TODO Show an error page!
const statusCode = this.getStatus(err)
res.status(statusCode)
res.end('An error occurred')
}
protected getStatus(err: Error): number {
if (typeof (err as any).status === 'number') {
return (err as any).status
}
return 500
}
}

View File

@ -0,0 +1,4 @@
import {Request, Response, NextFunction} from 'express'
export type IErrorHandler =
(err: Error, req: Request, res: Response, next: NextFunction) => any

View File

@ -0,0 +1,3 @@
import {Request, Response, NextFunction} from 'express'
export type IHandler = (req: Request, res: Response, next: NextFunction) => any

View File

@ -0,0 +1,6 @@
import {IHandler} from './IHandler'
import {IErrorHandler} from './IErrorHandler'
export interface IMiddleware {
handle: IHandler | IHandler[] | IErrorHandler
}

View File

@ -0,0 +1,4 @@
import {Request, Response, NextFunction} from 'express'
export type IPromiseHandler<T> =
(req: Request, res: Response, next: NextFunction) => Promise<T>

View File

@ -0,0 +1,19 @@
import {IHandler} from './IHandler'
import {ILogger} from '../logger/ILogger'
import {IMiddleware} from './IMiddleware'
export class RequestLogger implements IMiddleware {
constructor(protected readonly logger: ILogger) {}
handle: IHandler = (req, res, next) => {
const start = Date.now()
res.on('finish', () => {
const duration = Date.now() - start
const { method, originalUrl } = req
const { statusCode } = res
this.logger.info('%s %s %d %sms',
method, originalUrl, statusCode, duration)
})
next()
}
}

View File

@ -0,0 +1,52 @@
import ExpressSession from 'express-session'
import {IHandler} from './IHandler'
import {IMiddleware} from './IMiddleware'
import {ISession} from '../session/ISession'
import {ITransactionManager} from '../database/ITransactionManager'
import {Session as SessionEntity} from '../entities/Session'
import {SessionStore} from '../session/SessionStore'
import {UrlWithStringQuery} from 'url'
export interface ISessionOptions {
transactionManager: ITransactionManager,
baseUrl: UrlWithStringQuery,
sessionName: string,
sessionSecret: string | string[],
}
export class Session implements IMiddleware {
readonly handle: IHandler
constructor(readonly params: ISessionOptions) {
this.handle = ExpressSession({
saveUninitialized: false,
secret: params.sessionSecret,
resave: false,
rolling: true,
name: params.sessionName,
cookie: {
maxAge: 3600,
httpOnly: true,
sameSite: true,
secure: params.baseUrl.protocol === 'https',
path: params.baseUrl.path,
},
store: new SessionStore({
cleanup: 1,
getRepository: this.getRepository,
ttl: 1,
buildSession: this.buildSession,
}),
})
}
protected buildSession = (sessionData: Express.SessionData, sess: ISession)
: SessionEntity => {
return {...sess, userId: sessionData.userId }
}
protected getRepository = () => {
return this.params.transactionManager.getRepository(SessionEntity)
}
}

View File

@ -0,0 +1,32 @@
import shortid from 'shortid'
import {IMiddleware} from './IMiddleware'
import {IHandler} from './IHandler'
import {Namespace} from 'cls-hooked'
export const CORRELATION_ID = 'CORRELATION_ID'
export class Transaction implements IMiddleware {
constructor(readonly ns: Namespace) {}
handle: IHandler = (req, res, next) => {
const {ns} = this
ns.bindEmitter(req)
ns.bindEmitter(res)
ns.run(() => {
const correlationId = shortid.generate();
(req as any).correlationId = correlationId
ns.set(CORRELATION_ID, correlationId)
next()
})
}
getCorrelationId = (): string => {
try {
return this.ns.get(CORRELATION_ID)
} catch (err) {
return ''
}
}
}

View File

@ -0,0 +1,6 @@
import Csurf from 'csurf'
import {IHandler} from './IHandler'
export const csrf: IHandler = Csurf({
sessionKey: 'session',
})

View File

@ -0,0 +1,68 @@
import {ensureLoggedInApi, ensureLoggedInSite} from './ensureLoggedIn'
import express, {
Application, Request, Response, NextFunction as Next,
} from 'express'
import request from 'supertest'
function createMockUserMiddleware() {
const context: {user?: any} = {}
function middleware(req: Request, res: Response, next: Next) {
(req as any).user = context.user
next()
}
return {context, middleware}
}
describe('user login', () => {
const {context, middleware} = createMockUserMiddleware()
let app: Application
beforeEach(() => {
context.user = null
app = express()
app.use('/', middleware)
app.use('/api', ensureLoggedInApi)
app.get('/api', (req, res) => res.json({status: 'ok'}))
app.use('/app', ensureLoggedInSite('/login'))
app.get('/app', (req, res) => res.end('ok'))
})
describe('userLoggedInApi', () => {
it('should result in 401 when user not logged in', async () => {
await request(app)
.get('/api')
.expect(401)
})
it('should result in 200 when user logged in', async () => {
context.user = {}
await request(app)
.get('/api')
.expect(200)
})
})
describe('userLoggedInSite', () => {
it('should result in redirect when user not logged in', async () => {
await request(app)
.get('/app')
.expect(302)
.expect('Location', '/login')
})
it('should result in 200 when user logged in', async () => {
context.user = {}
await request(app)
.get('/app')
.expect(200)
})
})
})

View File

@ -0,0 +1,23 @@
import createError from 'http-errors'
import {Request} from 'express'
import {IHandler} from './IHandler'
const isLoggedIn = (req: Request) => !!(req as any).user
export const ensureLoggedInApi: IHandler = (req, res, next) => {
if (!isLoggedIn(req)) {
next(createError(401))
return
}
next()
}
export const ensureLoggedInSite = (redirectTo: string): IHandler => {
return function _ensureLoggedInSite(req, res, next) {
if (!isLoggedIn(req)) {
res.redirect(redirectTo)
return
}
next()
}
}

View File

@ -0,0 +1,11 @@
import {IHandler} from './IHandler'
import {IPromiseHandler} from './IPromiseHandler'
export function handlePromise<T>(endpoint: IPromiseHandler<T>): IHandler {
return (req, res, next) => {
const promise = endpoint(req, res, next)
promise
.then(result => res.json(result))
.catch(next)
}
}

View File

@ -0,0 +1,13 @@
export * from './Authenticator'
export * from './csrf'
export * from './ensureLoggedIn'
export * from './ErrorApiHandler'
export * from './ErrorPageHandler'
export * from './handlePromise'
export * from './IErrorHandler'
export * from './IHandler'
export * from './IMiddleware'
export * from './IPromiseHandler'
export * from './RequestLogger'
export * from './Session'
export * from './Transaction'

View File

@ -0,0 +1,23 @@
import {MigrationInterface, QueryRunner} from "typeorm";
export class user1547031984999 implements MigrationInterface {
public async up(queryRunner: QueryRunner): Promise<any> {
await queryRunner.query(`CREATE TABLE "user_email" ("id" integer PRIMARY KEY AUTOINCREMENT NOT NULL, "email" varchar NOT NULL, "userId" integer, CONSTRAINT "UQ_f2bff75d7c18f08db06f81934b6" UNIQUE ("email"))`);
await queryRunner.query(`CREATE TABLE "user" ("id" integer PRIMARY KEY AUTOINCREMENT NOT NULL)`);
await queryRunner.query(`CREATE TABLE "temporary_user_email" ("id" integer PRIMARY KEY AUTOINCREMENT NOT NULL, "email" varchar NOT NULL, "userId" integer, CONSTRAINT "UQ_f2bff75d7c18f08db06f81934b6" UNIQUE ("email"), CONSTRAINT "FK_9ada349d19d368d20fbf613eef9" FOREIGN KEY ("userId") REFERENCES "user" ("id"))`);
await queryRunner.query(`INSERT INTO "temporary_user_email"("id", "email", "userId") SELECT "id", "email", "userId" FROM "user_email"`);
await queryRunner.query(`DROP TABLE "user_email"`);
await queryRunner.query(`ALTER TABLE "temporary_user_email" RENAME TO "user_email"`);
}
public async down(queryRunner: QueryRunner): Promise<any> {
await queryRunner.query(`ALTER TABLE "user_email" RENAME TO "temporary_user_email"`);
await queryRunner.query(`CREATE TABLE "user_email" ("id" integer PRIMARY KEY AUTOINCREMENT NOT NULL, "email" varchar NOT NULL, "userId" integer, CONSTRAINT "UQ_f2bff75d7c18f08db06f81934b6" UNIQUE ("email"))`);
await queryRunner.query(`INSERT INTO "user_email"("id", "email", "userId") SELECT "id", "email", "userId" FROM "temporary_user_email"`);
await queryRunner.query(`DROP TABLE "temporary_user_email"`);
await queryRunner.query(`DROP TABLE "user"`);
await queryRunner.query(`DROP TABLE "user_email"`);
}
}

View File

@ -0,0 +1,67 @@
import {MigrationInterface, QueryRunner} from "typeorm";
export class session1547474320589 implements MigrationInterface {
public async up(queryRunner: QueryRunner): Promise<any> {
await queryRunner.query(`CREATE TABLE "temporary_user_email" ("id" integer PRIMARY KEY AUTOINCREMENT NOT NULL, "email" varchar NOT NULL, "userId" integer, CONSTRAINT "UQ_f2bff75d7c18f08db06f81934b6" UNIQUE ("email"), CONSTRAINT "FK_9ada349d19d368d20fbf613eef9" FOREIGN KEY ("userId") REFERENCES "user" ("id") ON DELETE NO ACTION ON UPDATE NO ACTION)`);
await queryRunner.query(`INSERT INTO "temporary_user_email"("id", "email", "userId") SELECT "id", "email", "userId" FROM "user_email"`);
await queryRunner.query(`DROP TABLE "user_email"`);
await queryRunner.query(`ALTER TABLE "temporary_user_email" RENAME TO "user_email"`);
await queryRunner.query(`CREATE TABLE "session" ("id" varchar PRIMARY KEY NOT NULL, "expiredAt" integer NOT NULL, "userId" integer NOT NULL, "json" text NOT NULL)`);
await queryRunner.query(`CREATE INDEX "IDX_28c5d1d16da7908c97c9bc2f74" ON "session" ("expiredAt") `);
await queryRunner.query(`CREATE TABLE "temporary_user" ("id" integer PRIMARY KEY AUTOINCREMENT NOT NULL, "password" varchar(60))`);
await queryRunner.query(`INSERT INTO "temporary_user"("id") SELECT "id" FROM "user"`);
await queryRunner.query(`DROP TABLE "user"`);
await queryRunner.query(`ALTER TABLE "temporary_user" RENAME TO "user"`);
await queryRunner.query(`CREATE TABLE "temporary_user_email" ("id" integer PRIMARY KEY AUTOINCREMENT NOT NULL, "email" varchar NOT NULL, "userId" integer, CONSTRAINT "UQ_f2bff75d7c18f08db06f81934b6" UNIQUE ("email"))`);
await queryRunner.query(`INSERT INTO "temporary_user_email"("id", "email", "userId") SELECT "id", "email", "userId" FROM "user_email"`);
await queryRunner.query(`DROP TABLE "user_email"`);
await queryRunner.query(`ALTER TABLE "temporary_user_email" RENAME TO "user_email"`);
await queryRunner.query(`CREATE TABLE "temporary_user_email" ("id" integer PRIMARY KEY AUTOINCREMENT NOT NULL, "email" varchar NOT NULL, "userId" integer NOT NULL, CONSTRAINT "UQ_f2bff75d7c18f08db06f81934b6" UNIQUE ("email"))`);
await queryRunner.query(`INSERT INTO "temporary_user_email"("id", "email", "userId") SELECT "id", "email", "userId" FROM "user_email"`);
await queryRunner.query(`DROP TABLE "user_email"`);
await queryRunner.query(`ALTER TABLE "temporary_user_email" RENAME TO "user_email"`);
await queryRunner.query(`CREATE TABLE "temporary_user_email" ("id" integer PRIMARY KEY AUTOINCREMENT NOT NULL, "email" varchar NOT NULL, "userId" integer NOT NULL, CONSTRAINT "UQ_f2bff75d7c18f08db06f81934b6" UNIQUE ("email"), CONSTRAINT "FK_9ada349d19d368d20fbf613eef9" FOREIGN KEY ("userId") REFERENCES "user" ("id"))`);
await queryRunner.query(`INSERT INTO "temporary_user_email"("id", "email", "userId") SELECT "id", "email", "userId" FROM "user_email"`);
await queryRunner.query(`DROP TABLE "user_email"`);
await queryRunner.query(`ALTER TABLE "temporary_user_email" RENAME TO "user_email"`);
await queryRunner.query(`DROP INDEX "IDX_28c5d1d16da7908c97c9bc2f74"`);
await queryRunner.query(`CREATE TABLE "temporary_session" ("id" varchar PRIMARY KEY NOT NULL, "expiredAt" integer NOT NULL, "userId" integer NOT NULL, "json" text NOT NULL, CONSTRAINT "FK_3d2f174ef04fb312fdebd0ddc53" FOREIGN KEY ("userId") REFERENCES "user" ("id"))`);
await queryRunner.query(`INSERT INTO "temporary_session"("id", "expiredAt", "userId", "json") SELECT "id", "expiredAt", "userId", "json" FROM "session"`);
await queryRunner.query(`DROP TABLE "session"`);
await queryRunner.query(`ALTER TABLE "temporary_session" RENAME TO "session"`);
await queryRunner.query(`CREATE INDEX "IDX_28c5d1d16da7908c97c9bc2f74" ON "session" ("expiredAt") `);
}
public async down(queryRunner: QueryRunner): Promise<any> {
await queryRunner.query(`DROP INDEX "IDX_28c5d1d16da7908c97c9bc2f74"`);
await queryRunner.query(`ALTER TABLE "session" RENAME TO "temporary_session"`);
await queryRunner.query(`CREATE TABLE "session" ("id" varchar PRIMARY KEY NOT NULL, "expiredAt" integer NOT NULL, "userId" integer NOT NULL, "json" text NOT NULL)`);
await queryRunner.query(`INSERT INTO "session"("id", "expiredAt", "userId", "json") SELECT "id", "expiredAt", "userId", "json" FROM "temporary_session"`);
await queryRunner.query(`DROP TABLE "temporary_session"`);
await queryRunner.query(`CREATE INDEX "IDX_28c5d1d16da7908c97c9bc2f74" ON "session" ("expiredAt") `);
await queryRunner.query(`ALTER TABLE "user_email" RENAME TO "temporary_user_email"`);
await queryRunner.query(`CREATE TABLE "user_email" ("id" integer PRIMARY KEY AUTOINCREMENT NOT NULL, "email" varchar NOT NULL, "userId" integer NOT NULL, CONSTRAINT "UQ_f2bff75d7c18f08db06f81934b6" UNIQUE ("email"))`);
await queryRunner.query(`INSERT INTO "user_email"("id", "email", "userId") SELECT "id", "email", "userId" FROM "temporary_user_email"`);
await queryRunner.query(`DROP TABLE "temporary_user_email"`);
await queryRunner.query(`ALTER TABLE "user_email" RENAME TO "temporary_user_email"`);
await queryRunner.query(`CREATE TABLE "user_email" ("id" integer PRIMARY KEY AUTOINCREMENT NOT NULL, "email" varchar NOT NULL, "userId" integer, CONSTRAINT "UQ_f2bff75d7c18f08db06f81934b6" UNIQUE ("email"))`);
await queryRunner.query(`INSERT INTO "user_email"("id", "email", "userId") SELECT "id", "email", "userId" FROM "temporary_user_email"`);
await queryRunner.query(`DROP TABLE "temporary_user_email"`);
await queryRunner.query(`ALTER TABLE "user_email" RENAME TO "temporary_user_email"`);
await queryRunner.query(`CREATE TABLE "user_email" ("id" integer PRIMARY KEY AUTOINCREMENT NOT NULL, "email" varchar NOT NULL, "userId" integer, CONSTRAINT "UQ_f2bff75d7c18f08db06f81934b6" UNIQUE ("email"), CONSTRAINT "FK_9ada349d19d368d20fbf613eef9" FOREIGN KEY ("userId") REFERENCES "user" ("id") ON DELETE NO ACTION ON UPDATE NO ACTION)`);
await queryRunner.query(`INSERT INTO "user_email"("id", "email", "userId") SELECT "id", "email", "userId" FROM "temporary_user_email"`);
await queryRunner.query(`DROP TABLE "temporary_user_email"`);
await queryRunner.query(`ALTER TABLE "user" RENAME TO "temporary_user"`);
await queryRunner.query(`CREATE TABLE "user" ("id" integer PRIMARY KEY AUTOINCREMENT NOT NULL)`);
await queryRunner.query(`INSERT INTO "user"("id") SELECT "id" FROM "temporary_user"`);
await queryRunner.query(`DROP TABLE "temporary_user"`);
await queryRunner.query(`DROP INDEX "IDX_28c5d1d16da7908c97c9bc2f74"`);
await queryRunner.query(`DROP TABLE "session"`);
await queryRunner.query(`ALTER TABLE "user_email" RENAME TO "temporary_user_email"`);
await queryRunner.query(`CREATE TABLE "user_email" ("id" integer PRIMARY KEY AUTOINCREMENT NOT NULL, "email" varchar NOT NULL, "userId" integer, CONSTRAINT "UQ_f2bff75d7c18f08db06f81934b6" UNIQUE ("email"), CONSTRAINT "FK_9ada349d19d368d20fbf613eef9" FOREIGN KEY ("userId") REFERENCES "user" ("id") ON DELETE NO ACTION ON UPDATE NO ACTION)`);
await queryRunner.query(`INSERT INTO "user_email"("id", "email", "userId") SELECT "id", "email", "userId" FROM "temporary_user_email"`);
await queryRunner.query(`DROP TABLE "temporary_user_email"`);
}
}

View File

@ -0,0 +1,51 @@
import {MigrationInterface, QueryRunner} from "typeorm";
export class sessionUserId1547480973242 implements MigrationInterface {
public async up(queryRunner: QueryRunner): Promise<any> {
await queryRunner.query(`DROP INDEX "IDX_28c5d1d16da7908c97c9bc2f74"`);
await queryRunner.query(`CREATE TABLE "temporary_session" ("id" varchar PRIMARY KEY NOT NULL, "expiredAt" integer NOT NULL, "userId" integer NOT NULL, "json" text NOT NULL, CONSTRAINT "FK_3d2f174ef04fb312fdebd0ddc53" FOREIGN KEY ("userId") REFERENCES "user" ("id") ON DELETE NO ACTION ON UPDATE NO ACTION)`);
await queryRunner.query(`INSERT INTO "temporary_session"("id", "expiredAt", "userId", "json") SELECT "id", "expiredAt", "userId", "json" FROM "session"`);
await queryRunner.query(`DROP TABLE "session"`);
await queryRunner.query(`ALTER TABLE "temporary_session" RENAME TO "session"`);
await queryRunner.query(`CREATE TABLE "temporary_session" ("id" varchar PRIMARY KEY NOT NULL, "expiredAt" integer NOT NULL, "userId" integer NOT NULL, "json" text NOT NULL)`);
await queryRunner.query(`INSERT INTO "temporary_session"("id", "expiredAt", "userId", "json") SELECT "id", "expiredAt", "userId", "json" FROM "session"`);
await queryRunner.query(`DROP TABLE "session"`);
await queryRunner.query(`ALTER TABLE "temporary_session" RENAME TO "session"`);
await queryRunner.query(`CREATE TABLE "temporary_session" ("id" varchar PRIMARY KEY NOT NULL, "expiredAt" integer NOT NULL, "userId" integer, "json" text NOT NULL)`);
await queryRunner.query(`INSERT INTO "temporary_session"("id", "expiredAt", "userId", "json") SELECT "id", "expiredAt", "userId", "json" FROM "session"`);
await queryRunner.query(`DROP TABLE "session"`);
await queryRunner.query(`ALTER TABLE "temporary_session" RENAME TO "session"`);
await queryRunner.query(`CREATE INDEX "IDX_28c5d1d16da7908c97c9bc2f74" ON "session" ("expiredAt") `);
await queryRunner.query(`DROP INDEX "IDX_28c5d1d16da7908c97c9bc2f74"`);
await queryRunner.query(`CREATE TABLE "temporary_session" ("id" varchar PRIMARY KEY NOT NULL, "expiredAt" integer NOT NULL, "userId" integer, "json" text NOT NULL, CONSTRAINT "FK_3d2f174ef04fb312fdebd0ddc53" FOREIGN KEY ("userId") REFERENCES "user" ("id"))`);
await queryRunner.query(`INSERT INTO "temporary_session"("id", "expiredAt", "userId", "json") SELECT "id", "expiredAt", "userId", "json" FROM "session"`);
await queryRunner.query(`DROP TABLE "session"`);
await queryRunner.query(`ALTER TABLE "temporary_session" RENAME TO "session"`);
await queryRunner.query(`CREATE INDEX "IDX_28c5d1d16da7908c97c9bc2f74" ON "session" ("expiredAt") `);
}
public async down(queryRunner: QueryRunner): Promise<any> {
await queryRunner.query(`DROP INDEX "IDX_28c5d1d16da7908c97c9bc2f74"`);
await queryRunner.query(`ALTER TABLE "session" RENAME TO "temporary_session"`);
await queryRunner.query(`CREATE TABLE "session" ("id" varchar PRIMARY KEY NOT NULL, "expiredAt" integer NOT NULL, "userId" integer, "json" text NOT NULL)`);
await queryRunner.query(`INSERT INTO "session"("id", "expiredAt", "userId", "json") SELECT "id", "expiredAt", "userId", "json" FROM "temporary_session"`);
await queryRunner.query(`DROP TABLE "temporary_session"`);
await queryRunner.query(`CREATE INDEX "IDX_28c5d1d16da7908c97c9bc2f74" ON "session" ("expiredAt") `);
await queryRunner.query(`DROP INDEX "IDX_28c5d1d16da7908c97c9bc2f74"`);
await queryRunner.query(`ALTER TABLE "session" RENAME TO "temporary_session"`);
await queryRunner.query(`CREATE TABLE "session" ("id" varchar PRIMARY KEY NOT NULL, "expiredAt" integer NOT NULL, "userId" integer NOT NULL, "json" text NOT NULL)`);
await queryRunner.query(`INSERT INTO "session"("id", "expiredAt", "userId", "json") SELECT "id", "expiredAt", "userId", "json" FROM "temporary_session"`);
await queryRunner.query(`DROP TABLE "temporary_session"`);
await queryRunner.query(`ALTER TABLE "session" RENAME TO "temporary_session"`);
await queryRunner.query(`CREATE TABLE "session" ("id" varchar PRIMARY KEY NOT NULL, "expiredAt" integer NOT NULL, "userId" integer NOT NULL, "json" text NOT NULL, CONSTRAINT "FK_3d2f174ef04fb312fdebd0ddc53" FOREIGN KEY ("userId") REFERENCES "user" ("id") ON DELETE NO ACTION ON UPDATE NO ACTION)`);
await queryRunner.query(`INSERT INTO "session"("id", "expiredAt", "userId", "json") SELECT "id", "expiredAt", "userId", "json" FROM "temporary_session"`);
await queryRunner.query(`DROP TABLE "temporary_session"`);
await queryRunner.query(`ALTER TABLE "session" RENAME TO "temporary_session"`);
await queryRunner.query(`CREATE TABLE "session" ("id" varchar PRIMARY KEY NOT NULL, "expiredAt" integer NOT NULL, "userId" integer NOT NULL, "json" text NOT NULL, CONSTRAINT "FK_3d2f174ef04fb312fdebd0ddc53" FOREIGN KEY ("userId") REFERENCES "user" ("id") ON DELETE NO ACTION ON UPDATE NO ACTION)`);
await queryRunner.query(`INSERT INTO "session"("id", "expiredAt", "userId", "json") SELECT "id", "expiredAt", "userId", "json" FROM "temporary_session"`);
await queryRunner.query(`DROP TABLE "temporary_session"`);
await queryRunner.query(`CREATE INDEX "IDX_28c5d1d16da7908c97c9bc2f74" ON "session" ("expiredAt") `);
}
}

View File

@ -0,0 +1,73 @@
import express from 'express'
import request from 'supertest'
import {AsyncRouter} from './AsyncRouter'
describe('AsyncRouter', () => {
interface IResponse {
value: string
}
interface IParam {
param: string
}
interface IHandler {
params: IParam,
response: IResponse,
}
interface IMyApi {
'/test/:param': {
get: IHandler
post: IHandler
put: IHandler
delete: IHandler
options: IHandler
patch: IHandler
head: {},
}
}
const app = express()
const router = express.Router()
app.use(router)
const asyncRouter = new AsyncRouter<IMyApi>(router)
asyncRouter.get('/test/:param', async req => {
return {value: req.params.param}
})
asyncRouter.post('/test/:param', async req => {
return {value: req.params.param}
})
asyncRouter.put('/test/:param', async req => {
return {value: req.params.param}
})
asyncRouter.delete('/test/:param', async req => {
return {value: req.params.param}
})
asyncRouter.options('/test/:param', async req => {
return {value: req.params.param}
})
asyncRouter.patch('/test/:param', async req => {
throw new Error('test')
})
asyncRouter.head('/test/:param', async req => {
return ''
})
it('creates its own router when not provided', () => {
const r = new AsyncRouter<IMyApi>()
expect(r.router).toBeTruthy()
})
it('should work and handle errors', async () => {
await request(app).get('/test/a').expect(200).expect('{"value":"a"}')
await request(app).post('/test/a').expect(200).expect('{"value":"a"}')
await request(app).put('/test/a').expect(200).expect('{"value":"a"}')
await request(app).delete('/test/a').expect(200).expect('{"value":"a"}')
await request(app).options('/test/a').expect(200).expect('{"value":"a"}')
await request(app).patch('/test/a').expect(500)
await request(app).head('/test/a').expect(200)
})
})

View File

@ -0,0 +1,76 @@
import {IRoutes, IRoute, IMethod} from '../../common/REST'
import express, {NextFunction} from 'express'
export interface IRequest<T extends IRoute> extends express.Request {
body: T['body']
params: T['params']
query: T['query']
}
export type IHandler<R extends IRoutes, P extends keyof R, M extends IMethod> =
(req: IRequest<R[P][M]>, res: express.Response, next: NextFunction) =>
Promise<R[P][M]['response']>
export class AsyncRouter<R extends IRoutes> {
readonly router: express.Router
readonly use: express.IRouterHandler<void> & express.IRouterMatcher<void>
constructor(router?: express.Application | express.Router) {
this.router = router ? router : express.Router()
this.use = this.router.use.bind(this.router) as any
}
protected addRoute<M extends IMethod, P extends keyof R & string>(
method: M,
path: P,
handler: IHandler<R, P, M>,
) {
const addRoute = this.router[method].bind(this.router)
addRoute(path, this.wrapHandler(handler))
}
protected wrapHandler<M extends IMethod, P extends keyof R & string>(
handler: IHandler<R, P, M>,
): express.RequestHandler {
return (req, res, next) => {
handler(req, res, next)
.then(response => {
res.json(response)
})
.catch(next)
}
}
get<P extends keyof R & string>(path: P, handler: IHandler<R, P, 'get'>) {
this.addRoute('get', path, handler)
}
post<P extends keyof R & string>(path: P, handler: IHandler<R, P, 'post'>) {
this.addRoute('post', path, handler)
}
put<P extends keyof R & string>(path: P, handler: IHandler<R, P, 'put'>) {
this.addRoute('put', path, handler)
}
delete<P extends keyof R & string>(
path: P, handler: IHandler<R, P, 'delete'>) {
this.addRoute('delete', path, handler)
}
head<P extends keyof R & string>(path: P, handler: IHandler<R, P, 'head'>) {
this.addRoute('head', path, handler)
}
options<P extends keyof R & string>(
path: P, handler: IHandler<R, P, 'options'>) {
this.addRoute('options', path, handler)
}
patch<P extends keyof R & string>(
path: P, handler: IHandler<R, P, 'patch'>) {
this.addRoute('patch', path, handler)
}
}

View File

@ -0,0 +1,23 @@
import express from 'express'
import {AsyncRouter, IHandler} from './AsyncRouter'
import {IRoutes, IMethod} from '../../common/REST'
import {ITransactionManager} from '../database/ITransactionManager'
export class TransactionalRouter<R extends IRoutes> extends AsyncRouter<R> {
constructor(readonly transactionManager: ITransactionManager) {
super()
}
protected wrapHandler<M extends IMethod, P extends keyof R & string>(
handler: IHandler<R, P, M>,
): express.RequestHandler {
return async (req, res, next) => {
await this.transactionManager
.doInTransaction(async () => {
const response = await handler(req, res, next)
res.json(response)
})
.catch(next)
}
}
}

View File

@ -0,0 +1,2 @@
export * from './AsyncRouter'
export * from './TransactionalRouter'

View File

@ -0,0 +1,14 @@
import {IHandler} from '../middleware/IHandler'
import {AsyncRouter} from '../router'
import {IAPIDef} from '../../common/IAPIDef'
export abstract class BaseRoute<T extends IAPIDef> {
readonly handle: IHandler
constructor(protected readonly t: AsyncRouter<T>) {
this.handle = t.router
this.setup(t)
}
protected abstract setup(t: AsyncRouter<T>): void
}

View File

@ -0,0 +1,41 @@
import {test} from '../test'
describe('login', () => {
test.withDatabase()
describe('/register', () => {
it('should create a new user account', async () => {
await test.registerAccount()
})
})
describe('/login', () => {
beforeEach(async () => {
await test.registerAccount()
})
it('should log in the newly created user', async () => {
await test.login()
})
})
describe('/logout', () => {
let cookie!: string
beforeEach(async () => {
await test.registerAccount()
cookie = (await test.login()).cookie
})
it('should log out the user', async () => {
await test.request('/app')
.get('/auth/logout')
.set('cookie', cookie)
.expect(302)
.expect('location', `${test.context}/app/auth/login`)
})
})
})

View File

@ -0,0 +1,43 @@
import {AsyncRouter} from '../router'
import {BaseRoute} from './BaseRoute'
import {IAPIDef} from '../../common/IAPIDef'
import {IUserService} from '../services'
import {Authenticator} from '../middleware'
export class LoginRoutes extends BaseRoute<IAPIDef> {
constructor(
protected readonly userService: IUserService,
protected readonly authenticator: Authenticator,
protected readonly t: AsyncRouter<IAPIDef>,
) {
super(t)
}
setup(t: AsyncRouter<IAPIDef>) {
t.post('/auth/register', async (req, res) => {
const user = await this.userService.createUser({
username: req.body.username,
password: req.body.password,
})
await req.logInPromise(user)
res.redirect(req.baseUrl)
})
t.post('/auth/login', async (req, res, next) => {
const user = await this.authenticator
.authenticate('local')(req, res, next)
if (!user) {
res.redirect(`${req.baseUrl}/auth/login`)
return
}
await req.logInPromise(user)
res.redirect(req.baseUrl)
})
t.get('/auth/logout', async (req, res) => {
req.logout()
res.redirect(`${req.baseUrl}/auth/login`)
})
}
}

View File

@ -0,0 +1,51 @@
import {test} from '../test'
describe('user', () => {
test.withDatabase()
const t = test.request('/api')
let cookie!: string
let token!: string
beforeEach(async () => {
await test.registerAccount()
const session = await test.login()
cookie = session.cookie
token = session.token
t.setHeaders({ cookie, 'x-csrf-token': token })
})
it('should prevent access when user not logged in', async () => {
await t
.setHeaders({ token })
.get(`/users/password`)
.expect(401)
})
describe('POST /users/password', () => {
it('changes user password when passwords match', async () => {
await t
.post('/users/password')
.send({ oldPassword: test.password, newPassword: 'newPass' })
.expect(200)
await test.login(test.username, 'newPass')
})
it('returns 400 when passwords do not match', async () => {
await t
.post('/users/password')
.send({ oldPassword: 'invalid-password', newPassword: 'newPass' })
.expect(400)
})
})
describe('GET /users/profile', () => {
it('fetches user profile', async () => {
t.setHeaders({ cookie })
await t
.get('/users/profile')
.expect(200)
})
})
})

View File

@ -0,0 +1,30 @@
import {AsyncRouter} from '../router'
import {BaseRoute} from './BaseRoute'
import {IAPIDef} from '../../common/IAPIDef'
import {IUserService} from '../services'
import {ensureLoggedInApi} from '../middleware'
export class UserRoutes extends BaseRoute<IAPIDef> {
constructor(
protected readonly userService: IUserService,
protected readonly t: AsyncRouter<IAPIDef>,
) {
super(t)
}
setup(t: AsyncRouter<IAPIDef>) {
t.use(ensureLoggedInApi)
t.post('/users/password', async req => {
await this.userService.changePassword({
userId: req.user!.id,
oldPassword: req.body.oldPassword,
newPassword: req.body.newPassword,
})
})
t.get('/users/profile', async req => {
return (await this.userService.findOne(req.user!.id))!
})
}
}

View File

@ -0,0 +1,45 @@
import React from 'react'
import {CComponent} from '../../client/components/Component'
import {Provider} from 'react-redux'
import {Router} from 'express'
import {createReadStream} from 'fs'
import {createStore} from '../../client/store'
import {join} from 'path'
import {renderToNodeStream} from 'react-dom/server'
export const application = Router()
application.get('/client.js', (req, res) => {
const stream = createReadStream(join(__dirname, '../build/client.js'))
stream.pipe(res)
})
application.get('/no-ssr', (req, res) => {
res.write('<!DOCTYPE html><html><head><title>My Page</title></head><body>')
res.write(`</body><script src='client.js'></script></html>`)
res.end()
})
application.get('/', (req, res) => {
const store = createStore({
csrfToken: req.csrfToken(),
value: '1234',
})
const stream = renderToNodeStream(
<Provider store={store}>
<CComponent />
</Provider>,
)
const state = store.getState()
res.write('<!DOCTYPE html><html><head><title>My Page</title></head><body>')
// TODO attach javascript
stream.pipe(res, { end: false })
stream.on('end', () => {
res.write(`</body>
<script>window.__PRELOADED_STATE__ = ${JSON.stringify(state)
.replace( /</g, '\\u003c')}</script>
<script src='client.js'></script>
</html>`)
res.end()
})
})

View File

@ -0,0 +1,4 @@
export * from './application'
export * from './BaseRoute'
export * from './LoginRoutes'
export * from './UserRoutes'

View File

@ -0,0 +1,21 @@
import {
EntityManager,
EntitySchema,
ObjectType,
Repository,
} from 'typeorm'
import {ITransactionManager} from '../database/ITransactionManager'
export abstract class BaseService {
constructor(protected readonly transactionManager: ITransactionManager) {}
getEntityManager(): EntityManager {
return this.transactionManager.getEntityManager()
}
getRepository<Entity>(
target: ObjectType<Entity> | EntitySchema<Entity> | string,
): Repository<Entity> {
return this.transactionManager.getRepository(target)
}
}

View File

@ -0,0 +1,4 @@
export interface ICredentials {
readonly username: string
readonly password: string
}

View File

@ -0,0 +1,3 @@
export interface IUser {
id: number
}

View File

@ -0,0 +1,13 @@
import {ICredentials} from './ICredentials'
import {IUser} from './IUser'
export interface IUserService {
createUser(credentials: ICredentials): Promise<IUser>
changePassword(params: {
userId: number,
oldPassword: string,
newPassword: string,
}): Promise<any>
validateCredentials(credentials: ICredentials): Promise<IUser | undefined>
findOne(id: number): Promise<IUser | undefined>
}

View File

@ -0,0 +1,93 @@
import {test} from '../test'
import {UserService} from './UserService'
describe('UserService', () => {
test.withDatabase()
const username = 'test@user.com'
const password = '1234567890'
const userService = new UserService(test.transactionManager)
async function createUser(u = username, p = password) {
return userService.createUser({
username: u,
password: p,
})
}
describe('createUser', () => {
it('creates a new user with bcrypted password', async () => {
const result = await createUser()
expect(result.id).toBeTruthy()
const user = await userService.findOne(result.id)
expect(user).toBeTruthy()
expect(user!.password).toBe(undefined)
})
it('throws when username is not an email', async () => {
const err = await test.getError(createUser('test', password))
expect(err.message).toMatch(/not a valid e-mail/)
})
it('throws when password is too short', async () => {
const err = await test.getError(createUser(username, 'p'))
expect(err.message).toMatch(/password/i)
})
it('fails on duplicate entry', async () => {
await createUser()
const error = await test.getError(createUser())
expect(error.message).toMatch(/unique/i)
})
})
describe('findUserByMail', () => {
it('returns user without password', async () => {
await createUser()
const user = await userService.findUserByEmail(username)
expect(user).toBeTruthy()
expect(user!.password).toBe(undefined)
})
})
describe('getUserEmails', () => {
it('returns user emails', async () => {
const {id} = await createUser()
const emails = await userService.findUserEmails(id)
expect(emails).toEqual([{
id: jasmine.any(Number),
userId: id,
email: username,
}])
})
})
describe('validateCredentials', () => {
it('returns user when password is valid', async () => {
await createUser()
expect(await userService.validateCredentials({ username, password }))
.toBeTruthy()
})
it('returns undefined when no user', async () => {
expect(await userService.validateCredentials({ username, password }))
.toBe(undefined)
})
it('returns undefined when password is invalid', async () => {
await createUser()
expect(await userService.validateCredentials({ username, password: 't' }))
.toBe(undefined)
})
it('does not return a password', async () => {
await createUser()
const user = await userService
.validateCredentials({ username, password })
expect(user!.password).toBe(undefined)
})
})
})

View File

@ -0,0 +1,93 @@
import createError from 'http-errors'
import {BaseService} from './BaseService'
import {ICredentials} from './ICredentials'
import {IUserService} from './IUserService'
import {UserEmail} from '../entities/UserEmail'
import {User} from '../entities/User'
import {compare, hash} from 'bcrypt'
import {validate as validateEmail} from 'email-validator'
const SALT_ROUNDS = 10
const MIN_PASSWORD_LENGTH = 10
export class UserService extends BaseService implements IUserService {
async createUser(payload: ICredentials): Promise<User> {
const username = payload.username
if (!validateEmail(username)) {
throw createError(400, 'Username is not a valid e-mail')
}
if (payload.password.length < MIN_PASSWORD_LENGTH) {
throw createError(400,
`Password must be at least ${MIN_PASSWORD_LENGTH} characters long`)
}
const password = await this.hash(payload.password)
const user = await this.getRepository(User).save({
password,
})
await this.getRepository(UserEmail).save({
email: username,
userId: user.id,
})
return user
}
async findOne(id: number) {
return this.getRepository(User).findOne(id)
}
async findUserByEmail(email: string) {
const userEmail = await this.getRepository(UserEmail)
.findOne({ email }, {
relations: ['user'],
})
return userEmail && userEmail.user
}
async changePassword(params: {
userId: number,
oldPassword: string,
newPassword: string,
}) {
const {userId, oldPassword, newPassword} = params
const userRepository = this.getRepository(User)
const user = await userRepository
.createQueryBuilder('user')
.select('user')
.addSelect('user.password')
.whereInIds([ userId ])
.getOne()
const isValid = await compare(oldPassword, user ? user.password! : '')
if (!(user && isValid)) {
throw createError(400, 'Passwords do not match')
}
const password = await this.hash(newPassword)
await userRepository
.update(userId, { password })
}
async validateCredentials(credentials: ICredentials) {
const {username, password} = credentials
const user = await this.getRepository(User)
.createQueryBuilder('user')
.select('user')
.addSelect('user.password')
.innerJoin('user.emails', 'emails', 'emails.email = :email', {
email: username,
})
.getOne()
const isValid = await compare(password, user ? user.password! : '')
if (user && isValid) {
delete user.password
return user
}
}
async findUserEmails(userId: number) {
return this.getRepository(UserEmail).find({ userId })
}
protected async hash(password: string): Promise<string> {
return hash(password, SALT_ROUNDS)
}
}

View File

@ -0,0 +1,4 @@
export * from './UserService'
export * from './IUserService'
export * from './IUser'
export * from './ICredentials'

View File

@ -0,0 +1,6 @@
export interface ISession {
// TODO use timestamp field
expiredAt: number
id: string
json: string
}

View File

@ -0,0 +1,152 @@
import express, {Application} from 'express'
import request from 'supertest'
import {SessionStore} from './SessionStore'
import {ISession} from './ISession'
import ExpressSession from 'express-session'
import {
createConnection, Column, Connection, Entity, Index, PrimaryColumn,
Repository,
} from 'typeorm'
@Entity()
class Session implements ISession {
@PrimaryColumn()
id!: string
@Column()
json!: string
@Column()
extraData!: string
@Column()
@Index()
expiredAt: number = Date.now()
}
describe('SessionStore', () => {
let connection!: Connection
let repository!: Repository<Session>
beforeEach(async () => {
connection = await createConnection({
type: 'sqlite',
database: ':memory:',
entities: [Session],
synchronize: true,
})
repository = connection.getRepository(Session)
})
afterEach(() => connection!.close())
function createApp(maxAge = 10) {
const app = express()
app.use(ExpressSession({
saveUninitialized: false,
secret: 'test',
resave: false,
rolling: true,
cookie: {
maxAge: 10,
},
store: new SessionStore({
cleanup: 1,
getRepository: () => repository,
ttl: 1,
buildSession: (sd, s) => ({...s, extraData: 'test'}),
}),
}))
app.post('/session/:param',
(req, res, next) => {
req.session!.param = req.params.param
req.session!.save(next)
},
(req, res) => res.json({
param: req.session!.param,
}),
)
app.get('/session', (req, res) => res.json({
param: req.session!.param,
}))
app.delete('/session',
(req, res, next) => req.session!.destroy(next),
(req, res) => res.end(),
)
return app
}
async function saveSession(app: Application) {
return await request(app)
.post('/session/value')
.expect(200)
}
function getSession(app: Application, cookie: string = '') {
return request(app)
.get('/session')
.set('cookie', cookie)
.expect(200)
}
describe('save session', () => {
it('saves a session to the database', async () => {
const app = createApp()
const response = await saveSession(app)
const param = response.body.param
expect(param).toEqual('value')
const result = await repository.findOne(response.body.sid)
expect(result).toBeTruthy()
const payload = JSON.parse(result!.json)
expect(payload.param).toEqual('value')
})
})
describe('retrieve session', () => {
it('retrieves a saved session via cookie', async () => {
const app = createApp()
const response = await saveSession(app)
const cookie = response.header['set-cookie']
expect(cookie).toBeTruthy()
await getSession(app)
.expect('{}')
await getSession(app, cookie)
.expect('{"param":"value"}')
})
})
describe('destroy session', () => {
it('destroys a saved session', async () => {
const app = createApp()
const response = await saveSession(app)
const cookie = response.header['set-cookie']
expect(cookie).toBeTruthy()
await request(app)
.delete('/session')
.set('cookie', cookie)
await getSession(app, cookie)
.expect('{}')
})
})
describe('error handling', () => {
it('handles errors', async () => {
(repository as any).save = () => Promise.reject(new Error('test'))
const app = createApp()
return await request(app)
.post('/session/value')
.expect(500)
})
})
})

View File

@ -0,0 +1,109 @@
import {Store} from 'express-session'
import {ISession} from './ISession'
import {Repository, LessThan} from 'typeorm'
type SessionData = Express.SessionData
type Callback = (err?: any, session?: SessionData) => void
type CallbackErr = (err?: any) => void
export interface ISessionStoreOptions<S extends ISession> {
readonly ttl: number
readonly cleanup: number
readonly getRepository: IRepositoryFactory<S>
buildSession(sessionData: SessionData, session: ISession): S
}
export type IRepositoryFactory<T> = () => Repository<T>
// TODO casting as any because TypeScript complains. Looks like this is a
// bug in TypeScript 3.2.2
//
// https://github.com/typeorm/typeorm/issues/1544
// https://github.com/Microsoft/TypeScript/issues/21592
export class SessionStore<S extends ISession> extends Store {
protected readonly getRepository: IRepositoryFactory<S>
constructor(
protected readonly options: ISessionStoreOptions<S>,
) {
super()
this.getRepository = options.getRepository
}
protected async promiseToCallback<T>(
promise: Promise<T | undefined>,
callback?: (err: any, result?: T | undefined) => void,
) {
let result: T | undefined
try {
result = await promise
} catch (err) {
if (callback) {
callback(err)
}
return
}
if (callback) {
callback(null, result)
}
}
get = (sid: string, callback: Callback) => {
const promise = this.getRepository().findOne(sid)
.then(session => {
if (session) {
return JSON.parse(session.json) as SessionData
}
})
this.promiseToCallback(promise, callback)
}
set = (sid: string, session: SessionData, callback?: CallbackErr) => {
const promise1 = this.options.cleanup
? this.cleanup() : Promise.resolve()
const promise2 = promise1.then(() => this.saveSession(
this.options.buildSession(session, {
id: sid,
expiredAt: Date.now() + this.getTTL(session) * 1000,
json: JSON.stringify(session),
}),
))
this.promiseToCallback(promise2, callback)
}
destroy = (sid: string, callback?: CallbackErr) => {
const promise = this.getRepository().delete(sid)
this.promiseToCallback(promise, callback)
}
touch = (
sid: string,
session: SessionData,
callback?: CallbackErr,
) => {
const promise = this.getRepository().update(sid, {
userId: session.userId,
expiredAt: Date.now() + this.getTTL(session) * 1000,
} as any)
this.promiseToCallback(promise, callback)
}
protected async saveSession(session: S) {
return this.getRepository().save(session as any)
}
protected getTTL(session: SessionData): number {
const maxAge = session.cookie.maxAge
return typeof maxAge === 'number' ? maxAge : this.options.ttl
}
protected async cleanup() {
const now = Date.now()
await this.getRepository().delete({
expiredAt: LessThan(now),
} as any)
}
}

View File

@ -0,0 +1,38 @@
import {Namespace} from 'cls-hooked'
export class NamespaceMock implements Namespace {
readonly context: {[key: string]: any} = {}
readonly active: {[key: string]: any} = this.context
set<T>(key: string, value: T): T {
this.context[key] = value
return value
}
get(key: string) {
return this.context[key]
}
// tslint:disable-next-line
run(fn: Function) {
return fn(this.context)
}
// tslint:disable-next-line
bind<F extends Function>(fn: F, context?: any): F {
return fn
}
bindEmitter(fn: any) {/* do not do anything */}
runAndReturn<T>(fn: (...args: any[]) => T): T {
return fn(this.context)
}
runPromise<T>(fn: (...args: any[]) => Promise<T>): Promise<T> {
return fn(this.context)
}
createContext(): any {/* do not do anything*/}
}
export const namespace = new NamespaceMock()

View File

@ -0,0 +1,34 @@
import express from 'express'
import {RequestTester} from './RequestTester'
describe('RequestTest', () => {
interface IAPI {
'/test': {
'get': {
response: {id: number},
},
}
}
const app = express()
app.get('/api/test', (req, res) => {
res.json({ id: 1 })
})
describe('constructor', () => {
it('creates a blank baseUrl', () => {
const t = new RequestTester<IAPI>(app)
expect(t.baseUrl).toEqual('')
})
})
describe('RequestTester.request', () => {
it('creates a response', async () => {
const t = new RequestTester<IAPI>(app, '/api')
const result = await t.request('get', '/test')
expect(result.body.id).toBe(1)
})
})
})

View File

@ -0,0 +1,69 @@
import supertest from 'supertest'
import {IMethod, IRoutes} from '../../common/REST'
// https://stackoverflow.com/questions/48215950/exclude-property-from-type
type Omit<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>>
interface ITest extends Omit<Omit<supertest.Test, 'then'>, 'catch'> {}
interface IResponse<
R extends IRoutes,
P extends keyof R,
M extends IMethod,
> extends supertest.Response {
body: R[P][M]['response']
header: {[key: string]: string}
}
interface IRequest<
R extends IRoutes,
P extends keyof R,
M extends IMethod,
> extends ITest, Promise<IResponse<R, P, M>> {
send(value: R[P][M]['body'] | string): this
expect(status: number, body?: any): this
expect(body: string | RegExp | object | ((res: Response) => any)): this
expect(field: string, val: string | RegExp): this
// any other method that's called will return "this" from supertest's
// or superagent's type definition and afterwards the promise will no longer
// contain type definitions. if you use any other methods, add them to this
// type definition
}
export interface IHeaders {
[key: string]: string
}
export class RequestTester<R extends IRoutes> {
protected headers: IHeaders = {}
constructor(
readonly app: Express.Application,
readonly baseUrl = '',
) {}
setHeaders(headers: IHeaders): this {
this.headers = headers
return this
}
request<M extends IMethod, P extends keyof R & string>(
method: M, path: P,
)
: IRequest<R, P, M> {
const test = supertest(this.app)[method](`${this.baseUrl}${path}`)
Object.keys(this.headers).forEach(key => {
test.set(key, this.headers[key])
})
return test
}
get<P extends keyof R & string>(path: P) {
return this.request('get', path)
}
post<P extends keyof R & string>(path: P) {
return this.request('post', path)
}
}

View File

@ -0,0 +1,127 @@
import express from 'express'
import supertest from 'supertest'
import {Connection, QueryRunner} from 'typeorm'
import {
ENTITY_MANAGER, ITransactionManager,
} from '../database/ITransactionManager'
import {IRoutes} from '../../common/REST'
import {IBootstrap} from '../application/IBootstrap'
import {RequestTester} from './RequestTester'
export class TestUtils<T extends IRoutes> {
readonly username = 'test@user.com'
readonly password = 'Password10'
readonly app: express.Application
readonly context: string
readonly transactionManager: ITransactionManager
constructor(readonly bootstrap: IBootstrap) {
this.app = bootstrap.application.server
this.context = this.bootstrap.config.app.context
this.transactionManager = this.bootstrap.database.transactionManager
}
/**
* Set up beforeEach and afterEach cases for jest tests. Helps create and
* execute the tests in transaction, and rolls it back in the end.
*/
withDatabase() {
const {database} = this.bootstrap
const {namespace} = database
let connection!: Connection
let queryRunner: QueryRunner
beforeEach(async () => {
connection = await database.connect()
queryRunner = connection.createQueryRunner()
await queryRunner.connect()
await queryRunner.startTransaction()
namespace.set(ENTITY_MANAGER, queryRunner.manager)
})
afterEach(async () => {
// TODO transaction should always be active, no?
if (queryRunner.isTransactionActive) {
await queryRunner.rollbackTransaction()
}
await queryRunner.release()
namespace.set(ENTITY_MANAGER, undefined)
await connection.close()
})
}
async getError(promise: Promise<any>): Promise<Error> {
let error!: Error
try {
await promise
} catch (err) {
error = err
}
expect(error).toBeTruthy()
return error
}
async getCsrf() {
const {context} = this
const response = await supertest(this.app)
.get(`${context}/app`)
.expect(200)
const cookie = response.header['set-cookie'] as string
const token = this.getCsrfToken(response.text)
expect(cookie).toBeTruthy()
expect(token).toBeTruthy()
return {cookie, token}
}
protected getCsrfToken(responseText: string) {
const match = responseText.match(/"csrfToken":"(.*?)"/)
expect(match).toBeTruthy()
expect(match!.length).toBe(2)
return match![1]
}
getLoginBody(csrfToken: string) {
const {username, password} = this
return `username=${username}&password=${password}&_csrf=${csrfToken}`
}
async registerAccount() {
const {context} = this
const {cookie, token} = await this.getCsrf()
const response = await supertest(this.app)
.post(`${context}/app/auth/register`)
.set('cookie', cookie)
.send(this.getLoginBody(token))
.expect(302)
.expect('location', `${context}/app`)
return {
cookie: response.header['set-cookie'] as string,
userId: response.body.userId,
}
}
async login(_username = this.username, _password = this.password) {
const {context} = this
const {cookie, token} = await this.getCsrf()
const response = await supertest(this.app)
.post(`${context}/app/auth/login`)
.set('cookie', cookie)
.send(`username=${_username}&password=${_password}&_csrf=${token}`)
.expect(302)
.expect('location', `${context}/app`)
return {cookie: response.header['set-cookie'] as string, token}
}
request = (baseUrl = '') => {
return new RequestTester<T>(
this.app,
`${this.bootstrap.config.app.baseUrl.path!}${baseUrl}`)
}
}

View File

@ -0,0 +1,3 @@
export * from './TestUtils'
export * from './RequestTester'
export * from './NamespaceMock'

View File

@ -0,0 +1,15 @@
import {Bootstrap} from './application/Bootstrap'
import {IAPIDef} from '../common/IAPIDef'
import {NamespaceMock, TestUtils} from './test-utils'
import {config} from './config'
export const exit = jest.fn()
const bootstrap = new Bootstrap(
config,
new NamespaceMock(),
exit,
)
export const test = new TestUtils<IAPIDef>(bootstrap)
export const {request} = test

View File

@ -0,0 +1,19 @@
{
"compilerOptions": {
"lib": ["es2015", "dom"],
"target": "es3",
"moduleResolution": "node",
"jsx": "react",
"noImplicitAny": true,
"strict": true,
"skipLibCheck": true,
"noUnusedLocals": true,
"esModuleInterop": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"plugins": [{
"name": "typescript-tslint-plugin",
"suppressWhileTypeErrorsPresent": true
}]
}
}

View File

@ -0,0 +1,43 @@
{
"defaultSeverity": "error",
"extends": [
"tslint:recommended"
],
"jsRules": {},
"rules": {
"quotemark": [true, "single", "jsx-single"],
"member-access": false,
"no-bitwise": false,
"semicolon": [true, "never"],
"object-literal-sort-keys": false,
"ordered-imports": false,
"max-line-length": [true, 80],
"arrow-parens": false,
"variable-name": [
true,
"ban-keywords",
"check-format",
"allow-leading-underscore",
"allow-pascal-case"
],
"member-ordering": false,
"max-classes-per-file": false,
"no-empty-interface": false,
"trailing-comma": [true, {
"multiline": {
"objects": "always",
"arrays": "always",
"functions": "always",
"typeLiterals": "ignore"
},
"singleline": "never",
"esSpecCompliant": true
}]
},
"linterOptions": {
"exclude": [
"src/server/migrations/*.ts"
]
},
"rulesDirectory": []
}