Integrate Parse with Pusher - android

As per the Pusher docs, for a client to subscribe to a private channel he needs to undergo some authorization process. Could someone guide me on how to achieve this using Parse? I already have integrated Facebook login with Parse for my android application. Im not too familiar with web development code so had difficulty in understand this
HttpAuthorizer authorizer = new HttpAuthorizer(http://example.com/some_auth_endpoint);
PusherOptions options = new PusherOptions().setAuthorizer(authorizer);
Pusher pusher = new Pusher( YOUR_APP_KEY, options );

Somebody has written a Parse module that offers authentication functionality: https://github.com/kashif/pusher-parse
The auth example from the README is:
app.post('/authorise', function(req, res) {
var socketId = req.body.socket_id;
var channel = req.body.channel_name;
var user_id = channel.split("-")[1];
var user = Parse.Object.extend("User");
var query = new Parse.Query(user);
query.get(user_id, {
success: function(userAgain) {
var presenceData = {
user_id: userAgain.id,
user_info: {
username: userAgain.get("username"),
email: userAgain.get("email")
}
};
var auth = pusher.authenticate( socketId, channel, presenceData );
res.send(auth);
},
error: function(model, error) {
res.status(403);
res.send('Forbidden');
}
});
});

Related

Using Azure KeyVault for React Native

I am not using Azure Active Directory authentication in my React Native application.
I want to keep some keys on the cloud so that a user can easily configure without redeploying the complete application.
I was thinking about Azure KeyVault, so the question is, is it possible to use key vault, can I do without showing the authentication page.
If there is any other solution for this let me know.
You can use script code to get the value of the key. Don't need to showing the authentication page.
Below is a simple console code:
//const { DefaultAzureCredential } = require("#azure/identity");
const { ClientSecretCredential } = require("#azure/identity");
const { SecretClient } = require("#azure/keyvault-secrets");
const readline = require('readline');
function askQuestion(query) {
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
return new Promise(resolve => rl.question(query, ans => {
rl.close();
resolve(ans);
}))
}
async function main() {
const keyVaultName = "bowmantest";
const KVUri = "https://" + keyVaultName + ".vault.azure.net";
//const credential = new DefaultAzureCredential();
tenantId = "e4c9ab4e-bdxxxxxx-230ba2a757fb";
clientId = "d340361e-5dxxxxxxbaf4-6e81aed46ed9";
clientSecret = "2X~43qA-~J2xxxxxxnT1a7_O2-dKyTK";
const credential = new ClientSecretCredential(tenantId, clientId, clientSecret);
const client = new SecretClient(KVUri, credential);
const secretName = "testbowmansecret";
console.log("Retrieving your secret from " + keyVaultName + ".");
const retrievedSecret = await client.getSecret(secretName);
console.log("Your secret is '" + retrievedSecret.value + "'.");
}
main()
And I can get: (don't need to go to authentication page, but authentication is still needed.)
By the way, you need to give the AD app the access permission:
This is the api documentation:
https://learn.microsoft.com/en-us/javascript/api/#azure/identity/clientsecretcredential?view=azure-node-latest
https://learn.microsoft.com/en-us/javascript/api/%40azure/keyvault-secrets/secretclient?view=azure-node-latest
(You can find everything about JavaScript with Azure in above documentation).

Firebase Trigger Razorpay Intergration for Android

I am creating an App Where user can buy coins and for that I have been trying to integrate Razorpay into my Android App since a long time now. Razorpay can directly be used in Android. It sends Success or Failure results for payment and I can act accordingly (adding points to database in this case). But the problem with this approach is that I have to write points (after success) to database from the app. Which means I have to give write access for points node to user app which is not a good idea. So I wanted to use Razorpay with Firebase Cloud Functions and searching for a long time I came across this tutorial which is for web. I am quite new to Cloud Functions and hence wanted a little help for Android.
Here is the Index.js code but For Web
const functions = require("firebase-functions");
var express = require("express");
var cors = require("cors");
var request = require("request");
const crypto = require("crypto");
const key = "----insert yout key here----";
const key_secret = "----- insert key secret here ----";
var app = express();
app.use(cors({ origin: true }));
app.post("/", (req, res) => {
const amount = req.body.amount;
//Allow Api Calls from local server
const allowedOrigins = [
"http://127.0.0.1:8080",
"http://localhost:8080",
"https://-------YourFirebaseApp-----.firebaseapp.com/"
];
const origin = req.headers.origin;
if (allowedOrigins.indexOf(origin) > -1) {
res.setHeader("Access-Control-Allow-Origin", origin);
}
var options = {
method: "POST",
url: "https://api.razorpay.com/v1/orders",
headers: {
//There should be space after Basic else you get a BAD REQUEST error
Authorization:
"Basic " + new Buffer(key + ":" + key_secret).toString("base64")
},
form: {
amount: amount,
currency: "INR",
receipt:
"----- create a order in firestore and pass order_unique id here ---",
payment_capture: 1
}
};
request(options, function(error, response, body) {
if (error) throw new Error(error);
res.send(body);
});
});
app.post("/confirmPayment", (req, res) => {
const order = req.body;
const text = order.razorpay_order_id + "|" + order.razorpay_payment_id;
var signature = crypto
.createHmac("sha256", key_secret)
.update(text)
.digest("hex");
if (signature === order.razorpay_signature) {
console.log("PAYMENT SUCCESSFULL");
res.send("PAYMENT SUCCESSFULL");
} else {
res.send("something went wrong!");
res.end();
}
});
exports.paymentApi = functions.https.onRequest(app);
I think this will help you.
In my case, I am accessing items(Array of Product IDs) from the user's cart and reading the current price of the items then passing it as an argument to SendOrderId function which will return an OrderId to proceed.
The important thing to keep in mind is that you must have added razorpay in your dependencies inside package.json. You can do that by simply running
npm i razorpay
inside your functions folder (Which include index.js) which will automatically add the dependency to your project
const functions = require("firebase-functions");
const admin = require('firebase-admin');
const Razorpay = require('razorpay')
const razorpay = new Razorpay({
key_id: 'Your_razorpay_key_id',
key_secret: 'your_secret'
})
admin.initializeApp();
function SendOrderId(amountData, response) {
var options = {
amount: amountData, // amount in the smallest currency unit
currency: "INR",
};
razorpay.orders.create(options, function(err, order) {
console.log(order);
response.send(order);
});
}
exports.getOrderId = functions.https.onRequest((req, res) => {
return admin.firestore().collection('Users').doc(req.query.uid).get().then(queryResult => {
console.log(queryResult.data().Cart);
admin.firestore().collectionGroup("Products").where('ProductId', 'in', queryResult.data().Cart).get().then(result => {
var amount = 0;
result.forEach(element => {
amount += element.data().price;
});
SendOrderId(amount * 100, res);
})
})
});

How to invoke lambda function in android?

So i made this lambda function, and in that function I made an if statement, which creates me a user in a user table in dynamoDB. How do i call that ONLY call that if statement in my lambda function from android?
Here is my lambda function
exports.handler = function(event, context)
{
console.log('stageA');
console.log(JSON.stringify(event, null, ' '));
var responseCode = 200;
var userTableName = "usersTable";
var requestBody = event.body;
var pathParams = event.path;
var httpMethod = event.httpMethod; // HTTP Method (e.g., POST, GET, HEAD)
//User parameters
var displayName;
var email;
var fbUserID;
var firstName;
var folders;
var lastName;
var origin;
var profileImageRef;
var level;
var username;
var birthdate;
var experience;
var folder;
if (pathParams == "/user/createByEmail" && httpMethod == "POST")
{
console.log('create by email action');
requestBody = JSON.parse(requestBody);
//Set variables
firstName = requestBody.firstName;
lastName = requestBody.lastName;
email = requestBody.email;
username = requestBody.username;
experience = "0";
birthdate = requestBody.birthdate;
dynamodb.putItem(
{
"TableName": userTableName,
"Item" :
{
"displayName":{"S": username},
"email":{"S": email},
"firstName" : {"S" : firstName},
"folderNames" : {"M" : {
"My Cards": {"N": "0" }
} },
//"folders" : {"M" : {"My Cards": {}}},
"lastName" : {"S" : lastName},
"experience" : {"N" : experience},
"username": {"S": username},
"birthdate": {"S": birthdate}
}
},
function(err, data)
{ if (err) {
console.log(err);
context.done(err);
} else {
var response =
{
statusCode: responseCode,
headers:
{
"x-custom-header" : "custom header value"
},
body: JSON.stringify(username)
};
console.log('great success: %j',data);
context.succeed(response);
}
});
}
And in android, i made an interface which will be called in an AsyncTask to call my lambda function:
public interface MyInterface {
/**
* Invoke lambda function "echo". The function name is the method name
*/
#LambdaFunction
String user(String userEmail);
/**
* Invoke lambda function "echo". The functionName in the annotation
* overrides the default which is the method name
*/
#LambdaFunction(functionName = "myUserAPiFxnName")
void noUser(NameInfo nameInfo);
}
I am new to AWS and lambda, and really hope for your guide. I am not sure if i am doing this write, and hope someone has a clear cut way with steps!
Cheers!
it seems as though you would use Cognito to map user identities to IAM roles providing temporary access privileges to call the function directly. I'm not using cognito in production, nor developing Android, but my cognito does two things for you: one, it provides authentication and authorization with many federated identity services ( facebook, google, saml, oath2, etc ), and two, it provides a user access model so you don't have to program one yourself. you can pull displayName, email, birthdate from the identity service, and not have to handle logins. You can go straight to the part where you make your program.
You'd configure an identity pool in cognito and attach some identity provider(s), and invoke apis of first the identity providers and then AWS. Finally, your application would be able to invoke the lambda functions you write.
Not knowing anything about android, I'd guess there was some user identity you already had access to, probably a google identity.

FCM (Firebase Cloud Messaging) Push Notification with Asp.Net

I have already push the GCM message to google server using asp .net in following method,
GCM Push Notification with Asp.Net
Now i have planned upgrade to FCM method, anyone have idea about this or developing this in asp .net let me know..
2019 Update
There's a new .NET Admin SDK that allows you to send notifications from your server.
Install via Nuget
Install-Package FirebaseAdmin
You'll then have to obtain the service account key by downloading it by following the instructions given here, and then reference it in your project. I've been able to send messages by initializing the client like this
using FirebaseAdmin;
using FirebaseAdmin.Messaging;
using Google.Apis.Auth.OAuth2;
...
public class MobileMessagingClient : IMobileMessagingClient
{
private readonly FirebaseMessaging messaging;
public MobileMessagingClient()
{
var app = FirebaseApp.Create(new AppOptions() { Credential = GoogleCredential.FromFile("serviceAccountKey.json").CreateScoped("https://www.googleapis.com/auth/firebase.messaging")});
messaging = FirebaseMessaging.GetMessaging(app);
}
//...
}
After initializing the app you are now able to create notifications and data messages and send them to the devices you'd like.
private Message CreateNotification(string title, string notificationBody, string token)
{
return new Message()
{
Token = token,
Notification = new Notification()
{
Body = notificationBody,
Title = title
}
};
}
public async Task SendNotification(string token, string title, string body)
{
var result = await messaging.SendAsync(CreateNotification(title, body, token));
//do something with result
}
..... in your service collection you can then add it...
services.AddSingleton<IMobileMessagingClient, MobileMessagingClient >();
C# Server Side Code For Firebase Cloud Messaging
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;
using System.Web.Script.Serialization;
namespace Sch_WCFApplication
{
public class PushNotification
{
public PushNotification(Plobj obj)
{
try
{
var applicationID = "AIza---------4GcVJj4dI";
var senderId = "57-------55";
string deviceId = "euxqdp------ioIdL87abVL";
WebRequest tRequest = WebRequest.Create("https://fcm.googleapis.com/fcm/send");
tRequest.Method = "post";
tRequest.ContentType = "application/json";
var data = new
{
to = deviceId,
notification = new
{
body = obj.Message,
title = obj.TagMsg,
icon = "myicon"
}
};
var serializer = new JavaScriptSerializer();
var json = serializer.Serialize(data);
Byte[] byteArray = Encoding.UTF8.GetBytes(json);
tRequest.Headers.Add(string.Format("Authorization: key={0}", applicationID));
tRequest.Headers.Add(string.Format("Sender: id={0}", senderId));
tRequest.ContentLength = byteArray.Length;
using (Stream dataStream = tRequest.GetRequestStream())
{
dataStream.Write(byteArray, 0, byteArray.Length);
using (WebResponse tResponse = tRequest.GetResponse())
{
using (Stream dataStreamResponse = tResponse.GetResponseStream())
{
using (StreamReader tReader = new StreamReader(dataStreamResponse))
{
String sResponseFromServer = tReader.ReadToEnd();
string str = sResponseFromServer;
}
}
}
}
}
catch (Exception ex)
{
string str = ex.Message;
}
}
}
}
APIKey and senderId , You get is here---------as follow(Below Images)
(go to your firebase App)
public class Notification
{
private string serverKey = "kkkkk";
private string senderId = "iiddddd";
private string webAddr = "https://fcm.googleapis.com/fcm/send";
public string SendNotification(string DeviceToken, string title ,string msg )
{
var result = "-1";
var httpWebRequest = (HttpWebRequest)WebRequest.Create(webAddr);
httpWebRequest.ContentType = "application/json";
httpWebRequest.Headers.Add(string.Format("Authorization: key={0}", serverKey));
httpWebRequest.Headers.Add(string.Format("Sender: id={0}", senderId));
httpWebRequest.Method = "POST";
var payload = new
{
to = DeviceToken,
priority = "high",
content_available = true,
notification = new
{
body = msg,
title = title
},
};
var serializer = new JavaScriptSerializer();
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = serializer.Serialize(payload);
streamWriter.Write(json);
streamWriter.Flush();
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
result = streamReader.ReadToEnd();
}
return result;
}
}
To hit Firebase API we need some information from Firebase, we need the API URL (https://fcm.googleapis.com/fcm/send) and unique keys that identify our Firebase project for security reasons.
We can use this method to send notifications from .NET Core backend:
public async Task<bool> SendNotificationAsync(string token, string title, string body)
{
using (var client = new HttpClient())
{
var firebaseOptionsServerId = _firebaseOptions.ServerApiKey;
var firebaseOptionsSenderId = _firebaseOptions.SenderId;
client.BaseAddress = new Uri("https://fcm.googleapis.com");
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.TryAddWithoutValidation("Authorization",
$"key={firebaseOptionsServerId}");
client.DefaultRequestHeaders.TryAddWithoutValidation("Sender", $"id={firebaseOptionsSenderId}");
var data = new
{
to = token,
notification = new
{
body = body,
title = title,
},
priority = "high"
};
var json = JsonConvert.SerializeObject(data);
var httpContent = new StringContent(json, Encoding.UTF8, "application/json");
var result = await _client.PostAsync("/fcm/send", httpContent);
return result.StatusCode.Equals(HttpStatusCode.OK);
}
}
These parameters are:
token: string represents a FCM token provided by Firebase on each app-installation. This is going to be the list of app-installations that the notification is going to send.
title: It’s the bold section of notification.
body: It represents “Message text” field of the Firebase SDK, this is the message you want to send to the users.
To find your Sender ID and API key you have to:
Login to the Firebase Developer Console and go to your Dashboard
Click on the “gear” icon and access “project settings”
Go to the
“Cloud Messaging Section” and you will have access to the sender ID
and the API Key.
Here is my VbScript sample for who prefers vb:
//Create Json body
posturl="https://fcm.googleapis.com/fcm/send"
body=body & "{ ""notification"": {"
body=body & """title"": ""Your Title"","
body=body & """text"": ""Your Text"","
body=body & "},"
body=body & """to"" : ""target Token""}"
//Set Headers :Content Type and server key
set xmlhttp = server.Createobject("MSXML2.ServerXMLHTTP")
xmlhttp.Open "POST",posturl,false
xmlhttp.setRequestHeader "Content-Type", "application/json"
xmlhttp.setRequestHeader "Authorization", "Your Server key"
xmlhttp.send body
result= xmlhttp.responseText
//response.write result to check Firebase response
Set xmlhttp = nothing
2020/11/28
download this file from Firebase -> Settings -> Service accounts -> Firebase Admin SDK
Move the downloaded file to Your dotnet Core Root folder then change it's name to key.json for example .
then add this code to your .csproj file: YourProjectName.csproj in your project root folder :
<ItemGroup>
<None Update="key.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
</ItemGroup>
then add this code to your Program.cs in Main function :
var defaultApp = FirebaseApp.Create(new AppOptions()
{
Credential =
GoogleCredential.FromFile(Path.Combine(AppDomain.CurrentDomain.BaseDirectory,
"key.json")),
});
Last thing is the code that will push notification :
public async Task SendNotificationAsync(string DeviceToken, string title ,string body){
var message = new Message()
{
Notification = new FirebaseAdmin.Messaging.Notification
{
Title = title,
Body = body
},
Token = DeviceToken,
};
var messaging = FirebaseMessaging.DefaultInstance;
var result = await messaging.SendAsync(message);
}
Put it in any Controller then u can call it to send notification ...
that is what i did to push notificaion and it is working very well and fast ...
Use CorePush lib
It's very lightweight. I use it across all my projects to send Firebase Android, WebPush and Apple iOS push notifications. Useful links:
NuGet package
Documentation
The interface is very simple and minimalistic:
Send APN message:
var apn = new ApnSender(settings, httpClient);
await apn.SendAsync(notification, deviceToken);
Send FCM message:
var fcm = new FcmSender(settings, httpClient);
await fcm.SendAsync(deviceToken, notification);
I don't believe there is any change in the way you are sending push notifications. In FCM also, you are going to make HTTP POST Request the same way you did for GCM:
https://fcm.googleapis.com/fcm/send
Content-Type:application/json
Authorization:key=AIzaSyZ-1u...0GBYzPu7Udno5aA
{ "data": {
"score": "5x1",
"time": "15:10"
},
"to" : "bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1..."
}
Read about FCM Server for more information.
The only change I could see now, is the target Url. Period.

Authenticate with OneDrive SDK in Xamarin Android App

I use the onedrive SDK in a Cross Plattform app. On Windows the Authentication works via the OneDriveClientExtensions.GetClientUsingWebAuthenticationBroker.
Now I'm trying to login on Android. I tried it with this:
oneDriveClient = OneDriveClient.GetMicrosoftAccountClient(
appId: MSA_CLIENT_ID,
returnUrl: RETURN_URL,
scopes: scopes,
clientSecret: MSA_CLIENT_SECRET);
await oneDriveClient.AuthenticateAsync();
But get an error that no valid token could be received. Do I have to implement a own AuthenticationProvider inhereting from WebAuthenticationBrokerAuthenticationProvider who shows a browser for the oauth? Or what would be the way to go here?
I solved this using the Xamarin Auth Component. Heres the code who calls the webview with the login:
private const string RETURN_URL = #"https://login.live.com/oauth20_desktop.srf";
private void ShowWebView()
{
var auth = new OAuth2Authenticator(
clientId: MSA_CLIENT_ID,
scope: string.Join(",", scopes),
authorizeUrl: new Uri(GetAuthorizeUrl()),
redirectUrl: new Uri(RETURN_URL));
auth.Completed += (sender, eventArgs) =>
{
if (eventArgs.IsAuthenticated)
{
//Do Something
}
};
var intent = auth.GetUI(Application.Context);
intent.SetFlags(ActivityFlags.NewTask);
Application.Context.StartActivity(intent);
}
private string GetAuthorizeUrl()
{
var requestUriStringBuilder = new StringBuilder();
requestUriStringBuilder.Append("https://login.live.com/oauth20_authorize.srf");
requestUriStringBuilder.AppendFormat("?{0}={1}", Constants.Authentication.RedirectUriKeyName, RETURN_URL);
requestUriStringBuilder.AppendFormat("&{0}={1}", Constants.Authentication.ClientIdKeyName, MSA_CLIENT_ID);
requestUriStringBuilder.AppendFormat("&{0}={1}", Constants.Authentication.ScopeKeyName,
string.Join("%20", scopes));
requestUriStringBuilder.AppendFormat("&{0}={1}", Constants.Authentication.ResponseTypeKeyName,
Constants.Authentication.TokenResponseTypeValueName);
return requestUriStringBuilder.ToString();
}

Categories

Resources