How to set custom message for regex in joi - error-handling

When I validate my graphql arguments, I'm getting error message like this for the password field.
"password" with value "" fails to match the required pattern: /^(?=\\S*[a-z])(?=\\S*[A-Z])(?=\\S*\\d)(?=\\S*[^\\w\\s])\\S{8,30}$/"
I don't want to show regex pattern in the error message. So I tried to set the custom error message for the password field but still it's showing the regex pattern.
import Joi from "joi";
export default Joi.object().keys({
email: Joi.string().email().required().label("Email"),
username: Joi.string().alphanum().min(4).max(20).required().label("Username"),
name: Joi.string().min(4).max(256).required().label("Name"),
password: Joi.string()
.min(8)
.regex(/^(?=\S*[a-z])(?=\S*[A-Z])(?=\S*\d)(?=\S*[^\w\s])\S{8,30}$/)
.required()
.label("Password")
.messages({
"string.min": "Must have at least 8 characters",
"object.regex": "Must have at least 8 characters",
}),
});
I think it's not selecting the regex by object.regex. Please help.

To know what error is being thrown, you can debug the error object (by logging it), and then finding the type of error.
Example:
const Joi = require('#hapi/joi');
const joiSchema = Joi.object().keys({
password: Joi.string()
.min(8)
.regex(/^(?=\S*[a-z])(?=\S*[A-Z])(?=\S*\d)(?=\S*[^\w\s])\S{8,30}$/)
.required()
.label("Password")
.messages({
"string.min": "Must have at least 8 characters",
"object.regex": "Must have at least 8 characters",
"string.pattern.base": "enter your custom error here..."
})
});
const validationResult = joiSchema.validate({ password: "2" }, { abortEarly: false });
console.log(validationResult.error.details.map(errDetail => errDetail.type), validationResult.error);
This outputs ["string.min", "string.pattern.base"]. details has 2 errors because of string.min and string.pattern.base, and abortEarly is set to false.

Related

Google blocks smtp in react-native

I am having trouble with google smtp for sending emails from my app.
The app works fine in my mobile and I am able to send emails without any issue.
But When I publish the app and people start using it, I get a security email from google telling me that it has blocked a login try.
I have even enabled less secure login.
Is there any other settings I should enable?
Here is my code for sending emails
import RNSmtpMailer from 'react-native-smtp-mailer'
async sendEmail(email: string, htmlBody: string, subject: string) {
try {
var settings = await this.getAppSettings();
if (!settings)
throw "Could not find the smtp settings"
var success = await RNSmtpMailer.sendMail({
mailhost: settings.smtp,
port: settings.port,
ssl: true, // optional. if false, then TLS is enabled. Its true by default in android. In iOS TLS/SSL is determined automatically, and this field doesn't affect anything
username: settings.email,
password: settings.password,
fromName: "NovelManager", // optional
replyTo: undefined, // optional
recipients: email,
bcc: [], // optional
subject: subject,
htmlBody: htmlBody,
attachmentPaths: [], // optional
attachmentNames: [], // required in android, these are renames of original files. in ios filenames will be same as specified in path. In a ios-only application, no need to define it
});
return true;
} catch (error) {
return false;
}
}
and here is the smtp settings
{
smtp: "smtp.gmail.com",
port: "465",
email: "test#gmail.com", // not the real email
password: "test"
}
Ok at last I found a solution, And that is using app password instead of simple password.
I am posting the solution here incase anyone is intressted.

Nodemailer SES TRANSPORT Error: "UnexpectedParameter: Unexpected key 'Destination' found in params"

Facing issue while sending AWS SES Templated email using SES TRANSPORT from Nodemailer.
In SES TRANSPORT Documentation, it says
To use SES transport, set a aws.SES object as the value for SES property in Nodemailer transport options.
Here's how my code looks.
transporter.sendMail({
ses: {
Destination: {
CcAddresses: [],
ToAddresses: 'recipient#example.com'
},
Source: 'sender#example.com' ,
Template: 'template_name' ,
TemplateData: JSON.stringify(data) ,
// optional extra arguments for SendRawEmail
Tags: [{
Name: 'tag name',
Value: 'tag value'
}]
}
}, (err, info) => {
console.log(info.envelope);
console.log(info.messageId);
});
This is the error I am getting.
2019-08-12T17:03:38.210Z error: There were 3 validation errors:
* UnexpectedParameter: Unexpected key 'Destination' found in params
* UnexpectedParameter: Unexpected key 'Template' found in params
* UnexpectedParameter: Unexpected key 'TemplateData' found in params

Identifying Mongoose schema validation errors as HTTP status codes

