Checking user entered details against response JSON - json

I am trying to setup an Angular app which authenticates users against a back-end server. I am able to get the list of users from server as a JSON in my Angular list. How can I now validate this against user input fields.
Since I have already got the list of users I just have to validate the user entered inputs against that. But for some reason it doesn't work.
Code to get list of all users
getListofUsers() {
return this.httpClient.get(this.userListURL);
}
this.authService.getListofUsers()
.subscribe(resp => {
console.log(resp, "res");
this.data = resp
},
error => {
console.log(error, "error");
})
Data variable contains the response JSON.
I want to validate user input fields against this JSON response
this.authService.authenticateUser({
userId: this.userId.value,
userPassword: this.userPassword.value},this.data)
If userID and password are present in response JSON then the user should be routed to next screen.
this.router.routeToDashboard();

Related

NodeJS: How to send entity from mysql to rabbitmq

I'm trying to send an "entity" obtained from MySQL to RabbitMQ.
I'm able to make the connection to the database and return data. Example:
dbConnection.query("SELECT * FROM customer WHERE Id = ?", customerId, (err, rows, fields) => {
...
res.status(200).json(rows)
...
}
After this I am able to watch in Postman the "JSON result", so, I want to send this "JSON result" as an string to RabbitMQ.
I can send to RabbitMq a fake data object with no problem:
const fakeData = {
name: "Elon Musk",
company: "SpaceX",
};
channel.sendToQueue("message-queue", Buffer.from(JSON.stringify(fakeData)));
So, how must I convert the "rows" object returned from MySQL to send it to the queue?
Thank you in advance!
The solution to my problem is as follows:
rows.forEach(function (row) {
channel.sendToQueue("message-queue", Buffer.from(JSON.stringify(row)));
});

How to send an Enum variant as integer, not string in Angular

I'm using Angular 11, and have to post some data to a backend service. Here's the data I need to post:
interface User {
id: Guid; // Guid is just a type alias to string, with some validation checks
email: string;
role: Role
}
enum Role {
User = 0,
Administrator = 1
}
Now the problem comes when I try to post to my backend using the default HttpClient from Angular. Here's the code:
createOrUpdateUser(user: User): Observable<User> {
return this.http.post<User>(`${this.baseUrl}/${this.userUrl}/${this.userCreateOrUpdate}`, user);
}
This works fine, but the JSON sent is "wrong". It sends this:
{
"id": "2abe50d6-4c81-4ace-ad95-c8182d4384a3",
"email": "someEmail#example.org",
"role": "0"
}
Where as the backend is expecting this
{
"id": "2abe50d6-4c81-4ace-ad95-c8182d4384a3",
"email": "someEmail#example.org",
"role": 0
}
The difference being the backend expects "role": 0, but Angular sends "role": "0". How can I make Angular send "role": 0?
This is may not be a good idea. But it will be helped you.
createOrUpdateUser(user: User): Observable<User> {
user.role = Number(user.role);
return this.http.post<User>(`${this.baseUrl}/${this.userUrl}/${this.userCreateOrUpdate}`, user);
}
you can use + to make it as number before sending it api user.role = +user.role. Some where else you are assigning value of role in user object which is making it as a string. its not enum issue.
TypeScript is compiled to plain old javascript code, where type enforcement is more or less non-existent. This means that, in theory, you might be assigning a string to your User model.
There can be multiple reason - i.e. you receive it this way from backend, assign it to a variable and re-send later without modifying the value. Or, for example, the User comes from a FormGroup which passes the value as a string. You can even have TypeScript code omit type checks:
let user: User = {
id: '2abe50d6-4c81-4ace-ad95-c8182d4384a3',
email: 'someEmail#example.org',
role: Role.Administrator
}
user['role'] = "2" // Not a valid enumeration
So, to instead of going for some strange workaround like using +user.role in the mapping, perhaps look for where / how the value is assigned in the first place.
As it is not really clear if it gets sent from angular or received from server as string we can debug a bit to find the right place to investigate (angular frontend or backend)
You can investigate by logging console.log(typeof user.role)and see what it returns. Also have a look at what gets sent from frontend to backend using Chrome Devtools -> Network -> click on the request -> and scroll down on first tab to see what data gets sent.
What might happen is frontend to send the right data type (integer) for the role and backend interpret it as string.
In this case you could just use parseInt(user.role) in the backend as a fallback or investigate how to get the integer type on the backend body request instead of string.

Express res.status(200).json(...) only sending json message. How to retrieve status code?

After a successful creation of new item in my database I send:
res.status(201).json({message:"Successfully Registered"});
On my angular front end I am able to console.log(res) and receive:
{message: "Successfully Registered"}
1) How do I get the status code on the front end? res.status returns undefined. The only response I'm getting is the JSON.
2) What would be the best way to confirm successful desired api calls? For example, when I log in and credentials are correct, should I check for a 200 and then proceed? Or send a custom JSON message and check if the message for example says "Successful login" then proceed?
A little bit late, but another option is to include the status in the JSON object:
res.status(201).json({message: "Successfully Registered", status: 201})
Now you can check the status in the front end doing res.status and use this to proceed with another action.
1- You can do res.status(200).send("You message here");
2- I would say your best option when doing the login and authenticating credentials is to create a session as such
req.session.user = req.body.username //username is the name attribute of the textfield
and then redirect to any page you'd like/you can also set status to 200
res.status(200);
I'm not familiar with Angular, but looking at the docs:
See https://angular.io/api/http/Response
You'll need to do something like:
http
.request('example.com')
.subscribe(response => console.log(response.status));
Sure, checking for 200 is fine. Typically with a REST API (inferred from what you've shown), after a login you're given back a JWT along with 200 OK. And any subsequent API all with that JWT will also yield a 200 OK along with the response body which is usually JSON.
You should tell your angular http client that you want to get the response status. By default, angular deserialize the response body, but you can set request option.observe:'response' to do so.
postData(model: MyModel): Observable<HttpResponse<{status: string}>> {
return this.http.post<{status: string}>(
model, { observe: 'response' });
}
See https://angular.io/guide/http#reading-the-full-response for details.
PS: sending a { status: 'message' } is not very useful, you may return an { id } or even nothing.
res.status(200).json({
status: 'success',
results: tours.length,
data:{
tour:tours
}
});
Usually, Jsend is a good choice to response, and also by convention. Absolutely you can see the 'status' in response data and the actually data you want in the data.
according to the angular guide, we can add observe in the options of our request.
getforgetpassword(email: string): Observable<any> {
const url = this.gatewayUrl + `newPasswordFor/${email}`;
return this.http.get(url, {observe: "response"});
}
using observe type as response will give total response along with request status, which you can use in your logic of controller.

Angular 2: How do I handle redirect routes to my page with incoming JSON data?

I have two problems, I need to be able to redirect users from facebook permissions acceptance from passportjs-facebook and from paypal payments redirect but I don't know how to do this in angular. I need to access posted JSON data coming from my own express server with an angular route which receives and uses that data.
If I do an a href="/auth" login button it sends my user to facebook's page to grant app permissions, after they do it redirects them to /auth/facebook/callback which is a blank white page with this json: {"ok":true,"status":"Login successful","success":true,"token":"...", user: {..}, }. How do I make it so they are redirected back to a page on my angular2 app and that this token is read into a json object within my apps so I can put it in local storage? This is my backend code:
userRouter.get('/auth', passport.authenticate('facebook', {scope: ['public_profile', 'user_friends', 'email']}), (req, res) => {});
userRouter.get('/auth/facebook/callback', function(req,res,next){
passport.authenticate('facebook', function(err, user, info) {
if (err) {
return next(err);
}
if (!user) {
return res.status(401).json({
err: info
});
}
req.logIn(user, function(err) {
if (err) {
return res.status(500).json({
err: 'Login failed'
});
}
var token = Verify.getToken(user);
res.status(200).json({
status: 'Login successful',
success: true,
token: token
});
});
})(req,res,next);
});
I'd use a res.redirect to the URL of one of your Angular pages, and include the token as a query string.
res.redirect('/#!/myprofile?token=MYTOKEN'); instead of the res.status(200).json... code
Alternatively you can parse the query string sent with the redirect right away in Angular as in this example, but I think that way can be a bit messy. That example will also help you through accessing query strings in Angular2.

Sencha Touch's proxy's reader's rootProperty and Parse.com's REST API response

My backend is Parse.com's REST API, and parse send me back a results object that looks like:
{
...fields...
}
when there is only object, meaning any time there is a create, a read or an update to one record. When I GET a collection of objects from Parse, it sends out a results object that looks like:
{
results: [
{
...fields...
}
]
}
In ST, when I have my proxy's reader's rootProperty set to: 'results', my reader isn't able to read the record Parse sends on a create or an update and therefore the local record doesn't get synced with the one the server sent.
When I have my reader's rootProperty set to: '', my local record gets synced with the one that Parse sent, but now my list, which takes a store, isn't displaying the list of records, because Parse sends that with a "results" node.
I tried using setRootProperty, but despite confirming that the reader's root property just before calling save() on a record is in fact: '', the local record doesn't sync with Parse's response. As soon as I remove the logic that does real time changes to root property, it starts working again.
What is the suggested way of handling this situation? Any help is much appreciated! Thanks!
So you have one store with a proxy that has a certain rootProperty but you olso have 2 type of response, single object or an array of objects inside results. If it is so, definitly your proxy is able to read only one type of response.
Some solutions:
-if you can operate on server make sure you send always an array of results whether the response contains none, one or many results.
-implement a custom reader (this is what i did when i had to manage different responses and make some changes on data in the meanwhile)
Ext.define('MyApp.store.MyStore',{
extend:'Ext.data.Store',
model:'MyApp.model.MyModel',
proxy: {
type:'jsonp',
url:'#'
},
autoLoad:false,
loadSolr:function(PARAMS){
this.groupField = groupField;
Ext.data.JsonP.request({
scope:this,
url: 'http://myserver.com',
callbackKey: 'json.wrf',
params: {
PARAMS
},
success: function(response) {
// handle your response here
var records = [];
Ext.each(response.results, function(record){
records.push({
field1: record.field1,
field2: record.field2
});
});
//load your data into store
this.loadData(records);
}
});
}
});
Hope it helps, post some code if i misunderstood something