mirror of
https://github.com/clusterio/clusterio.git
synced 2026-11-16 23:30:41 +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
@@ -9,6 +9,7 @@ import * as lib from "@clusterio/lib";
|
||||
const { logFilter, logger } = lib;
|
||||
|
||||
import BaseConnection from "./BaseConnection";
|
||||
import ControllerUser from "./ControllerUser";
|
||||
import * as routes from "./routes";
|
||||
import Controller from "./Controller";
|
||||
|
||||
@@ -43,7 +44,7 @@ export default class ControlConnection extends BaseConnection {
|
||||
registerData: { agent:string, version:string },
|
||||
connector: WsServerConnector,
|
||||
controller: Controller,
|
||||
public user: lib.User, // The user making this connection.
|
||||
public user: ControllerUser, // The user making this connection.
|
||||
public id: number
|
||||
) {
|
||||
super(connector, controller);
|
||||
@@ -635,28 +636,11 @@ export default class ControlConnection extends BaseConnection {
|
||||
}
|
||||
|
||||
async handlePermissionListRequest() {
|
||||
let list = [];
|
||||
for (let permission of lib.permissions.values()) {
|
||||
list.push(new lib.RawPermission(
|
||||
permission.name,
|
||||
permission.title,
|
||||
permission.description,
|
||||
));
|
||||
}
|
||||
return list;
|
||||
return [...lib.permissions.values()];
|
||||
}
|
||||
|
||||
async handleRoleListRequest() {
|
||||
let list = [];
|
||||
for (let role of this._controller.userManager.roles.values()) {
|
||||
list.push(new lib.RawRole(
|
||||
role.id,
|
||||
role.name,
|
||||
role.description,
|
||||
[...role.permissions],
|
||||
));
|
||||
}
|
||||
return list;
|
||||
return [...this._controller.userManager.roles.values()];
|
||||
}
|
||||
|
||||
async handleRoleCreateRequest(request: lib.RoleCreateRequest) {
|
||||
@@ -664,7 +648,7 @@ export default class ControlConnection extends BaseConnection {
|
||||
|
||||
// Start at 5 to leave space for future default roles
|
||||
let id = Math.max(5, lastId+1);
|
||||
this._controller.userManager.roles.set(id, new lib.Role({ id, ...request }));
|
||||
this._controller.userManager.roles.set(id, lib.Role.fromJSON({ id, ...request }));
|
||||
this._controller.userManager.dirty = true;
|
||||
return id;
|
||||
}
|
||||
@@ -694,57 +678,31 @@ export default class ControlConnection extends BaseConnection {
|
||||
|
||||
async handleRoleDeleteRequest(request: lib.RoleDeleteRequest) {
|
||||
let id = request.id;
|
||||
let role = this._controller.userManager.roles.get(id);
|
||||
if (!role) {
|
||||
|
||||
if (!this._controller.userManager.roles.delete(id)) {
|
||||
throw new lib.RequestError(`Role with ID ${id} does not exist`);
|
||||
}
|
||||
|
||||
this._controller.userManager.roles.delete(id);
|
||||
this._controller.userManager.dirty = true;
|
||||
|
||||
for (let user of this._controller.userManager.users.values()) {
|
||||
user.roles.delete(role);
|
||||
this._controller.userPermissionsUpdated(user);
|
||||
if (user.roleIds.delete(id)) {
|
||||
this._controller.userPermissionsUpdated(user);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async handleUserGetRequest(request: lib.UserGetRequest) {
|
||||
async handleUserGetRequest(request: lib.UserGetRequest): Promise<lib.User> {
|
||||
let name = request.name;
|
||||
let user = this._controller.userManager.users.get(name);
|
||||
if (!user) {
|
||||
throw new lib.RequestError(`User ${name} does not exist`);
|
||||
}
|
||||
|
||||
return new lib.RawUser(
|
||||
user.name,
|
||||
[...user.roles].map(role => role.id),
|
||||
[...user.instances],
|
||||
user.isAdmin,
|
||||
user.isBanned,
|
||||
user.isWhitelisted,
|
||||
user.banReason,
|
||||
undefined,
|
||||
user.playerStats,
|
||||
user.instanceStats,
|
||||
);
|
||||
return user;
|
||||
}
|
||||
|
||||
async handleUserListRequest() {
|
||||
let list = [];
|
||||
for (let user of this._controller.userManager.users.values()) {
|
||||
list.push(new lib.RawUser(
|
||||
user.name,
|
||||
[...user.roles].map(role => role.id),
|
||||
[...user.instances],
|
||||
user.isAdmin,
|
||||
user.isBanned,
|
||||
user.isWhitelisted,
|
||||
undefined,
|
||||
undefined,
|
||||
user.playerStats,
|
||||
undefined,
|
||||
));
|
||||
}
|
||||
return list;
|
||||
async handleUserListRequest(): Promise<lib.User[]> {
|
||||
return [...this._controller.userManager.users.values()];
|
||||
}
|
||||
|
||||
async handleUserCreateRequest(request: lib.UserCreateRequest) {
|
||||
@@ -776,17 +734,13 @@ export default class ControlConnection extends BaseConnection {
|
||||
throw new lib.RequestError(`User '${request.name}' does not exist`);
|
||||
}
|
||||
|
||||
let resolvedRoles: Set<lib.Role> = new Set();
|
||||
for (let roleId of request.roles) {
|
||||
let role = this._controller.userManager.roles.get(roleId);
|
||||
if (!role) {
|
||||
if (!this._controller.userManager.roles.has(roleId)) {
|
||||
throw new lib.RequestError(`Role with ID ${roleId} does not exist`);
|
||||
}
|
||||
|
||||
resolvedRoles.add(role);
|
||||
}
|
||||
|
||||
user.roles = resolvedRoles;
|
||||
user.roleIds = new Set(request.roles);
|
||||
this._controller.userPermissionsUpdated(user);
|
||||
this._controller.userUpdated(user);
|
||||
}
|
||||
|
||||
@@ -19,6 +19,7 @@ import HttpCloser from "./HttpCloser";
|
||||
import InstanceInfo, { InstanceStatus } from "./InstanceInfo";
|
||||
import * as metrics from "./metrics";
|
||||
import * as routes from "./routes";
|
||||
import ControllerUser from "./ControllerUser";
|
||||
import UserManager from "./UserManager";
|
||||
import WsServer from "./WsServer";
|
||||
import HostConnection, { type HostInfo } from "./HostConnection";
|
||||
@@ -879,22 +880,9 @@ export default class Controller {
|
||||
lib.invokeHook(this.plugins, "onModUpdated", mod);
|
||||
}
|
||||
|
||||
userUpdated(user: lib.User) {
|
||||
userUpdated(user: ControllerUser) {
|
||||
this.userManager.dirty = true;
|
||||
this.subscriptions.broadcast(new lib.UserUpdateEvent(
|
||||
new lib.RawUser(
|
||||
user.name,
|
||||
[...user.roles].map(role => role.id),
|
||||
[...user.instances],
|
||||
user.isAdmin,
|
||||
user.isBanned,
|
||||
user.isWhitelisted,
|
||||
user.banReason,
|
||||
user.isDeleted,
|
||||
user.playerStats,
|
||||
user.instanceStats,
|
||||
)
|
||||
));
|
||||
this.subscriptions.broadcast(new lib.UserUpdateEvent(user));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -902,7 +890,7 @@ export default class Controller {
|
||||
* permissions for this user may have changed.
|
||||
* @param user - User permisions updated for.
|
||||
*/
|
||||
userPermissionsUpdated(user: lib.User) {
|
||||
userPermissionsUpdated(user: ControllerUser) {
|
||||
for (let controlConnection of this.wsServer.controlConnections.values()) {
|
||||
if (controlConnection.user === user) {
|
||||
controlConnection.send(
|
||||
|
||||
@@ -0,0 +1,92 @@
|
||||
import { Static, Type } from "@sinclair/typebox";
|
||||
import { IControllerUser, PermissionError, PlayerStats, Role, User, permissions } from "@clusterio/lib";
|
||||
import type UserManager from "./UserManager";
|
||||
|
||||
export default class ControllerUser extends User implements IControllerUser {
|
||||
constructor(
|
||||
public userManager: UserManager,
|
||||
/** Unix time in seconds the user token must be issued after to be valid. */
|
||||
public tokenValidAfter = 0,
|
||||
...args: ConstructorParameters<typeof User>
|
||||
) {
|
||||
super(...args);
|
||||
}
|
||||
|
||||
static jsonSchema = Type.Object({
|
||||
...User.jsonSchema.properties,
|
||||
token_valid_after: Type.Optional(Type.Number()),
|
||||
});
|
||||
|
||||
static fromJSON(json: Static<typeof this.jsonSchema>, userManager: UserManager) {
|
||||
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(
|
||||
userManager,
|
||||
json.token_valid_after,
|
||||
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(controller?: boolean): Static<typeof ControllerUser.jsonSchema> {
|
||||
if (!controller) {
|
||||
return super.toJSON();
|
||||
}
|
||||
|
||||
const json: Static<typeof ControllerUser.jsonSchema> = super.toJSON();
|
||||
if (this.tokenValidAfter) {
|
||||
json.token_valid_after = this.tokenValidAfter;
|
||||
}
|
||||
|
||||
return json;
|
||||
}
|
||||
|
||||
get roles(): ReadonlySet<Readonly<Role>> {
|
||||
return new Set([...this.roleIds].map(
|
||||
id => this.userManager.roles.get(id)
|
||||
).filter(
|
||||
(r): r is Role => Boolean(r)
|
||||
));
|
||||
}
|
||||
|
||||
/**
|
||||
* 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);
|
||||
}
|
||||
|
||||
checkPermission(permission: string) {
|
||||
if (!permissions.has(permission)) {
|
||||
throw new Error(`permission ${permission} does not exist`);
|
||||
}
|
||||
|
||||
for (let roleId of this.roleIds) {
|
||||
let role = this.userManager.roles.get(roleId);
|
||||
if (!role) {
|
||||
continue;
|
||||
}
|
||||
if (role.permissions.has("core.admin") || role.permissions.has(permission)) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
throw new PermissionError("Permission denied");
|
||||
}
|
||||
}
|
||||
@@ -2,7 +2,7 @@ import type Controller from "./Controller";
|
||||
import type WsServerConnector from "./WsServerConnector";
|
||||
|
||||
import * as lib from "@clusterio/lib";
|
||||
const { logger, PlayerStats } = lib;
|
||||
const { logger } = lib;
|
||||
|
||||
import BaseConnection from "./BaseConnection";
|
||||
import InstanceInfo, { InstanceStatus } from "./InstanceInfo";
|
||||
@@ -272,7 +272,6 @@ export default class HostConnection extends BaseConnection {
|
||||
}
|
||||
|
||||
async handleInstancePlayerUpdateEvent(event: lib.InstancePlayerUpdateEvent, src: lib.Address) {
|
||||
|
||||
let instanceId = src.id;
|
||||
let user = this._controller.userManager.users.get(event.name);
|
||||
if (!user) {
|
||||
@@ -280,9 +279,9 @@ export default class HostConnection extends BaseConnection {
|
||||
}
|
||||
|
||||
if (event.type === "join") {
|
||||
user.notifyJoin(instanceId);
|
||||
this._controller.userManager.notifyJoin(user, instanceId);
|
||||
} else if (event.type === "leave") {
|
||||
user.notifyLeave(instanceId);
|
||||
this._controller.userManager.notifyLeave(user, instanceId);
|
||||
}
|
||||
|
||||
if (event.stats) {
|
||||
|
||||
@@ -3,15 +3,22 @@ import jwt from "jsonwebtoken";
|
||||
|
||||
import * as lib from "@clusterio/lib";
|
||||
|
||||
import ControllerUser from "./ControllerUser";
|
||||
|
||||
/**
|
||||
* Manages users and roles
|
||||
* @alias module:controller/src/UserManager
|
||||
*/
|
||||
export default class UserManager {
|
||||
roles: Map<number, lib.Role> = new Map();
|
||||
users: Map<string, lib.User> = new Map();
|
||||
users: Map<string, ControllerUser> = new Map();
|
||||
dirty = false;
|
||||
|
||||
/**
|
||||
* Set of users currently online in the cluster.
|
||||
*/
|
||||
onlineUsers = new Set<ControllerUser>();
|
||||
|
||||
constructor(
|
||||
private _config: lib.ControllerConfig
|
||||
) {
|
||||
@@ -21,12 +28,12 @@ export default class UserManager {
|
||||
try {
|
||||
let content = JSON.parse(await fs.readFile(filePath, { encoding: "utf8" }));
|
||||
for (let serializedRole of content.roles) {
|
||||
let role = new lib.Role(serializedRole);
|
||||
let role = lib.Role.fromJSON(serializedRole);
|
||||
this.roles.set(role.id, role);
|
||||
}
|
||||
|
||||
for (let serializedUser of content.users) {
|
||||
let user = new lib.User(serializedUser, this.roles);
|
||||
let user = ControllerUser.fromJSON(serializedUser, this);
|
||||
this.users.set(user.name, user);
|
||||
}
|
||||
|
||||
@@ -44,12 +51,12 @@ export default class UserManager {
|
||||
async save(filePath:string): Promise<void> {
|
||||
let serializedRoles = [];
|
||||
for (let role of this.roles.values()) {
|
||||
serializedRoles.push(role.serialize());
|
||||
serializedRoles.push(role.toJSON());
|
||||
}
|
||||
|
||||
let serializedUsers = [];
|
||||
for (let user of this.users.values()) {
|
||||
serializedUsers.push(user.serialize());
|
||||
serializedUsers.push(user.toJSON(true));
|
||||
}
|
||||
|
||||
let serialized = {
|
||||
@@ -65,18 +72,18 @@ export default class UserManager {
|
||||
* @param name - Name of the user to create.
|
||||
* @returns The created user.
|
||||
*/
|
||||
createUser(name:string): lib.User {
|
||||
createUser(name:string): ControllerUser {
|
||||
if (this.users.has(name)) {
|
||||
throw new Error(`User '${name}' already exists`);
|
||||
}
|
||||
|
||||
let roles = [];
|
||||
let roles = new Set<number>();
|
||||
let defaultRoleId = this._config.get("controller.default_role_id");
|
||||
if (defaultRoleId !== null) {
|
||||
roles.push(defaultRoleId);
|
||||
if (defaultRoleId !== null && this.roles.has(defaultRoleId)) {
|
||||
roles.add(defaultRoleId);
|
||||
}
|
||||
|
||||
let user = new lib.User({ name, roles }, this.roles);
|
||||
let user = new ControllerUser(this, 0, name, roles);
|
||||
this.users.set(name, user);
|
||||
this.dirty = true;
|
||||
return user;
|
||||
@@ -94,4 +101,16 @@ export default class UserManager {
|
||||
Buffer.from(this._config.get("controller.auth_secret"), "base64")
|
||||
);
|
||||
}
|
||||
|
||||
notifyJoin(user: ControllerUser, instance_id: number) {
|
||||
user.instances.add(instance_id);
|
||||
this.onlineUsers.add(user);
|
||||
}
|
||||
|
||||
notifyLeave(user: ControllerUser, instance_id: number) {
|
||||
user.instances.delete(instance_id);
|
||||
if (!user.instances.size) {
|
||||
this.onlineUsers.delete(user);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user