how to store login information using onsen ui? - angularjs

I want to use onsen ui and angularjs to develop a hybird application, but now I meet a problem, this application cannot store user's login information, so user must login everytime after they close the application.
I use $cookies, service, and $rootScope to store user's login information, but all of them can not work at android platform.
Anyone can help me to solve this problem?

On HTML5 mobile framework like Onsenui, I suggest to use localStorage.
You can take a look at these two AngularJs modules:
angular-local-storage
ngStorage
They have very well written instructions and demo codes as references.

use this plugin https://github.com/litehelpers/Cordova-sqlite-storage or something similar to create a sqlite database. Create a table with the information you want to keep (username and password). You can create a hash of the password and store it for better security (md5 or sha1).
You can also keep the timestamp of the login and keep the user logged in for a specific interval of time, so when he opens the app, check if you are inside this interval (e.g. day, week, etc.) from the last login and if yes, log him in automatically else show the login screen again.

if (window.localStorage.getItem("rememberMe") == "true") {
$scope.userEmail = window.localStorage.getItem("userName");
$scope.userPassword = window.localStorage.getItem("password");
document.getElementById("rememberMe").checked = true;
}
else {
document.getElementById("rememberMe").checked = false;
}
if (document.getElementById("rememberMe").checked == true) {
window.localStorage.setItem("rememberMe", "true");
window.localStorage.setItem("userName", $scope.userEmail);
window.localStorage.setItem("password", $scope.userPassword);
}
else if (document.getElementById("rememberMe").checked == false) {
window.localStorage.setItem("rememberMe", "false");
window.localStorage.setItem("userName", "");
window.localStorage.setItem("password", "");
}
Hi! have a look at the above code. It stores in local storage

Related

How to know Order is placed from authenticated customer or guest In salesforce commerce cloud?

