How to concatenate email and OTP in graphql POST query - graphql

I have to verify OTP in graphql POST request using cy.request() in cypress.
I want to create a suite so it will enter a new email and get OTP from that email and after that, I want to use that email and OTP in my query so it will verify using request.
describe('Sign Up Test', function () {
beforeEach("Load", function () {
Cypress.Cookies.preserveOnce('session_id', 'event_id', 'uuid', '_cltk', 'amp_394a99_outsized.site', '_clsk', 'amp_394a99')
cy.fixture("data").then((data) => {
this.key = data
})
})
it('Sign up', function () {
cy.visit('/')
cy.xpath('//button[text()=" Sign Up with Email"]').click()
cy.get('#email').type(email.toLocaleLowerCase())
cy.fixture("data.json").then(profile => {
profile.email = email
cy.writeFile("cypress/fixtures/data.json", profile);
cy.get('.ant-btn').click()
cy.wait(2000)
})
})
it('Check Otp', function () {
cy.visit("https://www.mailinator.com/", { timeout: 30000 })
cy.readFile('cypress/fixtures/Data.json').then((profile) => {
cy.get("#search").type(profile.email)
})
cy.xpath('//*[text()="GO"]').click()
cy.wait(2000)
cy.contains('table tbody tr', 'OTP').click() // find the right email
cy.get('#html_msg_body') // iframe
.its('0.contentDocument.body').should('not.be.empty') // wait for loading
.then(console.log) // works with this but errors without - totally weird
.wait(2000)
.find("table > tbody > tr:nth-child(3) > td > h2")
.then($h2 => {
const OTP = $h2.text()
cy.fixture("data.json").then(profile => {
profile.OTP = OTP
cy.writeFile("cypress/fixtures/data.json", profile);
})
})
cy.request({
method: "POST",
url: "https://api.outsized.site/graphql",
failOnStatusCode: false,
body: {
query: "mutation { verifyEmailOtp(email: " + this.key.email + ", otp: " + this.key.OTP + "){ message } }"
}
}).then((res) => {
expect(res.status).to.eq(200)
});
})
it.only('Sign up', function () {
const otpQuery = `mutation {
verifyEmailOtp(email: "test.01#getnada.com", otp: 3262)
{ message }
}`
cy.request({
method: "POST",
url: "https://api.outsized.site/graphql",
headers:{
'Content-Type': 'text/plain'
},
body: {
query: "mutation: { verifyEmailOtp(email: " + this.key.email + ", otp: " + this.key.OTP + "){ message } }"
},
failOnStatusCode: false,
}).then((res) => {
expect(res.status).to.eq(200)
});
// Cypress.Cookies.preserveOnce('session_id', 'event_id', 'uuid', '_cltk', 'amp_394a99_outsized.site', '_clsk', 'amp_394a99')
cy.visit('/')
cy.xpath('//button[text()=" Sign up with email"]').click({ force: true })
cy.wait(2000)
cy.fixture("data.json").then(profile => {
cy.get('#email').type(profile.email)
})
cy.wait(2000)
cy.get('.ant-btn').click()
cy.wait(3000)
cy.reload()
})
})
This is my test, first, one generates random emails using the faker library. and send OTP in that email and also save the email into my data file.
The second one gets OTP from that email and saves it to my data file.
And the third one is making a request using email and OTP.
My output:

Related

Do a HTTP Post in Cypress without using a test

