Identifying users in Rails Web push notifications - ruby-on-rails

I'm developing a Rails application, and I'd like to send web push notifications to specific users when certain actions happen, e.g:
A user started tracking a timer, but the timer has been running for more than 6 hours. Then the app sends that user a web notification.
I've been doing research and found this tutorial, the author implements push notifications for Rails, however there's no insight on how to identify the users.
From what I understood, the users needs to subscribe from their browser to be able to get push notifications, however, considering each user can use the application from multiple browsers, how can I automatically subscribe/unsubscribe a user for notifications in all browsers they use the app from?

So, what I did was adding a notification_subscription model to my User model.
On my javascript, I check if there's a current browser subscription present:
this.serviceWorkerReady()
.then((serviceWorkerRegistration) => {
serviceWorkerRegistration.pushManager.getSubscription()
.then((pushSubscription) => {
if (pushSubscription && _.includes(subscriptionEndpoints, pushSubscription.endpoint)) {
return;
}
this.subscribe();
});
});
I check if the current subscription is already present in the user stored endpoints, and subscribe if it isn't.
On subscription I send the new endpoint to the backend, which adds the new subscription to the user:
$.post(Routes.users_subscriptions_path({ format: 'json' }), {
subscription: subscription.toJSON()
});
Then I can send notifications to users to every endpoint:
def push_notifications_to_user(user)
message = {
title: "A message!",
tag: 'notification-tag'
}
user.notification_subscriptions.each do |subscription|
begin
Webpush.payload_send(
message: JSON.generate(message),
endpoint: endpoint,
p256dh: p256dh,
auth: auth,
api_key: public_key
)
rescue Webpush::InvalidSubscription => exception
subscription.destroy
end
end
end
The webpush gem raises an InvalidSubscription exception if the endpoint is invalid, we can destroy that endpoint to keep only the valid endpoints from the user.

The endpoint is unique by browser so you need an additional authentication scheme on the top of your app to send user's information along with the new endpoint.

You need to attach metadata (i.e. the user ID) to the endpoint when you store it on your server:
#subscription = Subscriptions.new endpoint: params[:endpoint]
#subscription.user = current_user
// or if you send with AJAX the user id together with the endpoint
#subscription.user = User.find params[:user_id]
In the second case I suggest to sign the user ID or use a secret token, otherwise anyone would be able to subscribe to push notifications as if it was another user.
Then you can delete from the database all the endpoints that belong to that user ID to unsubscribe all his devices.
However I don't think it's a good practice: a user may want to receive notifications on a device and not on another one.

Related

How to handle payment success in stripe?

After a user visits the payments page and successfully makes a payment, Stripe will redirect the customer to whatever url is provided to success_url
Stripe.api_key = 'sk_test_51HYHSFGtUKse83O9J4QeAib3cp8sHzGaOQRrn7sba92Hd8dCHE3AIHe5ModevMK7TVAUCyJU0ADSwIUoX00qxZmBI9r'
session = Stripe::Checkout::Session.create({
payment_method_types: ['card'],
line_items: [{
name: 'Kavholm rental',
amount: 1000,
currency: 'aud',
quantity: 1,
}],
payment_intent_data: {
application_fee_amount: 123,
transfer_data: {
destination: '{{CONNECTED_STRIPE_ACCOUNT_ID}}',
},
},
success_url: 'https://example.com/success',
cancel_url: 'https://example.com/failure',
})
Now the app/platform must arrange 'fulfillment':
After the payment is completed, you’ll need to handle any fulfillment necessary on your end. A home-rental company that requires payment upfront, for instance, would connect the homeowner with the renter after a successful payment.
Also (bold from me):
Do not rely on the redirect to the success_url param alone for fulfilling purchases as:
Malicious users could directly access the success_url without paying and gain access to your goods or services.
Customers may not always reach the success_url after a successful payment. It is possible they close their browser tab before the redirect occurs.
Up to this point, everything is very well explained in the stripe docs and very understandable.
But I want to know: what is the best thing to do next, noting that:
a payment may not go through immediately, so simply loading the success_url might be premature
a webhook can be (easily) configured to listen for events, however if the success_url is loaded even 1 second before the webhook receives a success message, then it won't know that the payment went through successfully (so, for example, displaying "Congrats, your product will be shipped!" message could be presumptuous
Question
So, finally, the question: what is best practice for the flow on from success_url? I am just confused as to what is the best pattern..
Ideas
Here are some things I've considered:
Upon routing to success_url, simply use sleep(5) and then check the webhook in the controller for the success_url so it takes 5 extra seconds to load giving the webhook a chance to receive incoming events, so you can display either "Congrats your product will be shipped!" or "Oh, no, something went wrong with your payment, please try again or contact your bank".
Routing directly to success_url, but then having a message saying "please refresh in a moment" (then listening for a webhook indicating the payment was successful, and then conditionally showing the "Congrats your product will be shipped!" message)
The documentation for fulfilling orders has this in an info box under the code snippet:
Your webhook endpoint redirects your customer to the success_url when you acknowledge you received the event. In scenarios where your endpoint is down or the event isn’t acknowledged properly, your handler redirects the customer to the success_url 10 seconds after a successful payment.
The event referenced above is the checkout.session.completed event sent to your webhook endpoint. The delay is designed to let you confirm the payment is successful and customize the success page based on the result of the Checkout Session's outcome.
In other words, Checkout won't send someone to your success_url until you've responded to the checkout.session.completed event request from your webhook endpoint with a successful (2xx) response, giving you time to customize the success page based on the outcome.
You can, for example, default to a "your payment is being processed" success page, but if you confirm the Checkout Session and payment succeeded after receiving the checkout.session.completed event, you can instead change the page to read "congrats your product will be shipped".
This approach means you can reliably present a success page that always has displays accurate information.

