Postman pre-request script login with Query Params - postman-pre-request-script

I want to create a pre-script in postman to login so that i can get tokens.
pm.sendRequest({
url: 'https://localhost/api/login',
method: 'POST',
header: {
'Content-Type': 'multipart/form-data',
},
body: {
mode: 'formdata',
formdata: [
{key: "email", value: "myemail#mydoman.com", disabled: false, description: {content:"", type:"text/plain"}},
{key: "password", value: "mypass", disabled: false, description: {content:"", type:"text/plain"}},
{key: "action", value: "login", disabled: false, description: {content:"", type:"text/plain"}}
]
}
}, function(err, response) {
pm.environment.set("access_token");
});
I'm still no get token with those pre-script, help needed

const loginRequest = {
url: pm.environment.get('my_url') +"/api/login",
method: 'POST',
header: 'Content-Type: application/json',
body: {
mode: 'application/json',
raw: JSON.stringify({
"email": "myemail#mydoman.com",
"password":"mypass"
})
}
};
pm.sendRequest(loginRequest, function (err, response) {
pm.environment.set("access_token", response.json().token);
});

Related

API Gateway - Return XML or JSON

I have a node API Gateway stack and a Node Lambda. I've been trying to get API gateway to return content-type: application/xml OR application/json depending on the request (returnType=xml or returnType=json).
I have tried adding response models and that didn't work. BinaryTypes didn't work either. I have gotten it to do either application/json OR application/xml but I can't get it to do both. Is what I'm trying to do even possible? or should I create two separate endpoints?
This example always returns application/json.
Here is my lambda:
exports.handler = async function (event, context, callback) {
var format = event.format;
if (!format) {
callback(Error("[BadRequest] missing parameters"));
}
const promise = new Promise(function (resolve, reject) {
https
.get("exampleendpoint.com", (res) => {
let body = "";
res.on("data", (chunk) => {
body += chunk;
});
res.on("end", () => {
var results = JSON.parse(body);
if (format && format.toUpperCase() === "XML") {
var response = {
statusCode: 200,
headers: { "content-type": "application/xml" },
body:
'<?xml version="1.0" encoding="UTF-8"?><result>' +
OBJtoXML(results) +
"</result>",
};
resolve(response);
} else {
var response = {
statusCode: 200,
headers: { "content-type": "application/json" },
body: JSON.stringify(results),
};
resolve(response);
}
});
})
.on("error", (e) => {
var response = {
statusCode: 500,
body: "",
errorMessage: "Error from example.com",
};
resolve(response);
});
});
return promise;
};
Here is my api gateway code:
const epqApi = new gateway.RestApi(this, "restApi", {
restApiName: "resultsApi",
cloudWatchRole: true,
description: "Calls the service for the app",
endpointTypes: [gateway.EndpointType.REGIONAL],
deployOptions: {
stageName: "prod",
loggingLevel: gateway.MethodLoggingLevel.OFF,
dataTraceEnabled: false,
},
});
const epqResource = epqApi.root.addResource("v1");
const epqIntegration: gateway.LambdaIntegration =
new gateway.LambdaIntegration(generatePqsResultFunction, {
proxy: false,
allowTestInvoke: true,
passthroughBehavior: gateway.PassthroughBehavior.NEVER,
contentHandling: gateway.ContentHandling.CONVERT_TO_TEXT,
requestTemplates: {
"application/json": `{
"format":"$input.params(\'format\')"
}`,
},
integrationResponses: [
{
statusCode: "200",
responseParameters: {
"method.response.header.Access-Control-Allow-Origin": "'*'",
},
responseTemplates: {
"application/json": "$input.path('$.body')",
"application/xml": "$input.path('$.body')",
},
},
{
statusCode: "400",
selectionPattern: "^\\[BadRequest\\].*",
responseParameters: {
"method.response.header.Access-Control-Allow-Origin": "'*'",
},
responseTemplates: {
"application/javascript":
"#set($inputRoot = $input.path('$')) {\"errorMessage\" : \"$input.path('$.errorMessage')\"}",
},
},
],
});
epqResource.addMethod("GET", epqIntegration, {
requestParameters: {
//all params need to be in here, even if they are not required
"method.request.querystring.x": false,
"method.request.querystring.y": false,
"method.request.querystring.units": false,
"method.request.querystring.format": false,
"method.request.querystring.wkid": false,
"method.request.querystring.includeDate": false,
},
methodResponses: [
// Successful response from the integration
{
statusCode: "200",
responseParameters: {
"method.response.header.Access-Control-Allow-Origin": true,
},
},
{
statusCode: "400",
responseParameters: {
"method.response.header.Access-Control-Allow-Origin": true,
},
},
],
});
}

Nuxt Auth redirects after refresh when cookie is set to false

I am using Nuxt-auth local strategy, I set the cookie in nuxt.config.js to false because my token is too large for cookie, but when I do that when refreshing the page it redirects me to login page.
Here is my auth configuration.
auth: {
cookie: false,
localStorage: {
prefix: "auth.",
},
redirect: {
login: "/auth/signin",
logout: "/auth/signin",
callback: "/auth/signin",
home: false,
},
strategies: {
local: {
token: {
property: "token",
global: true,
required: true,
type: "Bearer",
},
user: {
property: "data",
autoFetch: true,
},
endpoints: {
login: { url: "/login", method: "post" },
logout: { url: "/logout", method: "post" },
user: { url: "/auth/user", method: "get" },
},
},
},
},
any solutions?

