mirror of
https://codeberg.org/timelimit/timelimit-server.git
synced 2026-08-31 19:03:45 +02:00
Extend transaction usage
This commit is contained in:
@@ -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()
|
||||
|
||||
@@ -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 }
|
||||
}
|
||||
|
||||
@@ -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({
|
||||
|
||||
@@ -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'
|
||||
})
|
||||
}
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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)
|
||||
})
|
||||
}
|
||||
|
||||
@@ -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
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
@@ -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
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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 }
|
||||
}
|
||||
|
||||
@@ -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 }
|
||||
}
|
||||
|
||||
@@ -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
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
@@ -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
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -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 })
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
@@ -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: {
|
||||
|
||||
@@ -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 }
|
||||
}
|
||||
@@ -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 })
|
||||
}
|
||||
})
|
||||
)
|
||||
}))
|
||||
}
|
||||
|
||||
@@ -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 })
|
||||
}
|
||||
})
|
||||
)
|
||||
}))
|
||||
}
|
||||
|
||||
@@ -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
|
||||
})
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user