username will be null when page is refreshed in angular6 - javascript

in my Dasboard Component i Need to Give a username and Send it
Form Server for Get Detail of User like fName , lName , Image , . . .
I Pass the username with this way :
when user is loggedin i u get the username from LocalStorage :
Login Component :
private usenameSource = new BehaviorSubject<string>('');
userName$ = this.usenameSource.asObservable();
getDecodedAccessToken(): any {
return jwt_decode(this.getRawAuthToken(AuthTokenType.AccessToken));
}
getUserNameDecode():any {
const decode = this.getDecodedAccessToken();
let userName = decode["http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name"];
return this.usenameSource.next(userName);
}
Dashboard Component :
this.loginService.userName$.subscribe((data) => {
this.userName = data;
})
Now, the problem is that when the browser is refreshing, the username will be null and I need to login again.
whats the problem ? how can i solve this problem ?

When the page refreshes, the "usenameSource" value will be cleared. To keep it, call your method "getUserNameDecode()" again in your service constructor.
constructor(...) {
this.getUserNameDecode();
}
getUserNameDecode():any {
const decode = this.getDecodedAccessToken();
if(!decode) {
// login failed
return;
}
let userName = decode["http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name"];
return this.usenameSource.next(userName);
}
....

I assume that Login Component will be loaded first when you start your application.
And also I assume that you are storing the userName details in local storage as soon as user logs in successfully.
So with that, we must check the userName in local storage first and based on that we must do the further operation.
Login Component
ngOnInit() {
const status = this.checkUserNameInLocalStorage();
if (status) {
this.userName = JSON.parse(window.localStorage['userName']);
} else {
// write your logic to get the userName details
}
}
checkUserNameInLocalStorage() {
if (window.localStorage['userName']) {
return true;
} else {
return false;
}
}
Hope this will help you.

Related

Remember the logged in user in mobile device

I created a login page on my mobile app using a node js file to test the credentials. If the credentials are correct you get to the homepage, but It doesn’t remember the logged-in user, so every time you clean the RAM you have to login again.
I'm trying to save the token I get back from the backend in the device using #ionic/storage, but that's how far I can go on the logic and code. I don't really know what to do with the token. Some explaining of the logic could help a lot, or some code, or a link. I would really appreciate any help I can get!
I’m using Ionic Angular [5] and Capacitor.
My code if needed:
.ts file
senduserdata(){
var dataToSend = {
username:this.Username,
password:this.Password,
usertype:this.getSelectedSubject,
}
var url = 'http://localhost:3000/login';
this.http.post(url,{data:JSON.stringify(dataToSend)},{responseType: 'text'}).subscribe(
(data)=>{
let decoded = helper.decodeToken(data);
console.log('Decoded: ', decoded);
//the code to save it in storage
this.storage.set('loggedToken', decoded);
if(decoded.usertype === "Customer")
{
alert('Hello Customer')
}
else if(decoded.usertype === "Staff")
{
alert('Hello Staff')
}
}
)
}
node js file
//Login
app.post('/login', function (_req, res) {
var data = JSON.parse(_req.body.data);
var username = data.username;
var password = data.password;
var usertype = data.usertype;
mysqlConnection.connect(function () {
if(usertype ==="Customer"){
var query = "SELECT * from " + usertype + " Where Username = '" + username + "' And Password = '" + sha1(password) + "'";
}
else{
var query = "SELECT * from Staff Where Username = '" + username + "' And Password = '" + password + "'";
}
mysqlConnection.query(query, function (err, results, _fields) {
if (err) {
res.send(err);
}
else {
if (results.length > 0 && usertype === "Customer") {
if(results[0].Subscription === "True"){
passs = sha1(password)
const token = jwt.sign({username, passs, usertype}, 'my_secret_key_customer');
console.log(token);
res.send(token);
}
else{
console.log("Email not verified!");
res.send('Email not verified! Check your email for the verification email!');
}
}
else if (results.length > 0 && usertype === "Staff") {
passs = sha1(password)
const token1 = jwt.sign({username, passs, usertype}, 'my_secret_key_staff');
console.log(token1);
res.send(token1);
}
else {
console.log("The password or username is incorrect!");
res.send('The Password or Username is incorrect!');
}
}
})
})
});
you can use that decoded value that you saved in ionic storage as and 'id' of the user (you can read about JWT that is a way of doing this that is a standard) so you can use that value when making new requests to your node-js server so you can know which user is sending the request (it is the equivalent of been logged in on REST). you can also use the value to change which is the default page of the app when you are logged in (login page when not logged in and home page when logged in for example.)
You need to setup authentication Guards to restrict pages based on storage and also add HTTP intercept to override HTTP header and passing the JWT token to backend on each and every API call's.
JWT is a JSON based web token to securely transfer data between Backend and JSON Objects. It may contain USER ID and other some secure information. You can pass your customized data using JWT.

Firebase checking two different database refs despite a if check