I'm leveraging Keystone.js to provide a lightweight CMS and API. I'm checking for duplicate entries on a List as such:
Registration.schema.post('save', function(error, registration, next) {
if (error && error.name === 'MongoError' && error.code === 11000) {
error = Error(`409|${ registration['email'] } is already registered`);
}
next(error);
});
I'm parsing the status code off the error message to return in my API endpoint.
Is there a different way to provide a friendly error message for duplicates in Keystone admin and be able to return the correct status code for API calls?
as db version v3.6.9
$ mongod --version
db version v3.6.9
git version: 167861a164723168adfaaa866f310cb94010428f
OpenSSL version: OpenSSL 1.0.1t 3 May 2016
allocator: tcmalloc
modules: none
build environment:
distmod: debian81
distarch: x86_64
target_arch: x86_64
I think you should check for ValidationError property instead MongoError as below:
RegistrationSchema.create(obj)
.then(...)
.catch(err => console.error('[registration] output: ', err);
We'll suppose the email is not mentioned before to simulate an is required error.
You'll see like that:
[registration] error: { ValidationError: Registration validation failed: email: Path `email` is required.
at ValidationError.inspect (....)
errors:
{
email:
{ Path `email` is required.
...
message: 'Path `email` is required.',
name: 'ValidatorError',
properties: [Object],
kind: 'required',
path: 'email',
value: [],
reason: undefined,
'$isValidatorError': true } },
_message: 'Registration validation failed',
name: 'ValidationError' }

Invalid CSRF when logging in to keystone

I'm entirely new to coding. I've looked around a bit, but not found anything relevant.
When logging into keystone to view our mongoDB database I get an error message saying:
Something went wrong; please refresh your browser and try again.
Doing that does not help. Neither does deleting the browser history or attempting from another lap top.
Looking at the javascript console in the browser, the error states invalid csrf.
I think this is the relevant source code in the keystone folder:
handleSubmit (e) {
e.preventDefault();
// If either password or mail are missing, show an error
if (!this.state.email || !this.state.password) {
return this.displayError('Please enter an email address and password to sign in.');
}
xhr({
url: `${Keystone.adminPath}/api/session/signin`,
method: 'post',
json: {
email: this.state.email,
password: this.state.password,
},
headers: assign({}, Keystone.csrf.header),
}, (err, resp, body) => {
if (err || body && body.error) {
return body.error === 'invalid csrf'
? this.displayError('Something went wrong; please refresh your browser and try again.')
: this.displayError('The email and password you entered are not valid.');
} else {
// Redirect to where we came from or to the default admin path
if (Keystone.redirect) {
top.location.href = Keystone.redirect;
} else {
top.location.href = this.props.from ? this.props.from : Keystone.adminPath;
}
}
});
},
How can I go about solving this / debugging the error? Thanks for any help!
This usually happens when session affinity fails. Are you using default in-memory session management? Maybe, try using a database for maintaining session state.
If you use MongoDB, Try the following config setting
'session store': 'mongo',
See 'session store' section under http://keystonejs.com/docs/configuration/#options-database for more details.

Watson TTS doesn't allow to choose voice

Created a Bluemix app to get the proper credentials and using Fiddler Text to Speech(TTS) to record prompts. Recordings use the default "Michael" voice. I want Allison.
If I try passing in "voice", I get the following error, even when I specify "Michael" as my choice:
{
"code_description": "Bad request",
"code": 400,
"error": "The argument(s) [u'voice'} are not allowed."
}
This is my payload:
{
"text": "Hello,, this is Dora. How are you today?",
"voice": "en-US_AllisonVoice"
}
I have a developer account, do I need to sign up to use "voice"? Even if I pass in the default "Michael"?
I think your problem is in the way you are specifing the voice parameter.
The voice and text parameters can be send as query parameters in a GET.
Examples
1. Curl
curl -u "{username}":"{password}" "https://stream.watsonplatform.net/text-to-speech/api/v1/synthesize?voice=en-US_AllisonVoice&text=Hello%2C%20this%20is%20Dora.%20How%20are%20you%20today%3F"
Node
var watson = require('watson-developer-cloud');
var fs = require('fs');
var text_to_speech = watson.text_to_speech({
username: '<username>',
password: '<password>',
version: 'v1'
});
var params = {
text: 'Hello, this is Dora. How are you today?',
voice: 'en-US_AllisonVoice',
accept: 'audio/wav'
};
// Pipe the synthesized text to a file
text_to_speech.synthesize(params).pipe(fs.createWriteStream('output.wav'));
See the Text to Speech API Reference for more examples on how to call the service.
Try the example above here:
https://text-to-speech-demo.mybluemix.net/api/synthesize?voice=en-US_AllisonVoice&text=Hello%2C%20this%20is%20Dora.%20How%20are%20you%20today%3F
Powered by the demo app: https://text-to-speech-demo.mybluemix.net