I have a Cypress test:
describe('Create a session ', () => {
it('creates a session', () => {
cy.request({
method: 'POST',
url: `${Cypress.env('apiURL')}/api/v1/user/login/`,
form: true,
body: {
email: Cypress.env('email'),
password: Cypress.env('password'),
},
}).then((response) => {
expect(response.status).to.eq(200);
cy.task('setKey', response.body.data.key);
});
});
});
This POST returns some session data needed to create a dummy account:
describe('Create a company ', () => {
it('creates a company', () => {
cy.task('getKey')
.then((data: Key) => {
key = data;
})
.then(() => {
createNonce();
cy.request({
method: 'POST',
url: `${Cypress.env('apiURL')}/api/v1/cli/`,
headers: {
'X-Auth-Timestamp': epochTime(),
'X-Auth-Key': key.key,
'X-Auth-Nonce': nonce,
'X-Auth-Signature': createSignature(),
},
body: {
args: ['seeder', 'create', 'abc1'],
},
}).then((response) => {
expect(response.status).to.eq(200);
// TODO: we need some REST endpoints to return a JSON object instead of a string
data = JSON.parse(response.body.substring(response.body.indexOf('{')));
cy.task('setCompany', data);
});
});
});
});
I'm not sure I need these functions to be tests since they don't test anything, but just do a POST request. Is it possible to maybe move the functionality into a cypress task?
You can add the post request in your commands file:
function postRequest() {
cy.request({
method: 'POST',
url: `${Cypress.env('apiURL')}/api/v1/cli/`,
headers: {
'X-Auth-Timestamp': epochTime(),
'X-Auth-Key': key.key,
'X-Auth-Nonce': nonce,
'X-Auth-Signature': createSignature(),
},
body: {
args: ['seeder', 'create', 'abc1'],
},
})
}
Cypress.Commands.add('postRequest', postRequest)
An assuming all the rest of your code is fine, and you want only to abstract the logic; then in your test you can invoke that command:
describe('Create a company ', () => {
it('creates a company', () => {
cy.task('getKey')
.then((data: Key) => {
key = data;
})
.then(() => {
createNonce();
cy.postRequest().then((response) => {
expect(response.status).to.eq(200);
data = JSON.parse(response.body.substring(response.body.indexOf('{')));
cy.task('setCompany', data);
});
});
});
});
You can move these into before() or beforeEach() so they will be separate from your tests.
describe('Create a company ', () => {
before(() => {
cy.task('getKey')
.then((data: Key) => {
key = data;
})
.then(() => {
createNonce();
cy.request({
method: 'POST',
url: `${Cypress.env('apiURL')}/api/v1/cli/`,
headers: {
'X-Auth-Timestamp': epochTime(),
'X-Auth-Key': key.key,
'X-Auth-Nonce': nonce,
'X-Auth-Signature': createSignature(),
},
body: {
args: ['seeder', 'create', 'abc1'],
},
}).then((response) => {
expect(response.status).to.eq(200);
// TODO: we need some REST endpoints to return a JSON object instead of a string
data = JSON.parse(response.body.substring(response.body.indexOf('{')));
cy.task('setCompany', data);
});
});
})
it('creates a company', () => {
//test code
});
});

How do I get the message using Office.js in a react add-in

