Creating private channel for user on login with pusher - laravel-5.1

I am attempting to implement pusher into a laravel application. Specifically I want to create a private channel when the user logs in.
I have a public channel "login" that has an event called "login-event" that gets triggered every time someone logs in.
The issue I am having is that the trigger that is supposed to create and subscribe to the private channel only fires for the users already logged in. not for the user that just logged in, which is the only user I actually need it to run for.
Pusher.js
$(function () {
var pusher = new Pusher('XXXXXXXXXX');
var channel = pusher.subscribe('login-channel');
channel.bind('login-event', function(data) {
// NOT RUNNING FOR USER WHO JUST LOGGED IN BUT RUNS FOR EVERYONE ELSE
var user = data.content.userID;
var newpusher = new Pusher('XXXXXXXXXXX', {
userid: $('meta[name="user"]').attr('content'),
authEndpoint: '/pusher/auth',
auth: {
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
}
});
var newchannel = newpusher.subscribe('private-channel-for-'+user+'');
console.log('Setting up a channel for user '+user+'.');
});
I need to "login-event' in the code above to also run for the user that just logged in.
I have looked over the docs about as much as I can take, if the answer is clearly in there feel free to provide a link but it would be great if I could get a suggestion in code.

Related

Re enter without password after revoke salesforce oauth token

I built a simple app that allows our customers to gather specific information from their Salesforce system. For authentication I used "WebServer Flow", which allows a user to log in to our site with his Salesforce account.
I should of course allow the user to log out of his account. But for some reason, even though I send a Revoke request to Salesforce and get an OK response, when the user redirected again to the Salesforce login page, it automatically logs in to the previous account without re-entering details.
this is the logout action in my backend,
public async Task<ContentResult> LogOutFromSalseforce(string code)
{
AuthenticationClient auth;
bool hasAuth = AuthSessionWrapper.AuthDic.TryGetValue(code, out auth);
if (!hasAuth) return Content(JsonConvert.SerializeObject(new { error = "session expired" }), "application/json");
var url = auth.InstanceUrl + _revokeEndpointUrl;
var cl = new HttpClient();
var res = await cl.PostAsync(url, new FormUrlEncodedContent(new[] { new KeyValuePair<string, string>("token", auth.RefreshToken) }));
AuthSessionWrapper.AuthDic.Remove(code);
return Content(JsonConvert.SerializeObject(new { success = res.StatusCode == HttpStatusCode.OK }), "application/json");
}
And after call from client to this action he redirected to our login page.
I found that even if i call to this revoke endpoint from client it's not work.
only if the user enter in another tab to Salesforce and click logout there, he need to re enter his details to login again to our site.
What I'm doing wrong?
If someone get into the same problem, I solved it with add "&prompt=login" to the login redirect url.

How to handle user creation with Firebase social auth and a Rails backend

I am building a react native application with a rails backend but I decided to go for Firebase for authentication only since it's quite a bit cheaper than Auth0 or Okta.
The setup went fine but I am having trouble figuring out where to call my own backend to create/update a user in the sign in process.
This is my current sign in function that is triggered when pressing the 'Sign in with Facebook' button:
async function handleAuthentication() {
const result = await LoginManager.logInWithPermissions(['public_profile', 'email']);
if (result.isCancelled) {
return;
}
const data = await AccessToken.getCurrentAccessToken();
if (!data) {
return Alert.alert('Error', 'Something went wrong while authenticating with Facebook.');
}
const facebookCredential = auth.FacebookAuthProvider.credential(data.accessToken);
// This token doesnt seem to work
await upsertUser(facebookCredential.token);
await auth().signInWithCredential(facebookCredential);
}
What I get back from the auth.FacebookAuthProvider.credential(data.accessToken) is an object with a token but that doesn't seem to be useful.
When I call auth().signInWithCredential(facebookCredential); I do get back the user data that I need to create a user BUT that already triggers the authentication system and sets the user as signed while he/she isn't created in the backend yet.
So ideally, I would like to create the user before calling signInWithCredential.
Although I'm not sure how to do this or with what token?
I use a Rails backend where I can also decode the token if necessary.
Any help would be greatly appreciated!

Parse cloud push notifications are pushing to all users instead of targeted user

I'm having trouble targeting the push notifications to a single user. Right now my test device is receiving a push notification no matter which user is logged into the device. Even when I send a push to _User that is currently logged out and the device is logged in with a completely different _User it receives the push notification.
I have set up cloud code with parse.com to enable push notifications to be sent to users. I have a "user" pointer in the installation class that points to the cooresponding _User that is to receive the push notification.
Example: _User "Sam" is logged in to the mobile device. I send a push from the iOS simulator in Xcode to _User "steve". The mobile device receives the push even though "Sam" is logged in. It receives the push even if NO user is logged in.
When I check the Push control on parse, it seems like the cloud cloud is correctly querying the "user" pointer in the installation that matches the objectId for the _User class, as seen here:
user advanced operator ($inQuery {"className"=>"_User", "objectId"=>"LJQXaJDzkU"})
SENDING TIME
August 5th, 2015 at 3:01 PM
EXPIRATION
None
FULL TARGET
{
"user": {
"$inQuery": {
"className": "_User",
"objectId": "LJQXaJDzkU"
}
}
}
FULL DATA
This is the cloud code that queries the user and sends the push from the parse cloud. The recipientUserId receives a string of the objectId for the _User whom is receiving the push.
Parse.Cloud.define("sendPush", function(request, response) {
var senderUser = request.user
var recipientUserId = request.params.recipientId;
var senderUserId = request.params.senderId;
var message = senderUserId + " sent a message"
var recipientUser = new Parse.User();
recipientUser.id = recipientUserId;
var pushQuery = new Parse.Query(Parse.Installation);
pushQuery.matchesQuery('user', recipientUser);
Parse.Push.send ({
where: pushQuery,
data: {
aps: {
alert: message,
badge: "Increment",
sound: "cow-moo1.wav"
}
}
}, {
success: function() {
response.success("Success!");
},
error: function(error) {
response.error(error);
}
});
});
The pushes send no problem, and I can open them on the device but I'm really lost as to why the pushes are being sent to the device even when the queried user isn't even logged in to the device. Any ideas as to whats going on would be greatly appreciated. Thanks!!!
Edit your code so that when you log out, you're removing the user from the installation.
Edit - This was mentioned in the comments below, so I want to make sure it was mentioned here in case it was the solution that worked. OP used matchesQuery, which requires a query to be passed in, but was passing in a Parse.User object instead. I suggested he used equalTo instead of matchesQuery.

Update database record after user has logged in

What I'm trying to achieve is similar to how the login works here on StackOverflow. If you are not logged in you can still see questions but if you try to +1 some of the questions you are asked to login. When you do login your +1 is remembered and added to the question.
This is my scenario:
A user search for members and selects one - login is not required
After selecting a member the user is redirected to a feedback page where the user can write a feedback message to the member
The user writes the feedback and click Save
No matter if the user is logged in or not the feedback is saved
If the user is not logged in a popup will open where the user will be asked to login
After the user logs in the feedback, created in step 4, will be updated with the user's Id
The user is redirected back to the search page from step 1
I'm stuck at step 6. I can't figure out what the best way of getting the Id of the logged in user and then update the feedback message after that.
This code represents step 5. It simply sends the feedback message to the controller and saves it. After the message is .done I call the login popup. The return message.Data contains the Id of the feedback message (which just has been created) and which I need after the user logs in.
function saveModel(feedbackMessage) {
cc.Ajax.jpost(urlSave, { feedbackMessage: feedbackMessage })
.done(function (message, textStatus, jqXHR) {
if (message.Status == 2) { // user not logged in
openSignInModal(message.Data);
}
})
}
This code represents step 6. The returned data is a partial view containing the login page.
function openSignInModal(feedbackId) {
var url = '/Account/LoginPartial';
$.ajax({
url: url,
type: 'get',
data: { returnUrl: '/Subscriber/Search', subTitle: feedbackNotSignedIn, modalTitle: '' },
success: function (data, textStatus, jqXHR) {
$('#pc_modal_container').html(data);
$('#pc_modal').modal('show');
},
});
}
If the user logs in then I want to get the Id of the user and update the feedback message with the logged in user's id (similar to what I explained in the beginning with StackOverflow).
My questions are:
Where should I keep the feedback message Id which I get in step 4 so I can use it to update the feedback message?
When the user is logged in and I want to update the feedback message how can I handle this best? I know I could store it in TempData but I don't really see this at the best option, or is it?
I have tried to find examples online but nothing that fits this well enough. Does anyone know of any examples which could fit this scenario?
Thanks
Try this process. It do not have any technical detail, but I believe it will be enougth to accomplish your goal.
During the feedback POST, preserve the feedback post ID into a Cache variable, as PendingFeedBacks
Make these cached data availabe only to current session, and with low expiration period
Somewhere, if the user is authenticated, and there is any pending feedback to be adopted, do it!
I do not believe that this should be the best solution, but it will do the trick.

Preventing strangers accessing WEBRTC pages

I am creating a sample application to tryout WEBRTC. I came across a tutorial that explains the process. I tried copying the code and it seems to work.
Question is:
I ONLY want a few people to access the page that containing the stream. How can i prevent other unauthorised users from accessing my page. A tutorial that walks through the process would be ideal.
the language i am using to develop is Grails.
You can use authentication plugin for the grails to deny unauthorized request. You can even use Socket.io over Node.js to prevent unauthorized users where you can check "userid":
// socket.io nodejs side code
io.sockets.on('connection', function (socket) {
var userid = socket.handshake.query.userid;
// verify userid
if (typeof objUserArrays[userid] == 'undefined') {
// don't broadcast messages; so that user can NEVER join any room.
return;
}
});
and browser side code:
var socket = io.connect('http://your-domain.com/?userid=something');
For last snippet; you can check meeting.js's openSignalingChannel method:
meeting.openSignalingChannel = function(callback) {
return io.connect('http://your-domain.com/?userid=something').on('message', callback);
};

Resources