What would be a good way to communicate between components and services in Angular - angular6

I am looking for best practices in Angular to communicate between a UI component and an Angular Service.
My UI has a status bar component. It has a signin button. When user signs in, the username and password are sent from the status bar component to a angular service. The angular service then uses http.post method to send the request to the server. The angular service handles the response from the server and then emits an Observable of its own which contains the outcome of login request. The status bar component subscribes to the observable of the angular service (at ngOnInit) and depending on the result value, it either pops an error message or replaces the login button with welcome ... message. Is this the right way of communicating between components and services in Angular or is there a better design pattern?

Yes this is a perfectly valid use case of services in a component, this type of service usage is called dependency injection.
One thing that should be known are "stores", such as Redux, RxJs or Ngrx Store..
Stores can be useful when the application is split up in lots of different component that may be sharing the same data.
In these cases there can be some difficulties keeping all the components data in the same "state". Stores is a good way to keep the shared data in sync

Related

Flutter: rendering an UI from JSON and store / map data dynamic

I want to render a UI from a jSON string that has multiple layers.
The user should be able to enter data, which will then be stored and shared, without the overhead of the jSON Render Structure.
However, the assignment of the data must be possible.
The app renders a template from a multidimensional json string that can capture metrics (user inputs). The measured data are entered via text fields by the user.
There are different windows in the app, which are rendered from different json UI-render-files.
The stored algorithms in the windows at the Frontend differ.
The following should be possible:
All windows are created with different jSON strings (works with build_value now).
The user's input is saved. (Currently only works by saving the render json string with the data under a different name (with Package: Shared Preferences)).
The data entered by the user is copied from one window to the other window. (Data Binding / Data Mapping)
The data entered by the user will be sent to a backend.
I only have the idea to use id's in the render json, which allow a mapping.
Are there better solutions?
Saving the entered data is possible by saving the whole jSON - String with an other name.
The goal is to map the data.
It should also be possible for the user to insert another object for the measurement data acquisition at the client / device. The entered data must also be saved.
This sounds like a REST API. Then you would use a frontend framework like angular or react to take user input.
I could build this with a .net core web api with sql db as the backend. this would be a web service (REST API solution) on the backend of your solution.
Next I would integrate Swagger with dependency injection and add authentication.
now its time to create the front end that will use your tested Web Service.
you would have 1 side of your SPA POST new JSON to the Web service in a form.
you would have the other side GET the new record as a new tab with pagination or in a table with pagination.
This would be a good PoC for your idea and will let you learn the parts of the solutions architecture in your language of choice. the "design" would be the same no matter what language your choice.
backend web service can be done in a flask and with a MySQL DB. or with any other combo you have skills with.
the Frontend could be done in knockout.js, making it a little easier to learn than angular or react.
Please create new questions when you choose your software design. I would love to give answers for each:)
I would love to level up with you! ;)

How to build a secure stateless authentication system for a client-side dart application

i'm building a stateless authentication system for a Dart frontend and have discovered that it's quite tricky to build a stateless authentication system that's actually secure.
The stack is as follow: Dart application that does JSON POSTs to a Spring MVC backend using Jackson to convert back and forth between JSON and Java objects. Everything will be behind SSL when it goes into production.
Scenario 1: User logs in, I keep a session on the Java side - this is not stateless and will cause problems when load balancing the backend.
Scenario 2: Upon hitting the login button, a POST is done by Dart to the Authentication controller which verifies the credentials and passes back a token (which could be a bunch of UUIDs concatenated together). The token comes back to the frontend - This token combined with the username will then have to be passed along with each request. The dart application now needs to store this token somewhere, since a Dart application compiles to JavaScript, cookies seems to be not an option (JavaScript can't access cookies ?). HTML5 localstorage comes to mind, but from what I've read, it's pretty easy to hijack that token if any form of XSS vulnerability is available (and I'm guessing browser plugins and toolbars that inject JavaScript into the page can also access this token).
Scenario 3: Just like in scenario 2, I get passed back a token from the Spring MVC backend, but instead of storing it in HTML5 localstorage, I keep in a JavaScript variable and pass it on if a new window is opened.
The same problem applies here, since it's inside a javascript variable, any kind of XSS vulnerability or browser plugin can nab that token and hijack the session.
So it seems for a stateless "session", HTML5 localstorage is the most convenient, but it's not secure. Is there a way to secure it or is there an alternative way that will allow me stateless authentication in the browser?
I got a fairly decent answer on Information Security which suggests using cookies with HttpOnly and Secure flags being set on them:
https://security.stackexchange.com/questions/84860/how-to-build-a-secure-stateless-authentication-system-for-a-client-side-javascri/84861#84861
I had to switch to servlet3 to allow setting HttpOnly flag:
Set http-only on cookies created in Spring MVC Controller
On the Dart side, I had to switch from BrowserClient as it doesn't allow cross-domain cookies:
Dart BrowserClient POST not including my cookies
I think about the question, i would save only the token in the session/local storage. All other data could be in a kind of user background controller, which can load needed data by the token(like the user profil).
The hijacking think is bad without ssl. You could try something like a hash comprising (Browser / OS / Plug in data...) as kind of controll but that would be pseudo. I think you need ssl.

