Hashing password with nestjs and mongoose crashes on production - docker

In my nestjs app i'm using mongoose's pre-save method to hash the password.
Locally it works fine. but on production/docker, it causes the whole nest app to crash. Here is the code:
export const UserSchema = new mongoose.Schema({
email: { type: String, unique: true, lowercase: true, trim: true },
password: {
type: String,
minlength: [8, 'Password must be 8 characters or more.'],
maxlength: 100,
},
username: String,
...
phone: { type: String, default: '' },
});
UserSchema.pre('save', async function (next: mongoose.HookNextFunction) {
try {
if (!this.isModified('password')) {
return next();
}
const saltRounds = 14;
const hashed = await bcrypt.hash(this['password'], saltRounds);
this['password'] = hashed;
return next();
} catch (err) {
return next(err);
}
});
Again, locally it works, but in docker any user saving is causing a crash ('exited with code 0').
Do you see anything wrong in this code, or do you have a better way of doing this?

Gosh! I've been wasting days on this. Here is the solution. bcrypt tends to fail on nodejs apps (wait, what? bcrypt? the npm package with 487K weekly downloads? yes.)
An alternative is bcryptjs, a javascript version that is a bit slower, but hey, it works!
Get it at your nearest npm store: https://www.npmjs.com/package/bcryptjs.
Here is where i found it: https://github.com/kelektiv/node.bcrypt.js/issues/432

Related

Trying to Script a Search Result into a Netsuite Entity Field

Having two issues with this. One is that I keep getting an error when trying to upload my script. The other is that one version that I did get to upload, didn't load any value into the field (ie. field blank after script ran)
The error I keep getting on upload is "Fail to evaluate script: All SuiteScript API Modules are unavailable while executing your define callback." And although I've made drastic changes to the script, it still won't allow me to upload.
/**
*#NApiVersion 2.x
*#NScriptType ScheduledScript
*/
define(['N/search', "N/record"],
function(search, record) {
function loadAndRunSearch(scriptContext) {
var mySearch = search.load({
id: 'customsearch1088'
});
mySearch.run().each(function (result) {
var countt = result.getValue({
name: 'number'
});
var entity = result.getValue({
name: 'internalid'
});
var objRecord = record.load({
type: record.Type.CUSTOMER,
id: entity,
isDynamic: true,
});
var vfield = objRecord.getField({
fieldId: 'custentity_orders_12m'
});
objRecord.setValue({fieldId: 'custentity_orders_12m', value: countt});
objRecord.save();
});
}
return {
execute: loadAndRunSearch
};
});
That's the script stripped down to the bare bones (FYI still doesn't upload), and the script that uploaded was basically a more complicated version of the same script, except it didn't set the field value. Can anyone see where I've gone wrong?
You haven't returned the entry function.
/**
*#NApiVersion 2.x
*#NScriptType ScheduledScript
*/
define(['N/search', 'N/record'],
function(search, record) {
function loadAndRunSearch(scriptContext) {
var mySearch = search.load({
id: 'customsearch1088'
});
mySearch.run().each(function (result) {
var countt = result.getValue({
name: 'number'
});
var entity = result.getValue({
name: 'internalid'
});
record.submitField({
type: record.Type.CUSTOMER,
id: entity,
values: {
'custentity_orders_12m' :countt
}
});
});
}
return {
execute : loadAndRunSearch
}
});

Changing Cognito-User-Pool/AWS-Amplify; leading to SignUp issue

I am, handling some SignUp/SignIn process within an iOS app, using AWS-Amplify (and Cognito).
It was working fine, but then I decided to require a few more information when signing up.
Namely: name, given_name, family_name.
Here is the function called to authenticate:
func showSignIn() {
AWSAuthUIViewController
.presentViewController(with: self.navigationController!,
configuration: nil,
completionHandler: {
(provider: AWSSignInProvider, error: Error?) in
if error != nil {
print("Error occurred: \(String(describing: error))")
} else {
print("Identity provider: \(provider.identityProviderName)")
}
})
}
After I did the necessary manipulations (using amplify-cli) to remove the old user pool and make a new one. I recompiled my iOS app and launched it.
This was OK, but now when I want to sign up a user I get this message:
The message content is not surprising, since now I require the indicated fields.
But the problem is that I don't see any space in the UI where to input those new fields.
Did I forget to do something so that the UI could be updated adequately?
Or am I suppose to do something (to update the UI by hand) by modifying the function above? If YES, what is the way to make the change?
These are my first steps with amplify, I may well be making some basic mistakes.
I'm only using AWS Amplify with JavaScript, but in JS you do need to update the UI manually.
Here is the JS code and how I have to call it manually, maybe this helps.
handleSignUpPressed = async ({
emailAddress = '',
firstName = '',
lastName = '',
password = '',
phoneNumber = '',
wantsToImproveApp = true,
} = {}) => {
if (emailAddress && firstName && lastName && password && phoneNumber) {
try {
const res = await Auth.signUp({
username: emailAddress,
password,
attributes: {
email: emailAddress,
name: firstName,
family_name: lastName,
phone_number: phoneNumber,
},
});
console.log('success', res);
this.props.navigation.push('VerificationScreen', {
username: res.username,
});
} catch (err) {
console.log(err);
}
}
};
You can use AWSMobileClient to show the drop-in Auth https://aws-amplify.github.io/docs/ios/authentication#user-attributes which is using AWSAuthUIViewController underneath the covers.
I didn't see a way to customize it with SignInUIOptions for your use case. There is also an existing RFC to improve the usability of AWSMobileClient and the drop-in UI: https://github.com/aws-amplify/aws-sdk-ios/issues/1158
If you roll your own sign-up/sign-in flow, you can then pass in user attributes to AWSMobileClient.signUp: https://aws-amplify.github.io/docs/ios/authentication#user-attributes

