WebStorm: How to move an individual line up or down - webstorm

So my code looks like this:
export const authConfig = {
oidc: {
clientId: "0oa19fzd9fdwFwrSF2p7",
devClientId: "0oa17vykv1gc7XM1Q2p7",
issuer: "https://blackboardinsurance.okta.com",
redirectUri: "/implicit/callback",
scope: "openid profile email",
},
};
export const oktaClientId =
process.env.NODE_ENV === "development"
? authConfig.oidc.devClientId
: authConfig.oidc.clientId;
if I put my cursor on the first line and press Shift + Command + down-arrow which is mapped to "Move line down", the entire export statement moves down and it then looks like this:
export const oktaClientId =
process.env.NODE_ENV === "development"
? authConfig.oidc.devClientId
: authConfig.oidc.clientId;
export const authConfig = {
oidc: {
clientId: "0oa19fzd9fdwFwrSF2p7",
devClientId: "0oa17vykv1gc7XM1Q2p7",
issuer: "https://blackboardinsurance.okta.com",
redirectUri: "/implicit/callback",
scope: "openid profile email",
},
};
Is there anyway to just move the line down one? Or does WebStorm prevent this from happening? I want it to looks like this:
oidc: {
export const authConfig = {
clientId: "0oa19fzd9fdwFwrSF2p7",
devClientId: "0oa17vykv1gc7XM1Q2p7",
issuer: "https://blackboardinsurance.okta.com",
redirectUri: "/implicit/callback",
scope: "openid profile email",
},
};

Shift + Command + down-arrow is mapped to Code | Move Statement Down action that is supposed to move a statement, not a line. To move individual line, try Code | Move Line Down - Alt + Shift + down-arrow

Related

