page refresh causing user to get log out automatically in angular js - javascript

I have a Login API which I am using it in my service
function logInToService(callback, errback, login, password, rememberLogin) {
var url = "User/Login";
var authorizationHeader = {'Authorization': "Basic " + login + ":" + password};
httpWrapperService.post(url, {login: login, password: password}, authorizationHeader).then(
function success(loginToken) {
// transform data here
self.currentUser.emailAddress = login;
self.currentUser.password = password;
// store token in a cookie
self.currentUser.token = loginToken;
$rootScope.currentUser = self.currentUser;
if (rememberLogin) {
localStorage.userName=login;
localStorage.password=password;
}
httpWrapperService.setAuthenticationToken(loginToken);
callback(loginToken);
},
function error(errorObject) {
errback(errorObject);
}
);
}
And in my header html I am displaying the user name on top when he gets logged in
Header.html
<div class="header-user-menu">
<div ng-show="isUserLoggedIn() == false ">
{{'HEADER.LOGIN' | translate}}
<!--<a ui-sref="app.sr.login" class="">{{'HEADER.LOGIN' | translate}}</a>-->
</div>
<div ng-show="isUserLoggedIn()" class="userName">{{'HEADER.WELCOME' | translate}} {{currentUser.emailAddress}}</div>
</div>
and js file is here
(function() {
'use strict';
angular
.module('safe-repository')
.controller('AppLayoutCtrl', appLayoutCtrl);
// Implementation of controller
appLayoutCtrl.$inject = ['$rootScope', '$scope'];
function appLayoutCtrl($rootScope, $scope) {
$scope.isUserLoggedIn = isUserLoggedIn;
function isUserLoggedIn() {
if ($rootScope.currentUser
&& $rootScope.currentUser.emailAddress != null
&& $rootScope.currentUser.emailAddress != '') {
return true;
}
return false;
}
}
})();
and here I have one registration service where I have defined logInToService method
function registrationService($rootScope, httpWrapperService, $modal, $state, $cookieStore) {
var self = this;
// expose functions
self.hasUserAccessToLevel = hasUserAccessToLevel;
self.logInToService = logInToService;
self.getCurrentUserToken = getCurrentUserToken;
self.showRegistrationViewForLevel = showRegistrationViewForLevel;
self.currentUser = {
//emailAddress: '',
//password: '',
//token: ''
}
$rootScope.currentUser = null;
self.currentUserToken = null;
function logInToservice (------){----}})();
The problem is that every time when user presses page refresh F5 , user gets logged out. Even though I am trying to store the data in localstorage , but actually I am not getting the flow of control.

You are trying to save the data into localStorage, but you are not reading it.
The currentUser variable you have the user data in is a regular javascript variable which gets reset when you reload the page.
You need to do something like this:
// ...
// user logs in, remember it into the local storage
// Note: is is better to use it via $window.localStorage
$window.localStorage.setItem('user', JSON.stringify(user));
this.currentUser = user;
//...
// function to get the user, if this.currentUser is not set,
// try to load from the local storage
getUser: function() {
if (this.currentUser) {
return this.currentUser;
}
var storageUser = $window.localStorage.getItem('user');
if (storageUser) {
try {
this.user = JSON.parse(storageUser);
} catch (e) {
$window.localStorage.removeItem('user');
}
}
return this.currentUser;
}
// you may also want to remove the user data from storage when he logs out
logout: function() {
$window.localStorage.removeItem('user');
this.currentUser = null;
},

you need to create a session for login so that it does not log out after page refresh. have a look at this link:
http://maffrigby.com/maintaining-session-info-in-angularjs-when-you-refresh-the-page/

Related

Angular js Web Application failed to Return Expected Message

