How to detect a period of inactivity in EmberJS? - ember.js

I am trying to detect a period of user inactivity in my EmberJS application so that, after a certain duration I can call a session.inValidate method and revoke their authentication.
The only resource I have been able to find is an article here which I was advised in an original question is out of date and doesn't use current Ember concepts.
The out-of-date article suggested adding a property to the App object and updating the property on certain events like mousemove but I was unable to find a location to set this property correctly in either app.js or the config environment.
ember-concurrency was recommended but after looking at some of the documentation I still don't understand where such code fits in an EmberJS application structure.
Unfortunately I'm stuck at a point before I can give a code sample. Any advice is appreciated.
Edit: As per #hernanvicente excellent question, I am defining inactivity as 'no user input'. So no mousemove or key press events within X period

The hard question here is what activity actually means. Generally I would advise against your idea. There is no way to know if the user is actually still looking on your page.
However if you really want to do something after the user hasn't done something for some amount of time the interesting question is where to place your code.
You have multiple options here, but probably not the worst option would be to use the application controller. You could also use a service, but then you need to use that service somewhere to initialize it. You could also just use a component.
If you want to couple this to authentication you could consider to use the existing session service.
However everything else is not really ember specific. You can just place some code in the application controllers init hook and access document.addEventListener(). Then you could just save a timestamp away and act accordingly.
To have a bit a nicer API for waiting you can utilize ember-concurrency with a restartable task:
didSomething: task(function * () {
yield timeout(1000); // number of miliseconds to wait
logout();
}).restartable(),
here logout() will be called, after the task hasn't been called for 1 second. A nice visual demonstration about task concurrency and restarable can be found here.
Here is an ember-twiddle showing a complete example.

Related

Best Practice Using Django Signal (For user authentication?)

I am new to Django and want to know deeper about the concept of signals.
I know how it works but really don't understand when should one really use it.
From the doc it says 'They’re especially useful when many pieces of code may be interested in the same events.'
What are some real applications that use signals for its advantage?
e.x. I'm trying to make a phone verification after user signup. Because it can be integrated inside the single app and the event that interested for the signal is only this 'verify' function, therefore I don't really need signal. I can just pass the information from one view to the other, rather than using pre_save signal from the registration.
I'm sorry if my question is kind of basic. But I really want to know some insight what is the real application, in which many codes interested in one particular event and what are some trade off in my application.
Thanks!!
Often signals is used when you need to do some database-specific low-level stuff. For example, if you use ElasticSearch for better searching documents on your site, you may want to automatically update search indexes, when new document is created or old one was edited.
Also you may have some complex logic of managing database objects. For example, you may need some specific logic of deleting object. For example, when user is deleted, you may want change all the links to his profile by some placeholder, or when new message is created or other action is performed by user, you want to update "last visited" field in user's profile and there's no direct relation between this action and updating the profile.
But when you're just implementing business-logic as in your example with verification, you don't need to use signals, because you don't need any universal logic related to deleting/creating/editing any object: you have a certain object with which you work and can do stuff directly.

how continuously run function on page request

I want to use third party's REST API providing real-time foreign exchange rates in my django app which should continuously show changing exchange rates.
my code works but only on every page reload. but I want my code to be running continuously and showing exchange rate on page even if the page is not reloaded.
def example(request)
RATE__API_URL = 'REST API url'
while True
rate = requests.get(RATE__API_URL).json()
b = rate['rates']['EURUSD']['rate']
context = {'b': b}
return render(request, 'example.html', context)
on my example.html
<h1>
{{b}}
</h1>
code is running and does not show any errors
There are a few ways you can solve your requirement and none of them are the "right way", also much of it depends of what you have in your code, so I'll try to lay them out for you, and given the extent of what needs to be done while providing some links so you can work on it, but I will not give code because you'll require a fair amount of tailored code (sorry for that) and the references are good enough for you to develop your own solution.
The first thing you have to keep in mind is than you'll need to solve two really big and really different requirements:
The first part of your solution is retrieving the data from the source in a timely manner. The second part is to have a way to update the data in the template without the need for the user to reload the page.
To retrieve the data you said you already have an API where you'll get the data, but your code is not an efficient way to approach this, and it also may generate a risk because it is prone to hit too many times the API server; the best way I can think of would be if the API has webhooks or push notifications to which you can subscribe (which I doubt), the second best choice is to implement a Celery task, that way you will be calling the data regularly, and you'll not eat the API service resources.
With the first part out of the way, what you have left to do is to implement a way to call regularly from the UI for the newest data. Perhaps the simplest way to solve it is to implement an asynchronous call with Javascript/JQuery embedded in a script inside your template, but remember:
For this to work you'll need a model to store the data (If you don't
have an use for historic data, then just keep the most recent
one).
You'll need a view that exposes the data to your UI call (one that sends a JSON)
Another solution is to implement websockets, and the best way to achieve this for Django is using django-channels. You'll have to implement two main things:
In the backed you need to define the consumers flow so you can send
the data to the UI.
In the template you need to implement the websocket connection and a way to handle the updating part of the data for the user.
If you choose this way, and given than you don't need historic data, you can obviate the model and go straight from the Celery task to the UI through the consumer.

