Cypress Testing : How to preserve access_token/cookies/sessions? - javascript

In my application, when I run the application, It redirects to Github Login to access the repository from the account. When the Sign In button is clicked, I get this message.
Cookies must be enabled to use GitHub.
So can anyone tell me what should I do. I tried using Cypress.Cookies.preserveOnce() , but it doesn't work.
Also, we get an access_token after successful login.
describe('Login Page', () => {
beforeEach(() => {
Cypress.Cookies.preserveOnce('access_token', 'value for the access_token')
})
it('successfully logged In', () => {
cy.get('#login_field').type('username')
cy.get('#password').type('password')
cy.get('.btn-block').click()
})
})

Take a look at this [Cypress Social Media Logins][1]. I think you are using Github Oauth to login and access.
You have to login using the plugin GitHubSocialLogin. Save the cookie that you get in the localStorage.
You will have to explore further on these lines to suit your particular use case.
[1]: https://github.com/lirantal/cypress-social-logins

Related

How can I use firebase without the emulator?

I am learning firebase and I checked this tutorial regards the authentication. (https://www.youtube.com/watch?v=rbuSx1yEgV8&t=502s). In this video, the emulator seems to be essential, however I want to communicate with the server. How do I do it? If I do not initialize the auth emulator ( by removing the connectEmulator() function) I just get the error 'auth/network-request-failed'.
const firebaseConfig = {
//...
};
const user = {
email: 'user#test.me',
password: 'test1234'
}
function func() {
createUserWithEmailAndPassword(auth, user.email, user.password)
.then((userCredential) => {
const user = userCredential.user;
console.log(user)
})
.catch((error) => {
console.log(error)
// ..
});
}
As you can see from the minute 7:37 of that video, I am getting his issue! So I assume I am following the wrong approach. Can someone help me? I would be really grateful.
You should be able to authenticate with the server.
The emulator is optional. Personally I rarely use it, and essentially always use the real online Firebase server. However there are many steps before you are able to authenticate with the server.
Step 1. Check you have copied the configuration correctly
Go to this link, but replace PROJECT_ID with your actual project Id:
https://console.firebase.google.com/u/0/project/PROJECT_ID/settings/general/
Check that you have correctly copied the value of this into your app code from that page. If you have not "added an app", you may need to click "Add app", to get this config to display.
const firebaseConfig = {
... blah blah ...
};
Step 2. Check that you have enabled a "Sign-in provider"
Go to this link (again PROJECT_ID should be replaced by your project Id):
https://console.firebase.google.com/u/0/project/PROJECT_ID/authentication/providers
At least one of the providers needs to be switched on, like so:
Step 3. Your code looks good.
I assume you have set up auth correctly - we can't see that in the snippet above.
Please paste into your question the exact error message you are seeing on the console, as text.
You might want to intensify the debugging as follows:
function func() {
console.log(`user: ${JSON.stringify(user,null,2)}`)
createUserWithEmailAndPassword(auth, user.email, user.password)
.then((userCredential) => {
console.log(`userCredential.user: ${JSON.stringify(userCredential.user,null,2)}`)
})
.catch((error) => {
console.error(error)
});
}
A small thing, but I suggest avoiding using the same variable name, user, for two different things. Javascript will keep them separate, but we as programmers sometimes will get muddled when looking back at the code.
Step 4. Make sure you have authorised the domain you are using.
Go to:
https://console.firebase.google.com/u/0/project/PROJECT_ID/authentication/settings
Make sure you have authorised the domain from which you are "calling" the Firebase server.
If your app is running on "127.0.0.1" instead of "localhost", you might need to add that IP address too. Or if you have deployed, the deployed domain.

What is the proper way to implement authentication in Firebase?

ok so I've built a few apps in Firebase and really enjoy using the simple API but always struggle with auth. see this code
I have a simple email and password "form" (not a form element, just two inputs)
and then a button (div) I click to call this function below
const logUserIn = () => {
firebase
.auth()
.signInWithEmailAndPassword(email, password)
.then((res) => {
console.log('here') // this WORKS but the history redirect below does not work :/
localStorage.setItem('authUser', JSON.stringify(res))
history.push('/account')
})
.catch((error) => {
console.log('ERROR:', error)
})
}
however when I put the lines below
firebase.auth().onAuthStateChanged((user) => {
if (user) {
console.log('user logged in')
} else {
console.log('user not logged in')
}
})
it seemed to pick it up correctly
but my question is, what is the point of signInWithEmailAndPassword? and also, how do I use both functions together? do I need to call onAuthStateChanged in the .then part of my signInWithEmailAndPassword function?
it's really confusing how to have a consistent state. my app seems to work after I refresh the page but I want it to work without refreshes (obviously)
any ideas on the best approach?
EDIT
also when I click sign out
firebaseApp.auth().onAuthStateChanged((user) => {
if (user) {
history.push('/account')
} else {
console.log('NO USER')
}
})
NO USER logs but then I click on an authenticated route it takes me there until I refresh
The point of signInWithEmailAndPassword is to allow the implementation of classic username/password authentication for people who don't have a Google, Facebook, Twitter, etc. account. If you decide to add it, Google will handle the user accounts and everything, but you'll have to build the login form, complete with the I forgot my password and Register as new user links. Other than that it's simply another provider.
I have a very simple little project on my Github repo which implements user/password authentication along with several others, I suggest you to look into it. I made it as a test assignment for a job interview. It's Angular.
https://github.com/tomcatmwi/morbidomega

How can I check or verify that a user is signed in with AWS Cognito Javascript?

I am creating a React web app where the user sign in/up and other authentication related processes are being handled by AWS Cognito and the accompanying Javascript SDK.
My app has some 'public' routes/pages that everybody, signed in or not, can view, such as /documentation/ and /sign-in/. There also exist various private routes which you can only see when you are logged in, such as /my-documents/.
At the moment, I have a working sign in page, where a user is signed in with code very similar to use case #4 (Cognito Docs).
My question now is: as soon as a user goes to /my-documents/, how do I check whether the user is signed in and actually has the rights to see this page?
I am not using AWS Amplify for the authentication in my app. I only use the NPM package 'amazon-cognito-identity-js'.
This is the code I currently use to check if the session is valid, in other words if the user is successfully signed in. This however, seems like a cumbersome way to check such a simple status.
const isAuthenticated = () => {
const cognitoUser = userPool.getCurrentUser();
let isSessionValid = false;
if (cognitoUser) {
cognitoUser.getSession((err: Error, result: CognitoUserSession) => {
if (!err) {
isSessionValid = result.isValid();
}
});
}
return isSessionValid;
};
isSessionValid is returned before the callback in getSession is executed.

firebase auth/operation-not-allowed

This is an angular web app.
Added the screenshot of the permission page
I'm trying to authenticate mobile using firebase.
In my firebase console > Authentication > signIn Method, I've enabled the phone and saved it.
But when I try to login It throws me an error saying that
auth/operation-not-allowed
sendLoginCode() {
const appVerifier = this.windowRef.recaptchaVerifier;
const num = this.firstFormGroup.value.mobileNo
console.log('num',num);
firebase.auth().signInWithPhoneNumber(num, appVerifier)
.then(result => {
this.windowRef.confirmationResult = result;
})
.catch(error => console.log(error));
}
verifyLoginCode() {
this.windowRef.confirmationResult
.confirm(this.verificationCode)
.then(result => {
this.user = result.user;
console.log('Login Successfull')
})
.catch(error => console.log(error, "Incorrect code entered?"));
}
It looks like you haven't enabled the Google sign in method in your firebase console. To solve the issue do the following:
Enter to the firebase console (https://console.firebase.google.com/).
Select your project.
On the right side of the screen you'll see a panel, click where it says "Authentication".
Once you've entered to the Authentication menu, go to Sign-in method.
After that look for the google access provider in the list that appears below the header and click on it.
Then click on the enable button.
It is probable that you'll have to configure a secure project ID (you'll see a dropdown below the enable button). What you have to do is, enter the android and/or ios client ID from your project, and hit save. This will tell firebase that it is secure to handle sign in operations with that client.
To be able to use the phone sign in method, you need to have a paid plan active.
Original author of answer: https://stackoverflow.com/a/65598080/6310260

How to implement LinkedIn Login in ionic 3? why Linked In Login is not working?

I am using this tutorial.
My code is:
linkedInSignup() {
console.log("linked in login....");
// check if there is an active session
this.linkedin.hasActiveSession().then((active) => {
console.log('has active session?', active);
if(active === false) {
// login
let scopes:any = ['r_basicprofile', 'r_emailaddress', 'rw_company_admin', 'w_share'];
this.linkedin.login(scopes, true)
.then(() => console.log('Logged in!'))
.catch(e => console.log('Error logging in', e));
// get connections
this.linkedin.getRequest('people/~')
.then(res => console.log(res))
.catch(e => console.log(e));
// share something on profile
const body = {
comment: 'Hello world!',
visibility: {
code: 'anyone'
}
};
this.linkedin.postRequest('~/shares', body)
.then(res => console.log(res))
.catch(e => console.log(e));
}
});
}
Installed plugin:
$ ionic cordova plugin add cordova-plugin-linkedin --variable APP_ID=YOUR_APP_ID
$ npm install --save #ionic-native/linkedin
There is not getting any error, but even doesn't login with Linked In.
Can you please help me to solve this issue? Thanks.
I am trying to implement LinkedIn login as well in my application and was also facing the same issue. The login function never passed the success callback.
After doing a little search I came across this - https://github.com/zyra/cordova-plugin-linkedin#deprecation-notice
Looks like LinkedIn has stopped support for mobile SDK and have asked all the developers to move to OAuth 2.0
Ref - https://engineering.linkedin.com/blog/2018/12/developer-program-updates
Edit:
So the workaround that I used to serve my purpose of allowing users to signup with LinkedIn was that as I was using Node.js for my server-side work. I used passport.js with LinkedIn oAuth, and in the ionic app, I made use of the Ionic InApp Browser to show the user the LinkedIn signup page and register user from the app through LinkedIn.
This is the solution that I have currently tried, but looking for some better option if possible using any Cordova plugin. Will update the answer again if I find any.

Categories