Loopback: Passing ctx object in remotemethods

I am trying to access the ctx object in my remote method.
I have the following code:
MyModel.remoteMethod("getdetails", {
accepts: [
{ arg: "options", type: "object", http: "optionsFromRequest" }
],
http: {
path: "/getdetails",
verb: "get"
},
returns: {
arg: "body",
type: "object",
root: true
}
});
MyModel.getdetails= function( options, cb) {
console.log(options.ctx);
};
I have added { arg: "options", type: "object", http: "optionsFromRequest" } but still I am not getting the ctx in my options. options contain only the accessToken and authorizedRules.
How can get access to ctx in remote methods? I am using loopback3.
Try this:
accepts: [
{arg: 'ctx', type: 'object', http: {source: 'context'}},
...

User Not receiving temporary password in email

Users are not receiving temporary passwords in email.
I'm trying to create user in cognito with lambda function.
'use strict'
const AWS= require('aws-sdk');
exports.handler = (event, context, callback) => {
console.log("event is ",event)
var cognitoidentityserviceprovider = new AWS.CognitoIdentityServiceProvider({apiVersion: '2016-04-18'});
var params = {
UserPoolId: process.env.userpool,
Username: event.queryStringParameters.username,
DesiredDeliveryMediums: ['EMAIL'],
ForceAliasCreation: false,
MessageAction: 'SUPPRESS',
TemporaryPassword: '******',
UserAttributes: [
{
Name: 'email_verified',
Value: "true"
},
{
Name: 'email',
Value: event.queryStringParameters.email
},
{
Name: 'name',
Value: event.queryStringParameters.name
}
]
};
cognitoidentityserviceprovider.adminCreateUser(params, function(err, data) {
if (err) console.log(err, err.stack); // an error occurred
else console.log(data); // successful response
var response = {
"statusCode": 200,
"headers": {
"User": "Created successful",
"x-custom-header" : "my custom header value",
"Access-Control-Allow-Origin": "*"
},
"body": JSON.stringify(data),
"isBase64Encoded": false
};
callback(null, response);
});
};
This is because you are using MessageAction: 'SUPPRESS'. Remove that and the proper email will be sent.

Redux Promise Middleware + Redux Mock Store Testing

I tried to test an action creator that returns a promise, using also redux mock store.
import promiseMiddleware from 'redux-promise-middleware';
import nock from 'nock';
import configureStore from 'redux-mock-store';
import { domain, port } from '../../config/environment';
import { GET_ITEMS_START,
GET_ITEMS_SUCCESS } from '../../constants/items';
import { getItems } from './items';
const promise = promiseMiddleware({
promiseTypeSuffixes: ['START', 'SUCCESS', 'ERROR']
});
describe('Get Items', () => {
it('should create GET_ITEMS_SUCCESS action after successfully getting items', (done) => {
nock(`${domain}:${port}`)
.get('/api/items')
.reply(200, {
_id: '1',
text: 'Make Eggs',
completed: false
});
const expectedActions = [
{ type: GET_ITEMS_START },
{ type: GET_ITEMS_SUCCESS, payload: {
data: { _id: '1', text: 'Make Eggs', completed: false }
}}
];
const store = mockStore({}, expectedActions, done);
store.dispatch(getItems());
});
});
and here is my action creator code
export function getItems() {
return {
type: GET_ITEMS,
payload: {
promise: axios.get(`${domain}:${port}/api/items`)
}
};
}
but the result is mismatch because the promise resolved a deep nested objects
Error: Expected { payload: { config: { headers: {}, method: 'get', timeout: 0, transformRequest: [ [Function] ], transformResponse: [ [Function] ], url: 'http://localhost:3000/api/items', withCredentials: undefined }, data: { _id: '1', completed: false, text: 'Make Eggs' }, headers: {}, status: 200, statusText: 'OK' }, type: 'GET_ITEMS_SUCCESS' } to equal { payload: { data: { _id: '1', completed: false, text: 'Make Eggs' } }, type: 'GET_ITEMS_SUCCESS' }
+ expected - actual
{
"payload": {
- "config": {
- "headers": {}
- "method": "get"
- "timeout": 0
- "transformRequest": [
- [Function]
- ]
- "transformResponse": [
- [Function]
- ]
- "url": "http://localhost:3000/api/items"
- "withCredentials": [undefined]
- }
"data": {
"_id": "1"
"completed": false
"text": "Make Eggs"
}
- "headers": {}
- "status": 200
- "statusText": "OK"
}
"type": "GET_ITEMS_SUCCESS"
}
I obviously don't want to copy all of those deep nested properties into my test suite.
Is there a better way of doing this?
If you're writing a unit test, you probably don't need to call the actual REST API. Instead you can mock axios and make it return some fake data which won't be so deep.