Hello I am new to salesforce commerce cloud and I am working on controller version of SFCC that is SGJC version. I wanted to know is there is any method or how will we know whether customer who has placed the order has placed as guest or as autheticated customer. I want to write a if else redirection logic. If placed order is from guest redirect to A.isml else redirect to B.isml. Any method from orderMgr class will be helpful.
You can try to use:
var order = OrderMgr.getOrder(orderNo);
var registered = order.getCustomer().isRegistered();
From the docs
There is also a difference between Registered and Authenticated customer. An Authenticated customer is a registered customer that is also logged, with an active authenticated session.
To check if the customer is authenticated you can use isAuthenticated() method instead of isRegistrered()
You can try the code same as below:
var order = OrderMgr.getOrder(orderNo);
if (!empty(order) && empty(order.getCustomerNo()) {
// Redirect to A.isml
}
if (!empty(order) && !empty(order.getCustomerNo()) {
// Redirect to B.isml
}
Ref docs.

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.

PrestaShop - Login programmatically

I am writing a android and windows native app. The native app stores the login details as reated for mulitple other web apps, and logs them into this when browsing to them from the native app.
one of the buttons in my app open a prestashop site for a authenticated user. How can i set the username and password and log that user in to the site programmitcally, giving the illusion and user experience that he has been seemlessly authenticated and accessed to his shop.
I know this is an old question, but theres another way which i find better for the purpose.
You include the AuthController from the controllers folder, set your post-parameters and execute the postProcess() method. After this, you can check the "$authController->errors" array for errors. If it's empty - the login was successful.
Example:
public function hookDisplayHeader()
{
if ($this->context->cookie->isLogged())
{
return;
} else {
$acceptLogin = false;
if( isset( $_POST["email"] ) && isset( $_POST["passwd"] ) )
{
$acceptLogin = $this->attemptLogin($_POST["email"],$_POST["passwd"]);
}
if( $acceptLogin )
return;
die( $this->display(__FILE__, 'logintemplate.tpl') );
}
}
protected function attemptLogin($email, $password)
{
include _PS_FRONT_CONTROLLER_DIR_ . "AuthController.php";
$auth = new AuthController();
$auth->isAjax = true;
$_POST["email"] = $email;
$_POST["passwd"] = $password;
$_POST["SubmitLogin"] = true;
$auth->postProcess();
if( count($auth->errors) > 0 )
{
$this->context->smarty->assign( "errors", $auth->errors );
return false;
} else {
return true;
}
}
Edit: This no longer works with Prestashop 1.6. As of PS 1.6 $auth->postProcess() either redirects or sends the ajaxs response immediately. There is no way to circumvent this. If you want to do something after login, you have to make two ajax calls.
Basically do the same as the PrestaShop login form does, which is (for v1.5 at least):
Sending a POST request to http(s)://yourshop.com/index.php?controller=authentication with the following parameters:
email: your customer's email address
passwd: your customer's password
back: name of the controller you want to be redirected to after success (ex: my-account)
SubmitLogin: put anything there, it just needs to be true, so that the controller knows it's a login action
If it doesn't work, your version may work differently and you will have to check the network tab of your favourite developer tool, to see what kind of request is sent with which parameters.

How do I test Cloud Endpoints with Oauth on devserver

My app uses Oauthed Cloud Endpoints and is working fine in production.
My problem is that on the local devserver, my User user is always set to example#example.com, even though I've gone through the usual auth, access code, etc etc etc and have a valid authed user.
I get that example#example.com is useful to test oauth endpoints before I have oauth working properly, but since my app is working I'd rather see the actual user there.
To be specific, my endpoint method is
#ApiMethod(name = "insertEmp"), etc
public Emp insertEmp(User user, Emp emp) {
System.out.println(user.getEmail()); // (A) log "appengine" email
System.out.println(OAuthServiceFactory.getOAuthService().getCurrentUser().getEmail(); // (B) log authed email
...
When deployed, everything is fine, and both (A) and (B) log the authenticated user (my.email#gmail.com).
When testing on my local devserver, (A) always logs "example#example.com", even though I have gone through the Oauth sequence and have a valid, authenticated user, and (B) logs my.email#gmail.com. So I can do hi-fidelity testing, I need the User to be the real authenticated user.
So in simple terms, how do I get (A) and (B) to be the same?
It seems it can't be done. I've ended up coding around it by putting the following code at the top of my Endpoint methods.
if ("example#example.com".equalsIgnoreCase(user.getEmail()) {
user = new User(OAuthServiceFactory.getOAuthService().getCurrentUser().getEmail(),"foo");
}
So now, even on devserver, the User email matches the Oauth email.
This is not so easy. You'll have to make your settings in the APIs Console. Here you will be able to add "localhost" (http://localhost/) Then you can authenticate, through Google, even though you are running you application on your localhost for development.
I have used it extensively, and it works OK
Links: https://code.google.com/apis/console/
Just remember the ID's you use here is completely independent of you appengine ID.
Took me a few hours to figure that one out.
The thing is that when you are doing the authentication in local, you are not doing it through the Google servers so authenticating your user is something that actually is not happening in local.
Google always provides the example#example.com user when you try to simulate the log in, it happens basically in all the services, like when you provide a log in through your Google Account in any web site (for instance using GWT and App Engine).
What can be different in your site if you test with your real user or you consider example#example.com user as your user?
In your endpoint API you need this
ApiMethod ( name="YourEndPointName", path="yourPath",
clientIds={"YourId.apps.googleusercontent.com"},
scopes = { "https://www.googleapis.com/auth/userinfo.profile" })
Then in the called method, you will have a User object from the GAPI.
Use this to get the actual email from the google User object like this
public myEndPointMethod( Foo foo, User user ){
email = user.getEmail();
}
I replaced the Oauth2 user (example#example.com) with user from UserFactory and it works fine. I use this method to validate user for all API authenticated API requests.
public static User isAuthenticated(User user) throws OAuthRequestException{
if(user == null){
throw new OAuthRequestException("Please login before making requests");
}
if(SystemProperty.environment.value() ==
SystemProperty.Environment.Value.Development && "example#example.com".equalsIgnoreCase(user.getEmail()) ) {
//Replace the user from the user factory here.
user = UserServiceFactory.getUserService().getCurrentUser();
}
return user;
}
Using the go runtime I have resorted to this function to obtain a User that is functional on both the dev server and production:
func currentUser(c context.Context) *user.User {
const scope = "https://www.googleapis.com/auth/userinfo.email"
const devClient = "123456789.apps.googleusercontent.com"
allowedClients := map[string]bool{
"client-id-here.apps.googleusercontent.com": true,
devClient: true, // dev server
}
usr, err := user.CurrentOAuth(c, scope)
if err != nil {
log.Printf("Warning: Could not get current user: %s", err)
return nil
}
if !allowedClients[usr.ClientID] {
log.Printf("Warning: Unauthorized client connecting with the server: %s", usr.ClientID)
return nil
}
if (usr.ClientID == devClient) {
usr = user.Current(c) // replace with a more interesting user for dev server
}
return usr
}
This will use the dev server login information entered using http://localhost:8080/_ah/login
It's not possible.
I use another endpoint to replace user_id in current session.

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/

Resources