architecture question - using sub routes vs components

I am trying to build a UI with left side bar having filters and right side having actual filtered data.
For loading data into the dynamic part of the UI(right side), which approach is considered better in terms of code quality and app performance ?
Use sub routes (for dynamic part of the UI)
Use separate components that load their own data (for dynamic part of
the UI)
There is not a direct correct answer for that; you can use both ways but here is a few things to consider and in the end I generally prefer to use sub-routes due to the following:
Waiting for UI to load: In case you are using separate components to load their own data; then you need to handle the loading state of the components. What I mean is; if you simply use sub-routes; then model hooks (model, beforeModel, etc.) will wait for the promises to be solved before displaying the data. If you simply provide a loading template (see the guide for details) it will be displayed by default. In case you use components, you might need to deal with displaying an overlay/spinner to give a better UX.
Error Handling: Similarly like loading state management; Ember has already built in support for error handling during route hook methods. You will need to deal with that on your own if you prefer components to make the remote calls. (See guide for details)
Application State: Ember is SPA framework; it is common practice to synchronize application state with the URL. If you use sub-routes; you can simply make use of the query parameters (see the guide for details) and you will be able to share the URL with others and the application will load with the same state. It is a little bit trickier to do the same with components; you still need to use query parameters within the routes and pass the parameters to the components to do that.
Use of component hook methods: If you intend to use the components then you will most likely need to use component hook methods to open the application with default filter values. This means you will need to make some remote call to the server within one or more of init, willRender, didReceiveAttrs component hook methods. I personally do not like remote calling within those methods; because I feel like this should better be done within routes and data should be passed to the components; but this is my personal taste of coding that you should approach the case differently and this is perfectly fine.
Data down, actions up keeps components flexible
In your specific example, I'll propose a third option: separate components that emit actions, have their data loaded by the route's controller, and never manipulate their passed parameters directly in alignment with DDAU.
I would have one component, search-filter searchParams=searchParams onFilterChange=(action 'filterChanged'), for the search filter and another component that is search-results data=searchResults to display the data.
Let's look at the search filter first. Using actions provides you with maximum flexibility since the search filter simply emits some sort of search object on change. Your controller action would look like:
actions: {
filterChanged(searchParams){
this.set('searchParams', searchParams);
//make the search and then update `searchResults`
}
}
which means your search-filter component would aggregate all of the search filter fields into a single search object that's used as the lone parameter of the onFilterChange.
You may think now, "well, why not just do the searching from within the component?" You can, but doing so in a DRY way would mean that on load, you first pass params to the component, a default search is made on didInsertElement which emits a result in an action, which updates the searchResults value. I find this control flow to not be the most obvious. Furthermore, you'd probably need to emit an onSearchError callback, and then potentially other actions / helper options if the act of searching / what search filter params can be applied together ever becomes conditionally dependent on the page in the app.
A component that takes in a search object and emits an action every time a search filter field changes is dead simple to reason about. Since the searchParams are one-way bound, any route that uses this component in it's template can control whether a field field updates (by optionally preventing the updating of searchParams in an invalid case) or whether the search ever fires based of validation rules that may differ between routes. Plus, theres no mocking of dependencies during unit testing.
Think twice before using subroutes
For the subroutes part of your question, I've found deeply nested routes to almost always be an antipattern. By deeply, I mean beyond app->first-child->second child where the first child is a sort of menu like structure that controls the changing between the different displays at the second child level by simple {{link-to}} helpers. If I have to share state between parents and children, I create a first-child-routes-shared-state service rather than doing the modelFor or controllerFor song and dance.
You must also consider when debating using children route vs handlebars {{if}} {{else}} sections whether the back button behavior should return to the previous step or return to the route before you entered the whole section. In a Wire transfer wizard that goes from create -> review -> complete, should I really be able to press the back button from complete to review after already having made the payment?
In the searchFilter + displayData case, they're always in the same route for me. If the search values need to be persistent on URL refresh, I opt for query params.
Lastly, note well that just because /users/:id/profile implies nesting, you can also just use this.route('user-profile', { 'path' : 'users/:id/profile' }) and avoid the nesting altogether.

