mirror of
https://codeberg.org/timelimit/timelimit-server.git
synced 2026-08-31 19:03:45 +02:00
Initial commit
This commit is contained in:
@@ -0,0 +1,56 @@
|
||||
/*
|
||||
* server component for the TimeLimit App
|
||||
* Copyright (C) 2019 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 { Unauthorized } from 'http-errors'
|
||||
import { Database } from '../../database'
|
||||
import { generateAuthToken } from '../../util/token'
|
||||
|
||||
export const createAuthTokenByMailAddress = async ({ mail, database }: {mail: string, database: Database}) => {
|
||||
const token = generateAuthToken()
|
||||
|
||||
await database.authtoken.create({
|
||||
token,
|
||||
mail,
|
||||
createdAt: Date.now().toString()
|
||||
})
|
||||
|
||||
return token
|
||||
}
|
||||
|
||||
export const getMailByAuthToken = async ({ mailAuthToken, database }: {mailAuthToken: string, database: Database}) => {
|
||||
const entry = await database.authtoken.findOne({
|
||||
where: {
|
||||
token: mailAuthToken
|
||||
}
|
||||
})
|
||||
|
||||
if (entry) {
|
||||
return entry.mail
|
||||
} else {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
export const requireMailByAuthToken = async ({ mailAuthToken, database }: {mailAuthToken: string, database: Database}) => {
|
||||
const mail = await getMailByAuthToken({ mailAuthToken, database })
|
||||
|
||||
if (!mail) {
|
||||
throw new Unauthorized()
|
||||
}
|
||||
|
||||
return mail
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
/*
|
||||
* server component for the TimeLimit App
|
||||
* Copyright (C) 2019 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 { Forbidden, Gone, InternalServerError, TooManyRequests } from 'http-errors'
|
||||
import { Database } from '../../database'
|
||||
import { sendAuthenticationMail } from '../../util/mail'
|
||||
import { randomWords } from '../../util/random-words'
|
||||
import { checkMailSendLimit } from '../../util/ratelimit-authmail'
|
||||
import { generateAuthToken } from '../../util/token'
|
||||
import { createAuthTokenByMailAddress } from './index'
|
||||
|
||||
export const sendLoginCode = async ({ mail, locale, database }: {
|
||||
mail: string
|
||||
locale: string
|
||||
database: Database
|
||||
}): Promise<{mailLoginToken: string}> => {
|
||||
try {
|
||||
await checkMailSendLimit(mail)
|
||||
} catch (ex) {
|
||||
throw new TooManyRequests()
|
||||
}
|
||||
|
||||
const mailLoginToken = generateAuthToken()
|
||||
const code = randomWords(3)
|
||||
|
||||
await sendAuthenticationMail({
|
||||
receiver: mail,
|
||||
code,
|
||||
locale
|
||||
})
|
||||
|
||||
await database.mailLoginToken.create({
|
||||
mailLoginToken,
|
||||
receivedCode: code,
|
||||
mail,
|
||||
createdAt: Date.now().toString(10),
|
||||
remainingAttempts: 3
|
||||
})
|
||||
|
||||
return {
|
||||
mailLoginToken
|
||||
}
|
||||
}
|
||||
|
||||
// 403 Forbidden = receivedCode is invalid
|
||||
// 410 Gone = mailLoginToken is invalid or expired
|
||||
export const signInByMailCode = async ({ mailLoginToken, receivedCode, database }: {
|
||||
mailLoginToken: string
|
||||
receivedCode: string
|
||||
database: Database
|
||||
}): Promise<{mailAuthToken: string}> => {
|
||||
const { mail, status } = await database.transaction(async (transaction) => {
|
||||
const entry = await database.mailLoginToken.findOne({
|
||||
where: {
|
||||
mailLoginToken
|
||||
},
|
||||
transaction
|
||||
})
|
||||
|
||||
if ((!entry) || entry.remainingAttempts === 0) {
|
||||
return {
|
||||
mail: null,
|
||||
status: 'gone'
|
||||
}
|
||||
}
|
||||
|
||||
if (entry.receivedCode !== receivedCode) {
|
||||
entry.remainingAttempts--
|
||||
|
||||
await entry.save({ transaction })
|
||||
|
||||
if (entry.remainingAttempts === 0) {
|
||||
return {
|
||||
mail: null,
|
||||
status: 'gone'
|
||||
}
|
||||
} else {
|
||||
return {
|
||||
mail: null,
|
||||
status: 'forbidden'
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
mail: entry.mail,
|
||||
status: null
|
||||
}
|
||||
})
|
||||
|
||||
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 }
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
/*
|
||||
* server component for the TimeLimit App
|
||||
* Copyright (C) 2019 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 { Unauthorized } from 'http-errors'
|
||||
import { RegisterChildDeviceRequest } from '../../api/schema'
|
||||
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'
|
||||
|
||||
export const addChildDevice = async ({ database, websocket, request }: {
|
||||
database: Database
|
||||
websocket: WebsocketApi
|
||||
request: RegisterChildDeviceRequest
|
||||
}) => {
|
||||
const { response, familyId } = await database.transaction(async (transaction) => {
|
||||
const entry = await database.addDeviceToken.findOne({
|
||||
where: {
|
||||
token: request.registerToken.toLowerCase()
|
||||
},
|
||||
transaction
|
||||
})
|
||||
|
||||
if (!entry) {
|
||||
throw new Unauthorized()
|
||||
}
|
||||
|
||||
await entry.destroy({ transaction })
|
||||
|
||||
const { deviceId, familyId } = entry
|
||||
const deviceAuthToken = generateAuthToken()
|
||||
|
||||
await database.device.create(prepareDeviceEntry({
|
||||
familyId,
|
||||
deviceId,
|
||||
deviceAuthToken,
|
||||
deviceName: request.deviceName,
|
||||
newDeviceInfo: request.childDevice,
|
||||
userId: ''
|
||||
}), { transaction })
|
||||
|
||||
await database.family.update({
|
||||
deviceListVersion: generateVersionId()
|
||||
}, {
|
||||
where: {
|
||||
familyId
|
||||
},
|
||||
transaction
|
||||
})
|
||||
|
||||
return {
|
||||
response: {
|
||||
deviceId,
|
||||
deviceAuthToken
|
||||
},
|
||||
familyId
|
||||
}
|
||||
})
|
||||
|
||||
await notifyClientsAboutChanges({ familyId, websocket, database, isImportant: true, sourceDeviceId: response.deviceId })
|
||||
|
||||
return response
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
/*
|
||||
* server component for the TimeLimit App
|
||||
* Copyright (C) 2019 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 { Conflict, Unauthorized } from 'http-errors'
|
||||
import { Database } from '../../database'
|
||||
import { WebsocketApi } from '../../websocket'
|
||||
|
||||
export const logoutAtPrimaryDevice = async ({ deviceAuthToken, database, websocket }: {
|
||||
deviceAuthToken: string
|
||||
database: Database
|
||||
websocket: WebsocketApi
|
||||
}) => {
|
||||
await database.transaction(async (transaction) => {
|
||||
const ownDeviceEntryUnsafe = await database.device.findOne({
|
||||
where: {
|
||||
deviceAuthToken
|
||||
},
|
||||
transaction,
|
||||
attributes: ['familyId', 'currentUserId', 'deviceId']
|
||||
})
|
||||
|
||||
if (!ownDeviceEntryUnsafe) {
|
||||
throw new Unauthorized()
|
||||
}
|
||||
|
||||
const ownDeviceEntry = {
|
||||
familyId: ownDeviceEntryUnsafe.familyId,
|
||||
currentUserId: ownDeviceEntryUnsafe.currentUserId
|
||||
}
|
||||
|
||||
const deviceUserEntryUnsafe = await database.user.findOne({
|
||||
where: {
|
||||
familyId: ownDeviceEntry.familyId,
|
||||
userId: ownDeviceEntry.currentUserId,
|
||||
type: 'child'
|
||||
},
|
||||
attributes: ['currentDevice'],
|
||||
transaction
|
||||
})
|
||||
|
||||
if (!deviceUserEntryUnsafe) {
|
||||
throw new Conflict()
|
||||
}
|
||||
|
||||
const deviceUserEntry = {
|
||||
currentDevice: deviceUserEntryUnsafe.currentDevice
|
||||
}
|
||||
|
||||
const otherDeviceEntryUnsafe = await database.device.findOne({
|
||||
where: {
|
||||
familyId: ownDeviceEntry.familyId,
|
||||
deviceId: deviceUserEntry.currentDevice,
|
||||
currentUserId: ownDeviceEntry.currentUserId
|
||||
},
|
||||
attributes: ['deviceAuthToken'],
|
||||
transaction
|
||||
})
|
||||
|
||||
if (!otherDeviceEntryUnsafe) {
|
||||
throw new Conflict()
|
||||
}
|
||||
|
||||
const otherDeviceEntry = {
|
||||
deviceAuthToken: otherDeviceEntryUnsafe.deviceAuthToken
|
||||
}
|
||||
|
||||
websocket.triggerLogoutByDeviceAuthToken({
|
||||
deviceAuthToken: otherDeviceEntry.deviceAuthToken
|
||||
})
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,192 @@
|
||||
/*
|
||||
* server component for the TimeLimit App
|
||||
* Copyright (C) 2019 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 { Conflict, Unauthorized } from 'http-errors'
|
||||
import * as Sequelize from 'sequelize'
|
||||
import { Database } from '../../database'
|
||||
import { generateVersionId } from '../../util/token'
|
||||
import { WebsocketApi } from '../../websocket'
|
||||
import { notifyClientsAboutChanges } from '../websocket'
|
||||
|
||||
export const setPrimaryDevice = async ({ database, websocket, deviceAuthToken, currentUserId, action }: {
|
||||
database: Database
|
||||
websocket: WebsocketApi
|
||||
deviceAuthToken: string
|
||||
currentUserId: string
|
||||
action: 'set this device' | 'unset this device'
|
||||
}): 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
|
||||
}> => {
|
||||
const deviceEntryUnsafe = await database.device.findOne({
|
||||
where: {
|
||||
deviceAuthToken
|
||||
},
|
||||
transaction,
|
||||
attributes: ['familyId', 'currentUserId', 'deviceId']
|
||||
})
|
||||
|
||||
if (!deviceEntryUnsafe) {
|
||||
throw new Unauthorized()
|
||||
}
|
||||
|
||||
const deviceEntry = {
|
||||
familyId: deviceEntryUnsafe.familyId,
|
||||
currentUserId: deviceEntryUnsafe.currentUserId,
|
||||
deviceId: deviceEntryUnsafe.deviceId
|
||||
}
|
||||
|
||||
if ((deviceEntry.currentUserId !== currentUserId) || (currentUserId === '')) {
|
||||
throw new Conflict()
|
||||
}
|
||||
|
||||
const userEntryUnsafe = await database.user.findOne({
|
||||
where: {
|
||||
familyId: deviceEntry.familyId,
|
||||
userId: deviceEntry.currentUserId
|
||||
},
|
||||
transaction,
|
||||
lock: Sequelize.Transaction.LOCK.UPDATE,
|
||||
attributes: ['currentDevice']
|
||||
})
|
||||
|
||||
if (!userEntryUnsafe) {
|
||||
throw new Conflict()
|
||||
}
|
||||
|
||||
const userEntry = {
|
||||
currentDevice: userEntryUnsafe.currentDevice
|
||||
}
|
||||
|
||||
const userDeviceEntriesUnsafe = await database.device.findAll({
|
||||
where: {
|
||||
familyId: deviceEntry.familyId,
|
||||
currentUserId
|
||||
},
|
||||
transaction,
|
||||
attributes: ['deviceId']
|
||||
})
|
||||
|
||||
const userDeviceEntries = userDeviceEntriesUnsafe.map((item) => ({
|
||||
deviceId: item.deviceId
|
||||
}))
|
||||
|
||||
if (userDeviceEntries.length >= 2) {
|
||||
const familyEntryUnsafe = await database.family.findOne({
|
||||
where: {
|
||||
familyId: deviceEntry.familyId
|
||||
},
|
||||
transaction,
|
||||
attributes: ['hasFullVersion']
|
||||
})
|
||||
|
||||
if (!familyEntryUnsafe) {
|
||||
throw new Conflict()
|
||||
}
|
||||
|
||||
const familyEntry = {
|
||||
hasFullVersion: familyEntryUnsafe.hasFullVersion
|
||||
}
|
||||
|
||||
if (!familyEntry.hasFullVersion) {
|
||||
return {
|
||||
response: 'requires full version',
|
||||
sourceDeviceId: deviceEntry.deviceId,
|
||||
familyId: deviceEntry.familyId
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
}
|
||||
|
||||
// update
|
||||
const [affectedRows] = await database.user.update({
|
||||
currentDevice: deviceEntry.deviceId
|
||||
}, {
|
||||
where: {
|
||||
familyId: deviceEntry.familyId,
|
||||
userId: currentUserId
|
||||
},
|
||||
transaction
|
||||
})
|
||||
|
||||
if (affectedRows !== 1) {
|
||||
throw new Conflict()
|
||||
}
|
||||
} else if (action === 'unset this device') {
|
||||
if (userEntry.currentDevice !== deviceEntry.deviceId) {
|
||||
throw new Conflict()
|
||||
}
|
||||
|
||||
// update
|
||||
const [affectedRows] = await database.user.update({
|
||||
currentDevice: ''
|
||||
}, {
|
||||
where: {
|
||||
familyId: deviceEntry.familyId,
|
||||
userId: currentUserId
|
||||
},
|
||||
transaction
|
||||
})
|
||||
|
||||
if (affectedRows !== 1) {
|
||||
throw new Conflict()
|
||||
}
|
||||
} else {
|
||||
throw new Error('illegal state')
|
||||
}
|
||||
|
||||
// invalidiate user list
|
||||
await database.family.update({
|
||||
userListVersion: generateVersionId()
|
||||
}, {
|
||||
transaction,
|
||||
where: {
|
||||
familyId: deviceEntry.familyId
|
||||
}
|
||||
})
|
||||
|
||||
return {
|
||||
response: 'success',
|
||||
sourceDeviceId: deviceEntry.deviceId,
|
||||
familyId: deviceEntry.familyId
|
||||
}
|
||||
})
|
||||
|
||||
if (response.response === 'success') {
|
||||
// trigger sync
|
||||
await notifyClientsAboutChanges({
|
||||
familyId: response.familyId,
|
||||
sourceDeviceId: response.sourceDeviceId,
|
||||
websocket,
|
||||
database,
|
||||
isImportant: false // the source device knows it already
|
||||
})
|
||||
}
|
||||
|
||||
return response.response
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
/*
|
||||
* server component for the TimeLimit App
|
||||
* Copyright (C) 2019 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 { NewDeviceInfo } from '../../api/schema'
|
||||
import { DeviceAttributes } from '../../database/device'
|
||||
import { generateVersionId } from '../../util/token'
|
||||
|
||||
export const prepareDeviceEntry = ({ familyId, userId, deviceAuthToken, deviceId, deviceName, newDeviceInfo }: {
|
||||
familyId: string
|
||||
userId: string
|
||||
deviceAuthToken: string
|
||||
deviceId: string
|
||||
deviceName: string
|
||||
newDeviceInfo: NewDeviceInfo
|
||||
}): DeviceAttributes => ({
|
||||
familyId,
|
||||
deviceId,
|
||||
currentUserId: userId,
|
||||
installedAppsVersion: generateVersionId(),
|
||||
name: deviceName,
|
||||
model: newDeviceInfo.model,
|
||||
addedAt: Date.now().toString(10),
|
||||
deviceAuthToken,
|
||||
networkTime: 'disabled',
|
||||
nextSequenceNumber: 0,
|
||||
currentProtectionLevel: 'none',
|
||||
highestProtectionLevel: 'none',
|
||||
currentUsageStatsPermission: 'not granted',
|
||||
highestUsageStatsPermission: 'not granted',
|
||||
currentNotificationAccessPermission: 'not granted',
|
||||
highestNotificationAccessPermission: 'not granted',
|
||||
currentAppVersion: 0,
|
||||
highestAppVersion: 0,
|
||||
triedDisablingDeviceAdmin: false,
|
||||
didReboot: false,
|
||||
hadManipulation: false,
|
||||
lastConnectivity: '0',
|
||||
notSeenForLongTime: false,
|
||||
didDeviceReportUninstall: false,
|
||||
isUserKeptSignedIn: false,
|
||||
showDeviceConnected: false,
|
||||
defaultUserId: '',
|
||||
defaultUserTimeout: 0,
|
||||
considerRebootManipulation: false
|
||||
})
|
||||
@@ -0,0 +1,109 @@
|
||||
/*
|
||||
* server component for the TimeLimit App
|
||||
* Copyright (C) 2019 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 { Conflict } from 'http-errors'
|
||||
import { Database } from '../../database'
|
||||
import { generateVersionId } from '../../util/token'
|
||||
import { WebsocketApi } from '../../websocket'
|
||||
import { notifyClientsAboutChanges } from '../websocket'
|
||||
|
||||
export async function removeDevice ({ database, familyId, deviceId, websocket }: {
|
||||
database: Database
|
||||
familyId: string
|
||||
deviceId: string
|
||||
websocket: WebsocketApi
|
||||
}) {
|
||||
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
|
||||
})
|
||||
|
||||
// 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 }
|
||||
})
|
||||
|
||||
await notifyClientsAboutChanges({
|
||||
database,
|
||||
websocket,
|
||||
familyId,
|
||||
sourceDeviceId: null,
|
||||
isImportant: false
|
||||
})
|
||||
|
||||
websocket.triggerSyncByDeviceAuthToken({
|
||||
deviceAuthToken: oldDeviceAuthToken,
|
||||
isImportant: true
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
/*
|
||||
* server component for the TimeLimit App
|
||||
* Copyright (C) 2019 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 } from '../../database'
|
||||
import { generateAuthToken, generateVersionId } from '../../util/token'
|
||||
import { WebsocketApi } from '../../websocket'
|
||||
import { sendUninstallWarnings } from '../warningmail/uninstall'
|
||||
import { notifyClientsAboutChanges } from '../websocket'
|
||||
|
||||
export async function reportDeviceRemoved ({ database, deviceAuthToken, websocket }: {
|
||||
database: Database
|
||||
deviceAuthToken: string
|
||||
websocket: WebsocketApi
|
||||
}) {
|
||||
const result = await database.transaction(async (transaction) => {
|
||||
const deviceEntry = await database.device.findOne({
|
||||
where: {
|
||||
deviceAuthToken
|
||||
},
|
||||
transaction
|
||||
})
|
||||
|
||||
if (deviceEntry) {
|
||||
deviceEntry.didDeviceReportUninstall = true
|
||||
deviceEntry.deviceAuthToken = generateAuthToken() // invalidiate the token
|
||||
deviceEntry.save({ transaction })
|
||||
|
||||
// invalidiate device list
|
||||
await database.family.update({
|
||||
deviceListVersion: generateVersionId()
|
||||
}, {
|
||||
where: {
|
||||
familyId: deviceEntry.familyId
|
||||
},
|
||||
transaction
|
||||
})
|
||||
|
||||
// add to old devices
|
||||
await database.oldDevice.create({
|
||||
deviceAuthToken: deviceEntry.deviceAuthToken
|
||||
}, {
|
||||
transaction
|
||||
})
|
||||
|
||||
return { familyId: deviceEntry.familyId, deviceName: deviceEntry.name }
|
||||
} else {
|
||||
const oldDeviceEntry = await database.oldDevice.findOne({
|
||||
where: {
|
||||
deviceAuthToken
|
||||
},
|
||||
transaction
|
||||
})
|
||||
|
||||
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
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
/*
|
||||
* server component for the TimeLimit App
|
||||
* Copyright (C) 2019 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 } from '../../database'
|
||||
import { requireMailByAuthToken } from '../authentication'
|
||||
|
||||
export const canRecoverPassword = async ({ database, mailAuthToken, parentUserId }: {
|
||||
database: Database
|
||||
mailAuthToken: string
|
||||
parentUserId: string
|
||||
}) => {
|
||||
const mail = await requireMailByAuthToken({ mailAuthToken, database })
|
||||
|
||||
const entry = await database.user.findOne({
|
||||
where: {
|
||||
mail,
|
||||
userId: parentUserId,
|
||||
type: 'parent'
|
||||
}
|
||||
})
|
||||
|
||||
return !!entry
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
/*
|
||||
* server component for the TimeLimit App
|
||||
* Copyright (C) 2019 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 } from '../../database'
|
||||
import { randomWords } from '../../util/random-words'
|
||||
import { generateIdWithinFamily } from '../../util/token'
|
||||
|
||||
export const createAddDeviceToken = async ({ familyId, database }: {
|
||||
familyId: string
|
||||
database: Database
|
||||
}) => {
|
||||
const token = randomWords(5)
|
||||
const deviceId = generateIdWithinFamily()
|
||||
|
||||
await database.addDeviceToken.destroy({
|
||||
where: {
|
||||
familyId
|
||||
}
|
||||
})
|
||||
|
||||
await database.addDeviceToken.create({
|
||||
familyId,
|
||||
token: token.toLowerCase(),
|
||||
deviceId,
|
||||
createdAt: Date.now().toString()
|
||||
})
|
||||
|
||||
return { token, deviceId }
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
/*
|
||||
* server component for the TimeLimit App
|
||||
* Copyright (C) 2019 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 { Conflict } from 'http-errors'
|
||||
import { NewDeviceInfo, ParentPassword } from '../../api/schema'
|
||||
import { Database } from '../../database'
|
||||
import {
|
||||
generateAuthToken, generateFamilyId, generateIdWithinFamily, generateVersionId
|
||||
} from '../../util/token'
|
||||
import { requireMailByAuthToken } from '../authentication'
|
||||
import { prepareDeviceEntry } from '../device/prepare-device-entry'
|
||||
|
||||
export const createFamily = async ({ database, mailAuthToken, firstParentDevice, password, timeZone, parentName, deviceName }: {
|
||||
database: Database,
|
||||
mailAuthToken: string,
|
||||
firstParentDevice: NewDeviceInfo,
|
||||
password: ParentPassword,
|
||||
timeZone: string,
|
||||
parentName: string,
|
||||
deviceName: string
|
||||
}) => {
|
||||
const now = Date.now().toString(10)
|
||||
const mail = await requireMailByAuthToken({ database, mailAuthToken })
|
||||
|
||||
return database.transaction(async (transaction) => {
|
||||
// ensure that no family was created for this mail yet
|
||||
const exisitngUserEntry = await database.user.findOne({
|
||||
where: {
|
||||
mail
|
||||
},
|
||||
transaction
|
||||
})
|
||||
|
||||
if (exisitngUserEntry) {
|
||||
throw new Conflict()
|
||||
}
|
||||
|
||||
const familyId = generateFamilyId()
|
||||
const userId = generateIdWithinFamily()
|
||||
const deviceId = generateIdWithinFamily()
|
||||
const deviceAuthToken = generateAuthToken()
|
||||
|
||||
// create family
|
||||
await database.family.create({
|
||||
familyId,
|
||||
name: '',
|
||||
createdAt: now,
|
||||
userListVersion: generateVersionId(),
|
||||
deviceListVersion: generateVersionId(),
|
||||
// 14 days demo version
|
||||
fullVersionUntil: (Date.now() + 1000 * 60 * 60 * 24 * 14).toString(10),
|
||||
hasFullVersion: true
|
||||
}, { transaction })
|
||||
|
||||
// create parent user
|
||||
await database.user.create({
|
||||
familyId,
|
||||
userId,
|
||||
name: parentName,
|
||||
passwordHash: password.hash,
|
||||
secondPasswordHash: password.secondHash,
|
||||
secondPasswordSalt: password.secondSalt,
|
||||
type: 'parent',
|
||||
mail,
|
||||
timeZone,
|
||||
disableTimelimitsUntil: '0',
|
||||
currentDevice: '',
|
||||
categoryForNotAssignedApps: '',
|
||||
relaxPrimaryDeviceRule: false,
|
||||
mailNotificationFlags: 1 // enable warning notifications
|
||||
}, { transaction })
|
||||
|
||||
// add parent device
|
||||
await database.device.create(prepareDeviceEntry({
|
||||
familyId,
|
||||
deviceId,
|
||||
deviceName,
|
||||
newDeviceInfo: firstParentDevice,
|
||||
userId,
|
||||
deviceAuthToken
|
||||
}), { transaction })
|
||||
|
||||
return {
|
||||
deviceAuthToken,
|
||||
deviceId
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
/*
|
||||
* server component for the TimeLimit App
|
||||
* Copyright (C) 2019 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 } from '../../database'
|
||||
import { requireMailByAuthToken } from '../authentication'
|
||||
|
||||
const getStatusByMailAddress = async ({ mail, database }: {mail: string, database: Database}) => {
|
||||
if (!mail) {
|
||||
throw new Error('no mail address')
|
||||
}
|
||||
|
||||
const entry = await database.user.findOne({
|
||||
where: {
|
||||
mail
|
||||
}
|
||||
})
|
||||
|
||||
if (entry) {
|
||||
return 'with family'
|
||||
} else {
|
||||
return 'without family'
|
||||
}
|
||||
}
|
||||
|
||||
export const getStatusByMailToken = async ({ mailAuthToken, database }: {mailAuthToken: string, database: Database}) => {
|
||||
const mail = await requireMailByAuthToken({ mailAuthToken, database })
|
||||
const status = await getStatusByMailAddress({ mail, database })
|
||||
|
||||
return { mail, status }
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
/*
|
||||
* server component for the TimeLimit App
|
||||
* Copyright (C) 2019 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 { Conflict, Unauthorized } from 'http-errors'
|
||||
import * as Sequelize from 'sequelize'
|
||||
import { Database } from '../../database'
|
||||
import { generateVersionId } from '../../util/token'
|
||||
import { WebsocketApi } from '../../websocket'
|
||||
import { requireMailByAuthToken } from '../authentication'
|
||||
import { notifyClientsAboutChanges } from '../websocket'
|
||||
|
||||
export const linkMailAddress = async ({ mailAuthToken, deviceAuthToken, parentUserId, parentPasswordSecondHash, database, websocket }: {
|
||||
mailAuthToken: string
|
||||
deviceAuthToken: string
|
||||
parentUserId: string
|
||||
parentPasswordSecondHash: string
|
||||
database: Database
|
||||
websocket: WebsocketApi
|
||||
}) => {
|
||||
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 parentEntry = await database.user.findOne({
|
||||
where: {
|
||||
type: 'parent',
|
||||
familyId,
|
||||
userId: parentUserId
|
||||
},
|
||||
transaction,
|
||||
lock: Sequelize.Transaction.LOCK.UPDATE
|
||||
})
|
||||
|
||||
if (!parentEntry) {
|
||||
throw new Conflict()
|
||||
}
|
||||
|
||||
if (parentEntry.mail !== '') {
|
||||
throw new Conflict()
|
||||
}
|
||||
|
||||
if (parentEntry.secondPasswordHash !== parentPasswordSecondHash) {
|
||||
throw new Conflict()
|
||||
}
|
||||
|
||||
if (!parentEntry.secondPasswordSalt) {
|
||||
throw new Conflict()
|
||||
}
|
||||
|
||||
parentEntry.mail = mailAddress
|
||||
|
||||
await parentEntry.save({ transaction })
|
||||
|
||||
// invalidiate client caches
|
||||
await database.family.update({
|
||||
userListVersion: generateVersionId()
|
||||
}, {
|
||||
where: {
|
||||
familyId
|
||||
},
|
||||
transaction
|
||||
})
|
||||
})
|
||||
|
||||
await notifyClientsAboutChanges({
|
||||
familyId,
|
||||
sourceDeviceId: null,
|
||||
database,
|
||||
websocket,
|
||||
isImportant: true
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
/*
|
||||
* server component for the TimeLimit App
|
||||
* Copyright (C) 2019 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 { 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'
|
||||
|
||||
export const recoverParentPassword = async ({ database, websocket, password, mailAuthToken }: {
|
||||
database: Database
|
||||
websocket: WebsocketApi
|
||||
password: ParentPassword
|
||||
mailAuthToken: string
|
||||
}) => {
|
||||
const mail = await requireMailByAuthToken({ mailAuthToken, database })
|
||||
|
||||
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
|
||||
})
|
||||
|
||||
if (!userEntry) {
|
||||
return { familyId: null }
|
||||
}
|
||||
|
||||
userEntry.passwordHash = password.hash
|
||||
userEntry.secondPasswordHash = password.secondHash
|
||||
userEntry.secondPasswordSalt = password.secondSalt
|
||||
|
||||
await userEntry.save({ transaction })
|
||||
|
||||
// invalidate the user list
|
||||
await database.family.update({
|
||||
userListVersion: generateVersionId()
|
||||
}, {
|
||||
where: {
|
||||
familyId: userEntry.familyId
|
||||
},
|
||||
transaction
|
||||
})
|
||||
|
||||
return { familyId: userEntry.familyId }
|
||||
})
|
||||
|
||||
if (familyId === null) {
|
||||
throw new Conflict()
|
||||
}
|
||||
|
||||
await notifyClientsAboutChanges({
|
||||
database,
|
||||
familyId,
|
||||
websocket,
|
||||
isImportant: true,
|
||||
sourceDeviceId: null
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
/*
|
||||
* server component for the TimeLimit App
|
||||
* Copyright (C) 2019 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 { Conflict } from 'http-errors'
|
||||
import { NewDeviceInfo } from '../../api/schema'
|
||||
import { Database } from '../../database'
|
||||
import { generateAuthToken, generateIdWithinFamily, generateVersionId } from '../../util/token'
|
||||
import { WebsocketApi } from '../../websocket'
|
||||
import { requireMailByAuthToken } from '../authentication'
|
||||
import { prepareDeviceEntry } from '../device/prepare-device-entry'
|
||||
import { notifyClientsAboutChanges } from '../websocket'
|
||||
|
||||
export const signInIntoFamily = async ({ database, mailAuthToken, newDeviceInfo, deviceName, websocket }: {
|
||||
database: Database
|
||||
mailAuthToken: string
|
||||
newDeviceInfo: NewDeviceInfo
|
||||
deviceName: string
|
||||
websocket: WebsocketApi
|
||||
}) => {
|
||||
const mail = await requireMailByAuthToken({ database, mailAuthToken })
|
||||
|
||||
const { response, familyId, sourceDeviceId } = await database.transaction(async (transaction) => {
|
||||
const userEntryUnsafe = await database.user.findOne({
|
||||
where: {
|
||||
mail
|
||||
},
|
||||
attributes: ['familyId', 'userId'],
|
||||
transaction
|
||||
})
|
||||
|
||||
if (!userEntryUnsafe) {
|
||||
throw new Conflict()
|
||||
}
|
||||
|
||||
const userEntry = {
|
||||
familyId: userEntryUnsafe.familyId,
|
||||
userId: userEntryUnsafe.userId,
|
||||
transaction
|
||||
}
|
||||
|
||||
const deviceAuthToken = generateAuthToken()
|
||||
const deviceId = generateIdWithinFamily()
|
||||
|
||||
await database.device.create(prepareDeviceEntry({
|
||||
familyId: userEntry.familyId,
|
||||
deviceId,
|
||||
userId: userEntry.userId,
|
||||
deviceName,
|
||||
deviceAuthToken,
|
||||
newDeviceInfo
|
||||
}), { transaction })
|
||||
|
||||
// notify about changes
|
||||
await database.family.update({
|
||||
deviceListVersion: generateVersionId()
|
||||
}, {
|
||||
where: {
|
||||
familyId: userEntry.familyId
|
||||
},
|
||||
transaction
|
||||
})
|
||||
|
||||
return {
|
||||
response: {
|
||||
deviceId,
|
||||
deviceAuthToken
|
||||
},
|
||||
sourceDeviceId: deviceId,
|
||||
familyId: userEntry.familyId
|
||||
}
|
||||
})
|
||||
|
||||
await notifyClientsAboutChanges({
|
||||
familyId,
|
||||
websocket,
|
||||
database,
|
||||
isImportant: true,
|
||||
sourceDeviceId
|
||||
})
|
||||
|
||||
return response
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
/*
|
||||
* server component for the TimeLimit App
|
||||
* Copyright (C) 2019 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 { Conflict } from 'http-errors'
|
||||
import * as Sequelize from 'sequelize'
|
||||
import { Database } from '../../database'
|
||||
import { notifyClientsAboutChanges } 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 }: {
|
||||
database: Database
|
||||
familyId: string
|
||||
type: 'month' | 'year'
|
||||
transactionId: string
|
||||
websocket: WebsocketApi
|
||||
}) => {
|
||||
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,
|
||||
service,
|
||||
transactionId,
|
||||
type,
|
||||
loggedAt: Date.now().toString(10),
|
||||
previousFullVersionEndTime,
|
||||
newFullVersionEndTime: newFullVersionUntil.toString(10)
|
||||
}, {
|
||||
transaction
|
||||
})
|
||||
|
||||
await notifyClientsAboutChanges({
|
||||
familyId,
|
||||
sourceDeviceId: null,
|
||||
database,
|
||||
websocket,
|
||||
isImportant: true
|
||||
})
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
/*
|
||||
* server component for the TimeLimit App
|
||||
* Copyright (C) 2019 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/>.
|
||||
*/
|
||||
|
||||
export const canDoNextPurchase = ({ fullVersionUntil }: {fullVersionUntil: number}) => (
|
||||
fullVersionUntil < (Date.now() + 1000 * 60 * 60 * 24 * 31) // 31 days
|
||||
)
|
||||
@@ -0,0 +1,21 @@
|
||||
/*
|
||||
* server component for the TimeLimit App
|
||||
* Copyright (C) 2019 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/>.
|
||||
*/
|
||||
|
||||
export { canDoNextPurchase } from './can-do-next-purchase'
|
||||
export { requireFamilyEntry } from './require-family-entry'
|
||||
export { isGooglePlayPurchaseSignatureValid, areGooglePlayPaymentsPossible } from './verification'
|
||||
export { addPurchase } from './add-purchase'
|
||||
@@ -0,0 +1,56 @@
|
||||
/*
|
||||
* server component for the TimeLimit App
|
||||
* Copyright (C) 2019 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 { InternalServerError, Unauthorized } from 'http-errors'
|
||||
import { Database } from '../../database'
|
||||
|
||||
export const requireFamilyEntry = async ({ database, deviceAuthToken }: {
|
||||
database: Database
|
||||
deviceAuthToken: string
|
||||
}) => {
|
||||
const deviceEntryUnsafe = await database.device.findOne({
|
||||
where: {
|
||||
deviceAuthToken
|
||||
},
|
||||
attributes: ['familyId']
|
||||
})
|
||||
|
||||
if (!deviceEntryUnsafe) {
|
||||
throw new Unauthorized()
|
||||
}
|
||||
|
||||
const deviceEntry = {
|
||||
familyId: deviceEntryUnsafe.familyId
|
||||
}
|
||||
|
||||
const familyEntryUnsafe = await database.family.findOne({
|
||||
where: {
|
||||
familyId: deviceEntry.familyId
|
||||
},
|
||||
attributes: ['fullVersionUntil']
|
||||
})
|
||||
|
||||
if (!familyEntryUnsafe) {
|
||||
throw new InternalServerError()
|
||||
}
|
||||
|
||||
const familyEntry = {
|
||||
fullVersionUntil: familyEntryUnsafe.fullVersionUntil
|
||||
}
|
||||
|
||||
return familyEntry
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
/*
|
||||
* server component for the TimeLimit App
|
||||
* Copyright (C) 2019 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/>.
|
||||
*/
|
||||
|
||||
const IABVerifier: new (publicKey: string) => {
|
||||
verifyReceipt: (data: string, signature: string) => boolean
|
||||
} = require('iab_verifier')
|
||||
|
||||
const googlePlayPublicKey = process.env.GOOGLE_PLAY_PUBLIC_KEY || ''
|
||||
|
||||
const verifier = new IABVerifier(googlePlayPublicKey)
|
||||
|
||||
export const areGooglePlayPaymentsPossible = !!googlePlayPublicKey
|
||||
export const isGooglePlayPurchaseSignatureValid = ({ receipt, signature }: {
|
||||
receipt: string
|
||||
signature: string
|
||||
}) => {
|
||||
if (googlePlayPublicKey) {
|
||||
return verifier.verifyReceipt(receipt, signature)
|
||||
} else {
|
||||
return false
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,242 @@
|
||||
/*
|
||||
* server component for the TimeLimit App
|
||||
* Copyright (C) 2019 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 { memoize, uniq } from 'lodash'
|
||||
import * as Sequelize from 'sequelize'
|
||||
import { VisibleConnectedDevicesManager } from '../../../connected-devices'
|
||||
import { Database } from '../../../database'
|
||||
import { generateVersionId } from '../../../util/token'
|
||||
|
||||
export class Cache {
|
||||
readonly familyId: string
|
||||
readonly hasFullVersion: boolean
|
||||
readonly transaction: Sequelize.Transaction
|
||||
readonly database: Database
|
||||
readonly connectedDevicesManager: VisibleConnectedDevicesManager
|
||||
private shouldTriggerFullSync = false
|
||||
|
||||
categoriesWithModifiedApps: Array<string> = []
|
||||
categoriesWithModifiedBaseData: Array<string> = []
|
||||
categoriesWithModifiedTimeLimitRules: Array<string> = []
|
||||
categoriesWithModifiedUsedTimes: Array<string> = []
|
||||
|
||||
devicesWithModifiedInstalledApps: Array<string> = []
|
||||
devicesWithModifiedShowDeviceConnected = new Map<string, boolean>()
|
||||
|
||||
invalidiateUserList = false
|
||||
invalidiateDeviceList = false
|
||||
areChangesImportant = false
|
||||
|
||||
constructor ({ familyId, hasFullVersion, database, transaction, connectedDevicesManager }: {
|
||||
familyId: string
|
||||
hasFullVersion: boolean
|
||||
database: Database
|
||||
transaction: Sequelize.Transaction
|
||||
connectedDevicesManager: VisibleConnectedDevicesManager
|
||||
}) {
|
||||
this.familyId = familyId
|
||||
this.hasFullVersion = hasFullVersion
|
||||
this.database = database
|
||||
this.transaction = transaction
|
||||
this.connectedDevicesManager = connectedDevicesManager
|
||||
}
|
||||
|
||||
getSecondPasswordHashOfParent = memoize(async (parentId: string) => {
|
||||
const userEntryUnsafe = await this.database.user.findOne({
|
||||
where: {
|
||||
familyId: this.familyId,
|
||||
userId: parentId,
|
||||
type: 'parent'
|
||||
},
|
||||
attributes: ['secondPasswordHash'],
|
||||
transaction: this.transaction
|
||||
})
|
||||
|
||||
if (!userEntryUnsafe) {
|
||||
throw new Error('user not found')
|
||||
}
|
||||
|
||||
return userEntryUnsafe.secondPasswordHash
|
||||
})
|
||||
|
||||
getSecondPasswordHashOfChild = memoize(async (childId: string) => {
|
||||
const userEntryUnsafe = await this.database.user.findOne({
|
||||
where: {
|
||||
familyId: this.familyId,
|
||||
userId: childId,
|
||||
type: 'child'
|
||||
},
|
||||
attributes: ['secondPasswordHash'],
|
||||
transaction: this.transaction
|
||||
})
|
||||
|
||||
if (!userEntryUnsafe) {
|
||||
throw new Error('user not found')
|
||||
}
|
||||
|
||||
if (!userEntryUnsafe.secondPasswordHash) {
|
||||
throw new Error('user does not have a password')
|
||||
}
|
||||
|
||||
return userEntryUnsafe.secondPasswordHash
|
||||
})
|
||||
|
||||
doesCategoryExist = memoize(async (categoryId: string) => {
|
||||
const categoryEntry = await this.database.category.findOne({
|
||||
where: {
|
||||
familyId: this.familyId,
|
||||
categoryId
|
||||
},
|
||||
transaction: this.transaction
|
||||
})
|
||||
|
||||
return !!categoryEntry
|
||||
})
|
||||
|
||||
doesUserExist = memoize(async (userId: string) => {
|
||||
const userEntry = await this.database.user.findOne({
|
||||
where: {
|
||||
familyId: this.familyId,
|
||||
userId
|
||||
},
|
||||
transaction: this.transaction
|
||||
})
|
||||
|
||||
return !!userEntry
|
||||
})
|
||||
|
||||
shouldDoFullSync = () => this.shouldTriggerFullSync
|
||||
requireFullSync = () => this.shouldTriggerFullSync = true
|
||||
|
||||
async saveModifiedVersionNumbers () {
|
||||
const { database, transaction, familyId } = this
|
||||
|
||||
if (this.categoriesWithModifiedApps.length > 0) {
|
||||
await database.category.update({
|
||||
assignedAppsVersion: generateVersionId()
|
||||
}, {
|
||||
where: {
|
||||
familyId,
|
||||
categoryId: {
|
||||
[Sequelize.Op.in]: uniq(this.categoriesWithModifiedApps)
|
||||
}
|
||||
},
|
||||
transaction
|
||||
})
|
||||
|
||||
this.categoriesWithModifiedApps = []
|
||||
}
|
||||
|
||||
if (this.categoriesWithModifiedBaseData.length > 0) {
|
||||
await database.category.update({
|
||||
baseVersion: generateVersionId()
|
||||
}, {
|
||||
where: {
|
||||
familyId,
|
||||
categoryId: {
|
||||
[Sequelize.Op.in]: uniq(this.categoriesWithModifiedBaseData)
|
||||
}
|
||||
},
|
||||
transaction
|
||||
})
|
||||
|
||||
this.categoriesWithModifiedBaseData = []
|
||||
}
|
||||
|
||||
if (this.categoriesWithModifiedTimeLimitRules.length > 0) {
|
||||
await database.category.update({
|
||||
timeLimitRulesVersion: generateVersionId()
|
||||
}, {
|
||||
where: {
|
||||
familyId,
|
||||
categoryId: {
|
||||
[Sequelize.Op.in]: uniq(this.categoriesWithModifiedTimeLimitRules)
|
||||
}
|
||||
},
|
||||
transaction
|
||||
})
|
||||
|
||||
this.categoriesWithModifiedTimeLimitRules = []
|
||||
}
|
||||
|
||||
if (this.categoriesWithModifiedUsedTimes.length > 0) {
|
||||
await database.category.update({
|
||||
usedTimesVersion: generateVersionId()
|
||||
}, {
|
||||
where: {
|
||||
familyId,
|
||||
categoryId: {
|
||||
[Sequelize.Op.in]: uniq(this.categoriesWithModifiedUsedTimes)
|
||||
}
|
||||
},
|
||||
transaction
|
||||
})
|
||||
|
||||
this.categoriesWithModifiedUsedTimes = []
|
||||
}
|
||||
|
||||
if (this.devicesWithModifiedInstalledApps.length > 0) {
|
||||
await database.device.update({
|
||||
installedAppsVersion: generateVersionId()
|
||||
}, {
|
||||
where: {
|
||||
familyId,
|
||||
deviceId: {
|
||||
[Sequelize.Op.in]: uniq(this.devicesWithModifiedInstalledApps)
|
||||
}
|
||||
},
|
||||
transaction
|
||||
})
|
||||
|
||||
this.devicesWithModifiedInstalledApps = []
|
||||
}
|
||||
|
||||
if (this.invalidiateUserList) {
|
||||
await database.family.update({
|
||||
userListVersion: generateVersionId()
|
||||
}, {
|
||||
where: {
|
||||
familyId: this.familyId
|
||||
},
|
||||
transaction
|
||||
})
|
||||
|
||||
this.invalidiateUserList = false
|
||||
}
|
||||
|
||||
if (this.invalidiateDeviceList) {
|
||||
await database.family.update({
|
||||
deviceListVersion: generateVersionId()
|
||||
}, {
|
||||
where: {
|
||||
familyId: this.familyId
|
||||
},
|
||||
transaction
|
||||
})
|
||||
|
||||
this.invalidiateDeviceList = false
|
||||
}
|
||||
|
||||
this.devicesWithModifiedShowDeviceConnected.forEach((showDeviceConnected, deviceId) => {
|
||||
this.connectedDevicesManager.notifyShareConnectedChanged({
|
||||
familyId: this.familyId,
|
||||
deviceId,
|
||||
showDeviceConnected
|
||||
})
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
/*
|
||||
* server component for the TimeLimit App
|
||||
* Copyright (C) 2019 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 * as Sequelize from 'sequelize'
|
||||
import { AddInstalledAppsAction } from '../../../../action'
|
||||
import { AppAttributes } from '../../../../database/app'
|
||||
import { Cache } from '../cache'
|
||||
|
||||
export async function dispatchAddInstalledApps ({ deviceId, action, cache }: {
|
||||
deviceId: string
|
||||
action: AddInstalledAppsAction
|
||||
cache: Cache
|
||||
}) {
|
||||
await cache.database.app.destroy({
|
||||
where: {
|
||||
familyId: cache.familyId,
|
||||
deviceId,
|
||||
packageName: {
|
||||
[Sequelize.Op.in]: action.apps.map((app) => app.packageName)
|
||||
}
|
||||
},
|
||||
transaction: cache.transaction
|
||||
})
|
||||
|
||||
await cache.database.app.bulkCreate(
|
||||
action.apps.map((app): AppAttributes => ({
|
||||
familyId: cache.familyId,
|
||||
deviceId,
|
||||
packageName: app.packageName,
|
||||
title: app.title,
|
||||
isLaunchable: app.isLaunchable,
|
||||
recommendation: app.recommendation
|
||||
})),
|
||||
{ transaction: cache.transaction }
|
||||
)
|
||||
|
||||
cache.devicesWithModifiedInstalledApps.push(deviceId)
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
/*
|
||||
* server component for the TimeLimit App
|
||||
* Copyright (C) 2019 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 * as Sequelize from 'sequelize'
|
||||
import { AddUsedTimeAction } from '../../../../action'
|
||||
import { Cache } from '../cache'
|
||||
|
||||
const getRoundedTimestamp = () => {
|
||||
const now = Date.now()
|
||||
|
||||
return now - (now % (1000 * 60 * 60 * 24 * 2 /* 2 days */))
|
||||
}
|
||||
|
||||
export async function dispatchAddUsedTime ({ deviceId, action, cache }: {
|
||||
deviceId: string
|
||||
action: AddUsedTimeAction
|
||||
cache: Cache
|
||||
}) {
|
||||
const roundedTimestamp = getRoundedTimestamp().toString(10)
|
||||
|
||||
const categoryEntryUnsafe = await cache.database.category.findOne({
|
||||
where: {
|
||||
familyId: cache.familyId,
|
||||
categoryId: action.categoryId
|
||||
},
|
||||
transaction: cache.transaction,
|
||||
attributes: [
|
||||
'childId',
|
||||
'parentCategoryId',
|
||||
'extraTimeInMillis'
|
||||
]
|
||||
})
|
||||
// verify that the category exists
|
||||
if (!categoryEntryUnsafe) {
|
||||
throw new Error('invalid category id')
|
||||
}
|
||||
|
||||
const categoryEntry = {
|
||||
childId: categoryEntryUnsafe.childId,
|
||||
parentCategoryId: categoryEntryUnsafe.parentCategoryId,
|
||||
extraTimeInMillis: categoryEntryUnsafe.extraTimeInMillis
|
||||
}
|
||||
|
||||
const handleAddUsedTime = async ({ categoryId, currentExtraTime }: {
|
||||
categoryId: string,
|
||||
currentExtraTime: number
|
||||
}) => {
|
||||
if (action.timeToAdd !== 0) {
|
||||
// try to update first
|
||||
const [updatedRows] = await cache.database.usedTime.update({
|
||||
usedTime: Sequelize.literal(`usedTime + ${action.timeToAdd}`) as any,
|
||||
lastUpdate: roundedTimestamp
|
||||
}, {
|
||||
where: {
|
||||
familyId: cache.familyId,
|
||||
categoryId: categoryId,
|
||||
dayOfEpoch: action.dayOfEpoch
|
||||
},
|
||||
transaction: cache.transaction
|
||||
})
|
||||
|
||||
// otherwise create
|
||||
if (updatedRows === 0) {
|
||||
await cache.database.usedTime.create({
|
||||
familyId: cache.familyId,
|
||||
categoryId: categoryId,
|
||||
dayOfEpoch: action.dayOfEpoch,
|
||||
usedTime: action.timeToAdd,
|
||||
lastUpdate: roundedTimestamp
|
||||
}, {
|
||||
transaction: cache.transaction
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
if (action.extraTimeToSubtract !== 0) {
|
||||
await cache.database.category.update({
|
||||
extraTimeInMillis: Math.max(0, currentExtraTime - action.extraTimeToSubtract)
|
||||
}, {
|
||||
where: {
|
||||
familyId: cache.familyId,
|
||||
categoryId: categoryId
|
||||
},
|
||||
transaction: cache.transaction
|
||||
})
|
||||
|
||||
cache.categoriesWithModifiedBaseData.push(categoryId)
|
||||
}
|
||||
|
||||
cache.categoriesWithModifiedUsedTimes.push(categoryId)
|
||||
}
|
||||
|
||||
await handleAddUsedTime({
|
||||
categoryId: action.categoryId,
|
||||
currentExtraTime: categoryEntry.extraTimeInMillis
|
||||
})
|
||||
|
||||
if (categoryEntry.parentCategoryId !== '') {
|
||||
const parentCategoryEntry = await cache.database.category.findOne({
|
||||
where: {
|
||||
familyId: cache.familyId,
|
||||
categoryId: categoryEntry.parentCategoryId,
|
||||
childId: categoryEntry.childId
|
||||
},
|
||||
transaction: cache.transaction
|
||||
})
|
||||
|
||||
if (parentCategoryEntry) {
|
||||
await handleAddUsedTime({
|
||||
categoryId: categoryEntry.parentCategoryId,
|
||||
currentExtraTime: parentCategoryEntry.extraTimeInMillis
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
/*
|
||||
* server component for the TimeLimit App
|
||||
* Copyright (C) 2019 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 {
|
||||
AddInstalledAppsAction,
|
||||
AddUsedTimeAction,
|
||||
AppLogicAction,
|
||||
RemoveInstalledAppsAction,
|
||||
SignOutAtDeviceAction,
|
||||
TriedDisablingDeviceAdminAction,
|
||||
UpdateDeviceStatusAction
|
||||
} from '../../../../action'
|
||||
import { Cache } from '../cache'
|
||||
import { dispatchAddInstalledApps } from './addinstalledapps'
|
||||
import { dispatchAddUsedTime } from './addusedtime'
|
||||
import { dispatchRemoveInstalledApps } from './removeinstalledapps'
|
||||
import { dispatchSignOutAtDevice } from './signoutatdevice'
|
||||
import { dispatchTriedDisablingDeviceAdmin } from './trieddisablingdeviceadmin'
|
||||
import { dispatchUpdateDeviceStatus } from './updatedevicestatus'
|
||||
|
||||
export const dispatchAppLogicAction = async ({ action, deviceId, cache }: {
|
||||
action: AppLogicAction
|
||||
deviceId: string
|
||||
cache: Cache
|
||||
}) => {
|
||||
if (action instanceof AddInstalledAppsAction) {
|
||||
await dispatchAddInstalledApps({ deviceId, action, cache })
|
||||
} else if (action instanceof AddUsedTimeAction) {
|
||||
await dispatchAddUsedTime({ deviceId, action, cache })
|
||||
} else if (action instanceof RemoveInstalledAppsAction) {
|
||||
await dispatchRemoveInstalledApps({ deviceId, action, cache })
|
||||
} else if (action instanceof SignOutAtDeviceAction) {
|
||||
await dispatchSignOutAtDevice({ deviceId, action, cache })
|
||||
} else if (action instanceof UpdateDeviceStatusAction) {
|
||||
await dispatchUpdateDeviceStatus({ deviceId, action, cache })
|
||||
} else if (action instanceof TriedDisablingDeviceAdminAction) {
|
||||
await dispatchTriedDisablingDeviceAdmin({ deviceId, action, cache })
|
||||
} else {
|
||||
throw new Error('unsupported action type')
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
/*
|
||||
* server component for the TimeLimit App
|
||||
* Copyright (C) 2019 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 * as Sequelize from 'sequelize'
|
||||
import { RemoveInstalledAppsAction } from '../../../../action'
|
||||
import { Cache } from '../cache'
|
||||
|
||||
export async function dispatchRemoveInstalledApps ({ deviceId, action, cache }: {
|
||||
deviceId: string
|
||||
action: RemoveInstalledAppsAction
|
||||
cache: Cache
|
||||
}) {
|
||||
await cache.database.app.destroy({
|
||||
where: {
|
||||
familyId: cache.familyId,
|
||||
deviceId,
|
||||
packageName: {
|
||||
[Sequelize.Op.in]: action.packageNames
|
||||
}
|
||||
},
|
||||
transaction: cache.transaction
|
||||
})
|
||||
|
||||
cache.devicesWithModifiedInstalledApps.push(deviceId)
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
/*
|
||||
* server component for the TimeLimit App
|
||||
* Copyright (C) 2019 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 { SetDeviceUserAction, SignOutAtDeviceAction } from '../../../../action'
|
||||
import { Cache } from '../cache'
|
||||
import { dispatchSetDeviceUser } from '../dispatch-parent-action/setdeviceuser'
|
||||
|
||||
export async function dispatchSignOutAtDevice ({ deviceId, action, cache }: {
|
||||
deviceId: string
|
||||
action: SignOutAtDeviceAction
|
||||
cache: Cache
|
||||
}) {
|
||||
if (!cache.hasFullVersion) {
|
||||
throw new Error('action requires full version')
|
||||
}
|
||||
|
||||
const deviceEntry = await cache.database.device.findOne({
|
||||
where: {
|
||||
familyId: cache.familyId,
|
||||
deviceId
|
||||
},
|
||||
transaction: cache.transaction
|
||||
})
|
||||
|
||||
if (!deviceEntry) {
|
||||
throw new Error('illegal state: missing device which dispatched the action')
|
||||
}
|
||||
|
||||
if (deviceEntry.defaultUserId === '') {
|
||||
throw new Error('no default user available')
|
||||
}
|
||||
|
||||
if (deviceEntry.currentUserId !== deviceEntry.defaultUserId) {
|
||||
await dispatchSetDeviceUser({
|
||||
cache,
|
||||
action: new SetDeviceUserAction({
|
||||
deviceId,
|
||||
userId: deviceEntry.defaultUserId
|
||||
})
|
||||
})
|
||||
}
|
||||
}
|
||||
+59
@@ -0,0 +1,59 @@
|
||||
/*
|
||||
* server component for the TimeLimit App
|
||||
* Copyright (C) 2019 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 { TriedDisablingDeviceAdminAction } from '../../../../action'
|
||||
import { hasDeviceManipulation } from '../../../../database/device'
|
||||
import { sendManipulationWarnings } from '../../../warningmail/manipulation'
|
||||
import { Cache } from '../cache'
|
||||
|
||||
export async function dispatchTriedDisablingDeviceAdmin ({ deviceId, action, cache }: {
|
||||
deviceId: string
|
||||
action: TriedDisablingDeviceAdminAction
|
||||
cache: Cache
|
||||
}) {
|
||||
const deviceEntry = await cache.database.device.findOne({
|
||||
where: {
|
||||
familyId: cache.familyId,
|
||||
deviceId
|
||||
},
|
||||
transaction: cache.transaction
|
||||
})
|
||||
|
||||
if (deviceEntry === null) {
|
||||
throw new Error('illegal state: missing device which dispatched the action')
|
||||
}
|
||||
|
||||
const hadManipulationBefore = hasDeviceManipulation(deviceEntry)
|
||||
|
||||
if (!deviceEntry.triedDisablingDeviceAdmin) {
|
||||
deviceEntry.triedDisablingDeviceAdmin = true
|
||||
|
||||
await deviceEntry.save({ transaction: cache.transaction })
|
||||
|
||||
cache.invalidiateDeviceList = true
|
||||
cache.areChangesImportant = true
|
||||
}
|
||||
|
||||
if (!hadManipulationBefore) {
|
||||
await sendManipulationWarnings({
|
||||
database: cache.database,
|
||||
transaction: cache.transaction,
|
||||
deviceName: deviceEntry.name,
|
||||
familyId: cache.familyId
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
/*
|
||||
* server component for the TimeLimit App
|
||||
* Copyright (C) 2019 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 { UpdateDeviceStatusAction } from '../../../../action'
|
||||
import { hasDeviceManipulation } from '../../../../database/device'
|
||||
import { newPermissionStatusValues } from '../../../../model/newpermissionstatus'
|
||||
import { protetionLevels } from '../../../../model/protectionlevel'
|
||||
import { runtimePermissionStatusValues } from '../../../../model/runtimepermissionstatus'
|
||||
import { enumMax } from '../../../../util/enum'
|
||||
import { sendManipulationWarnings } from '../../../warningmail/manipulation'
|
||||
import { Cache } from '../cache'
|
||||
|
||||
export async function dispatchUpdateDeviceStatus ({ deviceId, action, cache }: {
|
||||
deviceId: string
|
||||
action: UpdateDeviceStatusAction
|
||||
cache: Cache
|
||||
}) {
|
||||
const deviceEntry = await cache.database.device.findOne({
|
||||
where: {
|
||||
familyId: cache.familyId,
|
||||
deviceId
|
||||
},
|
||||
transaction: cache.transaction
|
||||
})
|
||||
|
||||
if (!deviceEntry) {
|
||||
throw new Error('device not found')
|
||||
}
|
||||
|
||||
const hadManipulationBefore = hasDeviceManipulation(deviceEntry)
|
||||
|
||||
if (action.newProtetionLevel) {
|
||||
const hasChanged = deviceEntry.currentProtectionLevel !== action.newProtetionLevel
|
||||
|
||||
deviceEntry.currentProtectionLevel = action.newProtetionLevel
|
||||
|
||||
deviceEntry.highestProtectionLevel = enumMax(
|
||||
deviceEntry.currentProtectionLevel,
|
||||
deviceEntry.highestProtectionLevel,
|
||||
protetionLevels
|
||||
)
|
||||
|
||||
if (hasChanged && (deviceEntry.currentProtectionLevel !== deviceEntry.highestProtectionLevel)) {
|
||||
deviceEntry.hadManipulation = true
|
||||
}
|
||||
}
|
||||
|
||||
if (action.newUsageStatsPermissionStatus) {
|
||||
const hasChanged = deviceEntry.currentUsageStatsPermission !== action.newUsageStatsPermissionStatus
|
||||
|
||||
deviceEntry.currentUsageStatsPermission = action.newUsageStatsPermissionStatus
|
||||
|
||||
deviceEntry.highestUsageStatsPermission = enumMax(
|
||||
deviceEntry.currentUsageStatsPermission,
|
||||
deviceEntry.highestUsageStatsPermission,
|
||||
runtimePermissionStatusValues
|
||||
)
|
||||
|
||||
if (hasChanged && (deviceEntry.currentUsageStatsPermission !== deviceEntry.highestUsageStatsPermission)) {
|
||||
deviceEntry.hadManipulation = true
|
||||
}
|
||||
}
|
||||
|
||||
if (action.newNotificationAccessPermission) {
|
||||
const hasChanged = deviceEntry.currentNotificationAccessPermission !== action.newNotificationAccessPermission
|
||||
|
||||
deviceEntry.currentNotificationAccessPermission = action.newNotificationAccessPermission
|
||||
|
||||
deviceEntry.highestNotificationAccessPermission = enumMax(
|
||||
deviceEntry.currentNotificationAccessPermission,
|
||||
deviceEntry.highestNotificationAccessPermission,
|
||||
newPermissionStatusValues
|
||||
)
|
||||
|
||||
if (hasChanged && (deviceEntry.currentNotificationAccessPermission !== deviceEntry.highestNotificationAccessPermission)) {
|
||||
deviceEntry.hadManipulation = true
|
||||
}
|
||||
}
|
||||
|
||||
if (action.newAppVersion !== undefined) {
|
||||
const hasChanged = deviceEntry.currentAppVersion !== action.newAppVersion
|
||||
|
||||
deviceEntry.currentAppVersion = action.newAppVersion
|
||||
|
||||
deviceEntry.highestAppVersion = Math.max(
|
||||
deviceEntry.currentAppVersion,
|
||||
deviceEntry.highestAppVersion
|
||||
)
|
||||
|
||||
if (hasChanged && (deviceEntry.currentAppVersion !== deviceEntry.highestAppVersion)) {
|
||||
deviceEntry.hadManipulation = true
|
||||
}
|
||||
}
|
||||
|
||||
if (action.didReboot) {
|
||||
deviceEntry.didReboot = true
|
||||
}
|
||||
|
||||
await deviceEntry.save({ transaction: cache.transaction })
|
||||
|
||||
if (hasDeviceManipulation(deviceEntry)) {
|
||||
if (!hadManipulationBefore) {
|
||||
await sendManipulationWarnings({
|
||||
database: cache.database,
|
||||
transaction: cache.transaction,
|
||||
deviceName: deviceEntry.name,
|
||||
familyId: cache.familyId
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
cache.invalidiateDeviceList = true
|
||||
cache.areChangesImportant = true
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
/*
|
||||
* server component for the TimeLimit App
|
||||
* Copyright (C) 2019 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 * as Sequelize from 'sequelize'
|
||||
import { ChildChangePasswordAction } from '../../../../action'
|
||||
import { Cache } from '../cache'
|
||||
|
||||
export const dispatchChildChangePassword = async ({ action, childUserId, cache }: {
|
||||
action: ChildChangePasswordAction
|
||||
childUserId: string
|
||||
cache: Cache
|
||||
}) => {
|
||||
const childEntry = await cache.database.user.findOne({
|
||||
where: {
|
||||
familyId: cache.familyId,
|
||||
userId: childUserId,
|
||||
type: 'child'
|
||||
},
|
||||
transaction: cache.transaction,
|
||||
lock: Sequelize.Transaction.LOCK.UPDATE
|
||||
})
|
||||
|
||||
if (!childEntry) {
|
||||
throw new Error('child entry not found')
|
||||
}
|
||||
|
||||
childEntry.passwordHash = action.password.hash
|
||||
childEntry.secondPasswordSalt = action.password.secondSalt
|
||||
childEntry.secondPasswordHash = action.password.secondHash
|
||||
|
||||
await childEntry.save({ transaction: cache.transaction })
|
||||
|
||||
cache.getSecondPasswordHashOfChild.cache.clear()
|
||||
cache.invalidiateUserList = true
|
||||
cache.areChangesImportant = true
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
/*
|
||||
* server component for the TimeLimit App
|
||||
* Copyright (C) 2019 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 { ChildSignInAction, SetDeviceUserAction } from '../../../../action'
|
||||
import { Cache } from '../cache'
|
||||
import { dispatchSetDeviceUser } from '../dispatch-parent-action/setdeviceuser'
|
||||
|
||||
export const dispatchChildSignIn = async ({ action, deviceId, childUserId, cache }: {
|
||||
action: ChildSignInAction
|
||||
deviceId: string
|
||||
childUserId: string
|
||||
cache: Cache
|
||||
}) => {
|
||||
if (!cache.hasFullVersion) {
|
||||
throw new Error('action requires full version')
|
||||
}
|
||||
|
||||
await dispatchSetDeviceUser({
|
||||
action: new SetDeviceUserAction({
|
||||
deviceId,
|
||||
userId: childUserId
|
||||
}),
|
||||
cache
|
||||
})
|
||||
|
||||
const userEntryUnsafe = await cache.database.user.findOne({
|
||||
where: {
|
||||
familyId: cache.familyId,
|
||||
type: 'child',
|
||||
userId: childUserId
|
||||
},
|
||||
transaction: cache.transaction,
|
||||
attributes: [
|
||||
'currentDevice'
|
||||
]
|
||||
})
|
||||
|
||||
if (!userEntryUnsafe) {
|
||||
throw new Error('illegal state')
|
||||
}
|
||||
|
||||
if (userEntryUnsafe.currentDevice === deviceId) {
|
||||
// unassign to prevent way aroundprimary device rule
|
||||
|
||||
await cache.database.user.update({
|
||||
currentDevice: ''
|
||||
}, {
|
||||
where: {
|
||||
familyId: cache.familyId,
|
||||
type: 'child',
|
||||
userId: childUserId
|
||||
},
|
||||
transaction: cache.transaction
|
||||
})
|
||||
|
||||
cache.invalidiateUserList = true
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
/*
|
||||
* server component for the TimeLimit App
|
||||
* Copyright (C) 2019 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 {
|
||||
ChildAction,
|
||||
ChildChangePasswordAction,
|
||||
ChildSignInAction
|
||||
} from '../../../../action'
|
||||
import { Cache } from '../cache'
|
||||
import { dispatchChildChangePassword } from './childchangepassword'
|
||||
import { dispatchChildSignIn } from './childsignin'
|
||||
|
||||
export const dispatchChildAction = async ({ action, deviceId, childUserId, cache }: {
|
||||
action: ChildAction
|
||||
deviceId: string
|
||||
childUserId: string
|
||||
cache: Cache
|
||||
}) => {
|
||||
if (action instanceof ChildChangePasswordAction) {
|
||||
await dispatchChildChangePassword({ action, childUserId, cache })
|
||||
} else if (action instanceof ChildSignInAction) {
|
||||
await dispatchChildSignIn({ action, childUserId, deviceId, cache })
|
||||
} else {
|
||||
throw new Error('unsupported action type')
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
/*
|
||||
* server component for the TimeLimit App
|
||||
* Copyright (C) 2019 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 * as Sequelize from 'sequelize'
|
||||
import { AddCategoryAppsAction } from '../../../../action'
|
||||
import { CategoryAppAttributes } from '../../../../database/categoryapp'
|
||||
import { Cache } from '../cache'
|
||||
|
||||
export async function dispatchAddCategoryApps ({ action, cache }: {
|
||||
action: AddCategoryAppsAction
|
||||
cache: Cache
|
||||
}) {
|
||||
const categoryEntryUnsafe = await cache.database.category.findOne({
|
||||
where: {
|
||||
familyId: cache.familyId,
|
||||
categoryId: action.categoryId
|
||||
},
|
||||
transaction: cache.transaction,
|
||||
attributes: ['childId']
|
||||
})
|
||||
|
||||
if (!categoryEntryUnsafe) {
|
||||
throw new Error('invalid category id')
|
||||
}
|
||||
|
||||
const { childId } = categoryEntryUnsafe
|
||||
|
||||
const categoriesOfSameChild = await cache.database.category.findAll({
|
||||
where: {
|
||||
familyId: cache.familyId,
|
||||
childId
|
||||
},
|
||||
attributes: ['categoryId'],
|
||||
transaction: cache.transaction
|
||||
}).map((item) => ({ categoryId: item.categoryId }))
|
||||
|
||||
await cache.database.categoryApp.destroy({
|
||||
where: {
|
||||
familyId: cache.familyId,
|
||||
categoryId: {
|
||||
[Sequelize.Op.in]: categoriesOfSameChild.map((item) => item.categoryId)
|
||||
},
|
||||
packageName: {
|
||||
[Sequelize.Op.in]: action.packageNames
|
||||
}
|
||||
},
|
||||
transaction: cache.transaction
|
||||
})
|
||||
|
||||
await cache.database.categoryApp.bulkCreate(
|
||||
action.packageNames.map((packageName): CategoryAppAttributes => ({
|
||||
familyId: cache.familyId,
|
||||
categoryId: action.categoryId,
|
||||
packageName
|
||||
})),
|
||||
{
|
||||
transaction: cache.transaction
|
||||
}
|
||||
)
|
||||
|
||||
cache.categoriesWithModifiedApps.push(action.categoryId)
|
||||
cache.areChangesImportant = true
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
/*
|
||||
* server component for the TimeLimit App
|
||||
* Copyright (C) 2019 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 { AddUserAction } from '../../../../action'
|
||||
import { Cache } from '../cache'
|
||||
|
||||
export async function dispatchAddUser ({ action, cache }: {
|
||||
action: AddUserAction
|
||||
cache: Cache
|
||||
}) {
|
||||
await cache.database.user.create({
|
||||
familyId: cache.familyId,
|
||||
userId: action.userId,
|
||||
type: action.userType,
|
||||
name: action.name,
|
||||
timeZone: action.timeZone,
|
||||
passwordHash: action.password ? action.password.hash : '',
|
||||
secondPasswordHash: action.password ? action.password.secondHash : '',
|
||||
secondPasswordSalt: action.password ? action.password.secondSalt : '',
|
||||
mail: '',
|
||||
disableTimelimitsUntil: '0',
|
||||
currentDevice: '',
|
||||
categoryForNotAssignedApps: '',
|
||||
relaxPrimaryDeviceRule: false,
|
||||
mailNotificationFlags: 0
|
||||
}, { transaction: cache.transaction })
|
||||
|
||||
cache.invalidiateUserList = true
|
||||
cache.areChangesImportant = true
|
||||
|
||||
cache.doesUserExist.cache.set(action.userId, true)
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
/*
|
||||
* server component for the TimeLimit App
|
||||
* Copyright (C) 2019 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 * as Sequelize from 'sequelize'
|
||||
import { ChangeParentPasswordAction } from '../../../../action'
|
||||
import { Cache } from '../cache'
|
||||
|
||||
export async function dispatchChangeParentPassword ({ action, cache }: {
|
||||
action: ChangeParentPasswordAction
|
||||
cache: Cache
|
||||
}) {
|
||||
const parentEntry = await cache.database.user.findOne({
|
||||
where: {
|
||||
familyId: cache.familyId,
|
||||
userId: action.parentUserId,
|
||||
type: 'parent'
|
||||
},
|
||||
transaction: cache.transaction,
|
||||
lock: Sequelize.Transaction.LOCK.UPDATE
|
||||
})
|
||||
|
||||
if (!parentEntry) {
|
||||
throw new Error('parent entry not found')
|
||||
}
|
||||
|
||||
action.assertIntegrityValid({ oldPasswordSecondHash: parentEntry.secondPasswordHash })
|
||||
const newSecondPasswordHash = action.decryptSecondHash({ oldPasswordSecondHash: parentEntry.secondPasswordHash })
|
||||
|
||||
parentEntry.passwordHash = action.newPasswordFirstHash
|
||||
parentEntry.secondPasswordSalt = action.newPasswordSecondSalt
|
||||
parentEntry.secondPasswordHash = newSecondPasswordHash
|
||||
|
||||
await parentEntry.save({ transaction: cache.transaction })
|
||||
|
||||
cache.getSecondPasswordHashOfParent.cache.clear()
|
||||
cache.invalidiateUserList = true
|
||||
cache.areChangesImportant = true
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
/*
|
||||
* server component for the TimeLimit App
|
||||
* Copyright (C) 2019 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 { CreateCategoryAction } from '../../../../action'
|
||||
import { generateVersionId } from '../../../../util/token'
|
||||
import { Cache } from '../cache'
|
||||
|
||||
export async function dispatchCreateCategory ({ action, cache }: {
|
||||
action: CreateCategoryAction
|
||||
cache: Cache
|
||||
}) {
|
||||
// check that the child exists
|
||||
const childEntry = await cache.database.user.findOne({
|
||||
where: {
|
||||
familyId: cache.familyId,
|
||||
userId: action.childId,
|
||||
type: 'child'
|
||||
},
|
||||
transaction: cache.transaction
|
||||
})
|
||||
|
||||
if (!childEntry) {
|
||||
throw new Error('missing child for new category')
|
||||
}
|
||||
|
||||
// no version number needs to be updated
|
||||
await cache.database.category.create({
|
||||
familyId: cache.familyId,
|
||||
categoryId: action.categoryId,
|
||||
childId: action.childId,
|
||||
title: action.title,
|
||||
blockedMinutesInWeek: '',
|
||||
temporarilyBlocked: false,
|
||||
extraTimeInMillis: 0,
|
||||
timeLimitRulesVersion: generateVersionId(),
|
||||
baseVersion: generateVersionId(),
|
||||
assignedAppsVersion: generateVersionId(),
|
||||
usedTimesVersion: generateVersionId(),
|
||||
parentCategoryId: ''
|
||||
}, { transaction: cache.transaction })
|
||||
|
||||
// update the cache
|
||||
cache.doesCategoryExist.cache.set(action.categoryId, true)
|
||||
cache.areChangesImportant = true
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
/*
|
||||
* server component for the TimeLimit App
|
||||
* Copyright (C) 2019 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 { CreateTimeLimitRuleAction } from '../../../../action'
|
||||
import { Cache } from '../cache'
|
||||
|
||||
export async function dispatchCreateTimeLimitRule ({ action, cache }: {
|
||||
action: CreateTimeLimitRuleAction
|
||||
cache: Cache
|
||||
}) {
|
||||
const doesCategoryExist = await cache.doesCategoryExist(action.rule.categoryId)
|
||||
|
||||
if (!doesCategoryExist) {
|
||||
throw new Error('invalid category id for new rule')
|
||||
}
|
||||
|
||||
await cache.database.timelimitRule.create({
|
||||
familyId: cache.familyId,
|
||||
ruleId: action.rule.ruleId,
|
||||
categoryId: action.rule.categoryId,
|
||||
applyToExtraTimeUsage: action.rule.applyToExtraTimeUsage,
|
||||
maximumTimeInMillis: action.rule.maxTimeInMillis,
|
||||
dayMaskAsBitmask: action.rule.dayMask
|
||||
}, { transaction: cache.transaction })
|
||||
|
||||
cache.categoriesWithModifiedTimeLimitRules.push(action.rule.categoryId)
|
||||
cache.areChangesImportant = true
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
/*
|
||||
* server component for the TimeLimit App
|
||||
* Copyright (C) 2019 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 { DeleteCategoryAction } from '../../../../action'
|
||||
import { Cache } from '../cache'
|
||||
|
||||
export async function dispatchDeleteCategory ({ action, cache }: {
|
||||
action: DeleteCategoryAction
|
||||
cache: Cache
|
||||
}) {
|
||||
// no version number needs to be updated
|
||||
const { familyId, transaction } = cache
|
||||
const { categoryId } = action
|
||||
|
||||
await cache.database.timelimitRule.destroy({
|
||||
where: {
|
||||
familyId,
|
||||
categoryId
|
||||
},
|
||||
transaction
|
||||
})
|
||||
|
||||
await cache.database.usedTime.destroy({
|
||||
where: {
|
||||
familyId,
|
||||
categoryId
|
||||
},
|
||||
transaction
|
||||
})
|
||||
|
||||
await cache.database.categoryApp.destroy({
|
||||
where: {
|
||||
familyId,
|
||||
categoryId
|
||||
},
|
||||
transaction
|
||||
})
|
||||
|
||||
const [affectedUserRows] = await cache.database.user.update({
|
||||
categoryForNotAssignedApps: ''
|
||||
}, {
|
||||
where: {
|
||||
familyId,
|
||||
categoryForNotAssignedApps: categoryId
|
||||
},
|
||||
transaction
|
||||
})
|
||||
|
||||
await cache.database.category.destroy({
|
||||
where: {
|
||||
familyId,
|
||||
categoryId
|
||||
},
|
||||
transaction
|
||||
})
|
||||
|
||||
// update the cache
|
||||
cache.doesCategoryExist.cache.set(action.categoryId, false)
|
||||
cache.areChangesImportant = true
|
||||
|
||||
if (affectedUserRows !== 0) {
|
||||
cache.invalidiateUserList = true
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
/*
|
||||
* server component for the TimeLimit App
|
||||
* Copyright (C) 2019 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 { DeleteTimeLimitRuleAction } from '../../../../action'
|
||||
import { Cache } from '../cache'
|
||||
|
||||
export async function dispatchDeleteTimeLimitRule ({ action, cache }: {
|
||||
action: DeleteTimeLimitRuleAction
|
||||
cache: Cache
|
||||
}) {
|
||||
const ruleEntry = await cache.database.timelimitRule.findOne({
|
||||
where: {
|
||||
familyId: cache.familyId,
|
||||
ruleId: action.ruleId
|
||||
},
|
||||
transaction: cache.transaction
|
||||
})
|
||||
|
||||
if (ruleEntry) {
|
||||
await ruleEntry.destroy({ transaction: cache.transaction })
|
||||
|
||||
cache.categoriesWithModifiedTimeLimitRules.push(ruleEntry.categoryId)
|
||||
cache.areChangesImportant = true
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
/*
|
||||
* server component for the TimeLimit App
|
||||
* Copyright (C) 2019 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 { IgnoreManipulationAction } from '../../../../action'
|
||||
import { Cache } from '../cache'
|
||||
|
||||
export async function dispatchIgnoreManipulation ({ action, cache }: {
|
||||
action: IgnoreManipulationAction
|
||||
cache: Cache
|
||||
}) {
|
||||
const deviceEntry = await cache.database.device.findOne({
|
||||
where: {
|
||||
familyId: cache.familyId,
|
||||
deviceId: action.deviceId
|
||||
},
|
||||
transaction: cache.transaction
|
||||
})
|
||||
|
||||
if (deviceEntry === null) {
|
||||
throw new Error('illegal state: missing device which dispatched the action')
|
||||
}
|
||||
|
||||
if (action.ignoreDeviceAdminManipulation) {
|
||||
deviceEntry.highestProtectionLevel = deviceEntry.currentProtectionLevel
|
||||
}
|
||||
|
||||
if (action.ignoreDeviceAdminManipulationAttempt) {
|
||||
deviceEntry.triedDisablingDeviceAdmin = false
|
||||
}
|
||||
|
||||
if (action.ignoreAppDowngrade) {
|
||||
deviceEntry.highestAppVersion = deviceEntry.currentAppVersion
|
||||
}
|
||||
|
||||
if (action.ignoreNotificationAccessManipulation) {
|
||||
deviceEntry.highestNotificationAccessPermission = deviceEntry.currentNotificationAccessPermission
|
||||
}
|
||||
|
||||
if (action.ignoreUsageStatsAccessManipulation) {
|
||||
deviceEntry.highestUsageStatsPermission = deviceEntry.currentUsageStatsPermission
|
||||
}
|
||||
|
||||
if (action.ignoreDidReboot) {
|
||||
deviceEntry.didReboot = false
|
||||
}
|
||||
|
||||
if (action.ignoreHadManipulation) {
|
||||
deviceEntry.hadManipulation = false
|
||||
}
|
||||
|
||||
await deviceEntry.save({ transaction: cache.transaction })
|
||||
cache.invalidiateDeviceList = true
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
/*
|
||||
* server component for the TimeLimit App
|
||||
* Copyright (C) 2019 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 * as Sequelize from 'sequelize'
|
||||
import { IncrementCategoryExtraTimeAction } from '../../../../action'
|
||||
import { Cache } from '../cache'
|
||||
|
||||
export async function dispatchIncrementCategoryExtraTime ({ action, cache }: {
|
||||
action: IncrementCategoryExtraTimeAction
|
||||
cache: Cache
|
||||
}) {
|
||||
if (!cache.hasFullVersion) {
|
||||
throw new Error('action requires full version')
|
||||
}
|
||||
|
||||
const categoryEntryUnsafe = await cache.database.category.findOne({
|
||||
where: {
|
||||
familyId: cache.familyId,
|
||||
categoryId: action.categoryId
|
||||
},
|
||||
transaction: cache.transaction,
|
||||
attributes: [
|
||||
'childId',
|
||||
'parentCategoryId'
|
||||
]
|
||||
})
|
||||
|
||||
if (!categoryEntryUnsafe) {
|
||||
throw new Error(`tried to add extra time to ${action.categoryId} but it does not exist`)
|
||||
}
|
||||
|
||||
const categoryEntry = {
|
||||
childId: categoryEntryUnsafe.childId,
|
||||
parentCategoryId: categoryEntryUnsafe.parentCategoryId
|
||||
}
|
||||
|
||||
await cache.database.category.update({
|
||||
extraTimeInMillis: Sequelize.literal(`extraTimeInMillis + ${action.addedExtraTime}`) as any
|
||||
}, {
|
||||
where: {
|
||||
familyId: cache.familyId,
|
||||
categoryId: action.categoryId
|
||||
},
|
||||
transaction: cache.transaction
|
||||
})
|
||||
|
||||
cache.categoriesWithModifiedBaseData.push(action.categoryId)
|
||||
cache.areChangesImportant = true
|
||||
|
||||
if (categoryEntry.parentCategoryId !== '') {
|
||||
const [affectedRows] = await cache.database.category.update({
|
||||
extraTimeInMillis: Sequelize.literal(`extraTimeInMillis + ${action.addedExtraTime}`) as any
|
||||
}, {
|
||||
where: {
|
||||
familyId: cache.familyId,
|
||||
categoryId: categoryEntry.parentCategoryId,
|
||||
childId: categoryEntry.childId
|
||||
},
|
||||
transaction: cache.transaction
|
||||
})
|
||||
|
||||
if (affectedRows !== 0) {
|
||||
cache.categoriesWithModifiedBaseData.push(categoryEntry.parentCategoryId)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
/*
|
||||
* server component for the TimeLimit App
|
||||
* Copyright (C) 2019 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 {
|
||||
AddCategoryAppsAction,
|
||||
AddUserAction,
|
||||
ChangeParentPasswordAction,
|
||||
CreateCategoryAction,
|
||||
CreateTimeLimitRuleAction,
|
||||
DeleteCategoryAction,
|
||||
DeleteTimeLimitRuleAction,
|
||||
IgnoreManipulationAction,
|
||||
IncrementCategoryExtraTimeAction,
|
||||
ParentAction,
|
||||
RemoveCategoryAppsAction,
|
||||
RemoveUserAction,
|
||||
RenameChildAction,
|
||||
SetCategoryExtraTimeAction,
|
||||
SetCategoryForUnassignedAppsAction,
|
||||
SetChildPasswordAction,
|
||||
SetConsiderRebootManipulationAction,
|
||||
SetDeviceDefaultUserAction,
|
||||
SetDeviceDefaultUserTimeoutAction,
|
||||
SetDeviceUserAction,
|
||||
SetKeepSignedInAction,
|
||||
SetParentCategoryAction,
|
||||
SetRelaxPrimaryDeviceAction,
|
||||
SetSendDeviceConnected,
|
||||
SetUserDisableLimitsUntilAction,
|
||||
SetUserTimezoneAction,
|
||||
UpdateCategoryBlockedTimesAction,
|
||||
UpdateCategoryTemporarilyBlockedAction,
|
||||
UpdateCategoryTitleAction,
|
||||
UpdateDeviceNameAction,
|
||||
UpdateNetworkTimeVerificationAction,
|
||||
UpdateParentNotificationFlagsAction,
|
||||
UpdateTimelimitRuleAction
|
||||
} from '../../../../action'
|
||||
import { Cache } from '../cache'
|
||||
import { dispatchAddCategoryApps } from './addcategoryapps'
|
||||
import { dispatchAddUser } from './adduser'
|
||||
import { dispatchChangeParentPassword } from './changeparentpassword'
|
||||
import { dispatchCreateCategory } from './createcategory'
|
||||
import { dispatchCreateTimeLimitRule } from './createtimelimitrule'
|
||||
import { dispatchDeleteCategory } from './deletecategory'
|
||||
import { dispatchDeleteTimeLimitRule } from './deletetimelimitrule'
|
||||
import { dispatchIgnoreManipulation } from './ignoremanipulation'
|
||||
import { dispatchIncrementCategoryExtraTime } from './incrementcategoryextratime'
|
||||
import { dispatchRemoveCategoryApps } from './removecategoryapps'
|
||||
import { dispatchRemoveUser } from './removeuser'
|
||||
import { dispatchRenameChild } from './renamechild'
|
||||
import { dispatchSetCategoryExtraTime } from './setcategoryextratime'
|
||||
import { dispatchSetCategoryForUnassignedApps } from './setcategoryforunassignedapps'
|
||||
import { dispatchSetChildPassword } from './setchildpassword'
|
||||
import { dispatchSetConsiderRebootManipulation } from './setconsiderrebootmanipulation'
|
||||
import { dispatchSetDeviceDefaultUser } from './setdevicedefaultuser'
|
||||
import { dispatchSetDeviceDefaultUserTimeout } from './setdevicedefaultusertimeout'
|
||||
import { dispatchSetDeviceUser } from './setdeviceuser'
|
||||
import { dispatchSetKeepSignedIn } from './setkeepsignedin'
|
||||
import { dispatchSetParentCategory } from './setparentcategory'
|
||||
import { dispatchSetRelaxPrimaryDevice } from './setrelaxprimarydevice'
|
||||
import { dispatchSetSendDeviceConnected } from './setsenddeviceconnected'
|
||||
import { dispatchUserSetDisableLimitsUntil } from './setuserdisablelmitsuntil'
|
||||
import { dispatchSetUserTimezone } from './setusertimezone'
|
||||
import { dispatchUpdateCategoryBlockedTimes } from './updatecategoryblockedtimes'
|
||||
import { dispatchUpdateCategoryTemporarilyBlocked } from './updatecategorytemporarilyblocked'
|
||||
import { dispatchUpdateCategoryTitle } from './updatecategorytitle'
|
||||
import { dispatchUpdateDeviceName } from './updatedevicename'
|
||||
import { dispatchUpdateNetworkTimeVerification } from './updatenetworktimeverification'
|
||||
import { dispatchUpdateParentNotificationFlags } from './updateparentnotificationflags'
|
||||
import { dispatchUpdateTimelimitRule } from './updatetimelimitrule'
|
||||
|
||||
export const dispatchParentAction = async ({ action, cache, parentUserId, sourceDeviceId }: {
|
||||
action: ParentAction
|
||||
cache: Cache
|
||||
parentUserId: string
|
||||
sourceDeviceId: string | null
|
||||
}) => {
|
||||
if (action instanceof AddCategoryAppsAction) {
|
||||
await dispatchAddCategoryApps({ action, cache })
|
||||
} else if (action instanceof AddUserAction) {
|
||||
await dispatchAddUser({ action, cache })
|
||||
} else if (action instanceof RemoveCategoryAppsAction) {
|
||||
await dispatchRemoveCategoryApps({ action, cache })
|
||||
} else if (action instanceof CreateCategoryAction) {
|
||||
await dispatchCreateCategory({ action, cache })
|
||||
} else if (action instanceof CreateTimeLimitRuleAction) {
|
||||
await dispatchCreateTimeLimitRule({ action, cache })
|
||||
} else if (action instanceof DeleteCategoryAction) {
|
||||
await dispatchDeleteCategory({ action, cache })
|
||||
} else if (action instanceof UpdateCategoryTitleAction) {
|
||||
await dispatchUpdateCategoryTitle({ action, cache })
|
||||
} else if (action instanceof SetCategoryExtraTimeAction) {
|
||||
await dispatchSetCategoryExtraTime({ action, cache })
|
||||
} else if (action instanceof SetCategoryForUnassignedAppsAction) {
|
||||
await dispatchSetCategoryForUnassignedApps({ action, cache })
|
||||
} else if (action instanceof SetChildPasswordAction) {
|
||||
await dispatchSetChildPassword({ action, cache })
|
||||
} else if (action instanceof SetConsiderRebootManipulationAction) {
|
||||
await dispatchSetConsiderRebootManipulation({ action, cache })
|
||||
} else if (action instanceof SetDeviceDefaultUserAction) {
|
||||
await dispatchSetDeviceDefaultUser({ action, cache })
|
||||
} else if (action instanceof SetDeviceDefaultUserTimeoutAction) {
|
||||
await dispatchSetDeviceDefaultUserTimeout({ action, cache })
|
||||
} else if (action instanceof SetDeviceUserAction) {
|
||||
await dispatchSetDeviceUser({ action, cache })
|
||||
} else if (action instanceof SetKeepSignedInAction) {
|
||||
await dispatchSetKeepSignedIn({ action, cache, parentUserId })
|
||||
} else if (action instanceof SetParentCategoryAction) {
|
||||
await dispatchSetParentCategory({ action, cache })
|
||||
} else if (action instanceof SetRelaxPrimaryDeviceAction) {
|
||||
await dispatchSetRelaxPrimaryDevice({ action, cache })
|
||||
} else if (action instanceof SetSendDeviceConnected) {
|
||||
await dispatchSetSendDeviceConnected({ action, cache, sourceDeviceId })
|
||||
} else if (action instanceof SetUserDisableLimitsUntilAction) {
|
||||
await dispatchUserSetDisableLimitsUntil({ action, cache })
|
||||
} else if (action instanceof SetUserTimezoneAction) {
|
||||
await dispatchSetUserTimezone({ action, cache })
|
||||
} else if (action instanceof UpdateCategoryBlockedTimesAction) {
|
||||
await dispatchUpdateCategoryBlockedTimes({ action, cache })
|
||||
} else if (action instanceof IncrementCategoryExtraTimeAction) {
|
||||
await dispatchIncrementCategoryExtraTime({ action, cache })
|
||||
} else if (action instanceof UpdateCategoryTemporarilyBlockedAction) {
|
||||
await dispatchUpdateCategoryTemporarilyBlocked({ action, cache })
|
||||
} else if (action instanceof DeleteTimeLimitRuleAction) {
|
||||
await dispatchDeleteTimeLimitRule({ action, cache })
|
||||
} else if (action instanceof UpdateDeviceNameAction) {
|
||||
await dispatchUpdateDeviceName({ action, cache })
|
||||
} else if (action instanceof UpdateNetworkTimeVerificationAction) {
|
||||
await dispatchUpdateNetworkTimeVerification({ action, cache })
|
||||
} else if (action instanceof UpdateParentNotificationFlagsAction) {
|
||||
await dispatchUpdateParentNotificationFlags({ action, cache })
|
||||
} else if (action instanceof UpdateTimelimitRuleAction) {
|
||||
await dispatchUpdateTimelimitRule({ action, cache })
|
||||
} else if (action instanceof RemoveUserAction) {
|
||||
await dispatchRemoveUser({ action, cache, parentUserId })
|
||||
} else if (action instanceof RenameChildAction) {
|
||||
await dispatchRenameChild({ action, cache })
|
||||
} else if (action instanceof ChangeParentPasswordAction) {
|
||||
await dispatchChangeParentPassword({ action, cache })
|
||||
} else if (action instanceof IgnoreManipulationAction) {
|
||||
await dispatchIgnoreManipulation({ action, cache })
|
||||
} else {
|
||||
throw new Error('unsupported action type')
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
/*
|
||||
* server component for the TimeLimit App
|
||||
* Copyright (C) 2019 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 * as Sequelize from 'sequelize'
|
||||
import { RemoveCategoryAppsAction } from '../../../../action'
|
||||
import { Cache } from '../cache'
|
||||
|
||||
export async function dispatchRemoveCategoryApps ({ action, cache }: {
|
||||
action: RemoveCategoryAppsAction
|
||||
cache: Cache
|
||||
}) {
|
||||
const affectedRows = await cache.database.categoryApp.destroy({
|
||||
where: {
|
||||
familyId: cache.familyId,
|
||||
categoryId: action.categoryId,
|
||||
packageName: {
|
||||
[Sequelize.Op.in]: action.packageNames
|
||||
}
|
||||
},
|
||||
transaction: cache.transaction
|
||||
})
|
||||
|
||||
if (affectedRows !== action.packageNames.length) {
|
||||
throw new Error('could not delete as much entries as requested')
|
||||
}
|
||||
|
||||
cache.categoriesWithModifiedApps.push(action.categoryId)
|
||||
cache.areChangesImportant = true
|
||||
}
|
||||
@@ -0,0 +1,159 @@
|
||||
/*
|
||||
* server component for the TimeLimit App
|
||||
* Copyright (C) 2019 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 { InternalServerError } from 'http-errors'
|
||||
import * as Sequelize from 'sequelize'
|
||||
import { RemoveUserAction } from '../../../../action'
|
||||
import { Cache } from '../cache'
|
||||
|
||||
export async function dispatchRemoveUser ({ action, cache, parentUserId }: {
|
||||
action: RemoveUserAction
|
||||
cache: Cache
|
||||
parentUserId: string
|
||||
}) {
|
||||
const user = await cache.database.user.findOne({
|
||||
where: {
|
||||
familyId: cache.familyId,
|
||||
userId: action.userId
|
||||
},
|
||||
transaction: cache.transaction
|
||||
})
|
||||
|
||||
if (!user) {
|
||||
throw new Error('invalid user id')
|
||||
}
|
||||
|
||||
if (user.type === 'parent') {
|
||||
if (!parentUserId) {
|
||||
throw new InternalServerError()
|
||||
}
|
||||
|
||||
if (parentUserId === action.userId) {
|
||||
throw new Error('users can not delete themself')
|
||||
}
|
||||
|
||||
const expectedIntegrityValue = createHash('sha512').update(
|
||||
action.userId + user.secondPasswordHash + 'remove'
|
||||
).digest('hex').substring(0, 16)
|
||||
|
||||
if (expectedIntegrityValue !== action.authentication) {
|
||||
throw new Error('invalid authentication value')
|
||||
}
|
||||
|
||||
if (user.mail !== '') {
|
||||
const usersWithLinkedMail = await cache.database.user.count({
|
||||
transaction: cache.transaction,
|
||||
where: {
|
||||
familyId: cache.familyId,
|
||||
type: 'parent',
|
||||
mail: {
|
||||
[Sequelize.Op.not]: ''
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
if (usersWithLinkedMail <= 1) {
|
||||
throw new Error('this user is the last one with a linked mail address')
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (user.type === 'child') {
|
||||
const categories = await cache.database.category.findAll({
|
||||
where: {
|
||||
familyId: cache.familyId,
|
||||
childId: action.userId
|
||||
},
|
||||
transaction: cache.transaction,
|
||||
lock: Sequelize.Transaction.LOCK.UPDATE
|
||||
})
|
||||
|
||||
await cache.database.categoryApp.destroy({
|
||||
where: {
|
||||
familyId: cache.familyId,
|
||||
categoryId: {
|
||||
[Sequelize.Op.in]: categories.map((category) => category.categoryId)
|
||||
}
|
||||
},
|
||||
transaction: cache.transaction
|
||||
})
|
||||
|
||||
await cache.database.timelimitRule.destroy({
|
||||
where: {
|
||||
familyId: cache.familyId,
|
||||
categoryId: {
|
||||
[Sequelize.Op.in]: categories.map((category) => category.categoryId)
|
||||
}
|
||||
},
|
||||
transaction: cache.transaction
|
||||
})
|
||||
|
||||
await cache.database.usedTime.destroy({
|
||||
where: {
|
||||
familyId: cache.familyId,
|
||||
categoryId: {
|
||||
[Sequelize.Op.in]: categories.map((category) => category.categoryId)
|
||||
}
|
||||
},
|
||||
transaction: cache.transaction
|
||||
})
|
||||
|
||||
await cache.database.category.destroy({
|
||||
where: {
|
||||
familyId: cache.familyId,
|
||||
categoryId: {
|
||||
[Sequelize.Op.in]: categories.map((category) => category.categoryId)
|
||||
}
|
||||
},
|
||||
transaction: cache.transaction
|
||||
})
|
||||
}
|
||||
|
||||
const [updatedDevices1] = await cache.database.device.update({
|
||||
currentUserId: '',
|
||||
isUserKeptSignedIn: false
|
||||
}, {
|
||||
where: {
|
||||
familyId: cache.familyId,
|
||||
currentUserId: action.userId
|
||||
},
|
||||
transaction: cache.transaction
|
||||
})
|
||||
|
||||
const [updatedDevices2] = await cache.database.device.update({
|
||||
defaultUserId: ''
|
||||
}, {
|
||||
where: {
|
||||
familyId: cache.familyId,
|
||||
defaultUserId: action.userId
|
||||
},
|
||||
transaction: cache.transaction
|
||||
})
|
||||
|
||||
if (updatedDevices1 > 0 || updatedDevices2 > 0) {
|
||||
cache.invalidiateDeviceList = true
|
||||
}
|
||||
|
||||
await user.destroy({ transaction: cache.transaction })
|
||||
|
||||
cache.invalidiateUserList = true
|
||||
cache.areChangesImportant = true
|
||||
|
||||
cache.doesUserExist.cache.set(action.userId, false)
|
||||
cache.getSecondPasswordHashOfParent.cache.delete(action.userId)
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
/*
|
||||
* server component for the TimeLimit App
|
||||
* Copyright (C) 2019 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 { RenameChildAction } from '../../../../action'
|
||||
import { Cache } from '../cache'
|
||||
|
||||
export async function dispatchRenameChild ({ action, cache }: {
|
||||
action: RenameChildAction
|
||||
cache: Cache
|
||||
}) {
|
||||
const [affectedRows] = await cache.database.user.update({
|
||||
name: action.newName
|
||||
}, {
|
||||
where: {
|
||||
familyId: cache.familyId,
|
||||
userId: action.childId,
|
||||
type: 'child'
|
||||
},
|
||||
transaction: cache.transaction
|
||||
})
|
||||
|
||||
if (affectedRows !== 1) {
|
||||
throw new Error('can not update child name if child does not exist')
|
||||
}
|
||||
|
||||
cache.invalidiateUserList = true
|
||||
cache.doesUserExist.cache.set(action.childId, false)
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
/*
|
||||
* server component for the TimeLimit App
|
||||
* Copyright (C) 2019 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 { SetCategoryExtraTimeAction } from '../../../../action'
|
||||
import { Cache } from '../cache'
|
||||
|
||||
export async function dispatchSetCategoryExtraTime ({ action, cache }: {
|
||||
action: SetCategoryExtraTimeAction
|
||||
cache: Cache
|
||||
}) {
|
||||
if (!cache.hasFullVersion) {
|
||||
throw new Error('action requires full version')
|
||||
}
|
||||
|
||||
const [affectedRows] = await cache.database.category.update({
|
||||
extraTimeInMillis: action.newExtraTime
|
||||
}, {
|
||||
where: {
|
||||
familyId: cache.familyId,
|
||||
categoryId: action.categoryId
|
||||
},
|
||||
transaction: cache.transaction
|
||||
})
|
||||
|
||||
if (affectedRows !== 0) {
|
||||
cache.categoriesWithModifiedBaseData.push(action.categoryId)
|
||||
cache.areChangesImportant = true
|
||||
}
|
||||
}
|
||||
+67
@@ -0,0 +1,67 @@
|
||||
/*
|
||||
* server component for the TimeLimit App
|
||||
* Copyright (C) 2019 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 { SetCategoryForUnassignedAppsAction } from '../../../../action'
|
||||
import { Cache } from '../cache'
|
||||
|
||||
export async function dispatchSetCategoryForUnassignedApps ({ action, cache }: {
|
||||
action: SetCategoryForUnassignedAppsAction
|
||||
cache: Cache
|
||||
}) {
|
||||
if (action.categoryId === '') {
|
||||
// nothing to check
|
||||
} else {
|
||||
const categoryEntryUnsafe = await cache.database.category.findOne({
|
||||
attributes: ['childId'],
|
||||
where: {
|
||||
familyId: cache.familyId,
|
||||
categoryId: action.categoryId
|
||||
},
|
||||
transaction: cache.transaction
|
||||
})
|
||||
|
||||
if (!categoryEntryUnsafe) {
|
||||
throw new Error('can not set a category which does not exist as category for unassigned apps')
|
||||
}
|
||||
|
||||
const categoryEntry = {
|
||||
childId: categoryEntryUnsafe.childId
|
||||
}
|
||||
|
||||
if (categoryEntry.childId !== action.childId) {
|
||||
throw new Error('can not set a category of one child as category for unassigned apps for an other child')
|
||||
}
|
||||
}
|
||||
|
||||
const [affectedRows] = await cache.database.user.update({
|
||||
categoryForNotAssignedApps: action.categoryId
|
||||
}, {
|
||||
where: {
|
||||
familyId: cache.familyId,
|
||||
userId: action.childId,
|
||||
type: 'child'
|
||||
},
|
||||
transaction: cache.transaction
|
||||
})
|
||||
|
||||
if (affectedRows !== 1) {
|
||||
throw new Error('could not find a child with matching id for setting the category for not assigned apps')
|
||||
}
|
||||
|
||||
cache.invalidiateUserList = true
|
||||
cache.areChangesImportant = true
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
/*
|
||||
* server component for the TimeLimit App
|
||||
* Copyright (C) 2019 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 * as Sequelize from 'sequelize'
|
||||
import { SetChildPasswordAction } from '../../../../action'
|
||||
import { Cache } from '../cache'
|
||||
|
||||
export async function dispatchSetChildPassword ({ action, cache }: {
|
||||
action: SetChildPasswordAction
|
||||
cache: Cache
|
||||
}) {
|
||||
const childEntry = await cache.database.user.findOne({
|
||||
where: {
|
||||
familyId: cache.familyId,
|
||||
userId: action.childUserId,
|
||||
type: 'child'
|
||||
},
|
||||
transaction: cache.transaction,
|
||||
lock: Sequelize.Transaction.LOCK.UPDATE
|
||||
})
|
||||
|
||||
if (!childEntry) {
|
||||
throw new Error('parent entry not found')
|
||||
}
|
||||
|
||||
childEntry.passwordHash = action.newPassword.hash
|
||||
childEntry.secondPasswordSalt = action.newPassword.secondSalt
|
||||
childEntry.secondPasswordHash = action.newPassword.secondHash
|
||||
|
||||
await childEntry.save({ transaction: cache.transaction })
|
||||
|
||||
cache.getSecondPasswordHashOfChild.cache.clear()
|
||||
cache.invalidiateUserList = true
|
||||
cache.areChangesImportant = true
|
||||
}
|
||||
+41
@@ -0,0 +1,41 @@
|
||||
/*
|
||||
* server component for the TimeLimit App
|
||||
* Copyright (C) 2019 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 { SetConsiderRebootManipulationAction } from '../../../../action'
|
||||
import { Cache } from '../cache'
|
||||
|
||||
export async function dispatchSetConsiderRebootManipulation ({ action, cache }: {
|
||||
action: SetConsiderRebootManipulationAction
|
||||
cache: Cache
|
||||
}) {
|
||||
const [affectedRows] = await cache.database.device.update({
|
||||
considerRebootManipulation: action.enable
|
||||
}, {
|
||||
transaction: cache.transaction,
|
||||
where: {
|
||||
familyId: cache.familyId,
|
||||
deviceId: action.deviceId
|
||||
}
|
||||
})
|
||||
|
||||
if (affectedRows === 0) {
|
||||
throw new Error('did not find device to update consider reboot manipulation')
|
||||
}
|
||||
|
||||
cache.invalidiateDeviceList = true
|
||||
cache.areChangesImportant = true
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
/*
|
||||
* server component for the TimeLimit App
|
||||
* Copyright (C) 2019 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 { SetDeviceDefaultUserAction } from '../../../../action'
|
||||
import { Cache } from '../cache'
|
||||
|
||||
export async function dispatchSetDeviceDefaultUser ({ action, cache }: {
|
||||
action: SetDeviceDefaultUserAction
|
||||
cache: Cache
|
||||
}) {
|
||||
if (action.defaultUserId !== '') {
|
||||
const doesUserExist = await cache.doesUserExist(action.defaultUserId)
|
||||
|
||||
if (!doesUserExist) {
|
||||
throw new Error('can not set invalid user as default user')
|
||||
}
|
||||
}
|
||||
|
||||
const [affectedRows] = await cache.database.device.update({
|
||||
defaultUserId: action.defaultUserId
|
||||
}, {
|
||||
transaction: cache.transaction,
|
||||
where: {
|
||||
familyId: cache.familyId,
|
||||
deviceId: action.deviceId
|
||||
}
|
||||
})
|
||||
|
||||
if (affectedRows === 0) {
|
||||
throw new Error('did not find device to update default user')
|
||||
}
|
||||
|
||||
cache.invalidiateDeviceList = true
|
||||
cache.areChangesImportant = true
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
/*
|
||||
* server component for the TimeLimit App
|
||||
* Copyright (C) 2019 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 { SetDeviceDefaultUserTimeoutAction } from '../../../../action'
|
||||
import { Cache } from '../cache'
|
||||
|
||||
export async function dispatchSetDeviceDefaultUserTimeout ({ action, cache }: {
|
||||
action: SetDeviceDefaultUserTimeoutAction
|
||||
cache: Cache
|
||||
}) {
|
||||
const [affectedRows] = await cache.database.device.update({
|
||||
defaultUserTimeout: action.timeout
|
||||
}, {
|
||||
transaction: cache.transaction,
|
||||
where: {
|
||||
familyId: cache.familyId,
|
||||
deviceId: action.deviceId
|
||||
}
|
||||
})
|
||||
|
||||
if (affectedRows === 0) {
|
||||
throw new Error('did not find device to update default user timeout')
|
||||
}
|
||||
|
||||
cache.invalidiateDeviceList = true
|
||||
cache.areChangesImportant = true
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
/*
|
||||
* server component for the TimeLimit App
|
||||
* Copyright (C) 2019 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 { SetDeviceUserAction } from '../../../../action'
|
||||
import { Cache } from '../cache'
|
||||
|
||||
export async function dispatchSetDeviceUser ({ action, cache }: {
|
||||
action: SetDeviceUserAction
|
||||
cache: Cache
|
||||
}) {
|
||||
if (action.userId !== '') {
|
||||
const doesUserExist = await cache.doesUserExist(action.userId)
|
||||
|
||||
if (!doesUserExist) {
|
||||
throw new Error('invalid user id provided')
|
||||
}
|
||||
}
|
||||
|
||||
const [affectedRows] = await cache.database.device.update({
|
||||
currentUserId: action.userId,
|
||||
isUserKeptSignedIn: false
|
||||
}, {
|
||||
where: {
|
||||
familyId: cache.familyId,
|
||||
deviceId: action.deviceId
|
||||
},
|
||||
transaction: cache.transaction
|
||||
})
|
||||
|
||||
if (affectedRows !== 0) {
|
||||
cache.invalidiateDeviceList = true
|
||||
cache.areChangesImportant = true
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
/*
|
||||
* server component for the TimeLimit App
|
||||
* Copyright (C) 2019 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 { SetKeepSignedInAction } from '../../../../action'
|
||||
import { Cache } from '../cache'
|
||||
|
||||
export async function dispatchSetKeepSignedIn ({ action, cache, parentUserId }: {
|
||||
action: SetKeepSignedInAction
|
||||
cache: Cache
|
||||
parentUserId: string
|
||||
}) {
|
||||
const doesUserExist = await cache.doesUserExist(parentUserId)
|
||||
|
||||
if (!doesUserExist) {
|
||||
throw new Error('invalid user id provided')
|
||||
}
|
||||
|
||||
const deviceEntry = await cache.database.device.findOne({
|
||||
where: {
|
||||
familyId: cache.familyId,
|
||||
deviceId: action.deviceId
|
||||
},
|
||||
transaction: cache.transaction
|
||||
})
|
||||
|
||||
if (!deviceEntry) {
|
||||
throw new Error('device does not exist')
|
||||
}
|
||||
|
||||
if (deviceEntry.currentUserId !== parentUserId) {
|
||||
if (action.keepSignedIn) {
|
||||
throw new Error('only the user itself can disable asking for the password')
|
||||
}
|
||||
}
|
||||
|
||||
const [affectedRows] = await cache.database.device.update({
|
||||
isUserKeptSignedIn: action.keepSignedIn
|
||||
}, {
|
||||
where: {
|
||||
familyId: cache.familyId,
|
||||
deviceId: action.deviceId,
|
||||
currentUserId: deviceEntry.currentUserId
|
||||
},
|
||||
transaction: cache.transaction
|
||||
})
|
||||
|
||||
if (affectedRows !== 0) {
|
||||
cache.invalidiateDeviceList = true
|
||||
cache.areChangesImportant = true
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
/*
|
||||
* server component for the TimeLimit App
|
||||
* Copyright (C) 2019 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 { SetParentCategoryAction } from '../../../../action'
|
||||
import { Cache } from '../cache'
|
||||
|
||||
export async function dispatchSetParentCategory ({ action, cache }: {
|
||||
action: SetParentCategoryAction
|
||||
cache: Cache
|
||||
}) {
|
||||
const categoryEntry = await cache.database.category.findOne({
|
||||
where: {
|
||||
familyId: cache.familyId,
|
||||
categoryId: action.categoryId
|
||||
},
|
||||
transaction: cache.transaction
|
||||
})
|
||||
|
||||
if (!categoryEntry) {
|
||||
throw new Error('tried to set parent category of non existent category')
|
||||
}
|
||||
|
||||
if (action.parentCategory !== '') {
|
||||
const parentCategoryEntry = await cache.database.category.findOne({
|
||||
where: {
|
||||
familyId: cache.familyId,
|
||||
categoryId: action.parentCategory,
|
||||
childId: categoryEntry.childId
|
||||
},
|
||||
transaction: cache.transaction
|
||||
})
|
||||
|
||||
if (!parentCategoryEntry) {
|
||||
throw new Error('tried to set parent category to non existent category')
|
||||
}
|
||||
|
||||
if (parentCategoryEntry.parentCategoryId !== '') {
|
||||
throw new Error('tried to set a category as parent which itself has got a parent')
|
||||
}
|
||||
|
||||
const countChildCategories = await cache.database.category.findAndCountAll({
|
||||
where: {
|
||||
familyId: cache.familyId,
|
||||
parentCategoryId: action.categoryId
|
||||
},
|
||||
transaction: cache.transaction
|
||||
})
|
||||
|
||||
if (countChildCategories.count > 0) {
|
||||
throw new Error('tried to make category a child category altough it is already a parent category')
|
||||
}
|
||||
}
|
||||
|
||||
await cache.database.category.update({
|
||||
parentCategoryId: action.parentCategory
|
||||
}, {
|
||||
where: {
|
||||
familyId: cache.familyId,
|
||||
categoryId: action.categoryId
|
||||
},
|
||||
transaction: cache.transaction
|
||||
})
|
||||
|
||||
cache.categoriesWithModifiedBaseData.push(action.categoryId)
|
||||
cache.areChangesImportant = true
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
/*
|
||||
* server component for the TimeLimit App
|
||||
* Copyright (C) 2019 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 { SetRelaxPrimaryDeviceAction } from '../../../../action'
|
||||
import { Cache } from '../cache'
|
||||
|
||||
export async function dispatchSetRelaxPrimaryDevice ({ action, cache }: {
|
||||
action: SetRelaxPrimaryDeviceAction
|
||||
cache: Cache
|
||||
}) {
|
||||
const [affectedRows] = await cache.database.user.update({
|
||||
relaxPrimaryDeviceRule: action.relax
|
||||
}, {
|
||||
transaction: cache.transaction,
|
||||
where: {
|
||||
familyId: cache.familyId,
|
||||
userId: action.userId,
|
||||
type: 'child'
|
||||
}
|
||||
})
|
||||
|
||||
if (affectedRows === 0) {
|
||||
throw new Error('did not find user to update relax primary device')
|
||||
}
|
||||
|
||||
cache.invalidiateUserList = true
|
||||
cache.areChangesImportant = true
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
/*
|
||||
* server component for the TimeLimit App
|
||||
* Copyright (C) 2019 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 { SetSendDeviceConnected } from '../../../../action'
|
||||
import { Cache } from '../cache'
|
||||
|
||||
export async function dispatchSetSendDeviceConnected ({ action, cache, sourceDeviceId }: {
|
||||
action: SetSendDeviceConnected
|
||||
cache: Cache
|
||||
sourceDeviceId: string | null
|
||||
}) {
|
||||
if (sourceDeviceId === null || action.deviceId !== sourceDeviceId) {
|
||||
throw new Error('only can do that from the device itself')
|
||||
}
|
||||
|
||||
const [affectedRows] = await cache.database.device.update({
|
||||
showDeviceConnected: action.enable
|
||||
}, {
|
||||
transaction: cache.transaction,
|
||||
where: {
|
||||
familyId: cache.familyId,
|
||||
deviceId: action.deviceId
|
||||
}
|
||||
})
|
||||
|
||||
if (affectedRows === 0) {
|
||||
throw new Error('did not find device to update send if connected')
|
||||
}
|
||||
|
||||
cache.devicesWithModifiedShowDeviceConnected.set(action.deviceId, action.enable)
|
||||
cache.invalidiateDeviceList = true
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
/*
|
||||
* server component for the TimeLimit App
|
||||
* Copyright (C) 2019 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 { SetUserDisableLimitsUntilAction } from '../../../../action'
|
||||
import { Cache } from '../cache'
|
||||
|
||||
export async function dispatchUserSetDisableLimitsUntil ({ action, cache }: {
|
||||
action: SetUserDisableLimitsUntilAction
|
||||
cache: Cache
|
||||
}) {
|
||||
if (action.timestamp !== 0) {
|
||||
if (!cache.hasFullVersion) {
|
||||
throw new Error('action requires full version')
|
||||
}
|
||||
}
|
||||
|
||||
const [affectedRows] = await cache.database.user.update({
|
||||
disableTimelimitsUntil: action.timestamp.toString(10)
|
||||
}, {
|
||||
where: {
|
||||
familyId: cache.familyId,
|
||||
userId: action.childId,
|
||||
type: 'child'
|
||||
},
|
||||
transaction: cache.transaction
|
||||
})
|
||||
|
||||
if (affectedRows === 0) {
|
||||
throw new Error('invalid user id provided')
|
||||
}
|
||||
|
||||
cache.invalidiateUserList = true
|
||||
cache.areChangesImportant = true
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
/*
|
||||
* server component for the TimeLimit App
|
||||
* Copyright (C) 2019 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 { SetUserTimezoneAction } from '../../../../action'
|
||||
import { Cache } from '../cache'
|
||||
|
||||
export async function dispatchSetUserTimezone ({ action, cache }: {
|
||||
action: SetUserTimezoneAction
|
||||
cache: Cache
|
||||
}) {
|
||||
const [affectedRows] = await cache.database.user.update({
|
||||
timeZone: action.timezone
|
||||
}, {
|
||||
transaction: cache.transaction,
|
||||
where: {
|
||||
familyId: cache.familyId,
|
||||
userId: action.userId
|
||||
}
|
||||
})
|
||||
|
||||
if (affectedRows === 0) {
|
||||
throw new Error('did not find user to update timezone')
|
||||
}
|
||||
|
||||
cache.invalidiateUserList = true
|
||||
cache.areChangesImportant = true
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
/*
|
||||
* server component for the TimeLimit App
|
||||
* Copyright (C) 2019 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 { UpdateCategoryBlockedTimesAction } from '../../../../action'
|
||||
import { Cache } from '../cache'
|
||||
|
||||
export async function dispatchUpdateCategoryBlockedTimes ({ action, cache }: {
|
||||
action: UpdateCategoryBlockedTimesAction
|
||||
cache: Cache
|
||||
}) {
|
||||
const [affectedRows] = await cache.database.category.update({
|
||||
blockedMinutesInWeek: action.blockedTimes
|
||||
}, {
|
||||
where: {
|
||||
familyId: cache.familyId,
|
||||
categoryId: action.categoryId
|
||||
},
|
||||
transaction: cache.transaction
|
||||
})
|
||||
|
||||
if (affectedRows === 0) {
|
||||
throw new Error('invalid category id provided')
|
||||
}
|
||||
|
||||
cache.categoriesWithModifiedBaseData.push(action.categoryId)
|
||||
cache.areChangesImportant = true
|
||||
}
|
||||
+45
@@ -0,0 +1,45 @@
|
||||
/*
|
||||
* server component for the TimeLimit App
|
||||
* Copyright (C) 2019 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 { UpdateCategoryTemporarilyBlockedAction } from '../../../../action'
|
||||
import { Cache } from '../cache'
|
||||
|
||||
export async function dispatchUpdateCategoryTemporarilyBlocked ({ action, cache }: {
|
||||
action: UpdateCategoryTemporarilyBlockedAction
|
||||
cache: Cache
|
||||
}) {
|
||||
if (action.blocked === true) {
|
||||
if (!cache.hasFullVersion) {
|
||||
throw new Error('action requires full version')
|
||||
}
|
||||
}
|
||||
|
||||
const [affectedRows] = await cache.database.category.update({
|
||||
temporarilyBlocked: action.blocked
|
||||
}, {
|
||||
where: {
|
||||
familyId: cache.familyId,
|
||||
categoryId: action.categoryId
|
||||
},
|
||||
transaction: cache.transaction
|
||||
})
|
||||
|
||||
if (affectedRows !== 0) {
|
||||
cache.categoriesWithModifiedBaseData.push(action.categoryId)
|
||||
cache.areChangesImportant = true
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
/*
|
||||
* server component for the TimeLimit App
|
||||
* Copyright (C) 2019 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 { UpdateCategoryTitleAction } from '../../../../action'
|
||||
import { Cache } from '../cache'
|
||||
|
||||
export async function dispatchUpdateCategoryTitle ({ action, cache }: {
|
||||
action: UpdateCategoryTitleAction
|
||||
cache: Cache
|
||||
}) {
|
||||
const [affectedRows] = await cache.database.category.update({
|
||||
title: action.newTitle
|
||||
}, {
|
||||
where: {
|
||||
familyId: cache.familyId,
|
||||
categoryId: action.categoryId
|
||||
},
|
||||
transaction: cache.transaction
|
||||
})
|
||||
|
||||
if (affectedRows !== 0) {
|
||||
cache.categoriesWithModifiedBaseData.push(action.categoryId)
|
||||
cache.areChangesImportant = true
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
/*
|
||||
* server component for the TimeLimit App
|
||||
* Copyright (C) 2019 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 { UpdateDeviceNameAction } from '../../../../action'
|
||||
import { Cache } from '../cache'
|
||||
|
||||
export async function dispatchUpdateDeviceName ({ action, cache }: {
|
||||
action: UpdateDeviceNameAction
|
||||
cache: Cache
|
||||
}) {
|
||||
const [affectedRows] = await cache.database.device.update({
|
||||
name: action.name
|
||||
}, {
|
||||
where: {
|
||||
familyId: cache.familyId,
|
||||
deviceId: action.deviceId
|
||||
},
|
||||
transaction: cache.transaction
|
||||
})
|
||||
|
||||
if (affectedRows === 0) {
|
||||
throw new Error('invalid device id')
|
||||
} else {
|
||||
cache.invalidiateDeviceList = true
|
||||
cache.areChangesImportant = true
|
||||
}
|
||||
}
|
||||
+41
@@ -0,0 +1,41 @@
|
||||
/*
|
||||
* server component for the TimeLimit App
|
||||
* Copyright (C) 2019 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 { UpdateNetworkTimeVerificationAction } from '../../../../action'
|
||||
import { Cache } from '../cache'
|
||||
|
||||
export async function dispatchUpdateNetworkTimeVerification ({ action, cache }: {
|
||||
action: UpdateNetworkTimeVerificationAction
|
||||
cache: Cache
|
||||
}) {
|
||||
const [affectedRows] = await cache.database.device.update({
|
||||
networkTime: action.mode
|
||||
}, {
|
||||
where: {
|
||||
familyId: cache.familyId,
|
||||
deviceId: action.deviceId
|
||||
},
|
||||
transaction: cache.transaction
|
||||
})
|
||||
|
||||
if (affectedRows === 0) {
|
||||
throw new Error('invalid device id')
|
||||
} else {
|
||||
cache.invalidiateDeviceList = true
|
||||
cache.areChangesImportant = true
|
||||
}
|
||||
}
|
||||
+47
@@ -0,0 +1,47 @@
|
||||
/*
|
||||
* server component for the TimeLimit App
|
||||
* Copyright (C) 2019 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 { UpdateParentNotificationFlagsAction } from '../../../../action'
|
||||
import { Cache } from '../cache'
|
||||
|
||||
export async function dispatchUpdateParentNotificationFlags ({ action, cache }: {
|
||||
action: UpdateParentNotificationFlagsAction
|
||||
cache: Cache
|
||||
}) {
|
||||
const parentEntry = await cache.database.user.findOne({
|
||||
where: {
|
||||
familyId: cache.familyId,
|
||||
userId: action.parentId,
|
||||
type: 'parent'
|
||||
},
|
||||
transaction: cache.transaction
|
||||
})
|
||||
|
||||
if (!parentEntry) {
|
||||
throw new Error('parent not found')
|
||||
}
|
||||
|
||||
if (action.set) {
|
||||
parentEntry.mailNotificationFlags |= action.flags
|
||||
} else {
|
||||
parentEntry.mailNotificationFlags &= ~action.flags
|
||||
}
|
||||
|
||||
await parentEntry.save({ transaction: cache.transaction })
|
||||
|
||||
cache.invalidiateUserList = true
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
/*
|
||||
* server component for the TimeLimit App
|
||||
* Copyright (C) 2019 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 { UpdateTimelimitRuleAction } from '../../../../action'
|
||||
import { Cache } from '../cache'
|
||||
|
||||
export async function dispatchUpdateTimelimitRule ({ action, cache }: {
|
||||
action: UpdateTimelimitRuleAction
|
||||
cache: Cache
|
||||
}) {
|
||||
const ruleEntry = await cache.database.timelimitRule.findOne({
|
||||
where: {
|
||||
familyId: cache.familyId,
|
||||
ruleId: action.ruleId
|
||||
},
|
||||
transaction: cache.transaction
|
||||
})
|
||||
|
||||
if (!ruleEntry) {
|
||||
throw new Error('invalid rule id provided')
|
||||
}
|
||||
|
||||
ruleEntry.applyToExtraTimeUsage = action.applyToExtraTimeUsage
|
||||
ruleEntry.dayMaskAsBitmask = action.dayMask
|
||||
ruleEntry.maximumTimeInMillis = action.maximumTimeInMillis
|
||||
|
||||
await ruleEntry.save({ transaction: cache.transaction })
|
||||
|
||||
cache.categoriesWithModifiedTimeLimitRules.push(ruleEntry.categoryId)
|
||||
cache.areChangesImportant = true
|
||||
}
|
||||
@@ -0,0 +1,231 @@
|
||||
/*
|
||||
* server component for the TimeLimit App
|
||||
* Copyright (C) 2019 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 { BadRequest, Unauthorized } from 'http-errors'
|
||||
import { parseAppLogicAction, parseChildAction, parseParentAction } from '../../../action/serialization'
|
||||
import { ClientPushChangesRequest } from '../../../api/schema'
|
||||
import { isSerializedAppLogicAction, isSerializedChildAction, isSerializedParentAction } from '../../../api/validator'
|
||||
import { VisibleConnectedDevicesManager } from '../../../connected-devices'
|
||||
import { Database } from '../../../database'
|
||||
import { WebsocketApi } from '../../../websocket'
|
||||
import { notifyClientsAboutChanges } 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'
|
||||
|
||||
export const applyActionsFromDevice = async ({ database, request, websocket, connectedDevicesManager }: {
|
||||
database: Database
|
||||
websocket: WebsocketApi
|
||||
request: ClientPushChangesRequest
|
||||
connectedDevicesManager: VisibleConnectedDevicesManager
|
||||
}) => {
|
||||
if (request.actions.length > 50) {
|
||||
throw new BadRequest()
|
||||
}
|
||||
|
||||
const { shouldDoFullSync, areChangesImportant, sourceDeviceId, familyId } = await database.transaction(async (transaction) => {
|
||||
const deviceEntryUnsafe = await database.device.findOne({
|
||||
where: {
|
||||
deviceAuthToken: request.deviceAuthToken
|
||||
},
|
||||
attributes: ['familyId', 'deviceId', 'nextSequenceNumber'],
|
||||
transaction
|
||||
})
|
||||
|
||||
if (!deviceEntryUnsafe) {
|
||||
throw new Unauthorized()
|
||||
}
|
||||
|
||||
const deviceEntry = {
|
||||
familyId: deviceEntryUnsafe.familyId,
|
||||
deviceId: deviceEntryUnsafe.deviceId,
|
||||
nextSequenceNumber: deviceEntryUnsafe.nextSequenceNumber
|
||||
}
|
||||
|
||||
const familyEntryUnsafe = await database.family.findOne({
|
||||
where: {
|
||||
familyId: deviceEntry.familyId
|
||||
},
|
||||
transaction,
|
||||
attributes: ['hasFullVersion']
|
||||
})
|
||||
|
||||
if (!familyEntryUnsafe) {
|
||||
throw new Error('missing family entry')
|
||||
}
|
||||
|
||||
const familyEntry = {
|
||||
hasFullVersion: familyEntryUnsafe.hasFullVersion
|
||||
}
|
||||
|
||||
const cache = new Cache({
|
||||
database,
|
||||
hasFullVersion: familyEntry.hasFullVersion,
|
||||
transaction,
|
||||
familyId: deviceEntry.familyId,
|
||||
connectedDevicesManager
|
||||
})
|
||||
|
||||
let { nextSequenceNumber } = deviceEntry
|
||||
|
||||
for (let i = 0; i < request.actions.length; i++) {
|
||||
const action = request.actions[i]
|
||||
|
||||
if (action.sequenceNumber < nextSequenceNumber) {
|
||||
// action was already received
|
||||
|
||||
cache.requireFullSync()
|
||||
continue
|
||||
}
|
||||
|
||||
try {
|
||||
// update the next sequence number
|
||||
nextSequenceNumber = action.sequenceNumber + 1
|
||||
|
||||
if (action.type === 'parent') {
|
||||
if (action.integrity === 'device') {
|
||||
const deviceEntryUnsafe2 = await cache.database.device.findOne({
|
||||
attributes: ['currentUserId'],
|
||||
where: {
|
||||
familyId: cache.familyId,
|
||||
deviceId: deviceEntry.deviceId,
|
||||
currentUserId: action.userId,
|
||||
isUserKeptSignedIn: true
|
||||
},
|
||||
transaction: cache.transaction
|
||||
})
|
||||
|
||||
if (!deviceEntryUnsafe2) {
|
||||
throw new Error('user is not signed in at this device')
|
||||
}
|
||||
|
||||
// this ensures that the parent exists
|
||||
await cache.getSecondPasswordHashOfParent(action.userId)
|
||||
} 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) {
|
||||
throw new Error('invalid integrity value')
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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) {
|
||||
throw new Error('invalid integrity value')
|
||||
}
|
||||
}
|
||||
|
||||
const parsedSerializedAction = JSON.parse(action.encodedAction)
|
||||
|
||||
if (action.type === 'appLogic') {
|
||||
if (!isSerializedAppLogicAction(parsedSerializedAction)) {
|
||||
throw new Error('invalid action: ' + action.encodedAction)
|
||||
}
|
||||
|
||||
const parsedAction = parseAppLogicAction(parsedSerializedAction)
|
||||
|
||||
await dispatchAppLogicAction({
|
||||
action: parsedAction,
|
||||
cache,
|
||||
deviceId: deviceEntry.deviceId
|
||||
})
|
||||
} else if (action.type === 'parent') {
|
||||
if (!isSerializedParentAction(parsedSerializedAction)) {
|
||||
throw new Error('invalid action' + action.encodedAction)
|
||||
}
|
||||
|
||||
const parsedAction = parseParentAction(parsedSerializedAction)
|
||||
|
||||
await dispatchParentAction({
|
||||
action: parsedAction,
|
||||
cache,
|
||||
parentUserId: action.userId,
|
||||
sourceDeviceId: deviceEntry.deviceId
|
||||
})
|
||||
} else if (action.type === 'child') {
|
||||
if (!isSerializedChildAction(parsedSerializedAction)) {
|
||||
throw new Error('invalid action: ' + action.encodedAction)
|
||||
}
|
||||
|
||||
const parsedAction = parseChildAction(parsedSerializedAction)
|
||||
|
||||
await dispatchChildAction({
|
||||
action: parsedAction,
|
||||
cache,
|
||||
childUserId: action.userId,
|
||||
deviceId: deviceEntry.deviceId
|
||||
})
|
||||
} else {
|
||||
throw new Error('illegal state')
|
||||
}
|
||||
} catch (ex) {
|
||||
cache.requireFullSync()
|
||||
}
|
||||
}
|
||||
|
||||
// save new next sequence number
|
||||
if (nextSequenceNumber !== deviceEntry.nextSequenceNumber) {
|
||||
await database.device.update({
|
||||
nextSequenceNumber
|
||||
}, {
|
||||
where: {
|
||||
familyId: deviceEntry.familyId,
|
||||
deviceId: deviceEntry.deviceId
|
||||
},
|
||||
transaction
|
||||
})
|
||||
}
|
||||
|
||||
await cache.saveModifiedVersionNumbers()
|
||||
|
||||
return {
|
||||
shouldDoFullSync: cache.shouldDoFullSync(),
|
||||
areChangesImportant: cache.areChangesImportant,
|
||||
sourceDeviceId: deviceEntry.deviceId,
|
||||
familyId: deviceEntry.familyId
|
||||
}
|
||||
})
|
||||
|
||||
await notifyClientsAboutChanges({
|
||||
familyId,
|
||||
sourceDeviceId,
|
||||
isImportant: areChangesImportant,
|
||||
websocket,
|
||||
database
|
||||
})
|
||||
|
||||
return { shouldDoFullSync }
|
||||
}
|
||||
@@ -0,0 +1,443 @@
|
||||
/*
|
||||
* server component for the TimeLimit App
|
||||
* Copyright (C) 2019 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 { difference, filter, intersection } from 'lodash'
|
||||
import * as Sequelize from 'sequelize'
|
||||
import { Database } from '../../database'
|
||||
import { ClientDataStatus } from '../../object/clientdatastatus'
|
||||
import {
|
||||
ServerDataStatus, ServerInstalledAppsData, ServerUpdatedCategoryAssignedApps,
|
||||
ServerUpdatedCategoryBaseData, ServerUpdatedCategoryUsedTimes,
|
||||
ServerUpdatedTimeLimitRules
|
||||
} from '../../object/serverdatastatus'
|
||||
|
||||
export const generateServerDataStatus = async ({ database, clientStatus, familyId, transaction }: {
|
||||
database: Database,
|
||||
clientStatus: ClientDataStatus,
|
||||
familyId: string
|
||||
transaction: Sequelize.Transaction
|
||||
}): Promise<ServerDataStatus> => {
|
||||
const familyEntryUnsafe = await database.family.findOne({
|
||||
where: {
|
||||
familyId
|
||||
},
|
||||
attributes: [
|
||||
'deviceListVersion',
|
||||
'userListVersion',
|
||||
'hasFullVersion',
|
||||
'fullVersionUntil'
|
||||
],
|
||||
transaction
|
||||
})
|
||||
|
||||
if (!familyEntryUnsafe) {
|
||||
throw new Error('illegal state')
|
||||
}
|
||||
|
||||
const familyEntry = {
|
||||
deviceListVersion: familyEntryUnsafe.deviceListVersion,
|
||||
userListVersion: familyEntryUnsafe.userListVersion,
|
||||
hasFullVersion: familyEntryUnsafe.hasFullVersion,
|
||||
fullVersionUntil: familyEntryUnsafe.fullVersionUntil
|
||||
}
|
||||
|
||||
let result: ServerDataStatus = {
|
||||
fullVersion: familyEntry.hasFullVersion ? parseInt(familyEntry.fullVersionUntil, 10) : 0,
|
||||
message: process.env.STATUS_MESSAGE || undefined
|
||||
}
|
||||
|
||||
if (familyEntry.deviceListVersion !== clientStatus.devices) {
|
||||
const devices = (await database.device.findAll({
|
||||
where: {
|
||||
familyId
|
||||
},
|
||||
transaction
|
||||
}))
|
||||
|
||||
result.devices = {
|
||||
version: familyEntry.deviceListVersion,
|
||||
data: devices.map((item) => ({
|
||||
deviceId: item.deviceId,
|
||||
name: item.name,
|
||||
model: item.model,
|
||||
addedAt: parseInt(item.addedAt, 10),
|
||||
currentUserId: item.currentUserId,
|
||||
networkTime: item.networkTime,
|
||||
cProtectionLevel: item.currentProtectionLevel,
|
||||
hProtectionLevel: item.highestProtectionLevel,
|
||||
cUsageStats: item.currentUsageStatsPermission,
|
||||
hUsageStats: item.highestUsageStatsPermission,
|
||||
cNotificationAccess: item.currentNotificationAccessPermission,
|
||||
hNotificationAccess: item.highestNotificationAccessPermission,
|
||||
cAppVersion: item.currentAppVersion,
|
||||
hAppVersion: item.highestAppVersion,
|
||||
tDisablingAdmin: item.triedDisablingDeviceAdmin,
|
||||
reboot: item.didReboot,
|
||||
hadManipulation: item.hadManipulation,
|
||||
reportUninstall: item.didDeviceReportUninstall,
|
||||
isUserKeptSignedIn: item.isUserKeptSignedIn,
|
||||
showDeviceConnected: item.showDeviceConnected,
|
||||
defUser: item.defaultUserId,
|
||||
defUserTimeout: item.defaultUserTimeout,
|
||||
rebootIsManipulation: item.considerRebootManipulation
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
||||
if (familyEntry.userListVersion !== clientStatus.users) {
|
||||
const users = (await database.user.findAll({
|
||||
where: {
|
||||
familyId
|
||||
},
|
||||
attributes: [
|
||||
'userId',
|
||||
'name',
|
||||
'passwordHash',
|
||||
'secondPasswordSalt',
|
||||
'type',
|
||||
'timeZone',
|
||||
'disableTimelimitsUntil',
|
||||
'mail',
|
||||
'currentDevice',
|
||||
'categoryForNotAssignedApps',
|
||||
'relaxPrimaryDeviceRule',
|
||||
'mailNotificationFlags'
|
||||
],
|
||||
transaction
|
||||
})).map((item) => ({
|
||||
userId: item.userId,
|
||||
name: item.name,
|
||||
passwordHash: item.passwordHash,
|
||||
secondPasswordSalt: item.secondPasswordSalt,
|
||||
type: item.type,
|
||||
timeZone: item.timeZone,
|
||||
disableTimelimitsUntil: item.disableTimelimitsUntil,
|
||||
mail: item.mail,
|
||||
currentDevice: item.currentDevice,
|
||||
categoryForNotAssignedApps: item.categoryForNotAssignedApps,
|
||||
relaxPrimaryDeviceRule: item.relaxPrimaryDeviceRule,
|
||||
mailNotificationFlags: item.mailNotificationFlags
|
||||
}))
|
||||
|
||||
result.users = {
|
||||
version: familyEntry.userListVersion,
|
||||
data: users.map((item) => ({
|
||||
id: item.userId,
|
||||
name: item.name,
|
||||
password: item.passwordHash,
|
||||
secondPasswordSalt: item.secondPasswordSalt,
|
||||
type: item.type,
|
||||
timeZone: item.timeZone,
|
||||
disableLimitsUntil: parseInt(item.disableTimelimitsUntil, 10),
|
||||
mail: item.mail,
|
||||
currentDevice: item.currentDevice,
|
||||
categoryForNotAssignedApps: item.categoryForNotAssignedApps,
|
||||
relaxPrimaryDevice: item.relaxPrimaryDeviceRule,
|
||||
mailNotificationFlags: item.mailNotificationFlags
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
||||
const serverInstalledAppsVersions = (await database.device.findAll({
|
||||
where: {
|
||||
familyId
|
||||
},
|
||||
attributes: ['deviceId', 'installedAppsVersion'],
|
||||
transaction
|
||||
})).map((item) => ({
|
||||
deviceId: item.deviceId,
|
||||
installedAppsVersion: item.installedAppsVersion
|
||||
}))
|
||||
|
||||
const getServerInstalledAppsVersionByDeviceId = (deviceId: string) => {
|
||||
const entry = serverInstalledAppsVersions.find((item) => item.deviceId === deviceId)
|
||||
|
||||
if (!entry) {
|
||||
throw new Error('illegal state')
|
||||
}
|
||||
|
||||
return entry.installedAppsVersion
|
||||
}
|
||||
|
||||
const serverDeviceIds = serverInstalledAppsVersions.map((item) => item.deviceId)
|
||||
const clientDeviceIds = Object.keys(clientStatus.apps)
|
||||
const addedDeviceIds = difference(serverDeviceIds, clientDeviceIds)
|
||||
const deviceIdsWhereInstalledAppsHaveChanged = filter(Object.keys(clientStatus.apps), (deviceId) => {
|
||||
const installedAppsVersion = clientStatus.apps[deviceId]
|
||||
|
||||
const serverEntry = serverInstalledAppsVersions.find((item) => item.deviceId === deviceId)
|
||||
|
||||
return !!serverEntry && serverEntry.installedAppsVersion !== installedAppsVersion
|
||||
})
|
||||
const idsOfDevicesWhereInstalledAppsMustBeSynced = [...addedDeviceIds, ...deviceIdsWhereInstalledAppsHaveChanged]
|
||||
|
||||
if (idsOfDevicesWhereInstalledAppsMustBeSynced.length > 0) {
|
||||
const dataToSync = (await database.app.findAll({
|
||||
where: {
|
||||
familyId,
|
||||
deviceId: {
|
||||
[Sequelize.Op.in]: idsOfDevicesWhereInstalledAppsMustBeSynced
|
||||
}
|
||||
},
|
||||
attributes: [
|
||||
'deviceId',
|
||||
'packageName',
|
||||
'title',
|
||||
'isLaunchable',
|
||||
'recommendation'
|
||||
],
|
||||
transaction
|
||||
})).map((item) => ({
|
||||
deviceId: item.deviceId,
|
||||
packageName: item.packageName,
|
||||
title: item.title,
|
||||
isLaunchable: item.isLaunchable,
|
||||
recommendation: item.recommendation
|
||||
}))
|
||||
|
||||
result.apps = idsOfDevicesWhereInstalledAppsMustBeSynced.map((deviceId): ServerInstalledAppsData => ({
|
||||
deviceId,
|
||||
apps: dataToSync.filter((item) => item.deviceId === deviceId).map((item) => ({
|
||||
packageName: item.packageName,
|
||||
title: item.title,
|
||||
isLaunchable: item.isLaunchable,
|
||||
recommendation: item.recommendation
|
||||
})),
|
||||
version: getServerInstalledAppsVersionByDeviceId(deviceId)
|
||||
}))
|
||||
}
|
||||
|
||||
const serverCategoriesVersions = (await database.category.findAll({
|
||||
where: {
|
||||
familyId
|
||||
},
|
||||
attributes: [
|
||||
'categoryId',
|
||||
'baseVersion',
|
||||
'assignedAppsVersion',
|
||||
'timeLimitRulesVersion',
|
||||
'usedTimesVersion'
|
||||
],
|
||||
transaction
|
||||
})).map((item) => ({
|
||||
categoryId: item.categoryId,
|
||||
baseVersion: item.baseVersion,
|
||||
assignedAppsVersion: item.assignedAppsVersion,
|
||||
timeLimitRulesVersion: item.timeLimitRulesVersion,
|
||||
usedTimesVersion: item.usedTimesVersion
|
||||
}))
|
||||
|
||||
const serverCategoryIds = serverCategoriesVersions.map((item) => item.categoryId)
|
||||
const clientCategoryIds = Object.keys(clientStatus.categories)
|
||||
|
||||
const removedCategoryIds = difference(clientCategoryIds, serverCategoryIds)
|
||||
|
||||
if (removedCategoryIds.length > 0) {
|
||||
result.rmCategories = removedCategoryIds
|
||||
}
|
||||
|
||||
const addedCategoryIds = difference(serverCategoryIds, clientCategoryIds)
|
||||
const categoryIdsOfClientAndServer = intersection(serverCategoryIds, clientCategoryIds)
|
||||
|
||||
const categoryIdsToSyncBaseData = [...addedCategoryIds]
|
||||
const categoryIdsToSyncAssignedApps = [...addedCategoryIds]
|
||||
const categoryIdsToSyncRules = [...addedCategoryIds]
|
||||
const categoryIdsToSyncUsedTimes = [...addedCategoryIds]
|
||||
|
||||
categoryIdsOfClientAndServer.forEach((categoryId) => {
|
||||
const serverEntry = serverCategoriesVersions.find((item) => item.categoryId === categoryId)
|
||||
const clientEntry = clientStatus.categories[categoryId]
|
||||
|
||||
if ((!serverEntry) || (!clientEntry)) {
|
||||
throw new Error('illegal state')
|
||||
}
|
||||
|
||||
if (serverEntry.baseVersion !== clientEntry.base) {
|
||||
categoryIdsToSyncBaseData.push(categoryId)
|
||||
}
|
||||
|
||||
if (serverEntry.assignedAppsVersion !== clientEntry.apps) {
|
||||
categoryIdsToSyncAssignedApps.push(categoryId)
|
||||
}
|
||||
|
||||
if (serverEntry.timeLimitRulesVersion !== clientEntry.rules) {
|
||||
categoryIdsToSyncRules.push(categoryId)
|
||||
}
|
||||
|
||||
if (serverEntry.usedTimesVersion !== clientEntry.usedTime) {
|
||||
categoryIdsToSyncUsedTimes.push(categoryId)
|
||||
}
|
||||
})
|
||||
|
||||
if (categoryIdsToSyncBaseData.length > 0) {
|
||||
const dataForSyncing = (await database.category.findAll({
|
||||
where: {
|
||||
familyId,
|
||||
categoryId: {
|
||||
[Sequelize.Op.in]: categoryIdsToSyncBaseData
|
||||
}
|
||||
},
|
||||
attributes: [
|
||||
'categoryId',
|
||||
'childId',
|
||||
'title',
|
||||
'blockedMinutesInWeek',
|
||||
'extraTimeInMillis',
|
||||
'temporarilyBlocked',
|
||||
'baseVersion',
|
||||
'parentCategoryId'
|
||||
],
|
||||
transaction
|
||||
})).map((item) => ({
|
||||
categoryId: item.categoryId,
|
||||
childId: item.childId,
|
||||
title: item.title,
|
||||
blockedMinutesInWeek: item.blockedMinutesInWeek,
|
||||
extraTimeInMillis: item.extraTimeInMillis,
|
||||
temporarilyBlocked: item.temporarilyBlocked,
|
||||
baseVersion: item.baseVersion,
|
||||
parentCategoryId: item.parentCategoryId
|
||||
}))
|
||||
|
||||
result.categoryBase = dataForSyncing.map((item): ServerUpdatedCategoryBaseData => ({
|
||||
categoryId: item.categoryId,
|
||||
childId: item.childId,
|
||||
title: item.title,
|
||||
blockedTimes: item.blockedMinutesInWeek,
|
||||
extraTime: item.extraTimeInMillis,
|
||||
tempBlocked: item.temporarilyBlocked,
|
||||
version: item.baseVersion,
|
||||
parentCategoryId: item.parentCategoryId
|
||||
}))
|
||||
}
|
||||
|
||||
if (categoryIdsToSyncAssignedApps.length > 0) {
|
||||
const dataForSyncing = (await database.categoryApp.findAll({
|
||||
where: {
|
||||
familyId,
|
||||
categoryId: {
|
||||
[Sequelize.Op.in]: categoryIdsToSyncAssignedApps
|
||||
}
|
||||
},
|
||||
attributes: ['categoryId', 'packageName'],
|
||||
transaction
|
||||
})).map((item) => ({
|
||||
categoryId: item.categoryId,
|
||||
packageName: item.packageName
|
||||
}))
|
||||
|
||||
const getCategoryAssingedAppsVersion = (categoryId: string) => {
|
||||
const categoryEntry = serverCategoriesVersions.find((item) => item.categoryId === categoryId)
|
||||
|
||||
if (!categoryEntry) {
|
||||
throw new Error('illegal state')
|
||||
}
|
||||
|
||||
return categoryEntry.assignedAppsVersion
|
||||
}
|
||||
|
||||
result.categoryApp = categoryIdsToSyncAssignedApps.map((categoryId): ServerUpdatedCategoryAssignedApps => ({
|
||||
categoryId,
|
||||
apps: dataForSyncing.filter((item) => item.categoryId === categoryId).map((item) => item.packageName),
|
||||
version: getCategoryAssingedAppsVersion(categoryId)
|
||||
}))
|
||||
}
|
||||
|
||||
if (categoryIdsToSyncRules.length > 0) {
|
||||
const dataForSyncing = (await database.timelimitRule.findAll({
|
||||
where: {
|
||||
familyId,
|
||||
categoryId: {
|
||||
[Sequelize.Op.in]: categoryIdsToSyncRules
|
||||
}
|
||||
},
|
||||
attributes: [
|
||||
'ruleId',
|
||||
'categoryId',
|
||||
'applyToExtraTimeUsage',
|
||||
'maximumTimeInMillis',
|
||||
'dayMaskAsBitmask'
|
||||
],
|
||||
transaction
|
||||
})).map((item) => ({
|
||||
ruleId: item.ruleId,
|
||||
categoryId: item.categoryId,
|
||||
applyToExtraTimeUsage: item.applyToExtraTimeUsage,
|
||||
maximumTimeInMillis: item.maximumTimeInMillis,
|
||||
dayMaskAsBitmask: item.dayMaskAsBitmask
|
||||
}))
|
||||
|
||||
const getCategoryRulesVersion = (categoryId: string) => {
|
||||
const categoryEntry = serverCategoriesVersions.find((item) => item.categoryId === categoryId)
|
||||
|
||||
if (!categoryEntry) {
|
||||
throw new Error('illegal state')
|
||||
}
|
||||
|
||||
return categoryEntry.timeLimitRulesVersion
|
||||
}
|
||||
|
||||
result.rules = categoryIdsToSyncRules.map((categoryId): ServerUpdatedTimeLimitRules => ({
|
||||
categoryId,
|
||||
rules: dataForSyncing.filter((item) => item.categoryId === categoryId).map((item) => ({
|
||||
id: item.ruleId,
|
||||
extraTime: item.applyToExtraTimeUsage,
|
||||
dayMask: item.dayMaskAsBitmask,
|
||||
maxTime: item.maximumTimeInMillis
|
||||
})),
|
||||
version: getCategoryRulesVersion(categoryId)
|
||||
}))
|
||||
}
|
||||
|
||||
if (categoryIdsToSyncUsedTimes.length > 0) {
|
||||
const dataForSyncing = (await database.usedTime.findAll({
|
||||
where: {
|
||||
familyId,
|
||||
categoryId: {
|
||||
[Sequelize.Op.in]: categoryIdsToSyncUsedTimes
|
||||
}
|
||||
},
|
||||
attributes: ['categoryId', 'dayOfEpoch', 'usedTime'],
|
||||
transaction
|
||||
})).map((item) => ({
|
||||
categoryId: item.categoryId,
|
||||
dayOfEpoch: item.dayOfEpoch,
|
||||
usedTime: item.usedTime
|
||||
}))
|
||||
|
||||
const getCategoryUsedTimesVersion = (categoryId: string) => {
|
||||
const categoryEntry = serverCategoriesVersions.find((item) => item.categoryId === categoryId)
|
||||
|
||||
if (!categoryEntry) {
|
||||
throw new Error('illegal state')
|
||||
}
|
||||
|
||||
return categoryEntry.usedTimesVersion
|
||||
}
|
||||
|
||||
result.usedTimes = categoryIdsToSyncUsedTimes.map((categoryId): ServerUpdatedCategoryUsedTimes => ({
|
||||
categoryId,
|
||||
times: dataForSyncing.filter((item) => item.categoryId === categoryId).map((item) => ({
|
||||
day: item.dayOfEpoch,
|
||||
time: item.usedTime
|
||||
})),
|
||||
version: getCategoryUsedTimesVersion(categoryId)
|
||||
}))
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
import * as Sequelize from 'sequelize'
|
||||
import { Database } from '../../database'
|
||||
import { sendManipulationWarningMail } from '../../util/mail'
|
||||
import { canSendWarningMail } from '../../util/ratelimit-warningmail'
|
||||
|
||||
export const sendManipulationWarnings = async ({ database, familyId, deviceName, transaction }: {
|
||||
database: Database
|
||||
familyId: string
|
||||
deviceName: string
|
||||
transaction: Sequelize.Transaction
|
||||
}) => {
|
||||
const parentEntries = await database.user.findAll({
|
||||
where: {
|
||||
familyId,
|
||||
type: 'parent'
|
||||
},
|
||||
transaction
|
||||
})
|
||||
|
||||
const targetMailAddresses = parentEntries
|
||||
.filter((item) => item.mail !== '')
|
||||
.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 })
|
||||
}
|
||||
})
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
import { Database } from '../../database'
|
||||
import { sendUninstallWarningMail } from '../../util/mail'
|
||||
import { canSendWarningMail } from '../../util/ratelimit-warningmail'
|
||||
|
||||
export const sendUninstallWarnings = async ({ database, familyId, deviceName }: {
|
||||
database: Database
|
||||
familyId: string
|
||||
deviceName: string
|
||||
}) => {
|
||||
const parentEntries = await database.user.findAll({
|
||||
where: {
|
||||
familyId,
|
||||
type: 'parent'
|
||||
}
|
||||
})
|
||||
|
||||
const targetMailAddresses = parentEntries
|
||||
.filter((item) => item.mail !== '')
|
||||
.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 })
|
||||
}
|
||||
})
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
/*
|
||||
* server component for the TimeLimit App
|
||||
* Copyright (C) 2019 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 * as Sequelize from 'sequelize'
|
||||
import { Database } from '../../database'
|
||||
import { WebsocketApi } from '../../websocket'
|
||||
|
||||
// this should be called AFTER an transaction was commited
|
||||
export const notifyClientsAboutChanges = async ({ familyId, sourceDeviceId, database, websocket, isImportant }: {
|
||||
familyId: string
|
||||
sourceDeviceId: string | null // this device will not get an push
|
||||
database: Database
|
||||
websocket: WebsocketApi
|
||||
isImportant: boolean
|
||||
}) => {
|
||||
const relatedDeviceEntries = (await database.device.findAll({
|
||||
where: sourceDeviceId ? {
|
||||
familyId,
|
||||
deviceId: {
|
||||
[Sequelize.Op.not]: sourceDeviceId
|
||||
}
|
||||
} : {
|
||||
familyId
|
||||
},
|
||||
attributes: ['deviceAuthToken']
|
||||
})).map((item) => ({
|
||||
deviceAuthToken: item.deviceAuthToken
|
||||
}))
|
||||
|
||||
relatedDeviceEntries.forEach((item) => {
|
||||
websocket.triggerSyncByDeviceAuthToken({
|
||||
deviceAuthToken: item.deviceAuthToken,
|
||||
isImportant
|
||||
})
|
||||
})
|
||||
}
|
||||
Reference in New Issue
Block a user