smartsocket/ts/smartsocket.classes.socketconnection.ts

92 lines
2.9 KiB
TypeScript
Raw Normal View History

2016-08-08 16:20:00 +00:00
import * as plugins from "./smartsocket.plugins";
import * as helpers from "./smartsocket.helpers";
// import classes
2016-08-09 09:42:21 +00:00
import { SocketFunction, ISocketFunctionRequestObject } from "./smartsocket.classes.socketfunction";
import { SocketRequest } from "./smartsocket.classes.socketrequest";
2016-08-08 16:20:00 +00:00
import { SocketRole } from "./smartsocket.classes.socketrole";
2016-08-09 09:42:21 +00:00
// export interfaces
/**
* interface for constructor of class SocketConnection
*/
2016-08-08 16:20:00 +00:00
export interface ISocketConnectionOptions {
alias?: string;
authenticated: boolean;
role?: SocketRole;
socket: SocketIO.Socket;
};
2016-08-09 09:42:21 +00:00
/**
* interface for authentication data
*/
export interface ISocketConnectionAuthenticationObject {
role: "coreflowContainer",
password: "somePassword",
alias: "coreflow1"
}
// export classes
/**
* class SocketConnection represents a websocket connection
*/
2016-08-08 16:20:00 +00:00
export class SocketConnection {
alias?: string;
authenticated: boolean;
role?: SocketRole;
socket: SocketIO.Socket;
constructor(optionsArg: ISocketConnectionOptions) {
this.alias = optionsArg.alias;
this.authenticated = optionsArg.authenticated;
this.role = optionsArg.role;
this.socket = optionsArg.socket;
}
/**
* authenticate the socket
*/
authenticate() {
let done = plugins.q.defer();
this.socket.on("dataAuth", dataArg => {
plugins.beautylog.log("received authentication data. now hashing and comparing...");
this.socket.removeListener("dataAuth", () => { });
if ((true)) { // TODO: authenticate password
this.alias = dataArg.alias
this.authenticated = true;
this.role = helpers.findSocketRoleByString(dataArg.role);
this.socket.emit("authenticated");
plugins.beautylog.ok(`socket with >>alias ${this.alias} >>role ${this.role} is authenticated!`);
done.resolve(this);
} else {
this.socket.disconnect();
done.reject("not authenticated");
};
});
this.socket.emit("requestAuth");
return done.promise;
};
/**
* listen to function requests
*/
listenToFunctionRequests() {
let done = plugins.q.defer();
if(this.authenticated){
2016-08-09 09:42:21 +00:00
this.socket.on("function", (dataArg:ISocketFunctionRequestObject) => {
let referencedFunction:SocketFunction = this.role.allowedFunctions.find((socketFunctionArg) => {
return socketFunctionArg.name === dataArg.functionName
});
if(referencedFunction !== undefined){
referencedFunction.invoke(dataArg);
} else {
plugins.beautylog.warn("function not existent or out of access scope");
};
2016-08-08 16:20:00 +00:00
})
} else {
done.reject("socket needs to be authenticated first");
};
return done.promise;
}
};