How to store user details for further use in angularjs - angularjs

I am working on web application using angularjs. I need the user's email address throughout my application, how can I store it for further use?
Currently what I am doing is:
I have created a user service
'use strict';
var module = angular.module('moduleName');
module.factory('UserService',['$resource',function($resource){
var currentUserEmail = null;
return {
getUserResource : function(){
return $resource('users',{email:'#email'});
},
saveCurrentUserEmail : function (email){
currentUserEmail = email;
},
getCurrentUserEmail : function (){
return currentUserEmail;
}
};
}]);
At login, I store the user email address using the user service:
UserService.saveCurrentUserEmail($scope.username);
Now, when I go to another view, in the controller, the user email is what I expect.
console.debug("Current User email "+UserService.getCurrentUserEmail());
Which prints the user's email address
But when I refresh the page with (ctrl+f5). then the current user email is null.
Current User email null
What I am doing wrong, or what should I do to save this email address for further use?

You are getting printed user email because before printing it you called your service UserService.saveCurrentUserEmail($scope.username);
Now when you refresh your page(ctrl+f5),this service is not called, so it is printed as null because its initialize with null value.
So you need to call saveCurrentUserEmail when your page gets load.

On Page refresh you need to make a call to server to check if your is login and update the
$scope.username
and store it using
UserService.saveCurrentUserEmail($scope.username);
Or
You can use client side store in browser or use cookie to http://docs.angularjs.org/api/ngCookies.$cookieStore to store user info

Instead of using service, use $cookieStore.
http://docs.angularjs.org/api/ngCookies.$cookieStore
emailAddress for example is - "a#a.com"
//That's how i am assigning value
$cookieStore.put('emailAddress', $scope.user.emailAddress);
//thats how i am retrieving it
addr = $cookieStore.get('emailAddress');

Related

force.com sites - direct link to salesforce visual force page not working

Am facing an obstacle using force.com site
a template email is used to send to portal users with direct link to some record in salesforce
example https://example.force.com/SamplePage?id=xxxxx
by trying to use refURL param half way was done as in the next example :
https://example.force.com?refURL=/SamplePage?id=xxxxx
but passing from an obstacle to facing another,now every time i click on the new link in the email i have to re-login again regardless that i just made a login.
so for the first attempt its logical to input the credentials to login to the site but i need to prevent when the session still on to re login again every time by clicking on the link from my email
my login code in Apex is as below :
global PageReference login() {
//Get refUrl
String strRefUrl = System.currentPageReference().getParameters().get('refURL');
//Get startUrl
String strStartUrl = System.currentPageReference().getParameters().get('startURL');
if(strRefUrl != null && strRefUrl != '' && ! strRefUrl.startsWithIgnoreCase(Site.getBaseInsecureUrl() )){
//Need to remove domain part because site.login() does not redirect to absolute URL
strStartUrl = strRefUrl.replace(Site.getBaseRequestUrl(),'');
}
else if (strRefUrl.startsWithIgnoreCase(Site.getBaseInsecureUrl())){
//Redirect to base URL if refUrl is empty
strStartUrl = Site.getBaseUrl() + '/LoginPage';
}
return Site.login(username, password, strStartUrl );
}

How to set the Access-Token for the password reset in LoopBack with the AngularJs SDK

My Project is based on the
Loopback Getting Started Tutorial 2
I use the AngularJs SDK on the Client-Side and I want to implement the "Password-Reset"-Function.
First there is the /reset-password view, where you can enter your email address and ask for another password.
Then you get a link send per email that directs you to /set-new-password/{{accessToken}}/{{userId}}
On this view, the user enters the password and submit it. Afterwards it should find the User by Id and update its password.
But for User.findById and User.updateById I need the access-token in the Request-Header.
"Normally" the Request-Header always contains the access-token after the login. But since it's a password-reset, I'm not logged in.
I can access the access-token via $stateparams, but how can I set it in the Request-Header,so I can still use the AngularJs-SDK?
(I hope everything is clear. English is not my native language)
Edit: I have found someone with nearly the same question here. The not accepted answer works for me now.
EditEdit: Doesn't work always.. Sometimes it doesn't change the "authorization"-parameter in the Header. Can't figure out why
The solution with the LoopBack AngularJs SDK
In your angularJs controller
.controller(function (UserAccount, $location, LoopBackAuth, $scope) {
var params = $location.search();
var access_token = params.access_token;
$scope.reset = function(inputs) {
LoopBackAuth.setUser(access_token);
UserAccount.setPassword({ newPassword: inputs.newPassword });
}
})
You need to implement error control and ideally check the password twice before sending.