Magento communicating with another system

I'm building a magento (1.9CE) store which needs to interface with another system and I could use some guidance.
Although not particularly relevant, I'm communicating with the 'other' system using web services (it's on another server) but what I need help with is finding the places where I need to put in code to do what I want.
There are three major functions that I need to implement:-
When a user clicks on the product detail page I need to make a call to check the stock levels on the other system, update the magento stock levels and THEN display the product detail page.
When a sale is completed, I need to send details of that sale to the other system.
When a new product is added I need to communicate with the other system. This may be a bit more complex because there are a few checks I need to do during the 'add product' process, for example, check the SKU is valid, that tghe product doesn't already exists, etc. I think until I start coding this I shan't realise the full extent of this functionality!
Any guidance gratefully received!
Even though this might (and probably will) dramatically slow down your store, if you want real-time information, I guess the easiest way would be with observers.
You can use catalog_controller_product_init_before: This will trigger when the product detail page is starting loading, so you should be able to upload the stock at this point, before the page has finished loading, so that if there is no stock it will not be buyable, which I guess that's what you want.
You can use sales_order_place_after: This will be triggered after a new order has been placed and saved in the database.
You can use catalog_product_new_action or catalog_product_save_after: Depending on how you create your products the first one might not be triggered. The second one will always be triggered once a product (new or existing) has been saved, so at this point you will need to check if the product is new or existing, and do your stuff depending on that.
For an example of how to create an extension and usage of observer events, check this out.
I hope it helps!

MVC protecting accessing some action

I have a question regarding some action accessing, i'm not talking here about authorization etc, but more about the direct access to actions.
Basically i have 2 question, 1 general and 1 more contextual:
Situation imaging i have an action : MyArticles/DeleteArticle/id
1) How can i prevent that if someone will just put this url with a proper id remove article? How can i say that it can only be used with a button on my website? And should this action be a get or post?
At this moment i use $.ajax and GET method ....
2) Now imagine i have many people, and if all th ppl are registered, they can delete each others article, what if i want to avoid that and let users only delete their own articles, because at this moment for example if they can guess the id they can directly access the action with id and delete it.
Can anyone provide explanation and some tips about that?
i'm not talking here about authorization etc
Yes, you are. The authorization to delete the article should take place within the action itself, it's not the responsibility of the calling code or of any UI which displays a link to the action.
How can i say that it can only be used with a button on my website?
I imagine any approach to that is going to complicate the issue tremendously. Understand how HTTP requests work... Your application isn't making the request to the action, the user is. They're doing so (in the general case) by clicking a link on an interface provided by your application, but the request itself is coming from the user. (Well, from the user's web browser, which is in their control and not yours.)
The most straightforward approach to this is to encapsulate authorization in the action itself (or, better still, in the model functionality being invoked by the action... but logically that's still part of the "request" being performed).
When you expose a piece of functionality which not everybody should be able to invoke, put the authorization on the functionality itself instead of on the UI which invokes it. That way no matter how it's invoked it always maintains the authorization, instead of just assuming that some other component maintained it.
You have a lot of control in MVC with respect to the USER. To allow a user to delete only his own work, you must remember in the database who wrote what. If this is the case - and you know it, a simple if statement in the beginning of the action will do the trick.