Get loggedin userinformation in extjs shopware backend - shopware

I know that I can access the javascript var userName everywhere in the extjs backend, cause its defined globally in the themes/Backend/ExtJs/backend/index/header.tpl, to get information about the logged in user. But is there a way to get userId or role of the user in some way (without ajax requests)?
//{block name="backend/order/view/list/list"}
//{$smarty.block.parent}
Ext.define('Shopware.apps.Test.view.List', {
/**
* Defines an override applied to a class.
* #string
*/
override: 'Shopware.apps.Order.view.list.List',
getToolbar: function() {
// get this
var me = this;
// get parent action column
var result = me.callParent( arguments );
console.log(userName);
},
});
//{/block}
{block name="backend/base/header/javascript" append}
<script type="text/javascript">
var currentTabState = 'active';
window.addEventListener('blur', function () {
currentTabState = 'inactive';
});
window.addEventListener('focus', function () {
currentTabState = 'active';
});
var userName = '{$user->name}',
maxParameterLength = '{$maxParameterLength}';

You need to make the user available as Smarty variable, so you can simply access the data from this object.
For this you can subscribe to the PostDispatch event of the order backend controller Enlight_Controller_Action_PostDispatchSecure_Backend_Order in a subscriber and then you use the same code as in the Shopware_Controllers_Backend_Index to add the $user variable.
//{block name="backend/order/view/list/list"}
//{$smarty.block.parent}
Ext.define('Shopware.apps.Test.view.List', {
/**
* Defines an override applied to a class.
* #string
*/
override: 'Shopware.apps.Order.view.list.List',
getToolbar: function() {
// get this
var me = this;
// get parent action column
var result = me.callParent( arguments );
var userId = '{$user->id}';
var roleId = '{$user->role->getId()}';
console.log(userName);
},
});
//{/block}
{$user->role} contains the Shopware\Models\User\Role model, so you can access all data from this object with the corresponding getters.
If you want to know, which data you have available, just make a debug output in the \Shopware_Controllers_Backend_Index::indexAction method, right after the call $identity = $auth->getIdentity();
echo '<pre>';
\Doctrine\Common\Util\Debug::dump($identity);
echo '</pre>';
exit();

Related

Create Multiple Jabber Client Echo Bot

Hai Stackoverflowers,
i had try so many ways to fix my problem and i end up with stack over flow
Programming Language:
Typescript
my main goals:
create Client Class as many as i want and can turn on and turn off the Client, the client will be as Bot that echo text from the friendlist
I use node-xmpp-client Library :
https://github.com/chris-rock/node-xmpp-client
My Code :
import * as Client from 'node-xmpp-client'; // Jabber Helper
export class TerminalJabber {
private ter;
private client;
constructor(ter: any) {
this.ter = ter;
this.client = new Client({
jid: this.ter.settings.username,
password: this.ter.settings.password,
});
}
public turnOn(){
// Turn on Jabber
this.client.on('online', () => {
console.log('online');
const stanza = new Client.Element('presence', { })
.c('show').t('chat').up()
.c('status').t('Happily echoing your <message/> stanzas');
this.client.send(stanza);
});
this.client.on('stanza', (stanza) => {
// Message come here and will echo from here
});
// Catch error
this.client.on('error', (e) => {
console.log('------>', e);
});
}
// Turn Off Jabber
public turnOff () {
// Turn Off Jabber
this.client.end();
return true;
}
}
The Problem is, The Bot Can Start, but never will be disconnect when i call a new class and turnOn() and turnOff().
How I call My code:
// Hit URL
/turnOn/:terId
// Hit URL
app.router.get(/turnOn/:id, turnOnController); // for turn On
app.router.get(/turnOff/:id, turnOfController); // for turn Off
TurnOnController(){
// Get data from database using id
const data = Query ~ ;
const terminal = new TerminalId(data)
terminal.turnOn();
}
TurnOffController(){
// Get data from database using id
const data = Query ~ ;
const terminal = new TerminalID(data)
terminal.turnOff();
}
Maybe you have a solution of my problems ?
have been thinking and read so many post about xmpp, but i cant solve this things,
Please help
sincerely,
Thank you
You need to call the turnOff method on the terminal instance before you create new one.
This also means you need to have access to the instance from both controllers.
var terminals = {};
function turnOnController(){
var id = getIdSomehow();
terminal[id] = new TerminalId(data);
terminal[id].turnOn();
}
function turnOffController(){
var id = getIdSomehow();
if (terminal[id])
terminal[id].turnOff();
}