how to filter out files during when ember-cli is building my app (filtering monaco's many files, specifically)

I am trying to reduce monaco-editor dependency size.
I found this answer which shows how to do it on angular - by editing the glob configuration in angular.json file.
What is the corresponding file for this configuration on ember?
EDIT
I found this read me for configuring on ember-cli-build, any idea how to configure?
module.exports = function (defaults) {
const app = new EmberApp(defaults, {
autoImport: {
alias: {
'monaco-editor': '** what here? **',
},
},
I don't know how to read the angular comment there, but what I did was build my own copy of Monaco, with esbuild.
I am trying to reduce monaco-editor dependency size.
generally, if you're using embroider, if you don't import it, it won't be a part of your build.
This is probably more try-hard than you're looking for, but gives you more control over your assets.
here is my package where I do that: https://github.com/NullVoxPopuli/limber/tree/main/packages/monaco
I use this build script:
'use strict';
const path = require('path');
const os = require('os');
const fs = require('fs').promises;
const copy = require('recursive-copy');
const esbuild = require('esbuild');
const { esBuildBrowserTargets } = require('#nullvoxpopuli/limber-consts');
const OUTPUT_DIR = path.join(__dirname, 'dist').toString();
const ME = path.dirname(require.resolve('monaco-editor/package.json'));
const cssLocation = path.join(`${ME}/min/vs/editor`);
const workers = {
base: path.join(ME, 'esm/vs/editor/editor.main.js'),
editor: path.join(ME, 'esm/vs/editor/editor.worker.js'),
json: path.join(ME, 'esm/vs/language/json/json.worker.js'),
css: path.join(ME, 'esm/vs/language/css/css.worker.js'),
html: path.join(ME, 'esm/vs/language/html/html.worker.js'),
ts: path.join(ME, 'esm/vs/language/typescript/ts.worker.js'),
};
/**
* - Builds Web Workers
* - Builds a preconfigured bundle with monaco-editor
* - Copies tall relevant CSS to the same output folder
*/
module.exports = async function build() {
let buildDir = await fs.mkdtemp(path.join(os.tmpdir(), 'monaco--workers-'));
await esbuild.build({
loader: { '.ts': 'ts', '.js': 'js', '.ttf': 'file' },
entryPoints: [
workers.editor,
workers.json,
workers.css,
workers.html,
workers.ts,
workers.base,
],
bundle: true,
outdir: buildDir,
format: 'esm',
target: esBuildBrowserTargets,
minify: false,
sourcemap: false,
});
await esbuild.build({
loader: { '.ts': 'ts', '.js': 'js', '.ttf': 'file' },
entryPoints: [path.join('preconfigured', 'index.ts')],
bundle: true,
outfile: path.join(buildDir, 'preconfigured.js'),
format: 'esm',
target: esBuildBrowserTargets,
// something silly is going on with Monaco and esbuild
// TODO: report this to ESBuild's GitHub
minify: false,
sourcemap: false,
});
await copy(`${buildDir}`, OUTPUT_DIR, {
overwrite: true,
filter: ['**/*', '!*.nls.*'],
rename(filePath) {
if (filePath.includes('ttf')) {
return 'codicon.ttf';
}
return filePath;
},
});
await copy(`${cssLocation}`, OUTPUT_DIR, {
overwrite: 'inline',
filter: ['**/*.css'],
});
// TODO: how to change the monaco config to allow this to be in a `monaco/` folder
// const ICON_PATH = 'base/browser/ui/codicons/codicon/codicon.ttf';
// await copy(path.join(ME, 'esm/vs', ICON_PATH), ICON_PATH)
};
if (require.main === module) {
module.exports();
}
and then in my ember-cli-build.js here: https://github.com/NullVoxPopuli/limber/blob/main/frontend/ember-cli-build.js#L50
(merging the extraPublic Trees)
I invoke:
// Desktop Editor
require('#nullvoxpopuli/limber-monaco/broccoli-funnel')(),
the broccoli-funnel
'use strict';
const path = require('path');
const Funnel = require('broccoli-funnel');
const SRC_FILES = path.join(__dirname, 'dist');
/**
* This broccoli funnel is for copying the built assets to a target
* app's public folder. No building occurs
*
*/
module.exports = function monacoFunnel() {
return new Funnel(SRC_FILES, {
destDir: 'monaco/',
});
};
I then load monaco via a modifier like this:
import { assert } from '#ember/debug';
import type { Args } from './-types';
/**
* I wish there was a way to specify types-only packages
* while Limber uses Monaco, it's provided by the limber-monaco
* broccoli funnel (copied into the public folder).
*
* So the devDep on monaco-editor in limber/frontend is *solely*
* for the type defs
*/
import type * as monaco from 'monaco-editor';
export default function installMonaco(element: HTMLElement, ...[value, updateText, named]: Args) {
assert(`Expected MONACO to exist`, MONACO);
element.innerHTML = '';
let { editor, setText } = MONACO(element, value, updateText, named);
named.setValue((text) => {
// changing the text this ways calls updateText for us
// updateText(text); // update the service / URL
setText(text); // update the editor
});
return () => editor?.dispose();
}
let MONACO:
| undefined
| ((
element: HTMLElement,
...args: Args
) => { editor: monaco.editor.IStandaloneCodeEditor; setText: (text: string) => void });
export async function setupMonaco() {
if (MONACO) return;
// TypeScript doesn't have a way to type files in the public folder
// eslint-disable-next-line #typescript-eslint/ban-ts-comment
// #ts-ignore
MONACO = (await import(/* webpackIgnore: true */ '/monaco/preconfigured.js')).default;
}
and usage:
import monacoModifier from './my-monaco-modifier';
export default class Demo extends Component {
monaco = monacoModifier
}
<div {{this.monaco}}></div>
You can view this in action here: https://limber.glimdown.com/
I solved the issue by skipping languages import (which I don't need since I use custom language.
adding the following under webpackConfig:
new MonacoWebpackPlugin({
languages: [],
}),
Here is the full config in ember-cli-build.js:
return require('#embroider/compat').compatBuild(app, Webpack, {
staticAddonTestSupportTrees: true,
staticAddonTrees: true,
staticHelpers: true,
// staticComponents: true,
onOutputPath(outputPath) {
writeFileSync(join(__dirname, '.embroider-app-path'), outputPath, 'utf8');
},
packagerOptions: {
webpackConfig: {
module: {
rules: [
{
test: /\.(png|jpg|gif|svg|woff|woff2|eot|ttf|otf|flac)$/i,
loader: 'file-loader',
options: {
name: '[path][name]-[contenthash].[ext]',
},
},
],
},
plugins: [
new MonacoWebpackPlugin({
languages: [],
}),
],
},
},
});

AWS cognito not storing cookies in prod

Context:
I am using the amazon-cognito-identity-js SDK for authentication, as I am not using amplify for this project, only need to use cognito services. So far locally, I can do pretty much every fine, tokens come back and using the new AmazonCognitoIdentity.CookieStorage() it seems to be to store cookies locally using ({ domain: 'localhost', secure: 'false' }).
Also using nextjs v10.0.6
Problem
I tried to deploy the app to netlify and after installing it gives me back the tokens but does not store them in cookies on my browser.
Here is the snippet of code that I am using to sign in a user, there is a use case where the user was created by the admin, and will be forced to change password, thus the redirect to /changePassword
Any guidance would be amazing! My suspicion is that I am not configuring the domain right... but have tried every combination such as, removing the https, only including the autoGenerated subdomain part, etc
export const userPoolData = (): ICognitoUserPoolData => ({
UserPoolId: process.env.USER_POOL_ID || '',
ClientId: process.env.CLIENT_ID || '',
Storage: new CookieStorage({
domain: 'https://<autoGeneratedURL>.netlify.app',
secure: true,
expires: 10,
path: '/',
}),
});
const authenticationData = {
Username: username,
Password: password,
};
const authenticationDetails = new AuthenticationDetails(authenticationData);
const poolData = userPoolData();
const userPool = new CognitoUserPool(poolData);
console.log({ poolData });
const userData = {
Username: username,
Pool: userPool,
Storage: new CookieStorage({
domain: 'https://<autoGeneratedURL>.netlify.app',
secure: true,
expires: 10,
path: '/',
}),
};
const cognitoUser: CognitoUser = new CognitoUser(userData);
const userTokens: Pick<ResponseMessage, 'tokens'> = {};
console.log(authenticationData);
const authResponse = new Promise(() => {
cognitoUser.authenticateUser(authenticationDetails, {
onSuccess: (result) => {
console.log(result);
router.push({ pathname: '/' });
},
onFailure: (error) => {
console.log(error);
if (error.code !== 'InvalidParameterException' && error.code !== 'NotAuthorizedException') {
router.push({ pathname: '/changePassword', query: { username, password } });
}
},
});
});
try {
await authResponse;
} catch (error) {
return {
success: false,
code: 500,
error,
};
}
In case anyone runs into this, it turned out my suspicion was right and the fault was in the domain pattern, for a netlify app it should be configured as domain: <autoGeneratedURL>.netlify.app

How to Get AccessToken Dynamically from Cognito OAuth2.0 in Electron JS

Hello i use Electron JS for a desktop app which is related to a cloud plateform from which in needto get a list of Patients.
As far as now i can get it but with a static AccessToken. I really struggled to get it dynamic, please help.
Here is my code :
This is my configuration file where i specify Cognito Parameters :
export default {
s3: {
REGION: 'YOUR_S3_UPLOADS_BUCKET_REGION',
BUCKET: 'YOUR_S3_UPLOADS_BUCKET_NAME',
},
apiGateway: {
REGION: 'YOUR_API_GATEWAY_REGION',
URL: 'YOUR_API_GATEWAY_URL',
},
cognito: {
REGION: 'eu-west-1',
USER_POOL_ID: 'eu-west-1_P0Jcr7nig',
APP_CLIENT_ID: '4m1utu56hjm835dshts9jg63ou',
IDENTITY_POOL_ID: 'YOUR_IDENTITY_POOL_ID',
authenticationFlowType: 'USER_PASSWORD_AUTH',
AUTHENTICATION_FLOW_TYPE: 'USER_PASSWORD_AUTH',
},
API: {
endpoints: [
{
name: 'PatientsList',
endpoint: 'https://uo992r7huf.execute-api.eu-west-1.amazonaws.com/Stage/patients',
//endpoint: 'https://uo992r7huf.execute-api.eu-west-1.amazonaws.com/Stage',
},
],
},
};
Auth.signIn({
username: process.env.username,
password: process.env.password,
}).then().catch(err => {
console.log(err)});
In another file this is my getaccesstoken function which i export to the main
function getAccessToken() {
const poolData = {
UserPoolId : COGNITO_USER_POOL_ID,
ClientId : COGNITO_CLIENT_ID,
};
const userPool = new CognitoUserPool(poolData);
var authenticationData = {
Username : process.env.username, // your username here
Password : process.env.password, // your password here,
authenticationFlowType: process.env.AUTHENTICATION_FLOW_TYPE,
Pool : userPool
};
var authenticationDetails = new AmazonCognitoIdentity.AuthenticationDetails(
authenticationData);
var cognitoUser = new CognitoUser(authenticationData);
cognitoUser.authenticateUser(authenticationDetails, {
onSuccess: function (result) {
console.log('access token + ' + result.getAccessToken().getJwtToken());
},
onFailure: function(err) {
console.log(err);
},
});
}
And finally here is how i get the data in main :
The declarations :
const { Auth } = require('./cognitoAuth');
const theAccessToken = require('./cognitoAuth');
The code :
//Get Data From Cloud ECS
const API_URL = 'https://uo992r7huf.execute-api.eu-west-1.amazonaws.com/Stage/patients';
const headers = {
"Content-Type": "application/json",
//Authorization: theAccessToken.getAccessToken()
Authorization: "eyJraWQiOiJBbE1DZnBCTHYyVUlNazhXSG4xaTk4RG1QNlFmcFpSSjFaSW1qcVVFZnVBPSIsImFsZyI6IlJTMjU2In0.eyJzdWIiOiI4OWYyZGMxZi1iMTI3LTQzM2QtODJhYS1iMjNkNWJhNzY5NGEiLCJjb2duaXRvOmdyb3VwcyI6WyJkb2N0b3IiXSwiZXZlbnRfaWQiOiI1OTM0ZmIwNC0yYTUzLTQ2NmQtYTU1Ni0zNTM3M2RhZmU1Y2UiLCJ0b2tlbl91c2UiOiJhY2Nlc3MiLCJzY29wZSI6ImF3cy5jb2duaXRvLnNpZ25pbi51c2VyLmFkbWluIiwiYXV0aF90aW1lIjoxNTk1NDI2NjQ2LCJpc3MiOiJodHRwczpcL1wvY29nbml0by1pZHAuZXUtd2VzdC0xLmFtYXpvbmF3cy5jb21cL2V1LXdlc3QtMV9QMEpjcjduaWciLCJleHAiOjE1OTcxNTUxMDUsImlhdCI6MTU5NzE1MTUwNSwianRpIjoiNGRkN2U5ZGUtYmQ2YS00NTg4LWIzZDAtMTVjMWM1NWQxY2Y2IiwiY2xpZW50X2lkIjoiNG0xdXR1NTZoam04MzVkc2h0czlqZzYzb3UiLCJ1c2VybmFtZSI6Ijg5ZjJkYzFmLWIxMjctNDMzZC04MmFhLWIyM2Q1YmE3Njk0YSJ9.LYvzPRBxvKw2P3gHwV8NhYPg_EB3F7ZK2F5HpRWHtBHksr6D4N5Fw56ZVupkRCxVJSq0f93DdljI7BBcBnp9d_hpLzmJLTfBhA3t870omTxalTqpGXN_SvsZmuwcfCX-awn1Um6x_-fhq3zcfPkB9FBljbtwPN-kvCc-Iynei9anVxXI686nIbkfbYfnuRnHrbY0vg8FtyDIDBMv277FPoJ96NwPD4mJvNBxQHi_KfWxQ1DmLiAC6c_l2jP_wawAPBv788CjD_8OlKBbjAHinGEkaL1K9vjI5MhNPyTA5ym1IaWar7Jr8RkUDzQGvqEUPKoOUe9PswmOOxLBjehMgQ"
};
//console.log('Token Value:', theAccessToken.getAccessToken());
const getPatients = async(API_URL) => {
try {
//get data from cloud specifiying get method and headers which contain token
const response = await fetch(API_URL,{
method: 'GET', headers: headers}
);
var listPatients = await response.json();
listPatients.items.forEach(patient => {
//Checking what i got
console.log(patient);
});
} catch(err) {
console.log("Error" + err);
}
};
getPatients(API_URL);
Now when i make it dynamic by specifying theAccessToken.getAccessToken
I get this error, USER_SRP is not enabled even if specify it, when i asked team told me the cloud service doesn't want to enable it.
So how can i get this access token please?
For a desktop app it is recommended to do these 2 things, according to security guidance:
Use Authorization Code Flow (PKCE)
Login via the system browser, so that the app never sees the user's password
I have a couple of Electron code samples that use Cognito, which you can easily run - maybe start here:
First desktop app

Why is request.auth.session undefined?

I've created an auth strategy using bell and another using hapi-auth-cookie. However, when I try to set a session request.auth.session is undefined. Can someone help me figure out where I am going wrong?
My route:
module.exports = [
{
method: 'GET',
path: '/create-an-account',
config: {
auth: {
strategy: 'auth0',
mode: 'try'
}
},
handler: function(request, reply) {
var credentials = request.auth.credentials;
request.auth.session.set(credentials);
return reply.view('create-an-account');
}
}
]
My auth strategies:
exports.register = function (server, options, next) {
server.register([Bell, Cookie], function (err) {
server.auth.strategy('auth0', 'bell', {
provider: 'auth0',
config: {
domain: process.env.AUTH0_CLIENT_DOMAIN,
},
password: 'cookie_encryption_password_secure',
clientId: process.env.AUTH0_CLIENT_ID,
clientSecret: process.env.AUTH0_CLIENT_SECRET,
isSecure: false // For developing locally
});
server.auth.strategy('session', 'cookie', {
password: 'cookie_encryption_password_secure',
cookie: 'sid',
redirectTo: '/create-an-account',
redirectOnTry: false,
isSecure: false
});
});
return next();
};
We had this issue a little while ago on one of our projects. Hapi-auth-cookie have changed their documentation so they longer use request.auth.session.set(credentials);
Here's a link to the commit
If you change that line to request.cookieAuth.set() instead it should work. A lot of the examples online seem to use the old example which is how we missed it first time.
This was also picked up in another SO answer here > request.auth.session.set(user_info) not working HapiJS

Modify Strongloop/Loopback built-in input arguments in API Explorer

I want to know if it is possible to change the default input parameters of builtin methods like 'create', but only for input (not using the hidden property) and only for this method. In this case, I want to suppress the "balance" parameter. In other words, in the pointed location, my api explorer needs to show the following:
{
"userId": "string"
}
I have managed change custom remote methods, like so:
Using the following code:
module.exports = function(User) {
User.makeDeposit = function(data, callback){
//Method logic
};
User.remoteMethod(
'makeDeposit',
{
http: {path: '/makedeposit', verb: 'post'},
returns: {type: User, default:'User', root: true},
accepts: {arg: 'req', type: 'object', default: prettyJSON(depositSchema), http: {source: 'body'}}
}
);
};
// Returns a pretty printed json
function prettyJSON(str){
return JSON.stringify(str, null, ' ');
}
// Input Schemas - Only used for API Explorer
var depositSchema = {};
depositSchema.userId = "hash123";
depositSchema.amount = 11.37;
But I cannot replicate for built-in methods. Any help?