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
Related
I use the following to send some data to another window;
try{
win.webContents.once('dom-ready', () => win.webContents.send('send-data', data));
}
catch(err){
console.log("Caught ",err);
}
And for receivig;
ipcRenderer.on('send-data', function (event,data) {
console.log("Loaded ", data);
});
The thing is, the "data" here is sometimes assembled very quickly and it works fine. However, sometimes it takes a while and the other window is already loaded at this point. No data is received in that case, and no error message either. But then I can simply use the following to send it without problems;
win.webContents.send('send-data', data)
I couldn't find a way to apply for both cases. Any suggestions?
The short answer is no.
Electron doesn't have a function to wait for the window to load, then send a message, or send a message right away if the window's already loaded.
However this can be done with some simple code:
var hasWindowLoaded = false;
var hasDataBeenSent = false;
var data = {};
win.webContents.once('dom-ready', () => {
hasWindowLoaded = true;
if (!hasDataBeenSent && data) {
win.webContents.send('send-data', data);
hasDataBeenSent = true;
}
});
// Now add this where you build the `data` variable.
function loadData () {
data = {'sampleData': 'xyz'};
if (!hasDataBeenSent && hasWindowLoaded) {
win.webContents.send('send-data', data);
hasDataBeenSent = true;
}
}
Once the data's loaded in loadData it'll check if the window's finished loading and if it has then it sends the data right away.
Otherwise it stores the data in a varible (data) and once the window loads it sends it to the window.
Another approach that you may want to consider is sending data to the browserWindow using query strings.
const data = { hello: "world" }; // sample data
// send it using query strings
browserWindow.loadFile(YOUR_HTML_FILE_PATH, {
query: { data: JSON.stringify(data) },
});
// parse this data in the browserWindow
const querystring = require("querystring");
const query = querystring.parse(global.location.search);
const data = JSON.parse(query["?data"]);
console.log(data); // { hello: "world" }
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.
I am trying to update the user account details in firebase but I have noticed that the input value for one of my fields keeps coming up as undefined even when I console.log it. I am working in two files one is a loginjs file in which I am defining the user input.
signUpForm.addEventListener('click', function (e) {
e.preventDefault();
isSigningUp = true;
var email = signUpEmailInput.value;
var password = signUpPasswordInput.value;
var displayNameUser = displayNameInput.value;
var userPrivateKey = signUpPrivateKey.value;
var user = firebase.auth().currentUser;
var photoURL = "https://www.gravatar.com/avatar/" + md5(email);
if (signUpPasswordInput.value !== signUpPasswordConfirmInput.value) {
setSignUpError('Passwords do not match!');
} else if (!displayNameUser) {
setSignUpError("Display Name is required!");
} else if (!userPrivateKey) {
setSignUpError('You need to set a Private Key!');
} else {
auth.createUserWithEmailAndPassword(email, password)
.then(function (user) {
user.updateProfile({
displayName: displayNameUser,
photoURL: photoURL,
privateKey: userPrivateKey
}).then(function () {
// Update successful.
window.location.href = 'chat.html';
}).catch(function (error) {
// An error happened.
window.alert("Some unexpected error happened!");
});
user.sendEmailVerification().then(function () {
// Email sent.
}).catch(function (error) {
// An error happened.
window.alert("Email was not able to send!");
});
})
.catch(function (error) {
// Display error messages
setSignUpError(error.message);
});
}});
The weird thing is that the user input for my displayname and photoURL are working just fine, but when it comes to my private key user input it registers the input when it goes to the chat page and I do a console.log(user.privatekey) It says it is undefined.
In my chatjs file, thats when I am pushing the all the user profile information. The chatjs file basically allows a user to send a message, the message and all the user profile information gets stored onto the firebase database.
messages.push({
displayName: displayName,
userId: userId,
pic: userPic,
text: myString.toString(),
privatekey: user.privatekey,
timestamp: new Date().getTime() // unix timestamp in milliseconds
})
.then(function () {
messageStuff.value = "";
})
.catch(function (error) {
windows.alert("Your message was not sent!");
messageStuff;
});
The thing again is that the privatekey does not get stored at all, which is what I am not understanding, since it is registering user input in the loginjs file but when I go to the chatjs file it keeps saying the value is undefiend. I have googled everywhere and I still haven't found a solution to it. Any help would be greatly appricated!
It's because the Firebase user object you receive from Firebase is not customizable. When you call the createUserWithEmailAndPassword(email, password) method, it returns a specifically defined user object back to you - check out the docs for the properties of this object.
The properties displayName and photoURL both work because they are already properties of the user returned. privateKey is not an existing property of the Firebase user object, and Firebase doesn't know how to handle an update call for a property that isn't defined. Check out this question & answer where Frank explains that Users in Firebase aren't customizable - you need to store any extra info separately.
This question already has an answer here:
How to wait for firebase.database().ref('users/' + userId).set() to finish before calling next function?
(1 answer)
Closed 5 years ago.
I am using this code after submit is pressed to add data to my firebase database.
I want to redirect it to a new page after the data has been written, but I cannot figure out a way to check if data is written in database.
var email = document.getElementById("email");
var phone = document.getElementById("phone");
var details = document.getElementById("details");
function submit() {
if(!(email.value == null)) {
var storage = firebase.storage();
var ref = storage.ref();
var letters = ref.child('letters');
var userref = letters.child(email.value+".txt");
var data = details.value;
userref.putString(data);
var database = firebase.database();
var databaseref = database.ref().child("users");
databaseref.child(email.value).set({email: email.value,phone:phone.value},);
// tried this window.alert("https://google.com");
}
}
The below is example is from the firebase docs here:
adaNameRef.set({ first: 'Ada', last: 'Lovelace' })
.then(function() {
console.log('Synchronization succeeded');
})
.catch(function(error) {
console.log('Synchronization failed');
});
You can see that the .set method returns a firebase promise which will resolve if the data updated successfully and reject if it doesn't.
You should redirect in the same place that console.log('Synchronization succeeded'); is running in the example.
I have been struggling with this problem all day.
I am developing a Windows 8 app using JavaScript and HTML5. I need to restrict some functionality on the app depending of the active directory group where an user account is assigned.
The question is: how I can check if a user account belongs to a Active Directory group?
I have tried using Windows.System.UserProfile.UserInformation and Windows.Security.Credentials.UI.CredentialPicker, but none of them returns either a way to test if a user account belongs to a group, or the group where the user account is assigned.
Thanks in advance for your help.
I found a solution to perform this, which was the one I implemented, and it works. You can create a web service that validates the credentials against Active Directory, where you pass the domain, username and password, then call it from the app using WinJS.xhr. To ask for the credentials, you can use the CredentialPicker control, which returns, the domain, username, and password entered by the user.
Here is the code:
Web Service Code:
ValidateUserResult vur = new ValidateUserResult();
try
{
using (PrincipalContext context =
new PrincipalContext(ContextType.Domain, domain))
{
vur.UserCredentialsAreValid = context
.ValidateCredentials(username, password);
if (vur.UserCredentialsAreValid)
{
vur.ProcessMessageText = "Ok";
vur.ProcessMessageCode = 0;
}
else
{
vur.ProcessMessageText =
"Credenciales invalidas";
vur.ProcessMessageCode = -1;
}
}
}
catch (Exception ex)
{
vur.UserCredentialsAreValid = false;
vur.ProcessMessageText = ex.Message;
vur.ProcessMessageCode = ex.HResult;
}
return vur;
Windows 8 App:
WinJS.xhr({
type: "get"
, url: {Web Service Url}
+ "/json/{Web Service Method Name}?domain="
+ domain + "&username=" + username
+ "&password=" + password
}).then(
function (result) {
if (result.status === 200) {
// Place code here.
}
},
function (error) {
// If an error occurs, manage here
});