How to check user password in angular's strongloop SDK?

I want to check the current user's password in order to allow him to change his/her password.
According to the user model docs, the way to do this is using the user.hasPassword method, by I get a "is not a function" error.
https://docs.strongloop.com/display/LB/User#user-prototype-haspassword
There is no reference to this in the angular SDK docs, so I'm guessing this method is not avalable from angular. https://docs.strongloop.com/display/public/LB/AngularJS+JavaScript+SDK#AngularJSJavaScriptSDK-Authentication
Any clues on how to accomplish this?
Sorry if this is just semantics, but if you are using the built in User model, you don't ever "check a user's password," you check if they are authenticated with a valid authToken that is set in a header.
But if you are trying to change a user's password and requiring them to log in before changing it, you can also just call User.login() and verify that you get a success response from the API. Then use the new password and persist it by updating the User instance with an update or updateAttributes.
See https://apidocs.strongloop.com/loopback-sdk-angular/#user
Will look something like this (warning: quick writeup, not tested!):
User.login({email: $scope.email, password: $scope.oldPassword}, function(response){
// user login was valid, now update user with new password by user id
//
User.prototype$updateAttributes({id: response.user.id}, {password: $scope.newPassword},
function(response) {
// success
}, function(response) {
// fail
});
}, function(response) {
// login failed, send to login screen
});

Google Custom Search and Passing along Querystring Variables

I am working on a web app project that has been in development for long time. The app has two sides, the majority of the site is publicly accessible. However, there are sections that require the user to be logged in before they can access certain content.
When the user logs in they get a sessionid (GUID) which is stored in a table in the database which tracks all sort for data about the user and their activity.
Every page of the app was written to look if this session id variable exists or not in the querystring. If a user tries to access one of these protected areas, the app checks to see if this sessiond variable is in the querystring. If i is not, they are redirected to the login screen.
The flow of the site moves has the user moving seamlessly from secured areas to non-secured areas, back and forth, etc.
So we did a test run with the Google Custom Search and it does an awesome job picking up all our dynamic content in these public areas. However, we have not been able to figure out how to pass the sessionid along with the search results IF the user is logged in already.
Is it possible to pas querystring variables that already exist in the url along with the search results?
As far as I know, this is not possible. Google doesn't give you the possibilty to modify the URL's of the Search Results in their Custom Search.
A possible solution would be to store your Session-Key to a Cookie, rather than passing it with every URL.
Use the parseQueryFromUrl function
function parseQueryFromUrl () {
var queryParamName = "q";
var search = window.location.search.substr(1);
var parts = search.split('&');
for (var i = 0; i < parts.length; i++) {
var keyvaluepair = parts[i].split('=');
if (decodeURIComponent(keyvaluepair[0]) == queryParamName) {
return decodeURIComponent(keyvaluepair[1].replace(/\+/g, ' '));
}
}
return '';
}
Select RESULTS ONLY option in the Look & Feel and it will provide you with the code.
www.google.com/cse/

how can i get current user name in Silverlight 2.0

Hi guys i m making one asp.net project with silverlight2.0 .But i cannot get current user name... how can i get current user name
thanks...
I basically handle this in one of two ways.
1) Use the ASP.NET Silverlight control. When the server control loads, grab the current user name using HttpContext.Current.User.Identity.Name and send it in as an InitParam into the silverlight control.
2) I generally only need the user name when I call back to the server. If the service requires windows authentication, you can just call HttpContext.Current.User.Identity.Name inside the service to get the user name
Basically, you need to implement a service that will return current user info to the client and call this service on Silverlight application startup.
The example of the service:
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Required)]
public class UserInfoService : IUserInfoService
{
public UserInfo GetUserInfo()
{
if (HttpContext.Current.User.Identity.IsAuthenticated)
return null;
var userInfo = new UserInfo
{
Login = HttpContext.Current.User.Identity.Name,
Fullname = ...,
};
return userInfo;
}
}

Resources