I am consuming WCF Rest Service into Angular js web application. First I am checking username in database . If the username name is exist then i want to display message in angular js web application is username name is exist please choose other username .If username is not exist then i want to insert the record into database .But the problem is its not displaying message username is not displaying expected message and i got following error .
The server encountered an error processing the request. The exception message is 'Non-static method requires a target.'. See server logs for more details. The exception stack trace is:
Here is the Method.
public bool RegisterUserEncryptPassword(tblUser user)
{
using (HalifaxDatabaseEntities context = new HalifaxDatabaseEntities())
{
var query = (from x in context.tblUsers
where x.Username == user.Username
select x).SingleOrDefault();
if (query != null)
{
return true;
}
else
{
tblUser createUser = new tblUser();
createUser.Username = user.Username;
createUser.Password = Utility.Encrypt(user.Password);
createUser.Email = user.Email;
ctx.tblUsers.Add(createUser);
ctx.SaveChanges();
}
}
return false;
}
Here is my script code..
var app = angular.module("WebClientModule", [])
.controller('Web_Client_Controller', ["$scope", 'myService', function ($scope, myService) {
$scope.OperType = 1;
$scope.createuser = function () {
var User = {
Username: $scope.Username,
Password: $scope.Password,
Email: $scope.Email
};
if ($scope.OperType === 1) {
var promisePost = myService.post(User);
promisePost.then(function (pl) {
$scope.Id = pl.data.Id;
window.location.href = "/Login/Index";
ClearModels();
}, function (err) {
$scope.msg = "Password Incorrect or username is exit !";**//Always Hit on This line**
console.log("Some error Occured" + err);
});
}
}]);
app.service("myService", function ($http) {
//Create new record
this.post = function (User) {
var request = $http({
method: "post",
url: "http://localhost:52098/HalifaxIISService.svc/RegisterUserEncryptPassword",
data: JSON.stringify(User)
});
return request;
};
})
Here is the Screen shot when i run the application.When i try to insert new record i i want to display
here is error message in network tab.
You need to bind the #scope.msg into an html element like label or span. This html element must be loaded inside the DOM with hidden status. You have to just show it with ng-show.

Get parameters and store and use them on variables to use on my method

I want to get some parameters and use them to reset password function from firebase.
This is how my link looks like:
http://localhost:8080/passwordreset?mode=resetPassword&oobCode=y6FIOAtRUKYf88Rt5OlEwxUuTyEmb3M4gquZSIseX2UAAAFevpj-gw&apiKey=AIzaSyBaCCvq-ZEfQmdrL7fmElXDjZF_J-tku2I
I want to get mode, oobCode and apiKey.
Here is what I have for now:
export default {
data: function() {
return {
passwordNew: '',
passwordConfirm: '',
mode:'',
actionCode: '',
continueUrl: '',
}
},
methods: {
handleResetPassword: function() {
var accountEmail;
firebase.auth().verifyPasswordResetCode(actionCode).then(function(email) {
var accountEmail = email;
firebase.auth().confirmPasswordReset(this.actionCode, this.passwordNew).then(function(resp) {
alert("Password reset success");
this.$router.push('hello')
}).catch(function(error) {
// Error occurred during confirmation. The code might have expired or the
// password is too weak.
console.log("error 1")
});
}).catch(function(error) {
// Invalid or expired action code. Ask user to try to reset the password
// again.
console.log("error 2")
});
},
}
}
From Firebase documentation:
Some user management actions, such as updating a user's email address
and resetting a user's password, result in emails being sent to the
user. These emails contain links that recipients can open to complete
or cancel the user management action. By default, user management
emails link to the default action handler, which is a web page hosted
at a URL in your project's Firebase Hosting domain.
link: https://firebase.google.com/docs/auth/custom-email-handler
You need to get those parameters and store them on variables, from firebase documentation i got those snippets and just wrote the getParameterByName function:
function getParameterByName( name ){
name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regexS = "[\\?&]"+name+"=([^&#]*)";
var regex = new RegExp( regexS );
var results = regex.exec( window.location.href );
if( results == null )
return "";
else
return decodeURIComponent(results[1].replace(/\+/g, " "));
}
// Get the action to complete.
var mode = getParameterByName('mode');
// Get the one-time code from the query parameter.
var actionCode = getParameterByName('oobCode');
// (Optional) Get the continue URL from the query parameter if available.
var continueUrl = getParameterByName('continueUrl');
You need to get those parameters first and verify the actioncode on the verifyPasswordResetCode method, then you can change the password and store it along with the action code to the method.
In your export default :
data: function() {
return {
passwordNew: '',
passwordConfirm: '',
mode: mode,
actionCode: actionCode,
continueUrl: continueUrl,
}
},
methods: {
handleResetPassword: function() {
var passwordNew = this.passwordNew
var actionCode = this.actionCode
firebase.auth().verifyPasswordResetCode(actionCode).then(function(email) {
console.log("ActionCode: "+ actionCode);
firebase.auth().confirmPasswordReset(actionCode, passwordNew).then(function(resp) {
alert("Password reset success");
this.$router.push('hello')
}).catch(function(error) {
console.log("error 1"+ error)
});
}).catch(function(error) {
console.log("Action code is invalid"+ error)
});
},
}

trouble on using lb-services (Loopback - Angular JS SDK)

I'm using lb-services from Angular JS SDK to create my default service, and currently, I have some trouble in logout & rememberMe function.
I'm following this tutorial : Angular Javascript SDK & Loopback getting started intermediate , and the way I create my authentication is as same as the example, with some adjustment to apply them in my application.
I'm not sure how to describe it, but here's some of the code for my logout & remember function
in my stateProvider, I have this kind of state as my root application
.state('app', {
url:'/',
abstract: true,
views:{
'bodyLogin': {templateUrl : 'views/login/body.html',
controller : 'BodyController'},
'bodyMain': {templateUrl : 'views/main/body.html',
controller : 'BodyController'}}
})
.state('app.mainUnreg', {
url:'home',
views: {
'content#app': {
templateUrl : 'views/login/home.html'
}}})
.state('app.mainReg', {
url:'mainMenu',
views: {
'header#app': {
templateUrl : 'views/main/header.html'
},
'sidebar#app': {
templateUrl : 'views/main/sidebar.html'
},
'middle#app': {
templateUrl : 'views/main/home.html'
},
'footer#app': {
templateUrl : 'views/main/footer.html'
}},
controller: 'HomeController'})
index.html
<div ng-if="!loggedIn" ui-view="bodyLogin" class="site-wrapper" ui-sref-active="app.mainUnreg"></div>
<div ng-if="loggedIn" ui-view="bodyMain" ui-sref-active="app.mainReg"></div>
so, if I haven't not logged in, I will enter to bodyLogin, which means I will show my login template, and otherwise, if I have logged in, I will enter to bodyMain
I have succeed to logged in and enter to my main page, but on here, and it should be have been authenticated, because in my bodyController,
.controller('BodyController', [..., function(...){
//this line is to check whether the user has been authenticated or not
if(Account.isAuthenticated() === false) {
$scope.loggedIn = false;}
// ------------
if($scope.loggedIn === false){
$scope.layout = 'login';
$state.go('app.mainUnreg');
}
else{$scope.loggedIn = true;
$scope.layout = 'styles';
$state.go('app.mainReg');
}}])
.controller('LoginController', [..., function (...) { $currentUserId = Account.getCurrentId();
$scope.$stateParams = $stateParams; $scope.loginData = {}; $scope.doLogin = function() { AuthService.login($scope.loginData)
.then(function() {
$scope.loggedIn = true;
location.reload(); }); };}])
.controller('LogoutController', [..., function(...) {
AuthService.logout()
.then(function() {
console.log("Logging out . . .");
$scope.loggedIn = false;
$state.go('app'); }); }]);
And some additional service beside lb-services.js to handle my authentication,
function login(loginData) {
var params = { rememberMe: loginData.rememberMe };
var credentials = {
email: loginData.email,
password : loginData.password
};
return User
.login(params, credentials)
.$promise.then(function(response){ $rootScope.currentUser = {...};
console.log($rootScope.currentUser);
},
function(response) {
console.log(response);
});
}
function logout(){
return User
.logout()
.$promise.then(function(){
$rootScope.currentUser = null;
});
};
I think, with this kind of code, especially I have checked with
if(Account.isAuthenticated() === false){...}
and succeed to enter my main page, I have successfully logged in and authenticated, haven't I?
But, if I tried to put ng-show="Account.isAuthenticated()" in the top div of my main page app.mainReg , my page can't be show, yet it means that my account haven't authenticated, even the loopback have successfully save my token, user id, and rememberMe boolean in local storage, like this
$LoopBack$accessTokenId = ....
$LoopBack$currentUserId = ...
$LoopBack$rememberMe = true // automatically become true?
So, do anyone know how to solve this problem? I think the problem is on the authentication.
I'm quite confused with this one, I have tried to search for solution, yet I could find any.
I just realized why I couldn't use rememberMe function, that's just because I made a silly mistake, by putting " ; " after my logout function in my additional services
And after several testing, It seems that my problem was inside my state provider. I tweaked my controller and my state provider and finally it has been work successfully.

Redirect view after login with facebook using Firebase and Ionic

Authentication is functioning normally, but once I login, it continues in the same view.
I need after login he goes to the view dash.html
As I redirect the user after he login?
$scope.loginFacebook = function(){
var ref = new Firebase("https://<NAME>.firebaseio.com");
var authObject = $firebaseAuth(ref);
authObject.$authWithOAuthRedirect("facebook").then(function(authData) {
console.log(authData);
}).catch(function(error) {
console.log('error' + error);
})
}
I had the same problem. I used $state.go('tabs.home'); but I had to put it in the app.factory rather than in the controller.
auth.$onAuth(function(authData) {
$state.go('tabs.home');
if(authData) {
angular.copy(authData, Auth.user);
Auth.user.profile = $firebaseObject(....));
} else {
if(Auth.user && Auth.user.profile) {
}
angular.copy({}, Auth.user);
}
});

