how to connect to sql database with js - javascript

I have form that to registering some site. I want to check when user is writing username code will check that have or not in database

You must use AJAX for this. The SQL database you speak of is on the host, not on the computer that is running the JavaScript.
When the user completes the registration page, you'll use AJAX to send the request to the host. The host might reply with an error response: "user already exists." It(!) is querying the database, which it(!) has access to, to determine this.
And ... if I may say ... "the Internet is positively stuffed with examples already!" Check out https://w3schools.com for some of the very-best free tutorials out there. Good luck!

Related

How to establish a communication between two users, if the id generated by the socketIO are auto generated?

Hello I hope you are very well, I would like to ask you a question that I have not been able to deduce the answer to.
In a course I was seeing that to send a message to a specific user with socketIO.js the to () method is used and the id as a parameter, but I have a doubt, that id is auto generated by socketIO as far as I understand, so I would like to know How can the frontend know that id? The example that I saw in the course does it from the console and sends it directly to the method with the id that it already knows, then that example is not so real, what I would like to know in itself How is it that it performs a one-to-one chat if the id is autogenerated by the socket? I don't know if I understand.
For example, to start a conversation with another user, you can click on a button, trigger an event that makes emit, send the id of the user who writes, the event that should trigger the backend with socket, but my question is how does it taste like who send the message? How do you know the id of who is being sent to when establishing communication between 2 users for the first time? Obviously this must be sent by frontent as a parameter but also how does the frontend give this id of who will it be sent to? I don't know if you can store a fixed socket id for a user in a DB or Can you use your DB id to use with sockets? more than everything is what I can not deduce how it would be done?
I do not know if I understood with the question, more than everything is that, I do not know how it obtains or assigns the id for the target from where the message is sent and if this can be fixed and stored in db or is there any method to this.
I thank you in advance for your response, and any resources that you share with me about it or if you recommend a course with, I would greatly appreciate it.
as an example I have this method
io.on('connection', (client) => {
client.on('privateMessage', (data)=>{
const person = user.getPersona(client.id) //get this
client.broadcast.to(data.para).emit('privateMessage', createMsj( person.name, data.messages));
});
}
But where does the front-end of the person to receive the message to pass it to the method?
The front-end will not know the socket.io id of any other clients. This is where your server needs to be involved.
Each of your users presumably has some username that is displayed in the client UI and this is the name that other clients would know them by.
So, your server needs to keep a mapping between username and socket.io clientID. So, a user can send a request to your server to connect to BobS. Your server then needs to be able to look up BobS, find out if that user is currently connected and, if they are, then what is their socket.id value. That way, your server can facilitate connecting the two users.
This mapping would not typically be kept in a permanent store (such as a database) because the socket.id is a transient value and is only good for the duration of that client's socket.io connection. As such, it is more typically just kept in some sort of Javascript data structure (such as a Map object).

How to check the existence of an email address

I am in charge of developing an application that needs to upload a lot of user data in a batch way. One of the users' data is an email address and we need to make sure that this email address really exists so that we can send a welcome message.
So, how could I check if an email address really exists?
You can check the format of an email address for RFC5322 compliance using npm email-validator:
const validator = require('email-validator')
...
if (validator.validate('test#email.com')) {
/* email format is correct */
}
But you're asking if there's a general and reliable way to ask the intertoobz if there's a real mailbox behind any given email address.
The answer is no, except by sending a message to the mailbox and asking the recipient to respond. There are unreliable ways to check for a mailbox's existence, but many mail transfer agents do not implement them. Why not? Spam.
Commercial mail services (Constant Contact, MailChimp, SendGrid) offer features to send a message to a mailbox requesting permission to give it a subscription to an email service. The person behind the mailbox usually responds by clicking a hyperlink. The hyperlink contains a nonce -- a hard-to-guess random value -- that identifies the mailbox. Only after the URL click can you be sure the address exists. Sometimes end-users are asked to "confirm your email address" using this technique.
Those same services are good about tracking email bounces and failures, so they can have a temporary idea about what mailboxes don't exist. They go to a lot of trouble to avoid sending junk, because the big email providers (gmail, outlook.com, comcast, charter, and the rest) routinely blacklist servers sending email, to lower their spam load. When you use a service, you're paying for a lot of network-engineering work to prevent blacklisting.
You can implement a similar "permission to subscribe" service in your own application, but explaining how to do that is beyond the scope of a StackOverflow answer. Keeping it from being blacklisted? Probably very difficult unless your volume is very low.
See this for more discussion.
Can I check if an email address exists using .net?
I've used SendGrid.com 's free service tier, and it works well. I've also used MailChimp successfully.
You can use a service like EmailChecker (I just did a quick google search) to check if the email really exists.
To use the API you need to pay for premium but you can see how it works here: https://email-checker.net
Validating that an email address is a legal (e.g., mailable) format is one thing, but it doesn't tell you that there's a mailbox at that address. The only way to know if an email address "exists" is to mail something to it. If it [eventually] bounces, you can be pretty sure that it doesn't exist. Otherwise, all you know is that somebody's SMTP server accepted the message.
See https://haacked.com/archive/2007/08/21/i-knew-how-to-validate-an-email-address-until-i.aspx/
and this:
How to check if an email address exists without sending an email?

Sending Message Requests

I am making a chat application using Socket.IO and Node.JS. I would like to implement message requests, such as the ones Facebook's Messenger has. I am not sure how to go about this problem.
If Mike wants to send a private message to Jake, Jake must first accept Mike's message request. Let's say Mike connects to the server using Socket.IO, and the server handles his request. Mike can then send sockets to the server, for example, a chat socket such as the one below:
socket.emit( 'chat', { // Emits the 'chat' socket to the server
name: 'Mike', // Sets the name of the sender
receiver: 'Jake', // Sets the name of the receiver
message: 'Hey Jake!' // Sets the message
} );
Now, obviously, this socket should be sent IF ANY ONLY IF Jake accepted the message request already. This is where the problem lies.
Message requests are stored in a database ( this is necessary for my application ).
I have a few ideas in mind on how to accomplish this:
Query the database each time a user sends a chat socket, to see if the receiver accepted the sender's request. Of course, this would mean that each time a chat is sent, I have a database query. This seems highly inefficient to me.
Query the database once somehow, and allow chat messages to go through without issuing a database query every time - although I am not sure how to accomplish this - hence this question.
I would love your input on this problem. Thanks!
The request you mentioned, is that request accepting should happen just once, like in facebook or it should be accepted for every message sent.
I hope it is just once, when the first message is sent. If this is the case then you can create a JSON file with an array containing Jake's friends(people accepted by Jake). Whenever someone tries to send a message to Jake, you just refer to the JSON files Jake's array to see if the sender is in the array list. If yes you can proceed with broadcasting message to Jake. If not in the array, send Jake a connection request from sender(Mike).
Since you are storing message requests in database, update the JSON file arrays when ever a new connection request is accepted by some one.
I hope this helps you. Comment below, if I am out of your scope anywhere.
There are multiple ways.
1) You can have caching done (as mentioned by #PM-77-1) which helps decrease number of database queries. Redis cache is really easy to use with Node.js. So whenever you are trying to check if Mike has Jake as a friend you can first check at cache level if Jake is in Mike's friend list. If Mike's friend list is not available you can fetch it from db once and store it in cache for future use.
2) You can also allow a user (Mike) to send around 100 to 200 short messages (just an example) and the messages are hidden for Jake until Jake accepts Mike's request. Having a limit on number of messages Mike can send without being a friend is a subjective question and it depends upon how famous application it is.