call json web api nopcommerce

Hi I am new for nopcommerce 3.5. I need to write a restful web service api to third party(for eg mobile) access the service. I know that we can access through Nop.Plugin.Misc.WebServices . I had enable the service from administrator site.
But now is my question. How can i call the web service for eg GetPaymentMethod , product list and etc
And if I want to write my custom web service by using web api. what is step to create? I cant find any documentation about the web service. Please guide me some example
Thanks
If you want a really quick start in writing a web service in NopCommerce, you can follow the MVC architecture and:
Create an Action method inside a Controller that you find appropriate for your purpose. For example, if you want access to a product list, you might create an Action inside CatalogController that follows the logic of the existing ProductList action.
Set up a Route in RouteProvider.cs to point to the Action you created. Based on this route you can deduce the URL of your service.
Do the processing that you need inside the Action. If this Action/service is to be called with parameters (in query string format: param=value&param2=value2), you can just put these parameters in the Action's header:
public ActionResult QuickService(int param, string param2) { ... and .NET will take care of having them initialized.
Store results in an object (can also be an anonymous object) and at the end of your action, return it as Json: return Json(resultsObject); Again, ASP.NET takes care of the JSON serialization and automatically sets the Content-Type HTTP response header to "application/json".
You can consume the service calling the URL that corresponds to the route of your Action.
If you want users to be able to log in, by using the above method, it gets a little bit trickier. You need the webservice client to be able to accept and send cookies, as well as make appropriate services for Login, Logout, Register,...
However, in this case, you might be better off with a mobile version of the site.
Final note: If you don't want to alter base NopCommerce code, you can apply the steps above to a plugin. The majority of NopCommerce plugins follow the MVC architecture, so you can apply the steps above.

Preventing access to JSON data in an Angular app

I got a (Flask) backend powering an API that serves JSON to an Angular app.
I love the fact that my backend (algorithms, database) is totally disconnected from my frontend (design, UI) as it could literally run from two distinct servers. However since the view is entirely generated client side everyone can access the JSON data obviously. Say the application is a simple list of things (the things are stored in a JSON file).
In order to prevent direct access to my database through JSON in the browser console I found these options :
Encrypting the data (weak since the decrypting function will be freely visible in the javascript, but not so easy when dealing with minified files)
Instead of $http.get the whole database then filtering with angular, $http.get many times (as the user is scrolling a list for example) so that it is programmatically harder to crawl
I believe my options are still weak. How could I make it harder for a hacker to crawl the whole database ? Any ideas ?
As I understand this question - the user should be permitted to access all of the data via your UI, but you do not want them to access the API directly. As you have figured out, any data accessed by the client cannot be secured but we can make accessing it a little more of PITA.
One common way of doing this is to check the HTTP referer. When you make a call from the UI the server will be given the page the request is coming from. This is typically used to prevent people creating mashups that use your data without permission. As with all the HTTP request headers, you are relying on the caller to be truthful. This will not protect you from console hacking or someone writing a scraper in some other language. #see CSRF
Another idea is to embed a variable token in the html source that bootstraps your app. You can specify this as an angular constant or a global variable and include it in all of your $http requests. The token itself could be unique for each session or be a encrypted expiration date that only the server can process. However, this method is flawed as well as someone could parse the html source, get the code, and then make a request.
So really, you can make it harder for someone, but it is hardly foolproof.
If users should only be able to access some of the data, you can try something like firebase. It allows you to define rules for who can access what.
Security Considerations When designing web applications, consider
security threats from:
JSON vulnerability XSRF Both server and the client must cooperate in
order to eliminate these threats. Angular comes pre-configured with
strategies that address these issues, but for this to work backend
server cooperation is required.
JSON Vulnerability Protection A JSON vulnerability allows third party
website to turn your JSON resource URL into JSONP request under some
conditions. To counter this your server can prefix all JSON requests
with following string ")]}',\n". Angular will automatically strip the
prefix before processing it as JSON.
For example if your server needs to return:
['one','two'] which is vulnerable to attack, your server can return:
)]}', ['one','two'] Angular will strip the prefix, before processing
the JSON.
Cross Site Request Forgery (XSRF) Protection XSRF is a technique by
which an unauthorized site can gain your user's private data. Angular
provides a mechanism to counter XSRF. When performing XHR requests,
the $http service reads a token from a cookie (by default, XSRF-TOKEN)
and sets it as an HTTP header (X-XSRF-TOKEN). Since only JavaScript
that runs on your domain could read the cookie, your server can be
assured that the XHR came from JavaScript running on your domain. The
header will not be set for cross-domain requests.
To take advantage of this, your server needs to set a token in a
JavaScript readable session cookie called XSRF-TOKEN on the first HTTP
GET request. On subsequent XHR requests the server can verify that the
cookie matches X-XSRF-TOKEN HTTP header, and therefore be sure that
only JavaScript running on your domain could have sent the request.
The token must be unique for each user and must be verifiable by the
server (to prevent the JavaScript from making up its own tokens). We
recommend that the token is a digest of your site's authentication
cookie with a salt for added security.
The name of the headers can be specified using the xsrfHeaderName and
xsrfCookieName properties of either $httpProvider.defaults at
config-time, $http.defaults at run-time, or the per-request config
object.
Please Kindly refer the below link,
https://docs.angularjs.org/api/ng/service/$http
From AngularJS DOCs
JSON Vulnerability Protection
A JSON vulnerability allows third party website to turn your JSON resource URL into JSONP request under some conditions. To counter this your server can prefix all JSON requests with following string ")]}',\n". Angular will automatically strip the prefix before processing it as JSON.
There are other techniques like XSRF protection and Transformations which will further add security to your JSON communications. more on this can be found in AngularJS Docs https://docs.angularjs.org/api/ng/service/$http
You might want to consider using JSON Web Tokens for this. I'm not sure how to implement this in Flask but here is a decent example of how it can be done with a Nodejs backend. This example at least shows how you can implement it in Angularjs.
http://www.kdelemme.com/2014/03/09/authentication-with-angularjs-and-a-node-js-rest-api/
Update: JWT for Flask:
https://github.com/mattupstate/flask-jwt

How to preserve data through AngularJS routing?

I'm new to AngularJS and am trying to build myself a simple little app. I have JSON data for the app being fetched with $resource, and this data should be the same across multiple views/routes. However, when I go to a new route, the JSON data (stored as $scope.data) is no longer available to the new view. What can I do to pass this data to the new view and not require another fetch? (The tutorial phone-catalog app re-fetches this data every time from what I can tell.)
From what I understand, $rootScope can do this but it seems to be generally frowned upon. I apologize if this doesn't make much sense; I'm very much diving in the deep end here.
Use a service to store the data. Inject that service into each controller that needs access to this data. Each time a controller is created and executes (because you switch to another view/route), it can ask the service for the data. If the service doesn't yet have the data, it can make a request to the server and return a promise to the controller (see below for how to do that). If the service has the data, it can return it to the controller immediately.
See also Processing $http response in service
Note that services are singletons, unlike controllers.
Another variation: when the service is created, it can go fetch the data itself, and then store it for later use. Controllers can than $watch properties or functions on the service. For an example of this approach see How do I store a current user context in Angular?