How to authenticate user with token (stay authenticated in iPhone)

I have two related questions and I hope someone help me because I've been stuck for 2 days
First: mobile phone failed to authenticate
Here is what I have done:
1- user signs up
2- token released
3- token saved in user's device
but then when the same user try to do API requests I get
Rooute to sign up :
$api = app('Dingo\Api\Routing\Router');
$api->version('v1', function ($api) {
$api->post('auth/signup', 'App\Api\V1\Controllers\AuthController#signup');
then I get a token , so I guess everything looks great!
then now when the same device sends a post request to laravel I get this message
"message": "Failed to authenticate because of bad credentials or an invalid authorization header."
this is the route to the post request
$api->group(['middleware'=>'api.auth'],
function ($api) {
$api->post('auth/ios', 'App\Api\V1\Controllers\AuthController#create');
Second: is my method right to save data made by a mobile phone?
Since I couldn't test this method I'd like to know if this is at least one of the right ways to receive data and save it. The reason to save it is because I will show it in a control panel.
public function create(Request $request)
{
$user = new User();
$id = Auth::id();
$user->phone = $request->input('phone');
$user->city = $request->input('city');
$user->street = $request->input('street');
$user->save();
return 'Employee record successfully created with id ' . $user->id;
}
I understand that you are authenticate users based on api token.
Here is what you could do :
set up a column called api_token in users table by adding the following migration
$table->string('api_token', 60)->unique();.This generates a random api token for every user.
send the api_token back to the user's device and save it there
Send it back with every request. Preferalbly set it up globally and send it in the request Authentication request header
Get the authenticated user like so$user= Auth::guard('api')->user();
Laravel takes care of all the authentication stuff behind the scenes.
Learn More about this here

Bigcommerce - How to request Authorization Code/Access Token

In my application, the user when installs the app, needs to fill a registration form. I need to save the access_token along with the user instance.
So, if the user is unregistered, I redirect to the signup form ie. I dont save the access_token, but at this time, the app is registered. Which means, suppose when the store admin logs back in to the app, he does not get the auth code again, but gets signed_payload.
Since, I dont want to store, unregistered users on my database, I prefer calling a api, that would grant me auth code and/or access_token.
Is there any such call I can make?
To answer your question, the access token can only be obtained at the point of the initial app install, when the user installs the app for the very first time. This is the only time that BigCommerce will send the information required to obtain the access token.
Therefore your app should always save the access_token at the point of install. Your registration page should be prompted after obtaining and saving the access token. If for some reason the user installs the app and does not complete the registration, then you should simply just check on your end if the registration was finished or not, and if it wasn't then you should display it during the app load phase as a requirement before displaying your main app dashboard.
Since you didn't specify a programming language, I'm going to illustrate one in Python.
There are two parts you mentioned, registration/access token and signed payload.
The initial callback flow would look something like this:
#app.route('/bigcommerce/callback')
def auth_callback():
# Put together params for token request
code = flask.request.args['code']
context = flask.request.args['context']
scope = flask.request.args['scope']
store_hash = context.split('/')[1]
redirect = app.config['APP_URL'] + flask.url_for('auth_callback')
# Fetch a permanent oauth token. This will throw an exception on error,
# which will get caught by our error handler above.
client = BigcommerceApi(client_id=client_id(), store_hash=store_hash)
token = client.oauth_fetch_token(client_secret(), code, context, scope, redirect)
bc_user_id = token['user']['id']
email = token['user']['email']
access_token = token['access_token']
The flow using a signed payload would look something like:
#app.route('/bigcommerce/load')
def load():
# Decode and verify payload
payload = flask.request.args['signed_payload']
user_data = BigcommerceApi.oauth_verify_payload(payload, client_secret())
if user_data is False:
return "Payload verification failed!", 401
bc_user_id = user_data['user']['id']
email = user_data['user']['email']
store_hash = user_data['store_hash']
When initially creating a user in your database, you can also denote the sign up date through a function of your code and then do a periodic cron job to check if they have a registered account with you. There's not an endpoint where we store whether they completed registration with you since that is a function of your app.

Twilio check if phone number has been blacklisted

I am currently integrating into the twilio rest api and need to perform a check on a users phone number to determine if that user has blacklisted themselves or not. I have little experience with this api and scouring through the documentation and google has turned up nothing.
In our application we are going to have a notification center and if the user has blacklisted themselves I do not want to give them the ability to turn on their SMS notifications. Potentially a user could have SMS notifications on but twilio would block any messages. I know there is the ability to get a status code back from twilio when an SMS is queued that shows the user is blacklisted (https://www.twilio.com/docs/api/rest/message). However, I will not be sending messages on the notifications screen and need a direct way (if at all possible) to check twilio to determine if a number is blacklisted. Any help is much appreciated. Let me know if anymore information will be of help.
Megan from Twilio.
I'd be curious to see if you ever tried your own workaround. But I wanted to note for others in a similar situation how you could grab the blacklist error and then do whatever you may want with it.
In Ruby it would look something like this:
require 'rubygems'
require 'twilio-ruby'
account_sid = 'YOUR_ACCOUNT_SID'
auth_token = 'YOUR_AUTH_TOKEN'
#client = Twilio::REST::Client.new account_sid, auth_token
begin
#message = #client.messages.create(
from: 'TWILIO_NUMBER',
to: 'USER_NUMBER',
body: 'Howdy!'
)
rescue Twilio::REST::RestError => e
if e.code == 21610
# User is blacklisted
# Store info however you choose
puts e.message
end
end
We check for blacklisting specifically using the code '21610'. For more information about errors you can visit the reference page.
Hope this helps!
Twilio recommends developers to store the opt-out/in statuses in their side. I have stored it in DB. There are 2 ways to collect the unsubscribed users list.
1) Use SMS webhooks. You can find how to configure your Twilio number to receive webhook events here
#PostMapping(value = "/twilio", consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE,
produces = MediaType.APPLICATION_ATOM_XML_VALUE)
public String twilioConsumer(TwilioEventDTO twilioEventDTO) {
// twilioEventDTO.getBody() => returns the body of the SMS user replied.
twilioService.consume(twilioEventDTO);
return new MessagingResponse.Builder().build().toXml();
}
2) Since I implemented webhooks later, I had to collect already unsubscribed users. When you send sms to the number that has been opted-out, Twilio API throws an exception with the status number of 21610. You can catch it and store the number in DB.
try {
Message result = Message.creator(
new PhoneNumber(toPhoneNumber),
new PhoneNumber(fromPhoneNumber),
messageBody)
.create();
response = result.getStatus().name();
} catch (ApiException e) {
if (e.getCode().equals(21610))
updateSubscription(toPhoneNumber, false);
logger.warn("Error on sending SMS: {}", e.getMessage());
}
P.S.: examples written in Java - Spring Boot framework.

Get notifications using Twitter gem

I'm trying to get Twitter notifications using Twitter gem.
I'm using the method notifications from Twitter::User but the value is always false even though I receive emails from Twitter about those new notifications :
twitter = current_user.get_twitter_api
#twitter_user = twitter.user(current_user.authentications.find_by_provider("twitter")['username'])[:notifications]
def get_twitter_api
twitter_info = self.authentications.find_by_provider("twitter")
twitter_api = Twitter::Client.new(:oauth_token => twitter_info['fb_token'],:oauth_token_secret => twitter_info['uid']) if twitter_info
return twitter_api
end
Have you tried calling notifications as a method on the user object, for example:
#twitter_user = twitter.user(current_user.authentications.find_by_provider("twitter")['username']).notifications
I remember using this gem and finding geo coordinates on an individual tweet by doing:
tweet.geo
Twitter doesn't have an API endpoint for receiving notifications, assuming that by notifications you mean the content at http://twitter.com/i/notifications. The notifications value that you can in the API response is actually
notifications
Boolean
Nullable. Deprecated. May incorrectly report “false” at times. Indicates whether the authenticated user has chosen to receive this user’s tweets by SMS
that's from https://dev.twitter.com/overview/api/users

Resources