I am trying to seperate two different logins for the different types of users that are in the account. One of the users is a regular consumer who is able to search through the app. The other is a business dashboard where businesses get to see what users are checkedin to their business.
The problem is that when I check my two different database references, it seems it checks both of them instead of validating the first check and proceeds to pull and error saying one of my nodes is null.
The case it apprently fails is the first if check but in my database the node userType is set properly:
The problem seems to be it auth().onStateChanged where it looks for the uid of in both database references. When I try to login with a business account it successfully enters that statement and redirects, when I log in with a consumer account it tries to check the business refs if and then pulls out the error userType is null cannot read
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
// This prompts the user to allow for location access
// When logged in it would allow us to show the
// nearby businesses to the user
var uid = user.uid
if(window.navigator.geolocation) {
window.navigator.geolocation.getCurrentPosition(function(position){
})
}
var uid = user.uid
console.log(uid)
business.child(uid).on("value", snap => {
if(snap.val().userType == "business") {
alert("This is not a consumer account!")
firebase.auth().signOut()
window.location.href = "businesslogin.html"
} else {
consumer.child(uid).on("value", snap => {
if(snap.val().userType == "consumer") {
if(snap.val().isPhoneVerified == true) {
window.location.href = 'nearbyBusinesses.html'
} else {
window.location.href = 'loginVerification.html'
}
if(snap.val().isUserCheckedin == true){
window.location.href = "leave.html" + '#' + snap.val().checkedInBusinessId
} else {
window.location.href = "nearbyBusinesses.html"
}
}
})
}
})
}
})
The bug is in this line if(snap.val() == "business"). It needs to be if(snap.val().userType == "business"). Atleast that is what i can see imediately. Try that and see if it solves your problem

Window variables not accessible between Javascript files [duplicate]

This question already has answers here:
Persist variables between page loads
(4 answers)
Closed 3 years ago.
I have two javascript files to handle my webpage login function. First js file authenticates the user and returns a session token which should be passed to second js file for session validation.
Here is the snippet of first js file.
var Login = window.Login || {};
(function scopeWrapper($) {
var apiEndPoint = 'https://4pmsdffwl2.execute-api.ap-southeast-2.amazonaws.com/prod';
Login.sessionId = 'null'
function signin(username, password, onSuccess, onFailure) {
let endpoint = apiEndPoint + '/signin'
let config = {
"username": username,
"password": password
}
return axios.post(endpoint, config)
.then((res) => {
Login.sessionId = res.session_id
console.log(Login.sessionId) \\this prints the session id correctly
onSuccess(res);
return Promise.resolve('/')
})
.catch((err) => {
console.error(err)
onFailure(err)
return Promise.reject('/')
})
}
$(function onDocReady() {
$('#signinForm').submit(handleSignin);
});
function handleSignin(event) {
var email = $('#emailInputSignin').val().toLowerCase();
var username = email;
var password = $('#passwordInputSignin').val();
event.preventDefault();
signin(username, password, email,
function signinSuccess() {
console.log('Successfully Logged In');
window.location.href = 'second.html';
},
function signinError(err) {
alert(err);
}
);
}
}(jQuery));
The idea is to initiate a global variable sessionId which is updated with the session id by login function.
Here is the snippet of second js file where I'm trying to use the sessionId passed in from the first js file.
var Login = window.Login || {};
Login.map = Login.map || {};
(function uploadScopeWrapper($) {
console.log(Login.sessionId) \\This prints null instead of sessionId
if (Login.sessionId) {
window.location.href = 'welcome.html';
} else {
window.location.href = 'login.html';
}
}(jQuery));
I'm not quite sure why the window object is not getting updated with the sessionId that is being generated in signin function.
Sample code in plnkr here:
https://plnkr.co/bYECNY
Any help is much appreciated.
Thanks
You are navigating to a different page and then load the second script file from that different page.
All global variables are lost when you navigate to a different page, the same page or just refresh the current page.
For ways to store information longer than the current document is loaded into the browser, see Persist variables between page loads

Checking for login credentials in HTML5 Storage

i'm building a quizz app , which asks me to : Add user authentication: allow users to log in, and save their login credentials to local storage (HTML5 browser storage). what i want to add is to check if the user name && password (together, because you can have the same username and not the same password and vice versa), so i can prompt a "Welcome back (name of the user)".
i spent 3 days trying to figure out which logic works , tried everything but every time i get a logic problem where things doesn't go the way it should be , here's the code :
var usersinfo = {
users : []
}
localStorage.setItem("users", JSON.stringify(usersinfo.users))
function registerInfo(){
var name = document.forms[0].username.value;
var pw = document.forms[0].pw.value;
if (name === "" || pw === "") {
alert ('please complete all the forms')
} else {
var adding = JSON.parse(localStorage.getItem("users"));
// logic that goes here : i tried everything , looping...etc
}
return false;
}
Note that the function is attached to a button , and everything works fine on the HTML , the problem is in login logic .
Untested, but try something like this:
const users = JSON.parse(localStorage.getItem("users"));
if (users.some((user) => {
return user.name === document.forms[0].username.value;
})) {
alert('Welcome back!');
}
Basically, we use some on the array to loop through and figure out if any of the elements have the same name as the one from your form. If they do, we immediately stop looping and return true. If not, we return false.
See also: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some
And, do take #AnilRedshift's advice and don't store usernames/passwords in localstorage...

How to require the user's password when you want to update the user's information in the Firebase JSON tree?

I've got a form which is used to update a user's information, both in the Firebase JSON tree and the seperate database which holds the email + password combination for the users. Whenever you want to update either the email or password, you need to provide an email + password combination for it to work.
However, when you only want to update the JSON tree you can do it without a password. My form requires you to enter your current password before anything can happen, but if you type in the wrong password it will still update the display name of the user.
So my question is, is there a way that I can require the correct password before actually updating anything in the database?
The code in my controller:
//If the user has entered a new display name
if (sharedInfo.getUser().displayName !== $scope.user.displayName) {
var isNameChanged = userLogic.changeDisplayName($scope.user);
isNameChanged.then(function(isSuccessful) {
if (isSuccessful === true) {
$scope.isSuccessful = true;
}
else {
$scope.error = 'Update failed';
}
});
}
Function in my service:
changeDisplayName: function(user) {
//Get the user ID
var userData = sharedInfo.getAuthState();
return fbRef.getSyncedReference('users/' + userData.uid).$update({displayName: user.displayName}).then(function() {
return true;
}, function(error) {
return false;
});
}

Categories