mirror of
https://github.com/clusterio/clusterio.git
synced 2026-11-21 08:03:13 +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
@@ -253,7 +253,7 @@ export async function resolveModPack(client: Link, modPackName: string) {
|
||||
export async function retrieveRole(client: Link, roleName: string) {
|
||||
let roles = await client.sendTo("controller", new libData.RoleListRequest());
|
||||
|
||||
let resolvedRole: libData.RawRole | undefined;
|
||||
let resolvedRole: libData.Role | undefined;
|
||||
if (/^-?\d+$/.test(roleName)) {
|
||||
let roleId = parseInt(roleName, 10);
|
||||
for (let role of roles) {
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
File renamed without changes.
@@ -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() {
|
||||
|
||||
@@ -7,8 +7,9 @@ import { dataClasses } from "./messages";
|
||||
import { BaseConnector, WebSocketBaseConnector } from "./connectors";
|
||||
import { strict as assert } from "assert";
|
||||
import type { PluginNodeEnvInfo, PluginWebpackEnvInfo } from "../plugin";
|
||||
import type { User } from "../users";
|
||||
import type { AddressType, JSONDeserialisable, MessageRoutable, MessageRequest, MessageEvent } from "../data";
|
||||
import type {
|
||||
AddressType, JSONDeserialisable, MessageRoutable, MessageRequest, MessageEvent, IControllerUser,
|
||||
} from "../data";
|
||||
|
||||
export interface Request<Req, Res> {
|
||||
constructor: Partial<JSONDeserialisable<Req & Request<Req, Res>>> & {
|
||||
@@ -17,7 +18,7 @@ export interface Request<Req, Res> {
|
||||
type: "request";
|
||||
src: AddressType | readonly AddressType[];
|
||||
dst: AddressType | readonly AddressType[];
|
||||
permission?: null | string | ((user: User, message: MessageRequest) => void);
|
||||
permission?: null | string | ((user: IControllerUser, message: MessageRequest) => void);
|
||||
plugin?: string;
|
||||
Response?: JSONDeserialisable<Res>,
|
||||
}
|
||||
@@ -31,7 +32,7 @@ export interface Event<T> {
|
||||
type: "event";
|
||||
src: AddressType | readonly AddressType[];
|
||||
dst: AddressType | readonly AddressType[];
|
||||
permission?: null | string | ((user: User, message: MessageEvent) => void);
|
||||
permission?: null | string | ((user: IControllerUser, message: MessageEvent) => void);
|
||||
plugin?: string;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,22 +6,9 @@
|
||||
* @author Hornwitser
|
||||
* @module lib/users
|
||||
*/
|
||||
import * as libErrors from "./errors";
|
||||
|
||||
import PlayerStats from "./PlayerStats";
|
||||
import { Permission, Role } from "./data";
|
||||
|
||||
|
||||
/**
|
||||
* Represents a permission that can be granted
|
||||
*/
|
||||
export class Permission {
|
||||
constructor(
|
||||
public name: string,
|
||||
public title: string,
|
||||
public description: string,
|
||||
public grantByDefault: boolean,
|
||||
) { }
|
||||
}
|
||||
export const permissions = new Map<string, Permission>();
|
||||
|
||||
/**
|
||||
@@ -70,40 +57,6 @@ export function definePermission({
|
||||
permissions.set(name, new Permission(name, title, description, grantByDefault));
|
||||
}
|
||||
|
||||
/**
|
||||
* Represents a collection of granted permissions
|
||||
*/
|
||||
export class Role {
|
||||
id: number;
|
||||
name: string;
|
||||
description: string;
|
||||
permissions: Set<string>;
|
||||
|
||||
constructor(serializedRole: ReturnType<Role["serialize"]>) {
|
||||
this.id = serializedRole.id;
|
||||
this.name = serializedRole.name;
|
||||
this.description = serializedRole.description;
|
||||
this.permissions = new Set(serializedRole.permissions);
|
||||
}
|
||||
|
||||
serialize() {
|
||||
return {
|
||||
id: this.id,
|
||||
name: this.name,
|
||||
description: this.description,
|
||||
permissions: [...this.permissions],
|
||||
};
|
||||
}
|
||||
|
||||
grantDefaultPermissions() {
|
||||
for (let permission of permissions.values()) {
|
||||
if (permission.grantByDefault) {
|
||||
this.permissions.add(permission.name);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Ensure the default admin role has full access
|
||||
@@ -116,7 +69,7 @@ export class Role {
|
||||
export function ensureDefaultAdminRole(roles: Map<number, Role>) {
|
||||
let admin = roles.get(0);
|
||||
if (!admin) {
|
||||
admin = new Role({
|
||||
admin = Role.fromJSON({
|
||||
id: 0,
|
||||
name: "Cluster Admin",
|
||||
description: "Cluster wide administrator.",
|
||||
@@ -140,7 +93,7 @@ export function ensureDefaultAdminRole(roles: Map<number, Role>) {
|
||||
export function ensureDefaultPlayerRole(roles: Map<number, Role>) {
|
||||
let player = roles.get(1);
|
||||
if (!player) {
|
||||
player = new Role({
|
||||
player = Role.fromJSON({
|
||||
id: 1,
|
||||
name: "Player",
|
||||
description: "Default player role.",
|
||||
@@ -152,188 +105,6 @@ export function ensureDefaultPlayerRole(roles: Map<number, Role>) {
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Represeents a user in the cluster
|
||||
*
|
||||
* Holds data about a Factorio user in the cluster.
|
||||
*/
|
||||
export class User {
|
||||
/** Factorio user name. */
|
||||
name: string;
|
||||
/** Instances this user is online on. */
|
||||
instances: Set<number>;
|
||||
/** Unix time in seconds the user token must be issued after to be valid. */
|
||||
tokenValidAfter: number;
|
||||
/** True if the user is promoted to admin on the Factorio instances. */
|
||||
isAdmin: boolean;
|
||||
/** True if the user is whitelisted on the Factorio instances. */
|
||||
isWhitelisted: boolean;
|
||||
/** True if the user is banned from Factorio instances. */
|
||||
isBanned: boolean;
|
||||
/** Reason for being banned. Ignored if isBanned is false. */
|
||||
banReason: string;
|
||||
/** Roles this user has */
|
||||
roles: Set<Role>;
|
||||
/** Per instance statistics for the player this user account is tied to. */
|
||||
instanceStats: Map<number, PlayerStats>;
|
||||
/** Combined statistics for the player this user account is tied to. */
|
||||
playerStats: PlayerStats;
|
||||
/** True if this user object has been removed from the cluster. */
|
||||
isDeleted: boolean;
|
||||
|
||||
constructor(
|
||||
serializedUser: ReturnType<User["serialize"]>,
|
||||
loadedRoles: Map<number, Role>
|
||||
) {
|
||||
this.name = serializedUser.name;
|
||||
this.instances = new Set();
|
||||
this.tokenValidAfter = serializedUser.token_valid_after || 0;
|
||||
this.isAdmin = Boolean(serializedUser.is_admin);
|
||||
this.isWhitelisted = Boolean(serializedUser.is_whitelisted);
|
||||
this.isBanned = Boolean(serializedUser.is_banned);
|
||||
this.banReason = serializedUser.ban_reason || "";
|
||||
this.roles = new Set();
|
||||
if (serializedUser.roles) {
|
||||
for (let roleId of serializedUser.roles) {
|
||||
let role = loadedRoles.get(roleId);
|
||||
if (role) {
|
||||
this.roles.add(role);
|
||||
}
|
||||
}
|
||||
}
|
||||
this.instanceStats = new Map(
|
||||
(serializedUser.instance_stats ? serializedUser.instance_stats : []).map(
|
||||
([id, stats]) => [id, new PlayerStats(stats)]
|
||||
)
|
||||
);
|
||||
this.playerStats = this._calculatePlayerStats();
|
||||
this.isDeleted = false;
|
||||
}
|
||||
|
||||
serialize() {
|
||||
let serialized: {
|
||||
name: string,
|
||||
roles?: number[],
|
||||
token_valid_after?: number,
|
||||
is_admin?: boolean,
|
||||
is_whitelisted?: boolean,
|
||||
is_banned?: boolean,
|
||||
ban_reason?: string,
|
||||
instance_stats?: [number, object][],
|
||||
} = {
|
||||
name: this.name,
|
||||
};
|
||||
|
||||
if (this.roles.size) {
|
||||
serialized.roles = [...this.roles].map(role => role.id);
|
||||
}
|
||||
|
||||
if (this.tokenValidAfter) {
|
||||
serialized.token_valid_after = this.tokenValidAfter;
|
||||
}
|
||||
|
||||
if (this.isAdmin) {
|
||||
serialized.is_admin = true;
|
||||
}
|
||||
|
||||
if (this.isWhitelisted) {
|
||||
serialized.is_whitelisted = true;
|
||||
}
|
||||
|
||||
if (this.isBanned) {
|
||||
serialized.is_banned = true;
|
||||
}
|
||||
|
||||
if (this.banReason) {
|
||||
serialized.ban_reason = this.banReason;
|
||||
}
|
||||
|
||||
if (this.instanceStats.size) {
|
||||
serialized.instance_stats = [...this.instanceStats].map(([id, stats]) => [id, stats.toJSON()]);
|
||||
}
|
||||
|
||||
return serialized;
|
||||
}
|
||||
|
||||
/**
|
||||
* Invalidate current tokens for the user
|
||||
*
|
||||
* Sets the tokenValidAfter property to the current time, which causes
|
||||
* all currently issued tokens for the user to become invalid.
|
||||
*/
|
||||
invalidateToken() {
|
||||
this.tokenValidAfter = Math.floor(Date.now() / 1000);
|
||||
}
|
||||
|
||||
/**
|
||||
* 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) {
|
||||
if (!permissions.has(permission)) {
|
||||
throw new Error(`permission ${permission} does not exist`);
|
||||
}
|
||||
|
||||
for (let role of this.roles) {
|
||||
if (role.permissions.has("core.admin") || role.permissions.has(permission)) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
throw new libErrors.PermissionError("Permission denied");
|
||||
}
|
||||
|
||||
notifyJoin(instance_id: number) {
|
||||
this.instances.add(instance_id);
|
||||
User.onlineUsers.add(this);
|
||||
}
|
||||
|
||||
notifyLeave(instance_id: number) {
|
||||
this.instances.delete(instance_id);
|
||||
if (!this.instances.size) {
|
||||
User.onlineUsers.delete(this);
|
||||
}
|
||||
}
|
||||
|
||||
recalculatePlayerStats() {
|
||||
this.playerStats = this._calculatePlayerStats();
|
||||
}
|
||||
|
||||
_calculatePlayerStats() {
|
||||
let playerStats = new PlayerStats();
|
||||
for (let instanceStats of this.instanceStats.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;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set of users currently online in the cluster.
|
||||
*/
|
||||
static onlineUsers = new Set<User>();
|
||||
}
|
||||
|
||||
// Definitions for the built in permissions used in Clusterio.
|
||||
// description should answer "this permission allows you to ___"
|
||||
definePermission({
|
||||
@@ -5,7 +5,7 @@
|
||||
import * as libHelpers from "./helpers";
|
||||
import type { Logger } from "./logging";
|
||||
import type { PluginConfigGroup } from "./config";
|
||||
import type PlayerStats from "./PlayerStats";
|
||||
import type { PlayerStats } from "./data";
|
||||
|
||||
// TODO Add proper typing for plugins
|
||||
/* Used to define the export of info.ts from plugins */
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import { Type, Static } from "@sinclair/typebox";
|
||||
import { Link, Event, EventClass, RequestHandler, WebSocketClientConnector, WebSocketBaseConnector } from "./link";
|
||||
import { Address, MessageRequest } from "./data";
|
||||
import { User } from "./users";
|
||||
import { Address, MessageRequest, IControllerUser } from "./data";
|
||||
|
||||
export type SubscriptionRequestHandler<T> = RequestHandler<SubscriptionRequest, Event<T> | null>;
|
||||
export type EventSubscriberCallback<T> = (value: T) => void;
|
||||
@@ -69,7 +68,7 @@ export class SubscriptionRequest {
|
||||
static src = ["control", "instance"] as const;
|
||||
static dst = "controller" as const;
|
||||
static Response = SubscriptionResponse;
|
||||
static permission(user: User, message: MessageRequest) {
|
||||
static permission(user: IControllerUser, message: MessageRequest) {
|
||||
if (typeof message.data === "object" && message.data !== null) {
|
||||
const data = message.data as Static<typeof SubscriptionRequest.jsonSchema>;
|
||||
const entry = Link._eventsByName.get(data[0]);
|
||||
|
||||
Reference in new issue
Block a user