i have already tried,but i don't no how to call the function in another file

sir/madam exlain the flow of node.js from client to server with the dynamic parameters passing from userinterface to api's based up on these parameters we will get the output from api.for example sabre api etc..
exports.flightDestinations = function(req, res) {
var callback = function(error, data) {
if (error) {
// Your error handling here
console.log(error);
} else {
// Your success handling here
// console.log(JSON.parse(data));
res.send(JSON.parse(data));
}
};
sabre_dev_studio_flight.airports_top_destinations_lookup({
topdestinations: '50'
}, callback);
};
we want this value 50 from user...and how to give this value?and how to call this function in node.js.
The exports variable is initially set to that same object (i.e. it's a shorthand "alias"), so in the module code you would usually write something like this:
var myFunc1 = function() { ... };
var myFunc2 = function() { ... };
exports.myFunc1 = myFunc1;
exports.myFunc2 = myFunc2;
to export (or "expose") the internally scoped functions myFunc1 and myFunc2.
And in the calling code you would use:
var m = require('mymodule');
m.myFunc1();
where the last line shows how the result of require is (usually) just a plain object whose properties may be accessed.
NB: if you overwrite exports then it will no longer refer to module.exports. So if you wish to assign a new object (or a function reference) to exports then you should also assign that new object to module.exports
It's worth noting that the name added to the exports object does not have to be the same as the module's internally scoped name for the value that you're adding, so you could have:
var myVeryLongInternalName = function() { ... };
exports.shortName = myVeryLongInternalName;
// add other objects, functions, as required
followed by:
var m = require('mymodule');
m.shortName(); // invokes module.myVeryLongInternalName

Accessing Marionette Apps from Views (using Require.js)

I'm trying to share a Marionette App with some of its Views. I've read the wiki here, but the example leaves me with a question.
I've got a file with a couple of views in it that will all need to use the request/response system and possibly the commands. I don't want to do var MyApp = require('app'); in all of the Views in the file. I came up with the following, but I think there's probably a better way to do it.
Example:
//Views.js
define( ["marionette"], function (Marionette) {
var App = function(){
return require('app');
};
var ExampleItemView = Marionette.ItemView.extend({
initialize: function(){
App().request("getInfo", "aboutStuff");
}
});
return Marionette.CollectionView.extend({
itemView: ExampleItemView,
initialize: function(){
App().request("getInfo", "aboutStuff");
}
});
Is there a better way to do this?
I'd definitely not inject your app into your views since it can create circular dependencies which are ALWAYS a code smell (regardless of whether they can be solved or not) The simples solution by far is to create a separate (singleton) reqres object which is handled by the app and injected into the views.
//reqres.js
define(['backbone.wreqr'], function( Wreqr ){
return new Wreqr.RequestResponse();
});
//app
define(['reqres'], function(reqres){
reqres.setHandlers({
'getInfo' : function(){
return 'foo';
}
});
});
//Views.js
define( ["marionette", "reqres"], function (Marionette, reqres) {
var ExampleItemView = Marionette.ItemView.extend({
initialize: function(){
reqres.request("getInfo", "aboutStuff");
}
});
return Marionette.CollectionView.extend({
itemView: ExampleItemView,
initialize: function(){
reqres.request("getInfo", "aboutStuff");
}
});
Backbone Wreqr is to be replaced by Backbone Radio in the next major release of Marionette, v3.
To use Backbone Radio you could create a channel and do the following:
/**
* App.js (for example)
*/
var Radio = require('backbone.radio');
// Use the 'data' channel - this could be whatever channel name you want
var dataChannel = Radio.channel('data');
// Handler for a request
dataChannel.reply('getMessage', function(name) {
return 'Hello ' + name + '. Alba gu brath!';
});
/**
* View.js (for example)
*/
var Radio = require('backbone.radio');
var dataChannel = Radio.channel('data');
// Make the request
console.log( dataChannel.request('getMessage', 'Craig') ); // -> Hello Craig. Alba gu brath!

I can't receive data from custom module in node.js

I wrote a module called accountManager.js
var sqlite3 = require('sqlite3');
var db = new sqlite3.Database("./users.db");
exports.userExists = function userExists(nickName) {
var stmt = 'SELECT * FROM users WHERE login="' + nickName + '"';
db.each(stmt,function(err,row) {
if(row) {
if(row.login==nickName) return true;
else return false;
}
});
}
In my main app.js file I've got
var accountManager = require('./lib/accountManager');
console.log(accountManager.userExists('user1'));
This app says 'undefined' in console... I checked that module is working fine, I guess it's problem with callback? Please, give me some help, I don't understand what is wrong with this code...
You need to understand how asynchronous functions and callbacks work.
Basically you cannot return anything inside the callback but need to invoke another callback which you pass to userExists.
var sqlite3 = require('sqlite3');
var db = new sqlite3.Database("./users.db");
exports.userExists = function userExists(nickName, cb) {
var stmt = 'SELECT * FROM users WHERE login="' + nickName + '"';
db.each(stmt,function(err,row) {
if(row) {
cb(row.login == nickName);
}
});
}
To use it:
accountManager.userExists('user1', function(found) {
console.log(found);
});
Besides that, your code has a gaping SQL injection hole and might not do what you intend to do. Here's a fixed version of the userExists function:
exports.userExists = function userExists(nickName, cb) {
var stmt = 'SELECT COUNT(*) AS cnt FROM users WHERE login = ?';
db.get(stmt, nickName, function(err, row) {
cb(row.cnt > 0);
});
};
Why is this better?
You do not interpolate the value in the SQL string (which is bad, you would have to escape stuff to avoid SQL injection). Passing it separately is much cleaner and better
You just want to know if a user exists. So retrieve the count (which will be exactly one row). If it's not zero the user exists.
Now the callback is always invoked. In the first example that is more closely based on your code it would only be invoked in case a user has been found - most likely not what you wanted.
You're returning a value from within the callback from db.each. However, this value is not returned by the outer function (userExists), which may return before the function passed to db.each is ever called.
You may want to provide a callback to the userExists function, like so:
exports.userExists = function (nickName, cb) {
var stmt = 'SELECT * FROM users WHERE login="' + nickName + '"';
var found=false;
db.each(stmt,function(err,row) {
if(row) {
if(row.login==nickName) {
found=true;
cb(true);
}
}
}, function () {
if (!found) {
cb(false);
}
});
}
Then, call it like:
var accountManager = require('./lib/accountManager');
accountManager.userExists('user1', function (found) {
console.log(found);
});

How to access instance variables anywhere in the class for node.js

I am working on a node.js application with postgresql, using the express framework. I am trying to follow MVC as much as possible.
I want to generate query results in a model class and then pass them to a controller class. That controller class is actually defined in the routes, so that controller class can take the results and pass them as http response.
This is my database helper class, i.e. the model class. My problem is at the listener at the very end of the class.
exports.DatabaseHelper = function()
{
var allVenues;
var client;
var customEventEmitter;
this.init = function()
{
this.customEventEmitter = new events.EventEmitter();
client = new pg.Client(
{
host:'localhost',
port:5432,
database:'postgres',
user:'postgres',
password:'password'
});
}
this.getVenuesWithEvents = function(searchParams)
{
allVenues = new Array();
var query_for_venues;
this.init();
client.connect();
client.addListener("error",function()
{
sys.puts("postgresql interface error");
});
query_for_venues = client.query("select id, name, location, latitude, longitude, category_generalized from venues");
query_for_venues.addListener("row",function(row)
{
//some code
});
query_for_venues.addListener("end",function(result)
{
this.customEventEmitter.emit("data",allVenues);
//////////////////////////////////////////////////////////
//this line shows error....'this' refers to the query object so customEventEmitter is undefined
//customEventEmitter is my idea of sharing the query results to my controller class.
//but I cannot do this becasue of this error
console.log("after emission");
});
}
}
How can I access the customEventEmitter instance variable from within the listener?
Just remove this from your init function:
this.customEventEmitter = new events.EventEmitter();
So you'll have:
customEventEmitter = new events.EventEmitter();
And in your listener just emit the emitter without this as follows:
query_for_venues.addListener("end",function(result){
customEventEmitter.emit("data",allVenues);
console.log("after emission");
});
let me show you a nice trick.
you could change custom
var customEventEmitter;
to
this.customEventEmitter =null;
at the top of the function. then you can call
var self = this;
outside of the query function. then inside the query function you reference the outer "this" with self.
as in:
self.customEventEmitter.emit()
the methodology I just described is standard.

Resources