I am building a new react Outlook add-in and need to be able to download the current email.
The Office.js API has the getFileAsync method off the Office.context.document object but not the Office.context.mailbox.item object.
also as a requirement this needs to work in both Office online and local installs of Outlook.
In the existing com add-in I had direct access to the mail item.
Here is the code that I currently have to call into the API, but this only retrieves metadata.
/*
https://learn.microsoft.com/en-us/outlook/add-ins/use-rest-api#get-the-item-id
*/
public getMessageViaRest = () => {
const context: Office.AsyncContextOptions & { isRest: boolean } = {
isRest: true
};
Office.context.mailbox.getCallbackTokenAsync(context, (tokenResults) => {
if (tokenResults.status === Office.AsyncResultStatus.Failed) {
this.setState({ error: 'Failed to get rest api auth token' });
return;
}
const apiId: string = Office.context.mailbox.convertToRestId(Office.context.mailbox.item.itemId, 'v2.0');
const apiUrl = Office.context.mailbox.restUrl + '/v2.0/me/messages/' + apiId;
try {
fetch(apiUrl, {
method: 'GET',
headers: new Headers({
Authorization: 'Bearer ' + tokenResults.value
})
}).then((response) => {
response.json().then((body) => {
for (const key in body) {
this.state.details.push({ name: key, value: JSON.stringify(body[key]) });
}
this.forceUpdate();
});
});
} catch (error) {
this.setState({ error: JSON.stringify(error) });
}
});
}
Its not perfect but the REST Api does have an end point that will return the file's EML contents.
public downloadViaRest = () => {
const context: Office.AsyncContextOptions & { isRest: boolean } = {
isRest: true
};
Office.context.mailbox.getCallbackTokenAsync(context, (tokenResults) => {
if (tokenResults.status === Office.AsyncResultStatus.Failed) {
this.setState({ error: 'Failed to get rest api auth token' });
return;
}
const apiId: string = Office.context.mailbox.convertToRestId(Office.context.mailbox.item.itemId, 'v2.0');
const apiUrl = Office.context.mailbox.restUrl + '/v2.0/me/messages/' + apiId + '/$value';
try {
fetch(apiUrl, {
method: 'GET',
headers: new Headers({
Authorization: 'Bearer ' + tokenResults.value
})
}).then((response) => {
response.blob().then((blob) => {
const url = window.URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = 'Message.eml';
a.click();
});
});
} catch (error) {
}
});
}

Network Request failed while sending image to server with react native

