Add limit login category support

This commit is contained in:
Jonas Lochmann
2020-06-29 02:00:00 +02:00
parent 7e7caae583
commit 5574ad415c
25 changed files with 666 additions and 51 deletions
+1
View File
@@ -67,3 +67,4 @@ export { UpdateParentBlockedTimesAction } from './updateparentblockedtimes'
export { UpdateParentNotificationFlagsAction } from './updateparentnotificationflags'
export { UpdateTimelimitRuleAction } from './updatetimelimitrule'
export { UpdateUserFlagsAction } from './updateuserflags'
export { UpdateUserLimitLoginCategory } from './updateuserlimitlogincategory'
+5 -1
View File
@@ -56,6 +56,7 @@ import { SerializedUpdateParentBlockedTimesAction, UpdateParentBlockedTimesActio
import { SerializedUpdateParentNotificationFlagsAction, UpdateParentNotificationFlagsAction } from '../updateparentnotificationflags'
import { SerializedUpdateTimelimitRuleAction, UpdateTimelimitRuleAction } from '../updatetimelimitrule'
import { SerializedUpdateUserFlagsAction, UpdateUserFlagsAction } from '../updateuserflags'
import { SerializedUpdateUserLimitLoginCategory, UpdateUserLimitLoginCategory } from '../updateuserlimitlogincategory'
export type SerializedParentAction =
SerializedAddCategoryAppsAction |
@@ -97,7 +98,8 @@ export type SerializedParentAction =
SerializedUpdateParentBlockedTimesAction |
SerializedUpdateParentNotificationFlagsAction |
SerializedUpdateTimelimitRuleAction |
SerializedUpdateUserFlagsAction
SerializedUpdateUserFlagsAction |
SerializedUpdateUserLimitLoginCategory
export const parseParentAction = (action: SerializedParentAction): ParentAction => {
if (action.type === 'ADD_CATEGORY_APPS') {
@@ -180,6 +182,8 @@ export const parseParentAction = (action: SerializedParentAction): ParentAction
return UpdateTimelimitRuleAction.parse(action)
} else if (action.type === 'UPDATE_USER_FLAGS') {
return UpdateUserFlagsAction.parse(action)
} else if (action.type === 'UPDATE_USER_LIMIT_LOGIN_CATEGORY') {
return UpdateUserLimitLoginCategory.parse(action)
} else {
throw new Error('illegal state: invalid type for action at parseParentAction')
}
@@ -0,0 +1,59 @@
/*
* server component for the TimeLimit App
* Copyright (C) 2019 - 2020 Jonas Lochmann
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, version 3 of the License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import { assertIdWithinFamily } from '../util/token'
import { ParentAction } from './basetypes'
export class UpdateUserLimitLoginCategory extends ParentAction {
readonly userId: string
readonly categoryId?: string
constructor ({ userId, categoryId }: {
userId: string,
categoryId?: string
}) {
super()
assertIdWithinFamily(userId)
if (categoryId !== undefined) {
assertIdWithinFamily(categoryId)
}
this.userId = userId
this.categoryId = categoryId
}
serialize = (): SerializedUpdateUserLimitLoginCategory => ({
type: 'UPDATE_USER_LIMIT_LOGIN_CATEGORY',
userId: this.userId,
categoryId: this.categoryId
})
static parse = ({ userId, categoryId }: SerializedUpdateUserLimitLoginCategory) => (
new UpdateUserLimitLoginCategory({
userId,
categoryId
})
)
}
export interface SerializedUpdateUserLimitLoginCategory {
type: 'UPDATE_USER_LIMIT_LOGIN_CATEGORY'
userId: string
categoryId?: string
}
+28
View File
@@ -1152,6 +1152,28 @@ const definitions = {
"values"
]
},
"SerializedUpdateUserLimitLoginCategory": {
"type": "object",
"properties": {
"type": {
"type": "string",
"enum": [
"UPDATE_USER_LIMIT_LOGIN_CATEGORY"
]
},
"userId": {
"type": "string"
},
"categoryId": {
"type": "string"
}
},
"additionalProperties": false,
"required": [
"type",
"userId"
]
},
"SerializedAddInstalledAppsAction": {
"type": "object",
"properties": {
@@ -2079,6 +2101,9 @@ const definitions = {
},
"flags": {
"type": "number"
},
"llc": {
"type": "string"
}
},
"additionalProperties": false,
@@ -2418,6 +2443,9 @@ export const isSerializedParentAction: (value: object) => value is SerializedPar
},
{
"$ref": "#/definitions/SerializedUpdateUserFlagsAction"
},
{
"$ref": "#/definitions/SerializedUpdateUserLimitLoginCategory"
}
],
"definitions": definitions,
+4 -1
View File
@@ -1,6 +1,6 @@
/*
* server component for the TimeLimit App
* Copyright (C) 2019 Jonas Lochmann
* Copyright (C) 2019 - 2020 Jonas Lochmann
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
@@ -33,6 +33,7 @@ import { createSessionDurationModel, SessionDurationModelStatic } from './sessio
import { createTimelimitRuleModel, TimelimitRuleModelStatic } from './timelimitrule'
import { createUsedTimeModel, UsedTimeModelStatic } from './usedtime'
import { createUserModel, UserModelStatic } from './user'
import { createUserLimitLoginCategoryModel, UserLimitLoginCategoryModelStatic } from './userlimitlogincategory'
export interface Database {
addDeviceToken: AddDeviceTokenModelStatic
@@ -51,6 +52,7 @@ export interface Database {
timelimitRule: TimelimitRuleModelStatic
usedTime: UsedTimeModelStatic
user: UserModelStatic
userLimitLoginCategory: UserLimitLoginCategoryModelStatic
transaction: <T> (autoCallback: (t: Sequelize.Transaction) => Promise<T>) => Promise<T>
}
@@ -71,6 +73,7 @@ const createDatabase = (sequelize: Sequelize.Sequelize): Database => ({
timelimitRule: createTimelimitRuleModel(sequelize),
usedTime: createUsedTimeModel(sequelize),
user: createUserModel(sequelize),
userLimitLoginCategory: createUserLimitLoginCategoryModel(sequelize),
transaction: <T> (autoCallback: (transaction: Sequelize.Transaction) => Promise<T>) => (sequelize.transaction({
isolationLevel: Sequelize.Transaction.ISOLATION_LEVELS.READ_COMMITTED
}, autoCallback) as any) as Promise<T>
@@ -0,0 +1,41 @@
/*
* server component for the TimeLimit App
* Copyright (C) 2019 - 2020 Jonas Lochmann
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, version 3 of the License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import { QueryInterface, Sequelize, Transaction } from 'sequelize'
export async function up (queryInterface: QueryInterface, sequelize: Sequelize) {
await sequelize.transaction({
type: Transaction.TYPES.EXCLUSIVE
}, async (transaction) => {
await sequelize.query(
'CREATE TABLE `UserLimitLoginCategories`' +
'(`familyId` TEXT NOT NULL, `userId` TEXT NOT NULL, `categoryId` TEXT NOT NULL,' +
'PRIMARY KEY(`familyId`, `userId`), FOREIGN KEY(`familyId`, `userId`) REFERENCES `Users`(`familyId`, `userId`) ON UPDATE CASCADE ON DELETE CASCADE , FOREIGN KEY(`familyId`, `categoryId`) REFERENCES `Categories`(`familyId`, `categoryId`) ON UPDATE CASCADE ON DELETE CASCADE )',
{ transaction }
)
await sequelize.query('CREATE INDEX `UserLimitLoginCategoriesIndexCategoryId` ON `UserLimitLoginCategories` (`familyId`, `categoryId`)', { transaction })
})
}
export async function down (queryInterface: QueryInterface, sequelize: Sequelize) {
await sequelize.transaction({
type: Transaction.TYPES.EXCLUSIVE
}, async (transaction) => {
await queryInterface.dropTable('UserLimitLoginCategories', { transaction })
})
}
+39
View File
@@ -0,0 +1,39 @@
/*
* server component for the TimeLimit App
* Copyright (C) 2019 - 2020 Jonas Lochmann
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, version 3 of the License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import * as Sequelize from 'sequelize'
import { familyIdColumn, idWithinFamilyColumn } from './columns'
import { SequelizeAttributes } from './types'
export interface UserLimitLoginCategoryAttributes {
familyId: string
userId: string
categoryId: string
}
export type UserLimitLoginCategoryModel = Sequelize.Model & UserLimitLoginCategoryAttributes
export type UserLimitLoginCategoryModelStatic = typeof Sequelize.Model & {
new (values?: object, options?: Sequelize.BuildOptions): UserLimitLoginCategoryModel;
}
export const attributes: SequelizeAttributes<UserLimitLoginCategoryAttributes> = {
familyId: { ...familyIdColumn, primaryKey: true },
userId: { ...idWithinFamilyColumn, primaryKey: true },
categoryId: { ...idWithinFamilyColumn }
}
export const createUserLimitLoginCategoryModel = (sequelize: Sequelize.Sequelize): UserLimitLoginCategoryModelStatic => sequelize.define('UserLimitLoginCategory', attributes) as UserLimitLoginCategoryModelStatic
@@ -56,7 +56,8 @@ import {
UpdateParentBlockedTimesAction,
UpdateParentNotificationFlagsAction,
UpdateTimelimitRuleAction,
UpdateUserFlagsAction
UpdateUserFlagsAction,
UpdateUserLimitLoginCategory
} from '../../../../action'
import { Cache } from '../cache'
import { dispatchAddCategoryApps } from './addcategoryapps'
@@ -99,6 +100,7 @@ import { dispatchUpdateParentBlockedTimes } from './updateparentblockedtimes'
import { dispatchUpdateParentNotificationFlags } from './updateparentnotificationflags'
import { dispatchUpdateTimelimitRule } from './updatetimelimitrule'
import { dispatchUpdateUserFlagsAction } from './updateuserflags'
import { dispatchUpdateUserLimitLoginCategoryAction } from './updateuserlimitlogincategory'
export const dispatchParentAction = async ({ action, cache, parentUserId, sourceDeviceId }: {
action: ParentAction
@@ -183,9 +185,11 @@ export const dispatchParentAction = async ({ action, cache, parentUserId, source
} else if (action instanceof ResetParentBlockedTimesAction) {
await dispatchResetParentBlockedTimes({ action, cache })
} else if (action instanceof UpdateParentBlockedTimesAction) {
await dispatchUpdateParentBlockedTimes({ action, cache })
await dispatchUpdateParentBlockedTimes({ action, cache, parentUserId })
} else if (action instanceof UpdateUserFlagsAction) {
await dispatchUpdateUserFlagsAction({ action, cache })
} else if (action instanceof UpdateUserLimitLoginCategory) {
await dispatchUpdateUserLimitLoginCategoryAction({ action, cache, parentUserId })
} else {
throw new Error('unsupported action type')
}
@@ -17,6 +17,7 @@
import { createHash } from 'crypto'
import { InternalServerError } from 'http-errors'
import { difference } from 'lodash'
import * as Sequelize from 'sequelize'
import { RemoveUserAction } from '../../../../action'
import { Cache } from '../cache'
@@ -71,6 +72,29 @@ export async function dispatchRemoveUser ({ action, cache, parentUserId }: {
throw new Error('this user is the last one with a linked mail address')
}
}
const usersWithLimitLoginCategories = (await cache.database.userLimitLoginCategory.findAll({
transaction: cache.transaction,
where: {
familyId: cache.familyId
},
attributes: ['userId']
})).map((item) => item.userId)
const allParentUserIds = (await cache.database.user.findAll({
transaction: cache.transaction,
where: {
familyId: cache.familyId,
type: 'parent'
},
attributes: ['userId']
})).map((item) => item.userId)
const allOtherParentUserIds = allParentUserIds.filter((item) => item !== action.userId)
if (difference(allOtherParentUserIds, usersWithLimitLoginCategories).length === 0) {
throw new Error('can not delete the last user without limit login category')
}
}
if (user.type === 'child') {
@@ -1,6 +1,6 @@
/*
* server component for the TimeLimit App
* Copyright (C) 2019 Jonas Lochmann
* Copyright (C) 2019 - 2020 Jonas Lochmann
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
@@ -18,10 +18,15 @@
import { UpdateParentBlockedTimesAction } from '../../../../action'
import { Cache } from '../cache'
export async function dispatchUpdateParentBlockedTimes ({ action, cache }: {
export async function dispatchUpdateParentBlockedTimes ({ action, cache, parentUserId }: {
action: UpdateParentBlockedTimesAction
cache: Cache
parentUserId: string
}) {
if (parentUserId !== action.parentId && action.blockedTimes !== '') {
throw new Error('only a parent itself can add limits')
}
const [affectedRows] = await cache.database.user.update({
blockedTimes: action.blockedTimes
}, {
@@ -0,0 +1,77 @@
/*
* server component for the TimeLimit App
* Copyright (C) 2019 - 2020 Jonas Lochmann
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, version 3 of the License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import { UpdateUserLimitLoginCategory } from '../../../../action'
import { Cache } from '../cache'
export async function dispatchUpdateUserLimitLoginCategoryAction ({ action, cache, parentUserId }: {
action: UpdateUserLimitLoginCategory
cache: Cache
parentUserId: string
}) {
const userEntry = await cache.database.user.findOne({
where: {
familyId: cache.familyId,
userId: action.userId
},
transaction: cache.transaction
})
if (!userEntry) {
throw new Error('user not found')
}
if (userEntry.type !== 'parent') {
throw new Error('user must be a parent')
}
if (action.categoryId !== undefined && parentUserId !== action.userId) {
throw new Error('only the user itself can add a limit')
}
await cache.database.userLimitLoginCategory.destroy({
where: {
familyId: cache.familyId,
userId: action.userId
},
transaction: cache.transaction
})
if (action.categoryId !== undefined) {
const categoryEntry = await cache.database.category.findOne({
where: {
familyId: cache.familyId,
categoryId: action.categoryId
},
transaction: cache.transaction
})
if (!categoryEntry) {
throw new Error('category must exist')
}
await cache.database.userLimitLoginCategory.create({
familyId: cache.familyId,
userId: action.userId,
categoryId: action.categoryId
}, {
transaction: cache.transaction
})
}
cache.invalidiateUserList = true
}
+26 -1
View File
@@ -146,6 +146,30 @@ export const generateServerDataStatus = async ({ database, clientStatus, familyI
flags: item.flags
}))
const limitLoginCategories = (await database.userLimitLoginCategory.findAll({
where: {
familyId
},
attributes: [
'userId',
'categoryId'
],
transaction
})).map((item) => ({
userId: item.userId,
categoryId: item.categoryId
}))
const getLimitLoginCategory = (userId: string) => {
const item = limitLoginCategories.find((item) => item.userId === userId)
if (item) {
return item.categoryId
} else {
return undefined
}
}
result.users = {
version: familyEntry.userListVersion,
data: users.map((item) => ({
@@ -162,7 +186,8 @@ export const generateServerDataStatus = async ({ database, clientStatus, familyI
relaxPrimaryDevice: item.relaxPrimaryDeviceRule,
mailNotificationFlags: item.mailNotificationFlags,
blockedTimes: item.blockedTimes,
flags: parseInt(item.flags, 10)
flags: parseInt(item.flags, 10),
llc: getLimitLoginCategory(item.userId)
}))
}
}
+1
View File
@@ -59,6 +59,7 @@ export interface ServerUserEntry {
mailNotificationFlags: number
blockedTimes: string
flags: number
llc?: string // limit login category
}
export interface ServerDeviceData {