Protect PHP endpoints called by AJAX

My app consists of several PHP endpoints which are accessible via AJAX. The problem is they are also accessible via anyone who makes an HTTP request to the same endpoint. I can add checks for HTTP_X_REQUESTED_WITH and HTTP_REFERER as specified in this answer, but these can be spoofed. I could add a secret key that needs to be posted with the request, but anyone viewing the javascript and/or the console would be able to see this key. What is the solution here?
People often think that because they're using Ajax requests regular sessions don't work. They do.
If you have an endpoint to delete something from the database that's visible in the source code, such as:
example.com/user/1/delete
You can protect this request from non authenticated users the same way you would when using a non Ajax HTTP request in the browser. Using sessions. If the user has the privileges to remove users, this route will work, otherwise return an error (or do nothing).
You can also protect an API using OAuth. There's a great document here that explains how it works: http://tatiyants.com/using-oauth-to-protect-internal-rest-api/
Most of the answers are not helpful if you have your app and your api on separate domains for example app.example.com and api.example.com - in that case sessions won't work and you would have to turn to OAuth which is quite a big hammer for such a simple problem.
Here is what I would do:
I assume you have users in a database and a unique identifier like user_id=12345. I also assume that you have your Jobs in a Database and they also have unique ID's like job_id=6789.
First on app.example.com you encrypt both IDs with something fast and easy like Blowfish:
$secret_uid = mcrypt_encrypt(MCRYPT_BLOWFISH, "your_secret", strval($user_id));
$secret_jid = mcrypt_encrypt(MCRYPT_BLOWFISH, "your_secret", strval($job_id));
I assume your endpoint would work somewhat like this:
api.example.com/jobs/delete/<job_id>/<user_id>
so now from Ajax you call that endpoint, but instead of calling with plain IDs
api.example.com/jobs/delete/6789/12345
you call it with the encrypted IDs:
api.example.com/jobs/delete/6A73D5B557C622B3/57F064C07F83644F
On the API side of your software you decrypt the parameters:
$jid = mcrypt_decrypt(MCRYPT_BLOWFISH, "your_secret", <param_1>);
$uid = mcrypt_decrypt(MCRYPT_BLOWFISH, "your_secret", <param_2>);
Now you can search your db for uid and jid and perform whichever task you were planning to do. Make sure that a user can only delete his own jobs of course.
I admit this is not a 100% solution, but it leaves an attacker with a lot of guess work - he would have to guess the user_id and a matching job_id, the encryption algo and your secret. It does not protect against running millions of brute force attempts to guess a matching pair, but it put's the odds in your favor (and you should have some sort of quota limitation protection of your endpoints anyway).
Good luck!
There isn't one. If you give someone some data, then they can process it in whatever way they like. You can't control what happens to it after it leaves your server.
Likewise, you can't control what data they send to the endpoint.
it is very important for a developer to put authentication for API or web services. dchacke and BugHunterUK has given perfect answers, I just want show you simple code I use to make very simple and easy to use authentication.
Adding Session for the authentication
you can add session, and session timeout for your APIs so, only your app can use this, you can start session when front page of your app is loaded, you can set timeouts and also restrict the different service for different users by sessions.
General Idea how to do that
<?php
if(!empty($_SESSION['api_session']) && $_SESSION['api_session'] == 'usertype'){
//usertype comprise of what access you want to give
//guest, registered user, stack holder, admin etc.
...
header('Content-Type:application/json;');
echo json_encode($output);
}