Emberjs authentication session not working

I have followed Authentication Tutorial, but running into some issues.
I have a php backend api which resides in another domain, http://rest.api {local development}
The ember js application uses ember-app-kit and connects to the rest api.
When the user submits the login form it sends the username/email with password to one of the route defined in the rest api Session Controller
import AuthManager from 'lms/config/auth_manager';
var SessionNewController = Ember.ObjectController.extend({
attemptedTransition : null,
loginText : 'Log In',
actions: {
loginUser : function() {
var self = this;
var router = this.get('target');
var data = this.getProperties('identity', 'password');
var attemptedTrans = this.get('attemptedTransition');
$.post('http://rest.api/login',
data,
function(results) {
console.log(results.session);
console.log(results.user_id);
AuthManager.authenticate(results.session, results.user_id);
if(attemptedTrans) {
attemptedTrans.retry();
self.set('attemptedTransition', null);
} else {
router.transitionTo('index');
}
}
)
}
}
});
export default SessionNewController;
After receiving the api result in the results variable which looks like this :
Object {success: "user login success", session: "2OmwKLPclC.YhYAT3745467my7t0m2uo", user_id: "1"}
But as soon as I capture the data and send it to the AuthManager which resides in Auth Manager Code
import User from 'lms/models/user';
import Application from 'lms/adapters/application';
var AuthManager = Ember.Object.extend({
init: function() {
this._super();
var accessToken = $.cookie('access_token');
var authUserId = $.cookie('auth_user');
if(!Ember.isEmpty(accessToken) || !Ember.isEmpty(authUserId)) {
this.authenticate(accessToken, authUserId);
}
},
isAuthenticated: function() {
return !Ember.isEmpty(this.get('ApiKey.accessToken')) && !Ember.isEmpty(this.get('ApiKey.user'));
},
authenticate: function(accessToken, userId) {
$.ajaxSetup({
headers: { 'Authorization': 'Bearer ' + accessToken }
});
var user = User.store.find(userId);
console.log(user);
this.set('ApiKey', ApiKey.create({
accessToken: accessToken,
user: user
}));
},
reset: function() {
this.set('ApiKey', null);
$.ajaxSetup({
headers: { 'Authorization': 'Bearer None' }
});
},
apiKeyObserver: function() {
Application.accessToken = this.get('apikey.accessToken');
if (Ember.isEmpty(this.get('ApiKey'))) {
$.removeCookie('access_token');
$.removeCookie('auth_user');
} else {
$.cookie('access_token', this.get('ApiKey.accessToken'));
$.cookie('auth_user', this.get('ApiKey.user.id'));
}
}.observes('ApiKey')
});
export default AuthManager;
I got an error in the console saying
Uncaught TypeError: Object function () {
if (!wasApplied) {
Class.proto(); // prepare prototype...
}
o_defineProperty(this, GUID_KEY, undefinedDescriptor);
o_defineProperty(this, '_super', undefinedDescriptor);
var m = met...<omitted>...e' new.js:23
(anonymous function) new.js:23
jQuery.Callbacks.fire jquery.js:1037
jQuery.Callbacks.self.fireWith jquery.js:1148
done jquery.js:8074
jQuery.ajaxTransport.send.callback jquery.js:8598
It is not able to pass the variables to the imported function.
Finally got this working. The error that was I doing is after extending the Ember.Object.extend() on auth_manager.js, I didn't create the object anywhere. Thats why it couldnt set create a cookie and throwing that error message.
All I had to do was, .create() after extending the object.
Don't know whether it is the right method or not. But it certainly works.

Categories

Resources