i want to send image to a server and getting the result with a json format but the application returns a Network Request failed error
react native 0.6 using genymotion as emulator
i tried RNFetchblob but the result take a long time to get response (5 min )
also i tried axios but it response with empty data with 200 ok
this is the function that import the image
OnClick = () => {
ImagePicker.showImagePicker(options, response => {
console.log("Response = ", response);
if (response.didCancel) {
console.log("User cancelled image picker");
} else if (response.error) {
console.log("Image Picker Error: ", response.error);
} else {
let source = { uri: response.uri };
// You can also display the image using data:
//let source = { uri: 'data:image/jpeg;base64,' + response.data };
this.setState({
avatarSource: source,
data: response.data,
BtnDisabled: false
});
console.log();
}
});
};
and this method that sends the image
Send = async () => {
let url = "http://web001.XXX.com:8000/api/prediction/check_prediction/";
let UplodedFile = new FormData();
UplodedFile.append('file',{ type:'image/jpeg', uri : this.state.avatarSource , name:'file.jpeg'});
fetch(url, {
method: 'POST',
body:UplodedFile
})
.then(response => response.json())
.then(response => {
console.log("success");
console.log(response);
})
.catch(error => {
console.error(error);
});
i expect json format
ScreenShot here
can you change your code like this?
OnClick = () => {
ImagePicker.showImagePicker(options, response => {
console.log("Response = ", response);
if (response.didCancel) {
console.log("User cancelled image picker");
} else if (response.error) {
console.log("Image Picker Error: ", response.error);
} else {
let source = { uri: response.uri };
// You can also display the image using data:
//let source = { uri: 'data:image/jpeg;base64,' + response.data };
this.setState({
pickerResponse: response,
data: response.data,
BtnDisabled: false
});
console.log();
}
});
};
Send = async () => {
let url = "http://web001.XXX.com:8000/api/prediction/check_prediction/";
let UplodedFile = new FormData();
UplodedFile.append('file',{ type:'image/jpeg', uri : this.state.pickerResponse.path , name:'file.jpeg'});
axios({
method: "post",
url: url,
data: UplodedFile
})
.then(response => {
console.log("success");
console.log(response);
})
.catch(error => {
console.error(error);
});

Apollo Client delays request

I have a very weird issue with Apollo Client.
We are using apollo-client#1.9.3 with react (react-apollo#1.4.16).
In our project, we notice that apollo always wait for 1 to 2 seconds before sending the request.
Below is a screenshot of the situation:
This is how our client config looks like:
const customNetworkInterface = {
query: request =>
fetch('/graphql', {
method: 'POST',
credentials: 'include',
mode: 'cors',
cache: 'default',
headers: {
Accept: '*/*',
'Content-Type': 'application/json',
'X-Requested-With': 'XMLHttpRequest',
},
body: JSON.stringify({
...request,
query: print(request.query),
}),
})
.then(resp => resp.json())
.then(({ data, errors }) => {
if (errors) {
const userErrors = errors
.filter(({ code }) => +code >= 400 && +code <= 401)
.map(({ message }) => message)
.join('\n');
const serverErrors = errors
.filter(
({ code }) => !code || (+code < 400 && +code > 401)
)
.map(({ message }) => message)
.join('\n');
if (serverErrors.length > 0) {
error(serverErrors);
if (isProduction) {
window.triggerAlert(
'danger',
'The server encountered an error. Our technical team has been notified.'
);
} else {
window.triggerAlert('danger', serverErrors);
}
} else if (userErrors.length > 0) {
window.triggerAlert('danger', userErrors);
}
}
return { data, errors };
}),
};
const networkInterface = createNetworkInterface({
uri: '/graphql',
opts: {
credentials: 'same-origin',
},
});
networkInterface.useAfter([
{
applyAfterware({ response }, next) {
response
.clone()
.json()
.then(responseJson => {
if (responseJson.errors) {
error(
responseJson.errors
.map(({ message }) => message)
.join('\n')
);
}
next();
});
},
},
]);
export const client = new ApolloClient({
networkInterface: customNetworkInterface,
queryDeduplication: true,
addTypename: true,
});
Then the query code is with react-apollo:
graphql(RaceResultsQuery, {
props: ({ ownProps, data }) => ({
race_results: _.get(data, 'me.my_race_results', []),
}),
}),
This would need a complete, minimal example to provide an answer for sure (delete as much of your code as possible with the issue still happening).
My guess would be that you have a parent component with a very expensive query and it only renders the component with the delayed query after the expensive query returned.

Google recaptcha v3 always returning error

Following the instructions I get a valid token from my front end (can see in dev tools):
window.grecaptcha
.execute(captchaPkey, { action: 'contact' })
.then((token) => {
// this is what I POST to my API
So in my React front end:
send = (event) => {
event.preventDefault()
this.setState({ busy: true })
window.grecaptcha.ready(() => {
window.grecaptcha
.execute(captchaPkey, { action: 'contact' })
.then((token) => {
// successfully get token
const payload = {
token,
name: this.state.name,
to: this.props.to,
email: this.state.email,
message: this.state.message,
}
// now I'm sending the payload to my API
// My API
update(`${api}/contact/`, {
method: 'POST',
body: JSON.stringify(payload)
}, null)
.then(data => {
this.setState({ busy: false, result: 'Email sent' });
})
.catch(error => {
this.setState({ busy: false, error: error.message });
});
})
})
}
my API controller
async function verifyCaptcha(token) {
return await axios.post('https://www.google.com/recaptcha/api/siteverify', {
secret: process.env.CAPTCHA_PKEY,
response: token
})
}
async function contact({ token, to, name, email, message }) {
const result = await verifyCaptcha(token)
if (!result || !result.data || !result.data.success) {
// always get an error here
throw new Error('Invalid captcha')
}
let targetEmail = 'default#emailaddress'
if (to !== 'admin') {
const user = await User.findOne({ username: to }, { email }).exec()
if (!user) {
throw new Error('User does not exist')
}
targetEmail = user.email
}
// rest of send
}
On my API POST endpoint sends to https://www.google.com/recaptcha/api/siteverify with the body of:
{
secret: process.env.CAPTCHA_PKEY,
response: token
}
Yet I always get "missing-input-response", "missing-input-secret" error. Is this because v3 is new? Still bugs?
Realised in the documentation it states "post params" not post body haha.

Resources