How to use my long (60day) access token to get user data from facebook (offline)

I cannot find any example on facebook dev. or here on stackoverflow so I need to make this post which i didn't thought i had to.
I have a website which uses the facebook JavaScript SDK to login users into it.
When I log in users I uses the
FB.login(), scope:{'email, offline_access'}
When the login in done i get the short lived access token and passes it to:
https://graph.facebook.com/oauth/access_token?
grant_type=fb_exchange_token&
client_id=APP_ID&
client_secret=APP_SECRET&
fb_exchange_token=SHORT_LIVED_ACCESS_TOKEN
So i get the long lived, 60day, token in response. This is done server-side and i save the new long lasting token in my database along with facebook id etc.
Now to my problem. Every day at a certain time I want to update the users data in my database using the access token, which i have read that could. But how do i do that?
I'm used to do like this after the FB.login() but now when the user do not login I don't know how to do the call to FB.api using my persisted token?
FB.api(/me....)
Regards,
Kristoffer
As you have to synchronize/update information when user is not logged in you will have to use server side interaction.
You may use your saved Extended Access Token and set it into Facebook PHP SDK using setAccessToken() method.
$facebook->setAccessToken($extended_access_token);
After this you may call $facebook->api(...) method to perform the task that you intend to.

Categories

Resources