Extend transaction usage

This commit is contained in:
Jonas Lochmann
2020-10-02 09:58:13 +02:00
parent 62f4e368a6
commit abc2102da5
47 changed files with 1367 additions and 860 deletions
+22 -18
View File
@@ -96,27 +96,31 @@ export const createAdminRouter = ({ database, websocket, eventHandler }: {
throw new BadRequest()
}
const userEntryUnsafe = await database.user.findOne({
where: {
mail
},
attributes: ['familyId']
})
await database.transaction(async (transaction) => {
const userEntryUnsafe = await database.user.findOne({
where: {
mail
},
attributes: ['familyId'],
transaction
})
if (!userEntryUnsafe) {
throw new Conflict('no user with specified mail address')
}
if (!userEntryUnsafe) {
throw new Conflict('no user with specified mail address')
}
const userEntry = {
familyId: userEntryUnsafe.familyId
}
const userEntry = {
familyId: userEntryUnsafe.familyId
}
await addPurchase({
database,
familyId: userEntry.familyId,
type,
transactionId: 'manual-' + type + '-' + generatePurchaseId(),
websocket
await addPurchase({
database,
familyId: userEntry.familyId,
type,
transactionId: 'manual-' + type + '-' + generatePurchaseId(),
websocket,
transaction
})
})
res.json({ ok: true })
+35 -22
View File
@@ -19,7 +19,7 @@ import { json } from 'body-parser'
import { Router } from 'express'
import { BadRequest, Forbidden, Unauthorized } from 'http-errors'
import { config } from '../config'
import { Database } from '../database'
import { Database, Transaction } from '../database'
import { removeDevice } from '../function/device/remove-device'
import { canRecoverPassword } from '../function/parent/can-recover-password'
import { createAddDeviceToken } from '../function/parent/create-add-device-token'
@@ -46,7 +46,9 @@ export const createParentRouter = ({ database, websocket }: {database: Database,
}
const { mailAuthToken } = req.body
const { status, mail } = await getStatusByMailToken({ database, mailAuthToken })
const { status, mail } = await database.transaction(async (transaction) => {
return getStatusByMailToken({ database, mailAuthToken, transaction })
})
res.json({
status,
@@ -148,15 +150,17 @@ export const createParentRouter = ({ database, websocket }: {database: Database,
}
})
async function assertAuthValidAndReturnDeviceEntry ({ deviceAuthToken, parentId, secondPasswordHash }: {
async function assertAuthValidAndReturnDeviceEntry ({ deviceAuthToken, parentId, secondPasswordHash, transaction }: {
deviceAuthToken: string
parentId: string
secondPasswordHash: string
transaction: Transaction
}) {
const deviceEntry = await database.device.findOne({
where: {
deviceAuthToken: deviceAuthToken
}
},
transaction
})
if (!deviceEntry) {
@@ -173,7 +177,8 @@ export const createParentRouter = ({ database, websocket }: {database: Database,
familyId: deviceEntry.familyId,
type: 'parent',
userId: deviceEntry.currentUserId
}
},
transaction
})
if (!parentEntry) {
@@ -186,7 +191,8 @@ export const createParentRouter = ({ database, websocket }: {database: Database,
type: 'parent',
userId: parentId,
secondPasswordHash: secondPasswordHash
}
},
transaction
})
if (!parentEntry) {
@@ -203,13 +209,16 @@ export const createParentRouter = ({ database, websocket }: {database: Database,
throw new BadRequest()
}
const deviceEntry = await assertAuthValidAndReturnDeviceEntry({
deviceAuthToken: req.body.deviceAuthToken,
parentId: req.body.parentId,
secondPasswordHash: req.body.parentPasswordSecondHash
})
const { token, deviceId } = await database.transaction(async (transaction) => {
const deviceEntry = await assertAuthValidAndReturnDeviceEntry({
deviceAuthToken: req.body.deviceAuthToken,
parentId: req.body.parentId,
secondPasswordHash: req.body.parentPasswordSecondHash,
transaction
})
const { token, deviceId } = await createAddDeviceToken({ familyId: deviceEntry.familyId, database })
return createAddDeviceToken({ familyId: deviceEntry.familyId, database, transaction })
})
res.json({ token, deviceId })
} catch (ex) {
@@ -244,17 +253,21 @@ export const createParentRouter = ({ database, websocket }: {database: Database,
throw new BadRequest()
}
const deviceEntry = await assertAuthValidAndReturnDeviceEntry({
deviceAuthToken: req.body.deviceAuthToken,
parentId: req.body.parentUserId,
secondPasswordHash: req.body.parentPasswordSecondHash
})
await database.transaction(async (transaction) => {
const deviceEntry = await assertAuthValidAndReturnDeviceEntry({
deviceAuthToken: req.body.deviceAuthToken,
parentId: req.body.parentUserId,
secondPasswordHash: req.body.parentPasswordSecondHash,
transaction
})
await removeDevice({
database,
familyId: deviceEntry.familyId,
deviceId: req.body.deviceId,
websocket
await removeDevice({
database,
familyId: deviceEntry.familyId,
deviceId: req.body.deviceId,
websocket,
transaction
})
})
res.json({ ok: true })
+53 -46
View File
@@ -1,6 +1,6 @@
/*
* server component for the TimeLimit App
* Copyright (C) 2019 Jonas Lochmann
* Copyright (C) 2019 - 2020 Jonas Lochmann
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
@@ -47,12 +47,15 @@ export const createPurchaseRouter = ({ database, websocket }: {
throw new BadRequest()
}
const familyEntry = await requireFamilyEntry({
database,
deviceAuthToken: req.body.deviceAuthToken
})
const result: boolean = await database.transaction(async (transaction) => {
const familyEntry = await requireFamilyEntry({
database,
deviceAuthToken: req.body.deviceAuthToken,
transaction
})
const result = canDoNextPurchase({ fullVersionUntil: parseInt(familyEntry.fullVersionUntil, 10) })
return canDoNextPurchase({ fullVersionUntil: parseInt(familyEntry.fullVersionUntil, 10) })
})
res.json({
canDoPurchase: result ? 'yes' : 'no due to old purchase',
@@ -69,56 +72,60 @@ export const createPurchaseRouter = ({ database, websocket }: {
throw new BadRequest()
}
const deviceEntryUnsafe = await database.device.findOne({
where: {
deviceAuthToken: req.body.deviceAuthToken
},
attributes: ['familyId']
})
await database.transaction(async (transaction) => {
const deviceEntryUnsafe = await database.device.findOne({
where: {
deviceAuthToken: req.body.deviceAuthToken
},
attributes: ['familyId'],
transaction
})
if (!deviceEntryUnsafe) {
throw new Unauthorized()
}
if (!deviceEntryUnsafe) {
throw new Unauthorized()
}
const deviceEntry = {
familyId: deviceEntryUnsafe.familyId
}
const deviceEntry = {
familyId: deviceEntryUnsafe.familyId
}
if (!isGooglePlayPurchaseSignatureValid({
receipt: req.body.receipt,
signature: req.body.signature
})) {
throw new Conflict()
}
if (!isGooglePlayPurchaseSignatureValid({
receipt: req.body.receipt,
signature: req.body.signature
})) {
throw new Conflict()
}
const receipt = JSON.parse(req.body.receipt)
const receipt = JSON.parse(req.body.receipt)
if (typeof receipt !== 'object') {
throw new Conflict()
}
if (typeof receipt !== 'object') {
throw new Conflict()
}
let type: 'month' | 'year'
let type: 'month' | 'year'
if (receipt.productId === 'premium_year_2018') {
type = 'year'
} else if (receipt.productId === 'premium_month_2018') {
type = 'month'
} else {
throw new Conflict()
}
if (receipt.productId === 'premium_year_2018') {
type = 'year'
} else if (receipt.productId === 'premium_month_2018') {
type = 'month'
} else {
throw new Conflict()
}
const orderId = receipt.orderId
const orderId = receipt.orderId
if (typeof orderId !== 'string') {
throw new Conflict()
}
if (typeof orderId !== 'string') {
throw new Conflict()
}
await addPurchase({
database,
familyId: deviceEntry.familyId,
type,
transactionId: orderId,
websocket
await addPurchase({
database,
familyId: deviceEntry.familyId,
type,
transactionId: orderId,
websocket,
transaction
})
})
res.json({ ok: true })
+9 -7
View File
@@ -20,13 +20,15 @@ import { optionalPasswordRegex, optionalSaltRegex } from '../util/password'
export interface ClientPushChangesRequest {
deviceAuthToken: string
actions: Array<{
encodedAction: string
sequenceNumber: number
integrity: string
type: 'appLogic' | 'parent' | 'child'
userId: string
}>
actions: Array<ClientPushChangesRequestAction>
}
export interface ClientPushChangesRequestAction {
encodedAction: string
sequenceNumber: number
integrity: string
type: 'appLogic' | 'parent' | 'child'
userId: string
}
export interface ClientPullChangesRequest {
+10 -5
View File
@@ -158,14 +158,19 @@ export const createSyncRouter = ({ database, websocket, connectedDevicesManager,
throw new BadRequest()
}
const removedEntry = await database.oldDevice.findOne({
where: {
deviceAuthToken: req.body.deviceAuthToken
}
const isDeviceRemoved: boolean = await database.transaction(async (transaction) => {
const removedEntry = await database.oldDevice.findOne({
where: {
deviceAuthToken: req.body.deviceAuthToken
},
transaction
})
return !!removedEntry
})
res.json({
isDeviceRemoved: !!removedEntry
isDeviceRemoved
})
} catch (ex) {
next(ex)
+35 -31
View File
@@ -4,6 +4,39 @@ const Ajv = require('ajv')
const ajv = new Ajv()
const definitions = {
"ClientPushChangesRequestAction": {
"type": "object",
"properties": {
"encodedAction": {
"type": "string"
},
"sequenceNumber": {
"type": "number"
},
"integrity": {
"type": "string"
},
"type": {
"enum": [
"appLogic",
"child",
"parent"
],
"type": "string"
},
"userId": {
"type": "string"
}
},
"additionalProperties": false,
"required": [
"encodedAction",
"integrity",
"sequenceNumber",
"type",
"userId"
]
},
"ClientDataStatus": {
"type": "object",
"properties": {
@@ -2219,37 +2252,7 @@ export const isClientPushChangesRequest: (value: object) => value is ClientPushC
"actions": {
"type": "array",
"items": {
"type": "object",
"properties": {
"encodedAction": {
"type": "string"
},
"sequenceNumber": {
"type": "number"
},
"integrity": {
"type": "string"
},
"type": {
"enum": [
"appLogic",
"child",
"parent"
],
"type": "string"
},
"userId": {
"type": "string"
}
},
"additionalProperties": false,
"required": [
"encodedAction",
"integrity",
"sequenceNumber",
"type",
"userId"
]
"$ref": "#/definitions/ClientPushChangesRequestAction"
}
}
},
@@ -2258,6 +2261,7 @@ export const isClientPushChangesRequest: (value: object) => value is ClientPushC
"actions",
"deviceAuthToken"
],
"definitions": definitions,
"$schema": "http://json-schema.org/draft-07/schema#"
})
export const isClientPullChangesRequest: (value: object) => value is ClientPullChangesRequest = ajv.compile({
+3 -2
View File
@@ -1,6 +1,6 @@
/*
* server component for the TimeLimit App
* Copyright (C) 2019 Jonas Lochmann
* Copyright (C) 2019 - 2020 Jonas Lochmann
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
@@ -46,5 +46,6 @@ export const attributes: SequelizeAttributes<ConfigAttributes> = {
export const createConfigModel = (sequelize: Sequelize.Sequelize): ConfigModelStatic => sequelize.define('Config', attributes) as ConfigModelStatic
export const configItemIds = {
statusMessage: 'status_message'
statusMessage: 'status_message',
selfTestData: 'self_test_data'
}
+54 -4
View File
@@ -15,7 +15,9 @@
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import { Promise as BluePromise } from 'bluebird'
import * as Sequelize from 'sequelize'
import { generateIdWithinFamily } from '../util/token'
import { AddDeviceTokenModelStatic, createAddDeviceTokenModel } from './adddevicetoken'
import { AppModelStatic, createAppModel } from './app'
import { AppActivityModelStatic, createAppActivityModel } from './appactivity'
@@ -23,7 +25,7 @@ import { AuthTokenModelStatic, createAuthtokenModel } from './authtoken'
import { CategoryModelStatic, createCategoryModel } from './category'
import { CategoryAppModelStatic, createCategoryAppModel } from './categoryapp'
import { CategoryNetworkIdModelStatic, createCategoryNetworkIdModel } from './categorynetworkid'
import { ConfigModelStatic, createConfigModel } from './config'
import { configItemIds, ConfigModelStatic, createConfigModel } from './config'
import { createDeviceModel, DeviceModelStatic } from './device'
import { createFamilyModel, FamilyModelStatic } from './family'
import { createMailLoginTokenModel, MailLoginTokenModelStatic } from './maillogintoken'
@@ -36,6 +38,8 @@ import { createUsedTimeModel, UsedTimeModelStatic } from './usedtime'
import { createUserModel, UserModelStatic } from './user'
import { createUserLimitLoginCategoryModel, UserLimitLoginCategoryModelStatic } from './userlimitlogincategory'
export type Transaction = Sequelize.Transaction
export interface Database {
addDeviceToken: AddDeviceTokenModelStatic
authtoken: AuthTokenModelStatic
@@ -55,7 +59,7 @@ export interface Database {
usedTime: UsedTimeModelStatic
user: UserModelStatic
userLimitLoginCategory: UserLimitLoginCategoryModelStatic
transaction: <T> (autoCallback: (t: Sequelize.Transaction) => Promise<T>) => Promise<T>
transaction: <T> (autoCallback: (t: Transaction) => Promise<T>, options?: { transaction: Transaction }) => Promise<T>
dialect: string
}
@@ -78,8 +82,9 @@ const createDatabase = (sequelize: Sequelize.Sequelize): Database => ({
usedTime: createUsedTimeModel(sequelize),
user: createUserModel(sequelize),
userLimitLoginCategory: createUserLimitLoginCategoryModel(sequelize),
transaction: <T> (autoCallback: (transaction: Sequelize.Transaction) => Promise<T>) => (sequelize.transaction({
isolationLevel: Sequelize.Transaction.ISOLATION_LEVELS.READ_COMMITTED
transaction: <T> (autoCallback: (transaction: Transaction) => Promise<T>, options?: { transaction: Transaction }) => (sequelize.transaction({
isolationLevel: Sequelize.Transaction.ISOLATION_LEVELS.READ_COMMITTED,
transaction: options?.transaction
}, autoCallback) as any) as Promise<T>,
dialect: sequelize.getDialect()
})
@@ -93,3 +98,48 @@ export const sequelize = new Sequelize.Sequelize(process.env.DATABASE_URL || 'sq
export const defaultDatabase = createDatabase(sequelize)
export const defaultUmzug = createUmzug(sequelize)
class NestedTransactionTestException extends Error {}
class TestRollbackException extends NestedTransactionTestException {}
class NestedTransactionsNotWorkingException extends NestedTransactionTestException { constructor () { super('NestedTransactionsNotWorkingException') } }
class IllegalStateException extends NestedTransactionTestException {}
export const wrapPromise = <T>(promise: Promise<T>) => BluePromise.resolve(promise)
export const warpPromiseReturner = <T>(fun: () => Promise<T>) => () => wrapPromise(fun())
export async function assertNestedTransactionsAreWorking (database: Database) {
const testValue = generateIdWithinFamily()
// clean up just for the case
await database.config.destroy({ where: { id: configItemIds.selfTestData } })
await database.transaction(async (transaction) => {
const readOne = await database.config.findOne({ where: { id: configItemIds.selfTestData }, transaction })
if (readOne) throw new IllegalStateException()
await database.transaction(async (transaction) => {
await database.config.create({ id: configItemIds.selfTestData, value: testValue }, { transaction })
const readTwo = await database.config.findOne({ where: { id: configItemIds.selfTestData }, transaction })
if (readTwo?.value !== testValue) throw new IllegalStateException()
try {
await database.transaction(async (transaction) => {
await database.config.destroy({ where: { id: configItemIds.selfTestData }, transaction })
throw new TestRollbackException()
}, { transaction })
} catch (ex) {
if (!(ex instanceof TestRollbackException)) throw ex
}
const readThree = await database.config.findOne({ where: { id: configItemIds.selfTestData }, transaction })
if (readThree?.value !== testValue) throw new NestedTransactionsNotWorkingException()
await database.config.destroy({ where: { id: configItemIds.selfTestData }, transaction })
}, { transaction })
})
}
+9 -8
View File
@@ -1,6 +1,6 @@
/*
* server component for the TimeLimit App
* Copyright (C) 2019 Jonas Lochmann
* Copyright (C) 2019 - 2020 Jonas Lochmann
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
@@ -16,26 +16,27 @@
*/
import { Unauthorized } from 'http-errors'
import { Database } from '../../database'
import { Database, Transaction } from '../../database'
import { generateAuthToken } from '../../util/token'
export const createAuthTokenByMailAddress = async ({ mail, database }: {mail: string, database: Database}) => {
export const createAuthTokenByMailAddress = async ({ mail, database, transaction }: { mail: string, database: Database, transaction: Transaction }) => {
const token = generateAuthToken()
await database.authtoken.create({
token,
mail,
createdAt: Date.now().toString()
})
}, { transaction })
return token
}
export const getMailByAuthToken = async ({ mailAuthToken, database }: {mailAuthToken: string, database: Database}) => {
export const getMailByAuthToken = async ({ mailAuthToken, database, transaction }: { mailAuthToken: string, database: Database, transaction: Transaction }) => {
const entry = await database.authtoken.findOne({
where: {
token: mailAuthToken
}
},
transaction
})
if (entry) {
@@ -45,8 +46,8 @@ export const getMailByAuthToken = async ({ mailAuthToken, database }: {mailAuthT
}
}
export const requireMailByAuthToken = async ({ mailAuthToken, database }: {mailAuthToken: string, database: Database}) => {
const mail = await getMailByAuthToken({ mailAuthToken, database })
export const requireMailByAuthToken = async ({ mailAuthToken, database, transaction }: { mailAuthToken: string, database: Database, transaction: Transaction }) => {
const mail = await getMailByAuthToken({ mailAuthToken, database, transaction })
if (!mail) {
throw new Unauthorized()
+21 -41
View File
@@ -1,6 +1,6 @@
/*
* server component for the TimeLimit App
* Copyright (C) 2019 Jonas Lochmann
* Copyright (C) 2019 - 2020 Jonas Lochmann
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
@@ -15,7 +15,7 @@
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import { Forbidden, Gone, InternalServerError, TooManyRequests } from 'http-errors'
import { Forbidden, Gone, TooManyRequests } from 'http-errors'
import { Database } from '../../database'
import { sendAuthenticationMail } from '../../util/mail'
import { areWordSequencesEqual, randomWords } from '../../util/random-words'
@@ -27,7 +27,8 @@ export const sendLoginCode = async ({ mail, locale, database }: {
mail: string
locale: string
database: Database
}): Promise<{mailLoginToken: string}> => {
// no transaction here because this is directly called from an API endpoint
}): Promise<{ mailLoginToken: string }> => {
try {
await checkMailSendLimit(mail)
} catch (ex) {
@@ -43,12 +44,14 @@ export const sendLoginCode = async ({ mail, locale, database }: {
locale
})
await database.mailLoginToken.create({
mailLoginToken,
receivedCode: code,
mail,
createdAt: Date.now().toString(10),
remainingAttempts: 3
await database.transaction(async (transaction) => {
await database.mailLoginToken.create({
mailLoginToken,
receivedCode: code,
mail,
createdAt: Date.now().toString(10),
remainingAttempts: 3
}, { transaction })
})
return {
@@ -62,8 +65,9 @@ export const signInByMailCode = async ({ mailLoginToken, receivedCode, database
mailLoginToken: string
receivedCode: string
database: Database
}): Promise<{mailAuthToken: string}> => {
const { mail, status } = await database.transaction(async (transaction) => {
// no transaction here because this is directly called from an API endpoint
}): Promise<{ mailAuthToken: string }> => {
return database.transaction(async (transaction) => {
const entry = await database.mailLoginToken.findOne({
where: {
mailLoginToken
@@ -72,10 +76,7 @@ export const signInByMailCode = async ({ mailLoginToken, receivedCode, database
})
if ((!entry) || entry.remainingAttempts === 0) {
return {
mail: null,
status: 'gone'
}
throw new Gone()
}
if (!areWordSequencesEqual(entry.receivedCode, receivedCode)) {
@@ -84,35 +85,14 @@ export const signInByMailCode = async ({ mailLoginToken, receivedCode, database
await entry.save({ transaction })
if (entry.remainingAttempts === 0) {
return {
mail: null,
status: 'gone'
}
throw new Gone()
} else {
return {
mail: null,
status: 'forbidden'
}
throw new Forbidden()
}
}
return {
mail: entry.mail,
status: null
}
const mailAuthToken = await createAuthTokenByMailAddress({ mail: entry.mail, database, transaction })
return { mailAuthToken }
})
if (!mail) {
if (status === 'gone') {
throw new Gone()
} else if (status === 'forbidden') {
throw new Forbidden()
} else {
throw new InternalServerError()
}
}
const mailAuthToken = await createAuthTokenByMailAddress({ mail, database })
return { mailAuthToken }
}
+8 -12
View File
@@ -1,6 +1,6 @@
/*
* server component for the TimeLimit App
* Copyright (C) 2019 Jonas Lochmann
* Copyright (C) 2019 - 2020 Jonas Lochmann
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
@@ -21,14 +21,15 @@ import { Database } from '../../database'
import { generateAuthToken, generateVersionId } from '../../util/token'
import { WebsocketApi } from '../../websocket'
import { prepareDeviceEntry } from '../device/prepare-device-entry'
import { notifyClientsAboutChanges } from '../websocket'
import { notifyClientsAboutChangesDelayed } from '../websocket'
export const addChildDevice = async ({ database, websocket, request }: {
database: Database
websocket: WebsocketApi
request: RegisterChildDeviceRequest
// no transaction here because this is directly called from an API endpoint
}) => {
const { response, familyId } = await database.transaction(async (transaction) => {
return database.transaction(async (transaction) => {
const entry = await database.addDeviceToken.findOne({
where: {
token: request.registerToken.toLowerCase()
@@ -63,16 +64,11 @@ export const addChildDevice = async ({ database, websocket, request }: {
transaction
})
await notifyClientsAboutChangesDelayed({ familyId, websocket, database, isImportant: true, sourceDeviceId: deviceId, transaction })
return {
response: {
deviceId,
deviceAuthToken
},
familyId
deviceId,
deviceAuthToken
}
})
await notifyClientsAboutChanges({ familyId, websocket, database, isImportant: true, sourceDeviceId: response.deviceId })
return response
}
@@ -1,6 +1,6 @@
/*
* server component for the TimeLimit App
* Copyright (C) 2019 Jonas Lochmann
* Copyright (C) 2019 - 2020 Jonas Lochmann
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
@@ -23,6 +23,7 @@ export const logoutAtPrimaryDevice = async ({ deviceAuthToken, database, websock
deviceAuthToken: string
database: Database
websocket: WebsocketApi
// no transaction here because this is directly called from an API endpoint
}) => {
await database.transaction(async (transaction) => {
const ownDeviceEntryUnsafe = await database.device.findOne({
+12 -30
View File
@@ -21,7 +21,7 @@ import { config } from '../../config'
import { Database } from '../../database'
import { generateVersionId } from '../../util/token'
import { WebsocketApi } from '../../websocket'
import { notifyClientsAboutChanges } from '../websocket'
import { notifyClientsAboutChangesDelayed } from '../websocket'
export const setPrimaryDevice = async ({ database, websocket, deviceAuthToken, currentUserId, action }: {
database: Database
@@ -29,12 +29,9 @@ export const setPrimaryDevice = async ({ database, websocket, deviceAuthToken, c
deviceAuthToken: string
currentUserId: string
action: 'set this device' | 'unset this device'
// no transaction here because this is directly called from an API endpoint
}): Promise<'assigned to other device' | 'requires full version' | 'success'> => {
const response = await database.transaction(async (transaction): Promise<{
response: 'assigned to other device' | 'requires full version' | 'success',
sourceDeviceId: string,
familyId: string
}> => {
return database.transaction(async (transaction): Promise<'assigned to other device' | 'requires full version' | 'success'> => {
const deviceEntryUnsafe = await database.device.findOne({
where: {
deviceAuthToken
@@ -106,22 +103,14 @@ export const setPrimaryDevice = async ({ database, websocket, deviceAuthToken, c
}
if (!(familyEntry.hasFullVersion || config.alwaysPro)) {
return {
response: 'requires full version',
sourceDeviceId: deviceEntry.deviceId,
familyId: deviceEntry.familyId
}
return 'requires full version'
}
}
if (action === 'set this device') {
// check that no other device is selected
if (userDeviceEntries.find((item) => item.deviceId === userEntry.currentDevice)) {
return {
response: 'assigned to other device',
sourceDeviceId: deviceEntry.deviceId,
familyId: deviceEntry.familyId
}
return 'assigned to other device'
}
// update
@@ -171,23 +160,16 @@ export const setPrimaryDevice = async ({ database, websocket, deviceAuthToken, c
}
})
return {
response: 'success',
sourceDeviceId: deviceEntry.deviceId,
familyId: deviceEntry.familyId
}
})
if (response.response === 'success') {
// trigger sync
await notifyClientsAboutChanges({
familyId: response.familyId,
sourceDeviceId: response.sourceDeviceId,
await notifyClientsAboutChangesDelayed({
familyId: deviceEntry.familyId,
sourceDeviceId: deviceEntry.deviceId,
websocket,
database,
isImportant: false // the source device knows it already
isImportant: false, // the source device knows it already
transaction
})
}
return response.response
return 'success'
})
}
+2 -1
View File
@@ -1,6 +1,6 @@
/*
* server component for the TimeLimit App
* Copyright (C) 2019 Jonas Lochmann
* Copyright (C) 2019 - 2020 Jonas Lochmann
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
@@ -22,6 +22,7 @@ import { Database } from '../../database'
export async function deleteFamilies ({ database, familiyIds }: {
database: Database
familiyIds: Array<string>
// no transaction here because this should run isolated
}) {
if (familiyIds.length === 0) {
return
+29 -25
View File
@@ -1,6 +1,6 @@
/*
* server component for the TimeLimit App
* Copyright (C) 2019 Jonas Lochmann
* Copyright (C) 2019 - 2020 Jonas Lochmann
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
@@ -34,30 +34,34 @@ export async function deleteOldFamilies (database: Database) {
}
export async function findOldFamilyIds (database: Database) {
const familyIdsWithExpiredLicenses = await database.family.findAll({
where: {
fullVersionUntil: {
[Sequelize.Op.lt]: (Date.now() - 1000 * 60 * 60 * 24 * 90 /* 90 days */).toString(10)
}
},
attributes: ['familyId']
}).map((item) => item.familyId)
if (familyIdsWithExpiredLicenses.length === 0) {
return []
}
const recentlyUsedFamilyIds = await database.device.findAll({
where: {
familyId: {
[Sequelize.Op.in]: familyIdsWithExpiredLicenses
return database.transaction(async (transaction) => {
const familyIdsWithExpiredLicenses = await database.family.findAll({
where: {
fullVersionUntil: {
[Sequelize.Op.lt]: (Date.now() - 1000 * 60 * 60 * 24 * 90 /* 90 days */).toString(10)
}
},
lastConnectivity: {
[Sequelize.Op.gt]: (Date.now() - 1000 * 60 * 60 * 24 * 90 /* 90 days */).toString(10)
}
},
attributes: ['familyId']
}).map((item) => item.familyId)
attributes: ['familyId'],
transaction
}).map((item) => item.familyId)
return difference(familyIdsWithExpiredLicenses, recentlyUsedFamilyIds)
if (familyIdsWithExpiredLicenses.length === 0) {
return []
}
const recentlyUsedFamilyIds = await database.device.findAll({
where: {
familyId: {
[Sequelize.Op.in]: familyIdsWithExpiredLicenses
},
lastConnectivity: {
[Sequelize.Op.gt]: (Date.now() - 1000 * 60 * 60 * 24 * 90 /* 90 days */).toString(10)
}
},
attributes: ['familyId'],
transaction
}).map((item) => item.familyId)
return difference(familyIdsWithExpiredLicenses, recentlyUsedFamilyIds)
})
}
+82 -82
View File
@@ -1,6 +1,6 @@
/*
* server component for the TimeLimit App
* Copyright (C) 2019 Jonas Lochmann
* Copyright (C) 2019 - 2020 Jonas Lochmann
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
@@ -16,102 +16,102 @@
*/
import { Conflict } from 'http-errors'
import { Database } from '../../database'
import { Database, Transaction } from '../../database'
import { generateVersionId } from '../../util/token'
import { WebsocketApi } from '../../websocket'
import { notifyClientsAboutChanges } from '../websocket'
import { notifyClientsAboutChangesDelayed } from '../websocket'
export async function removeDevice ({ database, familyId, deviceId, websocket }: {
export async function removeDevice ({ database, familyId, deviceId, websocket, transaction }: {
database: Database
familyId: string
deviceId: string
websocket: WebsocketApi
transaction: Transaction
}) {
const { oldDeviceAuthToken } = await database.transaction(async (transaction) => {
const deviceEntry = await database.device.findOne({
where: {
familyId,
deviceId
},
transaction
})
if (!deviceEntry) {
throw new Conflict()
}
// remove app entries
await database.app.destroy({
where: {
familyId,
deviceId
},
transaction
})
await database.appActivity.destroy({
where: {
familyId,
deviceId
},
transaction
})
// remove as current device
await database.user.update({
currentDevice: ''
}, {
where: {
familyId,
currentDevice: deviceId
},
transaction
})
// add to old devices if it is not yet there (it could be there if it reported a uninstall)
const oldOldDeviceEntry = await database.oldDevice.findOne({
where: {
deviceAuthToken: deviceEntry.deviceAuthToken
},
transaction
})
if (!oldOldDeviceEntry) {
await database.oldDevice.create({
deviceAuthToken: deviceEntry.deviceAuthToken
}, {
transaction
})
}
// remove from the device list
await deviceEntry.destroy({ transaction })
// invalidiate the caches
await database.family.update({
deviceListVersion: generateVersionId(),
// the device could have become unassigned during this
userListVersion: generateVersionId()
}, {
where: {
familyId: deviceEntry.familyId
},
transaction
})
return { oldDeviceAuthToken: deviceEntry.deviceAuthToken }
const deviceEntry = await database.device.findOne({
where: {
familyId,
deviceId
},
transaction
})
await notifyClientsAboutChanges({
if (!deviceEntry) {
throw new Conflict()
}
// remove app entries
await database.app.destroy({
where: {
familyId,
deviceId
},
transaction
})
await database.appActivity.destroy({
where: {
familyId,
deviceId
},
transaction
})
// remove as current device
await database.user.update({
currentDevice: ''
}, {
where: {
familyId,
currentDevice: deviceId
},
transaction
})
// add to old devices if it is not yet there (it could be there if it reported a uninstall)
const oldOldDeviceEntry = await database.oldDevice.findOne({
where: {
deviceAuthToken: deviceEntry.deviceAuthToken
},
transaction
})
if (!oldOldDeviceEntry) {
await database.oldDevice.create({
deviceAuthToken: deviceEntry.deviceAuthToken
}, {
transaction
})
}
// remove from the device list
await deviceEntry.destroy({ transaction })
// invalidiate the caches
await database.family.update({
deviceListVersion: generateVersionId(),
// the device could have become unassigned during this
userListVersion: generateVersionId()
}, {
where: {
familyId: deviceEntry.familyId
},
transaction
})
await notifyClientsAboutChangesDelayed({
database,
websocket,
familyId,
sourceDeviceId: null,
isImportant: false
isImportant: false,
transaction
})
websocket.triggerSyncByDeviceAuthToken({
deviceAuthToken: oldDeviceAuthToken,
isImportant: true
transaction.afterCommit(() => {
websocket.triggerSyncByDeviceAuthToken({
deviceAuthToken: deviceEntry.deviceAuthToken,
isImportant: true
})
})
}
+19 -22
View File
@@ -1,6 +1,6 @@
/*
* server component for the TimeLimit App
* Copyright (C) 2019 Jonas Lochmann
* Copyright (C) 2019 - 2020 Jonas Lochmann
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
@@ -19,14 +19,15 @@ import { Database } from '../../database'
import { generateAuthToken, generateVersionId } from '../../util/token'
import { WebsocketApi } from '../../websocket'
import { sendUninstallWarnings } from '../warningmail/uninstall'
import { notifyClientsAboutChanges } from '../websocket'
import { notifyClientsAboutChangesDelayed } from '../websocket'
export async function reportDeviceRemoved ({ database, deviceAuthToken, websocket }: {
database: Database
deviceAuthToken: string
websocket: WebsocketApi
// no transaction here because this is directly called from an API endpoint
}) {
const result = await database.transaction(async (transaction) => {
await database.transaction(async (transaction) => {
const deviceEntry = await database.device.findOne({
where: {
deviceAuthToken
@@ -58,7 +59,21 @@ export async function reportDeviceRemoved ({ database, deviceAuthToken, websocke
transaction
})
return { familyId: deviceEntry.familyId, deviceName: deviceEntry.name }
await notifyClientsAboutChangesDelayed({
database,
websocket,
familyId: deviceEntry.familyId,
sourceDeviceId: null,
isImportant: false,
transaction
})
await sendUninstallWarnings({
database,
familyId: deviceEntry.familyId,
deviceName: deviceEntry.name,
transaction
})
} else {
const oldDeviceEntry = await database.oldDevice.findOne({
where: {
@@ -70,24 +85,6 @@ export async function reportDeviceRemoved ({ database, deviceAuthToken, websocke
if (!oldDeviceEntry) {
throw new Error('device not found')
}
return null
}
})
if (result) {
await notifyClientsAboutChanges({
database,
websocket,
familyId: result.familyId,
sourceDeviceId: null,
isImportant: false
})
await sendUninstallWarnings({
database,
familyId: result.familyId,
deviceName: result.deviceName
})
}
}
+15 -11
View File
@@ -1,6 +1,6 @@
/*
* server component for the TimeLimit App
* Copyright (C) 2019 Jonas Lochmann
* Copyright (C) 2019 - 2020 Jonas Lochmann
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
@@ -22,16 +22,20 @@ export const canRecoverPassword = async ({ database, mailAuthToken, parentUserId
database: Database
mailAuthToken: string
parentUserId: string
}) => {
const mail = await requireMailByAuthToken({ mailAuthToken, database })
// no transaction here because this is directly called from an API endpoint
}): Promise<boolean> => {
return database.transaction(async (transaction) => {
const mail = await requireMailByAuthToken({ mailAuthToken, database, transaction })
const entry = await database.user.findOne({
where: {
mail,
userId: parentUserId,
type: 'parent'
}
const entry = await database.user.findOne({
where: {
mail,
userId: parentUserId,
type: 'parent'
},
transaction
})
return !!entry
})
return !!entry
}
@@ -1,6 +1,6 @@
/*
* server component for the TimeLimit App
* Copyright (C) 2019 Jonas Lochmann
* Copyright (C) 2019 - 2020 Jonas Lochmann
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
@@ -15,13 +15,14 @@
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import { Database } from '../../database'
import { Database, Transaction } from '../../database'
import { randomWords } from '../../util/random-words'
import { generateIdWithinFamily } from '../../util/token'
export const createAddDeviceToken = async ({ familyId, database }: {
export const createAddDeviceToken = async ({ familyId, database, transaction }: {
familyId: string
database: Database
transaction: Transaction
}) => {
const token = randomWords(5)
const deviceId = generateIdWithinFamily()
@@ -29,7 +30,8 @@ export const createAddDeviceToken = async ({ familyId, database }: {
await database.addDeviceToken.destroy({
where: {
familyId
}
},
transaction
})
await database.addDeviceToken.create({
@@ -37,7 +39,7 @@ export const createAddDeviceToken = async ({ familyId, database }: {
token: token.toLowerCase(),
deviceId,
createdAt: Date.now().toString()
})
}, { transaction })
return { token, deviceId }
}
+5 -4
View File
@@ -1,6 +1,6 @@
/*
* server component for the TimeLimit App
* Copyright (C) 2019 Jonas Lochmann
* Copyright (C) 2019 - 2020 Jonas Lochmann
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
@@ -32,11 +32,12 @@ export const createFamily = async ({ database, mailAuthToken, firstParentDevice,
timeZone: string,
parentName: string,
deviceName: string
// no transaction here because this is directly called from an API endpoint
}) => {
const now = Date.now().toString(10)
const mail = await requireMailByAuthToken({ database, mailAuthToken })
return database.transaction(async (transaction) => {
const now = Date.now().toString(10)
const mail = await requireMailByAuthToken({ database, mailAuthToken, transaction })
// ensure that no family was created for this mail yet
const exisitngUserEntry = await database.user.findOne({
where: {
@@ -1,6 +1,6 @@
/*
* server component for the TimeLimit App
* Copyright (C) 2019 Jonas Lochmann
* Copyright (C) 2019 - 2020 Jonas Lochmann
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
@@ -15,10 +15,12 @@
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import { Database } from '../../database'
import { Database, Transaction } from '../../database'
import { requireMailByAuthToken } from '../authentication'
const getStatusByMailAddress = async ({ mail, database }: {mail: string, database: Database}) => {
const getStatusByMailAddress = async ({
mail, database, transaction
}: { mail: string, database: Database, transaction: Transaction }) => {
if (!mail) {
throw new Error('no mail address')
}
@@ -26,7 +28,8 @@ const getStatusByMailAddress = async ({ mail, database }: {mail: string, databas
const entry = await database.user.findOne({
where: {
mail
}
},
transaction
})
if (entry) {
@@ -36,9 +39,11 @@ const getStatusByMailAddress = async ({ mail, database }: {mail: string, databas
}
}
export const getStatusByMailToken = async ({ mailAuthToken, database }: {mailAuthToken: string, database: Database}) => {
const mail = await requireMailByAuthToken({ mailAuthToken, database })
const status = await getStatusByMailAddress({ mail, database })
export const getStatusByMailToken = async ({
mailAuthToken, database, transaction
}: { mailAuthToken: string, database: Database, transaction: Transaction }) => {
const mail = await requireMailByAuthToken({ mailAuthToken, database, transaction })
const status = await getStatusByMailAddress({ mail, database, transaction })
return { mail, status }
}
+38 -33
View File
@@ -1,6 +1,6 @@
/*
* server component for the TimeLimit App
* Copyright (C) 2019 Jonas Lochmann
* Copyright (C) 2019 - 2020 Jonas Lochmann
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
@@ -21,7 +21,7 @@ import { Database } from '../../database'
import { generateVersionId } from '../../util/token'
import { WebsocketApi } from '../../websocket'
import { requireMailByAuthToken } from '../authentication'
import { notifyClientsAboutChanges } from '../websocket'
import { notifyClientsAboutChangesDelayed } from '../websocket'
export const linkMailAddress = async ({ mailAuthToken, deviceAuthToken, parentUserId, parentPasswordSecondHash, database, websocket }: {
mailAuthToken: string
@@ -30,32 +30,35 @@ export const linkMailAddress = async ({ mailAuthToken, deviceAuthToken, parentUs
parentPasswordSecondHash: string
database: Database
websocket: WebsocketApi
// no transaction here because this is directly called from an API endpoint
}) => {
const deviceEntry = await database.device.findOne({
where: {
deviceAuthToken
}
})
if (!deviceEntry) {
throw new Unauthorized()
}
const familyId = deviceEntry.familyId
const mailAddress = await requireMailByAuthToken({ mailAuthToken, database })
const exisitingUser = await database.user.findOne({
where: {
mail: mailAddress
}
})
if (exisitingUser) {
throw new Conflict()
}
await database.transaction(async (transaction) => {
const deviceEntry = await database.device.findOne({
where: {
deviceAuthToken
},
transaction
})
if (!deviceEntry) {
throw new Unauthorized()
}
const familyId = deviceEntry.familyId
const mailAddress = await requireMailByAuthToken({ mailAuthToken, database, transaction })
const exisitingUser = await database.user.findOne({
where: {
mail: mailAddress
},
transaction
})
if (exisitingUser) {
throw new Conflict()
}
const parentEntry = await database.user.findOne({
where: {
type: 'parent',
@@ -95,13 +98,15 @@ export const linkMailAddress = async ({ mailAuthToken, deviceAuthToken, parentUs
},
transaction
})
})
await notifyClientsAboutChanges({
familyId,
sourceDeviceId: null,
database,
websocket,
isImportant: true
// notify
await notifyClientsAboutChangesDelayed({
familyId,
sourceDeviceId: null,
database,
websocket,
isImportant: true,
transaction
})
})
}
+15 -21
View File
@@ -1,6 +1,6 @@
/*
* server component for the TimeLimit App
* Copyright (C) 2019 Jonas Lochmann
* Copyright (C) 2019 - 2020 Jonas Lochmann
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
@@ -16,34 +16,33 @@
*/
import { Conflict } from 'http-errors'
import * as Sequelize from 'sequelize'
import { ParentPassword } from '../../api/schema'
import { Database } from '../../database'
import { generateVersionId } from '../../util/token'
import { WebsocketApi } from '../../websocket'
import { requireMailByAuthToken } from '../authentication'
import { notifyClientsAboutChanges } from '../websocket'
import { notifyClientsAboutChangesDelayed } from '../websocket'
export const recoverParentPassword = async ({ database, websocket, password, mailAuthToken }: {
database: Database
websocket: WebsocketApi
password: ParentPassword
mailAuthToken: string
// no transaction here because this is directly called from an API endpoint
}) => {
const mail = await requireMailByAuthToken({ mailAuthToken, database })
await database.transaction(async (transaction) => {
const mail = await requireMailByAuthToken({ mailAuthToken, database, transaction })
const { familyId } = await database.transaction(async (transaction) => {
// update the user entry
const userEntry = await database.user.findOne({
where: {
mail
},
transaction,
lock: Sequelize.Transaction.LOCK.UPDATE
transaction
})
if (!userEntry) {
return { familyId: null }
throw new Conflict()
}
userEntry.passwordHash = password.hash
@@ -62,18 +61,13 @@ export const recoverParentPassword = async ({ database, websocket, password, mai
transaction
})
return { familyId: userEntry.familyId }
})
if (familyId === null) {
throw new Conflict()
}
await notifyClientsAboutChanges({
database,
familyId,
websocket,
isImportant: true,
sourceDeviceId: null
await notifyClientsAboutChangesDelayed({
database,
familyId: userEntry.familyId,
websocket,
isImportant: true,
sourceDeviceId: null,
transaction
})
})
}
+16 -20
View File
@@ -22,7 +22,7 @@ import { generateAuthToken, generateIdWithinFamily, generateVersionId } from '..
import { WebsocketApi } from '../../websocket'
import { requireMailByAuthToken } from '../authentication'
import { prepareDeviceEntry } from '../device/prepare-device-entry'
import { notifyClientsAboutChanges } from '../websocket'
import { notifyClientsAboutChangesDelayed } from '../websocket'
export const signInIntoFamily = async ({ database, mailAuthToken, newDeviceInfo, deviceName, websocket }: {
database: Database
@@ -30,10 +30,11 @@ export const signInIntoFamily = async ({ database, mailAuthToken, newDeviceInfo,
newDeviceInfo: NewDeviceInfo
deviceName: string
websocket: WebsocketApi
}) => {
const mail = await requireMailByAuthToken({ database, mailAuthToken })
// no transaction here because this is directly called from an API endpoint
}): Promise<{ deviceId: string; deviceAuthToken: string }> => {
return database.transaction(async (transaction) => {
const mail = await requireMailByAuthToken({ database, mailAuthToken, transaction })
const { response, familyId, sourceDeviceId } = await database.transaction(async (transaction) => {
const userEntryUnsafe = await database.user.findOne({
where: {
mail
@@ -73,23 +74,18 @@ export const signInIntoFamily = async ({ database, mailAuthToken, newDeviceInfo,
transaction
})
return {
response: {
deviceId,
deviceAuthToken
},
await notifyClientsAboutChangesDelayed({
familyId: userEntry.familyId,
websocket,
database,
isImportant: true,
sourceDeviceId: deviceId,
familyId: userEntry.familyId
transaction
})
return {
deviceId,
deviceAuthToken
}
})
await notifyClientsAboutChanges({
familyId,
websocket,
database,
isImportant: true,
sourceDeviceId
})
return response
}
+55 -55
View File
@@ -1,6 +1,6 @@
/*
* server component for the TimeLimit App
* Copyright (C) 2019 Jonas Lochmann
* Copyright (C) 2019 - 2020 Jonas Lochmann
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
@@ -17,75 +17,75 @@
import { Conflict } from 'http-errors'
import * as Sequelize from 'sequelize'
import { Database } from '../../database'
import { notifyClientsAboutChanges } from '../../function/websocket'
import { Database, Transaction } from '../../database'
import { notifyClientsAboutChangesDelayed } from '../../function/websocket'
import { WebsocketApi } from '../../websocket'
const day = 1000 * 60 * 60 * 24
const month = day * 31
const year = day * 366
export const addPurchase = async ({ database, familyId, type, transactionId, websocket }: {
export const addPurchase = async ({ database, familyId, type, transactionId, websocket, transaction }: {
database: Database
familyId: string
type: 'month' | 'year'
transactionId: string
websocket: WebsocketApi
transaction: Transaction
}) => {
const service = 'googleplay'
await database.transaction(async (transaction) => {
const oldPurchaseEntry = await database.purchase.findOne({
where: {
service,
transactionId
},
transaction
})
if (oldPurchaseEntry) {
return
}
const familyEntry = await database.family.findOne({
where: {
familyId
},
transaction,
lock: Sequelize.Transaction.LOCK.UPDATE
})
if (!familyEntry) {
throw new Conflict()
}
const previousFullVersionEndTime = familyEntry.fullVersionUntil
const newFullVersionUntil = Math.max(parseInt(familyEntry.fullVersionUntil, 10), Date.now()) + (type === 'year' ? year : month)
familyEntry.fullVersionUntil = newFullVersionUntil.toString(10)
familyEntry.hasFullVersion = true
await familyEntry.save({ transaction })
await database.purchase.create({
familyId,
const oldPurchaseEntry = await database.purchase.findOne({
where: {
service,
transactionId,
type,
loggedAt: Date.now().toString(10),
previousFullVersionEndTime,
newFullVersionEndTime: newFullVersionUntil.toString(10)
}, {
transaction
})
transactionId
},
transaction
})
await notifyClientsAboutChanges({
familyId,
sourceDeviceId: null,
database,
websocket,
isImportant: true
})
if (oldPurchaseEntry) {
return
}
const familyEntry = await database.family.findOne({
where: {
familyId
},
transaction,
lock: Sequelize.Transaction.LOCK.UPDATE
})
if (!familyEntry) {
throw new Conflict()
}
const previousFullVersionEndTime = familyEntry.fullVersionUntil
const newFullVersionUntil = Math.max(parseInt(familyEntry.fullVersionUntil, 10), Date.now()) + (type === 'year' ? year : month)
familyEntry.fullVersionUntil = newFullVersionUntil.toString(10)
familyEntry.hasFullVersion = true
await familyEntry.save({ transaction })
await database.purchase.create({
familyId,
service,
transactionId,
type,
loggedAt: Date.now().toString(10),
previousFullVersionEndTime,
newFullVersionEndTime: newFullVersionUntil.toString(10)
}, {
transaction
})
await notifyClientsAboutChangesDelayed({
familyId,
sourceDeviceId: null,
database,
websocket,
isImportant: true,
transaction
})
}
@@ -1,6 +1,6 @@
/*
* server component for the TimeLimit App
* Copyright (C) 2019 Jonas Lochmann
* Copyright (C) 2019 - 2020 Jonas Lochmann
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
@@ -16,17 +16,19 @@
*/
import { InternalServerError, Unauthorized } from 'http-errors'
import { Database } from '../../database'
import { Database, Transaction } from '../../database'
export const requireFamilyEntry = async ({ database, deviceAuthToken }: {
export const requireFamilyEntry = async ({ database, deviceAuthToken, transaction }: {
database: Database
deviceAuthToken: string
transaction: Transaction
}) => {
const deviceEntryUnsafe = await database.device.findOne({
where: {
deviceAuthToken
},
attributes: ['familyId']
attributes: ['familyId'],
transaction
})
if (!deviceEntryUnsafe) {
@@ -41,7 +43,8 @@ export const requireFamilyEntry = async ({ database, deviceAuthToken }: {
where: {
familyId: deviceEntry.familyId
},
attributes: ['fullVersionUntil']
attributes: ['fullVersionUntil'],
transaction
})
if (!familyEntryUnsafe) {
+16 -13
View File
@@ -1,6 +1,6 @@
/*
* server component for the TimeLimit App
* Copyright (C) 2019 Jonas Lochmann
* Copyright (C) 2019 - 2020 Jonas Lochmann
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
@@ -33,16 +33,19 @@ export const setStatusMessage = async ({ database, newStatusMessage }: {
database: Database
newStatusMessage: string
}) => {
if (newStatusMessage === '') {
await database.config.destroy({
where: {
id: configItemIds.statusMessage
}
})
} else {
await database.config.upsert({
id: configItemIds.statusMessage,
value: newStatusMessage
})
}
await database.transaction(async (transaction) => {
if (newStatusMessage === '') {
await database.config.destroy({
where: {
id: configItemIds.statusMessage
},
transaction
})
} else {
await database.config.upsert({
id: configItemIds.statusMessage,
value: newStatusMessage
}, { transaction })
}
})
}
+17 -1
View File
@@ -25,7 +25,7 @@ import { generateVersionId } from '../../../util/token'
export class Cache {
readonly familyId: string
readonly hasFullVersion: boolean
readonly transaction: Sequelize.Transaction
transaction: Sequelize.Transaction
readonly database: Database
readonly connectedDevicesManager: VisibleConnectedDevicesManager
private shouldTriggerFullSync = false
@@ -56,6 +56,22 @@ export class Cache {
this.connectedDevicesManager = connectedDevicesManager
}
async subtransaction<T> (callback: () => Promise<T>): Promise<T> {
const oldTransaction = this.transaction
return this.database.transaction(async (newTransaction) => {
try {
this.transaction = newTransaction
const result = await callback()
return result
} finally {
this.transaction = oldTransaction
}
}, { transaction: oldTransaction })
}
getSecondPasswordHashOfParent = memoize(async (parentId: string) => {
const userEntryUnsafe = await this.database.user.findOne({
where: {
+148 -202
View File
@@ -15,7 +15,6 @@
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import { createHash } from 'crypto'
import { BadRequest, Unauthorized } from 'http-errors'
import { parseAppLogicAction, parseChildAction, parseParentAction } from '../../../action/serialization'
import { ClientPushChangesRequest } from '../../../api/schema'
@@ -25,11 +24,12 @@ import { Database } from '../../../database'
import { UserFlags } from '../../../model/userflags'
import { EventHandler } from '../../../monitoring/eventhandler'
import { WebsocketApi } from '../../../websocket'
import { notifyClientsAboutChanges } from '../../websocket'
import { notifyClientsAboutChangesDelayed } from '../../websocket'
import { Cache } from './cache'
import { dispatchAppLogicAction } from './dispatch-app-logic-action'
import { dispatchChildAction } from './dispatch-child-action'
import { dispatchParentAction } from './dispatch-parent-action'
import { assertActionIntegrity } from './integrity'
export const applyActionsFromDevice = async ({ database, request, websocket, connectedDevicesManager, eventHandler }: {
database: Database
@@ -37,7 +37,7 @@ export const applyActionsFromDevice = async ({ database, request, websocket, con
request: ClientPushChangesRequest
connectedDevicesManager: VisibleConnectedDevicesManager
eventHandler: EventHandler
}) => {
}): Promise<{ shouldDoFullSync: boolean }> => {
eventHandler.countEvent('applyActionsFromDevice')
if (request.actions.length > 50) {
@@ -46,7 +46,7 @@ export const applyActionsFromDevice = async ({ database, request, websocket, con
throw new BadRequest()
}
const { shouldDoFullSync, areChangesImportant, sourceDeviceId, familyId } = await database.transaction(async (transaction) => {
return database.transaction(async (transaction) => {
const deviceEntryUnsafe = await database.device.findOne({
where: {
deviceAuthToken: request.deviceAuthToken
@@ -91,9 +91,7 @@ export const applyActionsFromDevice = async ({ database, request, websocket, con
let { nextSequenceNumber } = deviceEntry
for (let i = 0; i < request.actions.length; i++) {
const action = request.actions[i]
for (const action of request.actions) {
if (action.sequenceNumber < nextSequenceNumber) {
// action was already received
@@ -104,191 +102,141 @@ export const applyActionsFromDevice = async ({ database, request, websocket, con
}
try {
// update the next sequence number
nextSequenceNumber = action.sequenceNumber + 1
await cache.subtransaction(async () => {
// update the next sequence number
nextSequenceNumber = action.sequenceNumber + 1
let isChildLimitAdding = false
const { isChildLimitAdding } = await assertActionIntegrity({
deviceId: deviceEntry.deviceId,
cache,
eventHandler,
action
})
if (action.type === 'parent') {
if (action.integrity === 'device') {
const deviceEntryUnsafe2 = await cache.database.device.findOne({
attributes: ['currentUserId'],
where: {
familyId: cache.familyId,
const parsedSerializedAction = JSON.parse(action.encodedAction)
if (action.type === 'appLogic') {
if (!isSerializedAppLogicAction(parsedSerializedAction)) {
eventHandler.countEvent('applyActionsFromDevice invalidAppLogicAction')
throw new Error('invalid action: ' + action.encodedAction)
}
eventHandler.countEvent('applyActionsFromDevice action:' + parsedSerializedAction.type)
const parsedAction = parseAppLogicAction(parsedSerializedAction)
try {
await dispatchAppLogicAction({
action: parsedAction,
cache,
deviceId: deviceEntry.deviceId,
currentUserId: action.userId,
isUserKeptSignedIn: true
},
transaction: cache.transaction
})
eventHandler
})
} catch (ex) {
eventHandler.countEvent('applyActionsFromDevice actionWithError:' + parsedSerializedAction.type)
if (!deviceEntryUnsafe2) {
throw new Error('user is not signed in at this device')
throw ex
}
} else if (action.type === 'parent') {
if (!isSerializedParentAction(parsedSerializedAction)) {
eventHandler.countEvent('applyActionsFromDevice invalidParentAction')
throw new Error('invalid action' + action.encodedAction)
}
// this ensures that the parent exists
await cache.getSecondPasswordHashOfParent(action.userId)
} else if (action.integrity === 'childDevice') {
// will be checked later
isChildLimitAdding = true
eventHandler.countEvent('applyActionsFromDevice, childAddLimit: ' + isChildLimitAdding + ' action:' + parsedSerializedAction.type)
const parsedAction = parseParentAction(parsedSerializedAction)
try {
if (isChildLimitAdding) {
const deviceEntryUnsafe2 = await cache.database.device.findOne({
attributes: ['currentUserId'],
where: {
familyId: cache.familyId,
deviceId: deviceEntry.deviceId,
currentUserId: action.userId
},
transaction: cache.transaction
})
if (!deviceEntryUnsafe2) {
throw new Error('illegal state')
}
const deviceUserId = deviceEntryUnsafe2.currentUserId
if (!deviceUserId) {
throw new Error('no device user id set but child add self limit action requested')
}
const deviceUserEntryUnsafe = await cache.database.user.findOne({
attributes: ['flags'],
where: {
familyId: cache.familyId,
userId: deviceUserId,
type: 'child'
},
transaction: cache.transaction
})
if (!deviceUserEntryUnsafe) {
throw new Error('no child user found for child limit adding action')
}
if ((parseInt(deviceUserEntryUnsafe.flags, 10) & UserFlags.ALLOW_SELF_LIMIT_ADD) !== UserFlags.ALLOW_SELF_LIMIT_ADD) {
throw new Error('child add limit action found but not allowed')
}
await dispatchParentAction({
action: parsedAction,
cache,
parentUserId: action.userId,
sourceDeviceId: deviceEntry.deviceId,
fromChildSelfLimitAddChildUserId: deviceUserId
})
} else {
await dispatchParentAction({
action: parsedAction,
cache,
parentUserId: action.userId,
sourceDeviceId: deviceEntry.deviceId,
fromChildSelfLimitAddChildUserId: null
})
}
} catch (ex) {
eventHandler.countEvent('applyActionsFromDeviceWithError, childAddLimit: ' + isChildLimitAdding + ' action:' + parsedSerializedAction.type)
throw ex
}
} else if (action.type === 'child') {
if (!isSerializedChildAction(parsedSerializedAction)) {
eventHandler.countEvent('applyActionsFromDevice invalidChildAction')
throw new Error('invalid action: ' + action.encodedAction)
}
eventHandler.countEvent('applyActionsFromDevice action:' + parsedSerializedAction.type)
const parsedAction = parseChildAction(parsedSerializedAction)
try {
await dispatchChildAction({
action: parsedAction,
cache,
childUserId: action.userId,
deviceId: deviceEntry.deviceId
})
} catch (ex) {
eventHandler.countEvent('applyActionsFromDevice actionWithError:' + parsedSerializedAction.type)
throw ex
}
} else {
const parentSecondHash = await cache.getSecondPasswordHashOfParent(action.userId)
const integrityData = action.sequenceNumber.toString(10) +
deviceEntry.deviceId +
parentSecondHash +
action.encodedAction
const expectedIntegrityValue = createHash('sha512').update(integrityData).digest('hex')
if (action.integrity !== expectedIntegrityValue) {
eventHandler.countEvent('applyActionsFromDevice parentActionInvalidIntegrityValue')
throw new Error('invalid integrity value')
}
throw new Error('illegal state')
}
}
if (action.type === 'child') {
const childSecondHash = await cache.getSecondPasswordHashOfChild(action.userId)
const integrityData = action.sequenceNumber.toString(10) +
deviceEntry.deviceId +
childSecondHash +
action.encodedAction
const expectedIntegrityValue = createHash('sha512').update(integrityData).digest('hex')
if (action.integrity !== expectedIntegrityValue) {
eventHandler.countEvent('applyActionsFromDevice childActionInvalidIntegrityValue')
throw new Error('invalid integrity value')
}
}
const parsedSerializedAction = JSON.parse(action.encodedAction)
if (action.type === 'appLogic') {
if (!isSerializedAppLogicAction(parsedSerializedAction)) {
eventHandler.countEvent('applyActionsFromDevice invalidAppLogicAction')
throw new Error('invalid action: ' + action.encodedAction)
}
eventHandler.countEvent('applyActionsFromDevice action:' + parsedSerializedAction.type)
const parsedAction = parseAppLogicAction(parsedSerializedAction)
try {
await dispatchAppLogicAction({
action: parsedAction,
cache,
deviceId: deviceEntry.deviceId,
eventHandler
})
} catch (ex) {
eventHandler.countEvent('applyActionsFromDevice actionWithError:' + parsedSerializedAction.type)
throw ex
}
} else if (action.type === 'parent') {
if (!isSerializedParentAction(parsedSerializedAction)) {
eventHandler.countEvent('applyActionsFromDevice invalidParentAction')
throw new Error('invalid action' + action.encodedAction)
}
eventHandler.countEvent('applyActionsFromDevice, childAddLimit: ' + isChildLimitAdding + ' action:' + parsedSerializedAction.type)
const parsedAction = parseParentAction(parsedSerializedAction)
try {
if (isChildLimitAdding) {
const deviceEntryUnsafe2 = await cache.database.device.findOne({
attributes: ['currentUserId'],
where: {
familyId: cache.familyId,
deviceId: deviceEntry.deviceId,
currentUserId: action.userId
},
transaction: cache.transaction
})
if (!deviceEntryUnsafe2) {
throw new Error('illegal state')
}
const deviceUserId = deviceEntryUnsafe2.currentUserId
if (!deviceUserId) {
throw new Error('no device user id set but child add self limit action requested')
}
const deviceUserEntryUnsafe = await cache.database.user.findOne({
attributes: ['flags'],
where: {
familyId: cache.familyId,
userId: deviceUserId,
type: 'child'
},
transaction: cache.transaction
})
if (!deviceUserEntryUnsafe) {
throw new Error('no child user found for child limit adding action')
}
if ((parseInt(deviceUserEntryUnsafe.flags, 10) & UserFlags.ALLOW_SELF_LIMIT_ADD) !== UserFlags.ALLOW_SELF_LIMIT_ADD) {
throw new Error('child add limit action found but not allowed')
}
await dispatchParentAction({
action: parsedAction,
cache,
parentUserId: action.userId,
sourceDeviceId: deviceEntry.deviceId,
fromChildSelfLimitAddChildUserId: deviceUserId
})
} else {
await dispatchParentAction({
action: parsedAction,
cache,
parentUserId: action.userId,
sourceDeviceId: deviceEntry.deviceId,
fromChildSelfLimitAddChildUserId: null
})
}
} catch (ex) {
eventHandler.countEvent('applyActionsFromDeviceWithError, childAddLimit: ' + isChildLimitAdding + ' action:' + parsedSerializedAction.type)
throw ex
}
} else if (action.type === 'child') {
if (!isSerializedChildAction(parsedSerializedAction)) {
eventHandler.countEvent('applyActionsFromDevice invalidChildAction')
throw new Error('invalid action: ' + action.encodedAction)
}
eventHandler.countEvent('applyActionsFromDevice action:' + parsedSerializedAction.type)
const parsedAction = parseChildAction(parsedSerializedAction)
try {
await dispatchChildAction({
action: parsedAction,
cache,
childUserId: action.userId,
deviceId: deviceEntry.deviceId
})
} catch (ex) {
eventHandler.countEvent('applyActionsFromDevice actionWithError:' + parsedSerializedAction.type)
throw ex
}
} else {
throw new Error('illegal state')
}
})
} catch (ex) {
eventHandler.countEvent('applyActionsFromDevice errorDispatchingAction')
@@ -313,25 +261,23 @@ export const applyActionsFromDevice = async ({ database, request, websocket, con
await cache.saveModifiedVersionNumbers()
return {
shouldDoFullSync: cache.shouldDoFullSync(),
areChangesImportant: cache.areChangesImportant,
await notifyClientsAboutChangesDelayed({
familyId: deviceEntry.familyId,
sourceDeviceId: deviceEntry.deviceId,
familyId: deviceEntry.familyId
isImportant: cache.areChangesImportant,
websocket,
database,
transaction
})
if (cache.areChangesImportant) {
transaction.afterCommit(() => {
eventHandler.countEvent('applyActionsFromDevice areChangesImportant')
})
}
return {
shouldDoFullSync: cache.shouldDoFullSync()
}
})
if (areChangesImportant) {
eventHandler.countEvent('applyActionsFromDevice areChangesImportant')
}
await notifyClientsAboutChanges({
familyId,
sourceDeviceId,
isImportant: areChangesImportant,
websocket,
database
})
return { shouldDoFullSync }
}
@@ -0,0 +1,89 @@
/*
* server component for the TimeLimit App
* Copyright (C) 2019 - 2020 Jonas Lochmann
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, version 3 of the License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import { createHash } from 'crypto'
import { ClientPushChangesRequestAction } from '../../../api/schema'
import { EventHandler } from '../../../monitoring/eventhandler'
import { Cache } from './cache'
export async function assertActionIntegrity ({ action, cache, eventHandler, deviceId }: {
action: ClientPushChangesRequestAction
cache: Cache
eventHandler: EventHandler
deviceId: string
}): Promise<{ isChildLimitAdding: boolean }> {
let isChildLimitAdding = false
if (action.type === 'parent') {
if (action.integrity === 'device') {
const deviceEntryUnsafe = await cache.database.device.findOne({
attributes: ['currentUserId'],
where: {
familyId: cache.familyId,
deviceId,
currentUserId: action.userId,
isUserKeptSignedIn: true
},
transaction: cache.transaction
})
if (!deviceEntryUnsafe) {
throw new Error('user is not signed in at this device')
}
// this ensures that the parent exists
await cache.getSecondPasswordHashOfParent(action.userId)
} else if (action.integrity === 'childDevice') {
// will be checked later
isChildLimitAdding = true
} else {
const parentSecondHash = await cache.getSecondPasswordHashOfParent(action.userId)
const integrityData = action.sequenceNumber.toString(10) +
deviceId +
parentSecondHash +
action.encodedAction
const expectedIntegrityValue = createHash('sha512').update(integrityData).digest('hex')
if (action.integrity !== expectedIntegrityValue) {
eventHandler.countEvent('applyActionsFromDevice parentActionInvalidIntegrityValue')
throw new Error('invalid integrity value')
}
}
}
if (action.type === 'child') {
const childSecondHash = await cache.getSecondPasswordHashOfChild(action.userId)
const integrityData = action.sequenceNumber.toString(10) +
deviceId +
childSecondHash +
action.encodedAction
const expectedIntegrityValue = createHash('sha512').update(integrityData).digest('hex')
if (action.integrity !== expectedIntegrityValue) {
eventHandler.countEvent('applyActionsFromDevice childActionInvalidIntegrityValue')
throw new Error('invalid integrity value')
}
}
return { isChildLimitAdding }
}
+28 -10
View File
@@ -1,5 +1,21 @@
import * as Sequelize from 'sequelize'
import { Database } from '../../database'
/*
* server component for the TimeLimit App
* Copyright (C) 2019 - 2020 Jonas Lochmann
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, version 3 of the License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import { Database, Transaction, warpPromiseReturner } from '../../database'
import { sendManipulationWarningMail } from '../../util/mail'
import { canSendWarningMail } from '../../util/ratelimit-warningmail'
@@ -7,7 +23,7 @@ export const sendManipulationWarnings = async ({ database, familyId, deviceName,
database: Database
familyId: string
deviceName: string
transaction: Sequelize.Transaction
transaction: Transaction
}) => {
const parentEntries = await database.user.findAll({
where: {
@@ -22,11 +38,13 @@ export const sendManipulationWarnings = async ({ database, familyId, deviceName,
.filter((item) => (item.mailNotificationFlags & 1) === 1)
.map((item) => item.mail)
await Promise.all(
targetMailAddresses.map(async (receiver) => {
if (await canSendWarningMail(receiver)) {
await sendManipulationWarningMail({ receiver, deviceName })
}
})
)
transaction.afterCommit(warpPromiseReturner(async () => {
await Promise.all(
targetMailAddresses.map(async (receiver) => {
if (await canSendWarningMail(receiver)) {
await sendManipulationWarningMail({ receiver, deviceName })
}
})
)
}))
}
+31 -10
View File
@@ -1,17 +1,36 @@
import { Database } from '../../database'
/*
* server component for the TimeLimit App
* Copyright (C) 2019 - 2020 Jonas Lochmann
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, version 3 of the License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import { Database, Transaction, warpPromiseReturner } from '../../database'
import { sendUninstallWarningMail } from '../../util/mail'
import { canSendWarningMail } from '../../util/ratelimit-warningmail'
export const sendUninstallWarnings = async ({ database, familyId, deviceName }: {
export const sendUninstallWarnings = async ({ database, familyId, deviceName, transaction }: {
database: Database
familyId: string
deviceName: string
transaction: Transaction
}) => {
const parentEntries = await database.user.findAll({
where: {
familyId,
type: 'parent'
}
},
transaction
})
const targetMailAddresses = parentEntries
@@ -19,11 +38,13 @@ export const sendUninstallWarnings = async ({ database, familyId, deviceName }:
.filter((item) => (item.mailNotificationFlags & 1) === 1)
.map((item) => item.mail)
await Promise.all(
targetMailAddresses.map(async (receiver) => {
if (await canSendWarningMail(receiver)) {
await sendUninstallWarningMail({ receiver, deviceName })
}
})
)
transaction.afterCommit(warpPromiseReturner(async () => {
await Promise.all(
targetMailAddresses.map(async (receiver) => {
if (await canSendWarningMail(receiver)) {
await sendUninstallWarningMail({ receiver, deviceName })
}
})
)
}))
}
+10 -8
View File
@@ -1,6 +1,6 @@
/*
* server component for the TimeLimit App
* Copyright (C) 2019 Jonas Lochmann
* Copyright (C) 2019 - 2020 Jonas Lochmann
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
@@ -16,16 +16,16 @@
*/
import * as Sequelize from 'sequelize'
import { Database } from '../../database'
import { Database, Transaction } from '../../database'
import { WebsocketApi } from '../../websocket'
// this should be called AFTER an transaction was commited
export const notifyClientsAboutChanges = async ({ familyId, sourceDeviceId, database, websocket, isImportant }: {
export const notifyClientsAboutChangesDelayed = async ({ familyId, sourceDeviceId, database, websocket, isImportant, transaction }: {
familyId: string
sourceDeviceId: string | null // this device will not get an push
database: Database
websocket: WebsocketApi
isImportant: boolean
transaction: Transaction
}) => {
const relatedDeviceEntries = (await database.device.findAll({
where: sourceDeviceId ? {
@@ -41,10 +41,12 @@ export const notifyClientsAboutChanges = async ({ familyId, sourceDeviceId, data
deviceAuthToken: item.deviceAuthToken
}))
relatedDeviceEntries.forEach((item) => {
websocket.triggerSyncByDeviceAuthToken({
deviceAuthToken: item.deviceAuthToken,
isImportant
transaction.afterCommit(() => {
relatedDeviceEntries.forEach((item) => {
websocket.triggerSyncByDeviceAuthToken({
deviceAuthToken: item.deviceAuthToken,
isImportant
})
})
})
}
+3 -1
View File
@@ -19,7 +19,7 @@ import { Server } from 'http'
import { createApi } from './api'
import { config } from './config'
import { VisibleConnectedDevicesManager } from './connected-devices'
import { defaultDatabase, defaultUmzug } from './database'
import { assertNestedTransactionsAreWorking, defaultDatabase, defaultUmzug } from './database'
import { EventHandler } from './monitoring/eventhandler'
import { InMemoryEventHandler } from './monitoring/inmemoryeventhandler'
import { createWebsocketHandler } from './websocket'
@@ -30,6 +30,8 @@ async function main () {
const database = defaultDatabase
const eventHandler: EventHandler = new InMemoryEventHandler()
await assertNestedTransactionsAreWorking(database)
const connectedDevicesManager = new VisibleConnectedDevicesManager({
database
})
+14 -15
View File
@@ -1,6 +1,6 @@
/*
* server component for the TimeLimit App
* Copyright (C) 2019 Jonas Lochmann
* Copyright (C) 2019 - 2020 Jonas Lochmann
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
@@ -17,7 +17,7 @@
import * as Sequelize from 'sequelize'
import { Database } from '../database'
import { notifyClientsAboutChanges } from '../function/websocket'
import { notifyClientsAboutChangesDelayed } from '../function/websocket'
import { WebsocketApi } from '../websocket'
export function initDeleteDeprecatedPurchasesWorker ({ database, websocket }: {
@@ -43,7 +43,7 @@ async function deleteDeprecatedPurchases ({ database, websocket }: {
database: Database
websocket: WebsocketApi
}) {
const { affectedFamilyIds } = await database.transaction(async (transaction) => {
await database.transaction(async (transaction) => {
const affectedFamilyIds = await database.family.findAll({
where: {
hasFullVersion: true,
@@ -68,18 +68,17 @@ async function deleteDeprecatedPurchases ({ database, websocket }: {
transaction
})
for (const familyId of affectedFamilyIds) {
await notifyClientsAboutChangesDelayed({
familyId,
sourceDeviceId: null,
database,
websocket,
isImportant: true,
transaction
})
}
return { affectedFamilyIds }
})
for (let i = 0; i < affectedFamilyIds.length; i++) {
const familyId = affectedFamilyIds[i]
await notifyClientsAboutChanges({
familyId,
sourceDeviceId: null,
database,
websocket,
isImportant: true
})
}
}