=============
-> Server :
/**
* Register model
* @param channel channel name
* @param model model name
* @param method method name
*/
@Method
registerListener(channel: string, model: string, method: string) {
nats.subscribe(`get.${channel}.${model}.${method}`, (msg: string, reply: string) => {
console.log('registerListener', msg);
nats.publish(reply, JSON.stringify({ result: { model: { message: `Model: ${model} register completed!` } } }));
});
}
@Action()
pushEventChange(ctx: Context) {
const { channel, model, method, message } = ctx.params;
nats.publish(
`event.${channel}.${model}.${method}.change`,
JSON.stringify({
values: message,
}),
);
}
@Method
authorizeRequest(channel: string, model: string) {
nats.subscribe(`auth.${channel}.${model}.login`, async (msg: string, reply: string) => {
const { params, cid } = JSON.parse(msg);
const checkTokenExistQuery = checkExistedToken(params.token);
const resultQuery = await knex.schema.raw(checkTokenExistQuery).then((result: any) => {
return result.rows[0];
});
if (params && resultQuery.token && params.token === resultQuery.token) {
// Set a token
nats.publish(`conn.${cid}.token`, <any>JSON.stringify({
token: { loggedIn: true },
}));
// Send successful response
nats.publish(reply, <any>JSON.stringify({
result: { message: 'Login successfully!', isLogged: true },
}));
} else {
// Send an custom error response
nats.publish(reply, <any>JSON.stringify({
error: {
code: 'system.accessDenied',
message: 'Invalid request',
},
}));
}
});
}
@Method
accessControlForModel(channel: string, model: string, method: string, allowedMethods?: string[]) {
nats.subscribe(`access.${channel}.${model}.${method}`, (msg: string, reply: string, subject: string) => {
const { token } = JSON.parse(msg);
// Validate we have logged in
if (token && token.loggedIn) {
if (allowedMethods && allowedMethods.length > 0) {
// Grant access for allowed methods
nats.publish(reply, <any>JSON.stringify({
result: { get: true, call: allowedMethods.join(',') },
}));
} else {
// Grant full access
nats.publish(reply, <any>JSON.stringify({
result: { get: true, call: '*' },
}));
}
} else {
// Deny all access except login method
nats.publish(reply, <any>JSON.stringify({
result: { get: false },
}));
}
});
}