Update database record after user has logged in - asp.net-mvc

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.

Related

How to detect that the current request is an authentication callback?

I have a single-page JavaScript application and I'm using the Auth0 service for signup/login.
I have integrated the Lock widget and I'm saving a string to localStorage after a user is authenticated, like so:
lock.on("authenticated", function(authResult)
{
localStorage.setItem('login', authResult.idToken);
}
The problem is that when Auth0 redirects them back to my application after logging in, the authenticated event is fired only after page loaded, but by that time, I've already done the check to see if the localStorage string is set (which it is not); therefore, the user just keeps getting asked to login again:
if(localStorage.getItem('login') == undefined)
{
lock.show(function(err, profile, token)
{
// ...
}
}
I tried to see if there was anything special passed in to the page after a callback - but the referrer isn't always there.
If I don't automatically prompt the user to login, but instead show a login button - the authenticated event never fires for some reason.
How do I get around this?
Based on the information provided you seem to be using Lock in redirect mode and if that's the case you can use the hash_parsed event as a way to know if Lock found a response that it will process.
Every time a new Auth0Lock object is initialized in redirect mode (the default), it will attempt to parse the hash part of the URL, looking for the result of a login attempt. After that, this event will be emitted with null if it couldn't find anything in the hash. It will be emitted with the same argument as the authenticated event after a successful login or with the same argument as authorization_error if something went wrong.
Leveraging this event you could do the following:
Subscribe to the hash_parsed event:
If hash_parsed is emitted with null and localStorage has no indication the user already logged in then redirect to login.
If hash_parsed is emitted with a non-null value that either the authenticated or authorization_error will be emitted and you can react accordingly.
Some sample code:
lock.on("hash_parsed", function (response) {
if (!response && !localStorage.getItem('login')) {
// Redirect to the login screen
} else {
// Either the user is already logged in or an authentication
// response will be processed by Lock so don't trigger
// an automatic redirect to login screen
}
});

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

How to force Google OAuth popup in Firebase when user already authenticated previously?

Whenever a user has previously authenticated with Google, it automatically defaults to logging them in with THAT account on subsequent attempts. I want to eliminate this and force the popup/redirect so that a user with multiple google accounts can choose which one to use. How?
Background:
The automatic logging in feature is proving problematic for me as I have a whitelisted set of e-mails for users allowed to use my app. If a Google user chooses the wrong account when first logging in, they can't go back and choose the one associated to their whitelisted e-mail.
Just as #nvnagr said, you can do this with the following code:
var provider = new firebase.auth.GoogleAuthProvider();
provider.setCustomParameters({
'prompt': 'select_account'
});
But I think you need to update the firebase version to 3.6.0 something.
Google supports a parameter in authentication url to deal with this issue.
If you add prompt=select_account in your request to Google authentication, it'll force the user to do an account selection. See the details and other values of prompt.
https://developers.google.com/identity/protocols/OpenIDConnect#authenticationuriparameters
I'm not sure if there is an easy way to add this parameter through firebase api.
When you're calling the oAuth function, you can pass a third options parameter to make the authentication last for the session only. This should solve your problem. Docs
var ref = new Firebase("https://<YOUR-FIREBASE-APP>.firebaseio.com");
ref.authWithOAuthPopup("google", function(error, authData) {
if (error) {
console.log("Login Failed!", error);
} else {
console.log("Authenticated successfully with payload:", authData);
}
}, {
remember: 'sessionOnly'
});

KIK Card - sending message directly

I'm building new KIK Card and i would like to create button which will send messages to 5 people selected from kik.pickUsers Is there any command that allow me to send messages directly, without pressing button "send"? This is my code:
cards.kik.pickUsers({
minResults: 5, // number >= 5
maxResults: 99 // number < 99
}, function (users) {
if (!users) {
return;
}
users.forEach(function (user) {
cards.kik.send(user.username, {
title: 'Message',
text: 'Text!!!'
});
});
});
Messages cannot be sent directly without user consent (via pressing the "send" button) - this is a tactic to avoid apps spamming content messages on behalf of the user.
Regarding sending to multiple people, as of this writing you can only send a message to a group if the conversation already exists in Kik.
Iterating over the array of users returned from the picker and trying to use kik.send() for each will only work for the first user in the array.
The Pop app on Kik has a good implementation to overcome this for inviting friends to use the app. This may or may not be relevant depending on what you are developing.

jQuery: Continue custom click event on successful ajax login

I have a set of links (add to wishlist) with click event . The click event checks if the user is logged in (ajax request) and depending on the result the click continues. In the case the user is not logged in I have a generic jQuery UI modal dialog that the user can use to log in.
That all works well but I would like to extend the functionality to be able to continue with click of the links after the user logs in using the dialog.
ie. CLICK ADD TO WISHLIST -> LOGGED IN ?
YES -> CONTINUE LINK CLICK (add to wishlist)
NO -> SHOW LOGIN DIALOG ->
USER SUBMITS CREDENTIALS -> LOGGED IN?
YES => CONTINUE LINK CLICK (add to
wishlist)
NO => SHOW LOGIN ERROR
Of course I do not want to perform any postbacks, all through ajax and jquery.
Thanks
You could pass the url of the click action to the login modal and redirect after successful login.
Alternativly, if you have set it up to login via AJAX, you could store the click event target and then trigger a click event after a successful login.
Something like the following:
var is_logged_in = false;
$('a.add_to_wishlist').click(function(e) {
if(is_logged_in) {
//do stuff
} else {
show_modal(e.target); //pass the event target to the modal
}
});
function show_modal(trigger) {
//do stuff
is_logged_in = true;
$(trigger).trigger('click');
}
Hopefully this helps.
If you're in control of your server side code then you should place the authentication + save to wish list in the same request.
User clicks add to wish list
Ajax request to add page to wish list is sent to server.
Server check to see if user is logged in.
If the user is logged in: save the item to the wish list and return a success response.
If the user it not logged in: return a failed response.
The ajax response callback should update the UI based on the response.
If you're not in control of your server code then you'll have to make two ajax request if the authentication request is successful.

Resources