React-Native + Apollo-Link-State + AWS Appsync : Defaults are not stored in cache

I'm struggling with this for days.
I've successfully configure Apollo-Link-State with AppSync a month ago and start adding defaults and resolvers like this :
const cache = new InMemoryCache() //create the cache to be shared by appsync and apollo-link-state
const appSyncAtrributes = {
//...
//setup appSync
}
const stateLink = createLinkWithCache(() => withClientState({
cache,
resolvers: {
Mutation: {
updateCurrentUser: (_, { username, thumbnailUrl }, { cache }) => {
// ...
// working mutation that store the login information when user authenticate.
}
}
},
defaults: {
currentUser: {
__typename: 'CurrentUser',
username: '',
thumbnailUrl: ''
}
}
}))
const appSyncLink = createAppSyncLink({
url: appSyncAtrributes.graphqlEndpoint,
region: appSyncAtrributes.region,
auth: appSyncAtrributes.auth,
complexObjectsCredentials: () => Auth.currentCredentials()
})
const link = ApolloLink.from([stateLink, appSyncLink])
const client = new AWSAppSyncClient({}, { link })
So long it worked (I'm calling the #client mutation and query around my app).
But now I'm trying to add other data in my Linked State as this (everything else stayed the same):
defaults: {
currentUser: {
__typename: 'CurrentUser',
username: '',
thumbnailUrl: '',
foo: 'bar',
},
hello: 'world',
userSettings: {
__typename: 'userSettings',
isLeftHanded: true
}
}
And my cache doesn't update. I mean :
currentUser still contains __typename: 'CurrentUser', username: '', thumbnailUrl: ' but doesn't contains foo: 'bar'. And the cache doensn't containshello: 'bar'oruserSettings`.
More confusing is the fact that if I give a value to username or thumbnailUrl like username: 'joe', the cache actually reflect that change! (while ignoring all my other modifications)
I tried all variation of this experiment and cleared all caches (even running it on a fresh colleague computer to be sure they were no dirty cache involved).
I'm completely clueless.
Context :
It happens in the iOS simulator
I'm debugging watching the redux cache of appsync
apollo-cache-inmemory: 1.2.8
apollo-client: 2.3.5
apollo-link: 1.2.2
apollo-link-state: 0.4.1
aws-appsync: 1.3.2
Update : Actually currentUser is not stored neither from defaults. It get into the cache when the mutation is called.
Ok my issue wasn't an issue after all (2 days wasted).
The lack of proper debug tools (had to watch the cache evolving thru redux) was the issue.
The cache is actually written correctly but doesn't show anywhere.
As soon as I start querying that cache, everything worked.
Can't wait for react-native-debugger to integrate a proper apollo/graphql analyser

Zapier Cli: Not able to set authentication.connectionLabel dynamically

Following the developer docs, I have attempted numerous variations trying to achieve this.
I would like to extract the label from the token payload, if not I can build it from the /me response body.
This is my latest attempt:
var jwtDecode = require('jwt-decode');
const getTokenFields = (z, bundle) => {
var sub = jwtDecode(bundle.authData.token)['sub']
console.log(sub)
return sub;
};
const getLabelField = (z, bundle) => {
var sub = jwtDecode(bundle.authData.token)['sub']['label']
console.log(sub)
return sub;
};
const authentication = {
type: 'session',
test: {
url: '{{process.env.AP_HOST}}/me'
},
fields: [
{
key: 'token',
type: 'string',
required: true,
helpText: 'See settings to get your token'
}
],
sessionConfig: {
perform: getTokenFields
},
connectionLabel: {
perform: getLabelField
}
};
module.exports = authentication;
the only thing that I can get to work is:
connectionLabel: "{{bundle.authData.token}}", but it looks terrible!
connectionLabel: "{{bundle.authData.responsefield}}" feels like it should be something that should work but it doesn't either
David here, from the Zapier Platform team.
Instead of connectionLabel: {perform: getLabelField}, it should just be connectionLabel: getLabelField. You can also use a string that pulls from the bundle (like you're seeing) or any data that comes back from the designated test endpoint (see here).
There should be validation that prevents what you have (that'll error when you run zapier validate) but if that comes back clean then definitely let us know.

ionic 2 FileOpener, mime-type is null

i use FileTransfer-Plugin to download a file over a API. After download i want open the file with FileOpener-Plugin. FileOpener requires the mime-type of the file, but data.type (mime-type) returns null.
File.resolveLocalFilesystemUrl(cordova.file.cacheDirectory)
.then((dirEntry) => {
this.transfer.download(url, path, true, {headers: headers})
.then((entry) => {
entry.file((data) => {
console.log('MimeType: ', data.type); // returns null
});
});
});
it works without setting mime-type, but i think it is better with. Anybody knows about this Problem. I working in iOS.
data returns:
end: 683008
lastModified: 1497256786396.6
lastModifiedDate: 1497256786396.6
localURL: "cdvfile://localhost/cache/file.ext"
name: "file.ext"
size: 683008
start: 0
type: null

Resources