mirror of
https://github.com/clusterio/clusterio.git
synced 2026-11-20 07:43:12 +09:00
Refactor User and Role into data classes (#531)
Use the JSON data class pattern for User, Role, and PlayerStats and move them into lib/src/data. This means that User is purely data now and can't reference role objects directly. To make it possible easily check permissions attached to roles and store data only visible on the controller on user objects a ControllerUser type is introduced which is linked with the UserManager and can therefore reference role objects directly. Resolves #525.
This commit is contained in:
1 parent
f802e6ba67
commit
e453a80155
37 files changed
+629
-613
No files matched your search
@@ -0,0 +1,23 @@
|
||||
import { Static, Type } from "@sinclair/typebox";
|
||||
|
||||
/**
|
||||
* Represents a permission that can be granted
|
||||
*/
|
||||
export default class Permission {
|
||||
constructor(
|
||||
public name: string,
|
||||
public title: string,
|
||||
public description: string,
|
||||
public grantByDefault?: boolean,
|
||||
) { }
|
||||
|
||||
static jsonSchema = Type.Object({
|
||||
name: Type.String(),
|
||||
title: Type.String(),
|
||||
description: Type.String(),
|
||||
});
|
||||
|
||||
static fromJSON(json: Static<typeof this.jsonSchema>) {
|
||||
return new this(json.name, json.title, json.description);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
import { Type, Static } from "@sinclair/typebox";
|
||||
|
||||
/**
|
||||
* Stastics collected about a player.
|
||||
*/
|
||||
export default class PlayerStats {
|
||||
/**
|
||||
* Count of the number of times this player has been seen joining this server.
|
||||
*/
|
||||
joinCount = 0;
|
||||
|
||||
/**
|
||||
* Time in ms this player has been seen online on this instance.
|
||||
*/
|
||||
onlineTimeMs = 0;
|
||||
|
||||
/**
|
||||
* Timestamp the player was last seen joining.
|
||||
*/
|
||||
lastJoinAt?: Date;
|
||||
|
||||
/**
|
||||
* Timestamp the player was last seen leaving.
|
||||
*/
|
||||
lastLeaveAt?: Date;
|
||||
|
||||
/**
|
||||
* Reason the player was last seen leaving with.
|
||||
*/
|
||||
lastLeaveReason?: string;
|
||||
|
||||
static jsonSchema = Type.Object({
|
||||
"join_count": Type.Optional(Type.Integer()),
|
||||
"online_time_ms": Type.Optional(Type.Number()),
|
||||
"last_join_at": Type.Optional(Type.Number()),
|
||||
"last_leave_at": Type.Optional(Type.Number()),
|
||||
"last_leave_reason": Type.Optional(Type.String()),
|
||||
});
|
||||
|
||||
constructor(json: Static<typeof PlayerStats.jsonSchema> = {}) {
|
||||
if (json["join_count"]) {
|
||||
this.joinCount = json["join_count"];
|
||||
}
|
||||
if (json["online_time_ms"]) {
|
||||
this.onlineTimeMs = json["online_time_ms"];
|
||||
}
|
||||
if (json["last_join_at"]) {
|
||||
this.lastJoinAt = new Date(json["last_join_at"]);
|
||||
}
|
||||
if (json["last_leave_at"]) {
|
||||
this.lastLeaveAt = new Date(json["last_leave_at"]);
|
||||
this.lastLeaveReason = json["last_leave_reason"] || "quit";
|
||||
}
|
||||
}
|
||||
|
||||
static fromJSON(json: Static<typeof PlayerStats.jsonSchema>) {
|
||||
return new this(json);
|
||||
}
|
||||
|
||||
toJSON() {
|
||||
let json: Static<typeof PlayerStats.jsonSchema> = {};
|
||||
if (this.joinCount) {
|
||||
json["join_count"] = this.joinCount;
|
||||
}
|
||||
if (this.onlineTimeMs) {
|
||||
json["online_time_ms"] = this.onlineTimeMs;
|
||||
}
|
||||
if (this.lastJoinAt) {
|
||||
json["last_join_at"] = this.lastJoinAt.getTime();
|
||||
}
|
||||
if (this.lastLeaveAt) {
|
||||
json["last_leave_at"] = this.lastLeaveAt.getTime();
|
||||
json["last_leave_reason"] = this.lastLeaveReason;
|
||||
}
|
||||
return json;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
import { Static, Type } from "@sinclair/typebox";
|
||||
import { permissions as globalPermissions } from "../permissions";
|
||||
|
||||
/**
|
||||
* Represents a collection of granted permissions
|
||||
*/
|
||||
export default class Role {
|
||||
constructor(
|
||||
public id: number,
|
||||
public name: string,
|
||||
public description: string,
|
||||
public permissions: Set<string>,
|
||||
) { }
|
||||
|
||||
static jsonSchema = Type.Object({
|
||||
id: Type.Number(),
|
||||
name: Type.String(),
|
||||
description: Type.String(),
|
||||
permissions: Type.Array(Type.String()),
|
||||
});
|
||||
|
||||
static fromJSON(json: Static<typeof this.jsonSchema>) {
|
||||
return new this(
|
||||
json.id,
|
||||
json.name,
|
||||
json.description,
|
||||
new Set(json.permissions),
|
||||
);
|
||||
}
|
||||
|
||||
toJSON() {
|
||||
return {
|
||||
id: this.id,
|
||||
name: this.name,
|
||||
description: this.description,
|
||||
permissions: [...this.permissions],
|
||||
};
|
||||
}
|
||||
|
||||
grantDefaultPermissions() {
|
||||
for (let permission of globalPermissions.values()) {
|
||||
if (permission.grantByDefault) {
|
||||
this.permissions.add(permission.name);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
import { Static, Type } from "@sinclair/typebox";
|
||||
|
||||
import PlayerStats from "./PlayerStats";
|
||||
|
||||
/**
|
||||
* Represeents a user in the cluster
|
||||
*
|
||||
* Holds data about a Factorio user in the cluster.
|
||||
*/
|
||||
export default class User {
|
||||
constructor(
|
||||
/** Factorio user name. */
|
||||
public name: string,
|
||||
/** Roles this user has */
|
||||
public roleIds = new Set<number>(),
|
||||
/** Instances this user is online on. */
|
||||
public instances = new Set<number>(),
|
||||
/** True if the user is promoted to admin on the Factorio instances. */
|
||||
public isAdmin = false,
|
||||
/** True if the user is banned from Factorio instances. */
|
||||
public isBanned = false,
|
||||
/** True if the user is whitelisted on the Factorio instances. */
|
||||
public isWhitelisted = false,
|
||||
/** Reason for being banned. Ignored if isBanned is false. */
|
||||
public banReason = "",
|
||||
/** True if this user object has been removed from the cluster. */
|
||||
public isDeleted = false,
|
||||
/** Combined statistics for the player this user account is tied to. */
|
||||
public playerStats = new PlayerStats(),
|
||||
/** Per instance statistics for the player this user account is tied to. */
|
||||
public instanceStats = new Map<number, PlayerStats>(),
|
||||
) {
|
||||
}
|
||||
|
||||
static jsonSchema = Type.Object({
|
||||
name: Type.String(),
|
||||
roles: Type.Optional(Type.Array(Type.Integer())),
|
||||
instances: Type.Optional(Type.Array(Type.Integer())),
|
||||
is_admin: Type.Optional(Type.Boolean()),
|
||||
is_banned: Type.Optional(Type.Boolean()),
|
||||
is_whitelisted: Type.Optional(Type.Boolean()),
|
||||
ban_reason: Type.Optional(Type.String()),
|
||||
is_deleted: Type.Optional(Type.Boolean()),
|
||||
instance_stats: Type.Optional(
|
||||
Type.Array(
|
||||
Type.Tuple([Type.Integer(), PlayerStats.jsonSchema]),
|
||||
)
|
||||
),
|
||||
});
|
||||
|
||||
static fromJSON(json: Static<typeof this.jsonSchema>, _hack?: any) {
|
||||
const roleIds = new Set<number>(json.roles ?? []);
|
||||
const instanceStats = new Map(
|
||||
(json.instance_stats ?? []).map(
|
||||
([id, stats]) => [id, PlayerStats.fromJSON(stats)]
|
||||
)
|
||||
);
|
||||
const playerStats = User._calculatePlayerStats(instanceStats);
|
||||
return new this(
|
||||
json.name,
|
||||
roleIds,
|
||||
new Set(json.instances),
|
||||
json.is_admin,
|
||||
json.is_banned,
|
||||
json.is_whitelisted,
|
||||
json.ban_reason,
|
||||
json.is_deleted,
|
||||
playerStats,
|
||||
instanceStats,
|
||||
);
|
||||
}
|
||||
|
||||
toJSON() {
|
||||
let json: Static<typeof User.jsonSchema> = {
|
||||
name: this.name,
|
||||
};
|
||||
|
||||
if (this.roleIds.size) {
|
||||
json.roles = [...this.roleIds];
|
||||
}
|
||||
|
||||
if (this.instances.size) {
|
||||
json.instances = [...this.instances];
|
||||
}
|
||||
|
||||
if (this.isAdmin) {
|
||||
json.is_admin = true;
|
||||
}
|
||||
|
||||
if (this.isWhitelisted) {
|
||||
json.is_whitelisted = true;
|
||||
}
|
||||
|
||||
if (this.isBanned) {
|
||||
json.is_banned = true;
|
||||
}
|
||||
|
||||
if (this.banReason) {
|
||||
json.ban_reason = this.banReason;
|
||||
}
|
||||
|
||||
if (this.isDeleted) {
|
||||
json.is_deleted = this.isDeleted;
|
||||
}
|
||||
|
||||
if (this.instanceStats.size) {
|
||||
json.instance_stats = [...this.instanceStats].map(([id, stats]) => [id, stats.toJSON()]);
|
||||
}
|
||||
|
||||
return json;
|
||||
}
|
||||
|
||||
recalculatePlayerStats() {
|
||||
this.playerStats = User._calculatePlayerStats(this.instanceStats);
|
||||
}
|
||||
|
||||
static _calculatePlayerStats(instanceStatsMap: Map<number, PlayerStats>) {
|
||||
let playerStats = new PlayerStats();
|
||||
for (let instanceStats of instanceStatsMap.values()) {
|
||||
if (
|
||||
instanceStats.lastJoinAt
|
||||
&& (!playerStats.lastJoinAt || instanceStats.lastJoinAt > playerStats.lastJoinAt)
|
||||
) {
|
||||
playerStats.lastJoinAt = instanceStats.lastJoinAt;
|
||||
}
|
||||
if (
|
||||
instanceStats.lastLeaveAt
|
||||
&& (!playerStats.lastLeaveAt || instanceStats.lastLeaveAt > playerStats.lastLeaveAt)
|
||||
) {
|
||||
playerStats.lastLeaveAt = instanceStats.lastLeaveAt;
|
||||
playerStats.lastLeaveReason = instanceStats.lastLeaveReason;
|
||||
}
|
||||
playerStats.joinCount += instanceStats.joinCount;
|
||||
playerStats.onlineTimeMs += instanceStats.onlineTimeMs;
|
||||
}
|
||||
return playerStats;
|
||||
}
|
||||
}
|
||||
|
||||
export interface IControllerUser extends User {
|
||||
/**
|
||||
* Check if a given permission is granted
|
||||
*
|
||||
* Checks the roles the user is member of for one that grants the given
|
||||
* permission. If the permission is not granted for the user a
|
||||
* "Permission denied" error is thrown.
|
||||
*
|
||||
* @param permission - The permission to check for.
|
||||
* @throws {Error} If the given permission does not exist.
|
||||
* @throws {libErrors.PermissionError} if the user does noh have the given permission.
|
||||
*/
|
||||
checkPermission(permission: string): void
|
||||
}
|
||||
@@ -7,6 +7,10 @@ export { default as ExportManifest } from "./ExportManifest";
|
||||
export { default as ModInfo } from "./ModInfo";
|
||||
export { default as ModPack, ModSetting, ModRecord } from "./ModPack";
|
||||
export { default as ModuleInfo } from "./ModuleInfo";
|
||||
export { default as Permission } from "./Permission";
|
||||
export { default as PlayerStats } from "./PlayerStats";
|
||||
export { default as Role } from "./Role";
|
||||
export { default as User, IControllerUser } from "./User";
|
||||
export * from "./composites";
|
||||
export * from "./messages_core";
|
||||
export * from "./messages_controller";
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import { Type, Static } from "@sinclair/typebox";
|
||||
import PlayerStats from "../PlayerStats";
|
||||
import PlayerStats from "./PlayerStats";
|
||||
import { JsonString, StringEnum, jsonArray } from "./composites";
|
||||
import { RawConfig } from "../config";
|
||||
import type { User } from "../users";
|
||||
import type { IControllerUser } from "./User";
|
||||
import type { MessageRequest } from "./messages_core";
|
||||
import { CollectorResultSerialized } from "../prometheus";
|
||||
|
||||
@@ -433,7 +433,7 @@ export class InstanceTransferSaveRequest {
|
||||
static type = "request" as const;
|
||||
static src = ["control", "controller"] as const;
|
||||
static dst = ["controller", "host"] as const;
|
||||
static permission(user: User, message: MessageRequest) {
|
||||
static permission(user: IControllerUser, message: MessageRequest) {
|
||||
user.checkPermission("core.instance.save.transfer");
|
||||
if (typeof message.data === "object" && message.data !== null) {
|
||||
const data = message.data as { copy: boolean, sourceName: string, targetName: string };
|
||||
|
||||
@@ -1,52 +1,16 @@
|
||||
import { Type, Static } from "@sinclair/typebox";
|
||||
import PlayerStats from "../PlayerStats";
|
||||
import Permission from "./Permission";
|
||||
import Role from "./Role";
|
||||
import User from "./User";
|
||||
import { JsonNumber, jsonArray } from "./composites";
|
||||
|
||||
export class RawPermission { // TODO refactor into lib/user.Permission
|
||||
constructor(
|
||||
public name: string,
|
||||
public title: string,
|
||||
public description: string,
|
||||
) { }
|
||||
|
||||
static jsonSchema = Type.Object({
|
||||
name: Type.String(),
|
||||
title: Type.String(),
|
||||
description: Type.String(),
|
||||
});
|
||||
|
||||
static fromJSON(json: Static<typeof this.jsonSchema>) {
|
||||
return new this(json.name, json.title, json.description);
|
||||
}
|
||||
}
|
||||
|
||||
export class PermissionListRequest {
|
||||
declare ["constructor"]: typeof PermissionListRequest;
|
||||
static type = "request" as const;
|
||||
static src = "control" as const;
|
||||
static dst = "controller" as const;
|
||||
static permission = "core.permission.list" as const;
|
||||
static Response = jsonArray(RawPermission);
|
||||
}
|
||||
|
||||
export class RawRole { // TODO refactor into lib/user.Role
|
||||
constructor(
|
||||
public id: number,
|
||||
public name: string,
|
||||
public description: string,
|
||||
public permissions: string[],
|
||||
) { }
|
||||
|
||||
static jsonSchema = Type.Object({
|
||||
id: Type.Integer(),
|
||||
name: Type.String(),
|
||||
description: Type.String(),
|
||||
permissions: Type.Array(Type.String()),
|
||||
});
|
||||
|
||||
static fromJSON(json: Static<typeof this.jsonSchema>) {
|
||||
return new this(json.id, json.name, json.description, json.permissions);
|
||||
}
|
||||
static Response = jsonArray(Permission);
|
||||
}
|
||||
|
||||
export class RoleListRequest {
|
||||
@@ -55,7 +19,7 @@ export class RoleListRequest {
|
||||
static src = "control" as const;
|
||||
static dst = "controller" as const;
|
||||
static permission = "core.role.list" as const;
|
||||
static Response = jsonArray(RawRole);
|
||||
static Response = jsonArray(Role);
|
||||
}
|
||||
|
||||
export class RoleCreateRequest {
|
||||
@@ -150,75 +114,6 @@ export class RoleDeleteRequest {
|
||||
}
|
||||
}
|
||||
|
||||
export class RawUser { // TODO refactor into lib/user.User
|
||||
constructor(
|
||||
public name: string,
|
||||
public roles: number[],
|
||||
public instances: number[],
|
||||
public isAdmin?: boolean,
|
||||
public isBanned?: boolean,
|
||||
public isWhitelisted?: boolean,
|
||||
public banReason?: string,
|
||||
public isDeleted?: boolean,
|
||||
public playerStats?: PlayerStats,
|
||||
public instanceStats?: Map<number, PlayerStats>,
|
||||
) { }
|
||||
|
||||
static jsonSchema = Type.Object({
|
||||
name: Type.String(),
|
||||
roles: Type.Array(Type.Integer()),
|
||||
instances: Type.Array(Type.Integer()),
|
||||
isAdmin: Type.Optional(Type.Boolean()),
|
||||
isBanned: Type.Optional(Type.Boolean()),
|
||||
isWhitelisted: Type.Optional(Type.Boolean()),
|
||||
banReason: Type.Optional(Type.String()),
|
||||
isDeleted: Type.Optional(Type.Boolean()),
|
||||
playerStats: Type.Optional(PlayerStats.jsonSchema),
|
||||
instanceStats: Type.Optional(
|
||||
Type.Array(
|
||||
Type.Tuple([Type.Integer(), PlayerStats.jsonSchema]),
|
||||
)
|
||||
),
|
||||
});
|
||||
|
||||
static fromJSON(json: Static<typeof this.jsonSchema>) {
|
||||
let playerStats: PlayerStats | undefined;
|
||||
if (json.playerStats) {
|
||||
playerStats = PlayerStats.fromJSON(json.playerStats);
|
||||
}
|
||||
let instanceStats: Map<number, PlayerStats> | undefined;
|
||||
if (json.instanceStats) {
|
||||
instanceStats = new Map(
|
||||
json.instanceStats.map(([id, stats]) => [id, PlayerStats.fromJSON(stats)])
|
||||
);
|
||||
}
|
||||
return new this(
|
||||
json.name, json.roles, json.instances, json.isAdmin, json.isBanned, json.isWhitelisted, json.banReason,
|
||||
json.isDeleted, playerStats, instanceStats
|
||||
);
|
||||
}
|
||||
|
||||
toJSON() {
|
||||
const json: Static<typeof RawUser.jsonSchema> = {
|
||||
name: this.name,
|
||||
roles: this.roles,
|
||||
instances: this.instances,
|
||||
isAdmin: this.isAdmin,
|
||||
isBanned: this.isBanned,
|
||||
isWhitelisted: this.isWhitelisted,
|
||||
banReason: this.banReason,
|
||||
isDeleted: this.isDeleted,
|
||||
};
|
||||
if (this.playerStats) {
|
||||
json.playerStats = this.playerStats.toJSON();
|
||||
}
|
||||
if (this.instanceStats) {
|
||||
json.instanceStats = [...this.instanceStats].map(([k, v]) => [k, v.toJSON()]);
|
||||
}
|
||||
return json;
|
||||
}
|
||||
}
|
||||
|
||||
export class UserGetRequest {
|
||||
declare ["constructor"]: typeof UserGetRequest;
|
||||
static type = "request" as const;
|
||||
@@ -238,7 +133,7 @@ export class UserGetRequest {
|
||||
return new this(json.name);
|
||||
}
|
||||
|
||||
static Response = RawUser;
|
||||
static Response = User;
|
||||
}
|
||||
|
||||
export class UserListRequest {
|
||||
@@ -247,7 +142,7 @@ export class UserListRequest {
|
||||
static src = "control" as const;
|
||||
static dst = "controller" as const;
|
||||
static permission = "core.user.list" as const;
|
||||
static Response = jsonArray(RawUser);
|
||||
static Response = jsonArray(User);
|
||||
}
|
||||
|
||||
export class UserCreateRequest {
|
||||
@@ -414,15 +309,15 @@ export class UserUpdateEvent {
|
||||
static permission = "core.user.subscribe" as const;
|
||||
|
||||
constructor(
|
||||
public user: RawUser,
|
||||
public user: User,
|
||||
) { }
|
||||
|
||||
static jsonSchema = Type.Object({
|
||||
"user": RawUser.jsonSchema,
|
||||
"user": User.jsonSchema,
|
||||
});
|
||||
|
||||
static fromJSON(json: Static<typeof this.jsonSchema>) {
|
||||
return new this(RawUser.fromJSON(json.user));
|
||||
return new this(User.fromJSON(json.user));
|
||||
}
|
||||
|
||||
get subscriptionChannel() {
|
||||
|
||||
Reference in new issue
Block a user