Flutter : Problem with FirebaseAuthException returning error in a variable - variables

I would like to store the result of my error: FirebaseAuthException in my ERROR variable, located in my main file, but I can't. I leave you the code of my two files. Thanks in advance
Fonction:
Future signInWithEmailAndPassword({
required String email,
required String password,
}) async {
try {
UserCredential result = await FirebaseAuth.instance
.signInWithEmailAndPassword(email: email, password: password);
User? user = result.user;
return user;
} on FirebaseAuthException catch (e) {
String erreur;
if (e.code == 'user-not-found') {
erreur = "Utilisateur non trouvé";
} else if (e.code == 'wrong-password') {
erreur = "Mauvais mot de passe";
} else if (e.code == 'invalid-email') {
erreur = "Email invalide";
} else {
return null;
}
return erreur;
}
}
File with my function when my button is clicked.
I specify that I created an "error" variable in this file
onOkButton() async {
if (_formKey.currentState!.validate()) {
await signInWithEmailAndPassword(
email: mailController.text.trim(),
password: passwordController.text.trim(),
)
.then((value) => user = value)
.onError((error, stackTrace) => erreur = error.toString());
}
print(user?.email);
mailController.clear();
passwordController.clear();
isConnected();
}

Related

Custom directive to check the value of two or more fields

I tried my best to write a custom directive in Apollo Server Express to validate two input type fields.
But the code even works but the recording of the mutation already occurs.
I appreciate if anyone can help me fix any error in the code below.
This is just sample code, I need to test the value in two fields at the same time.
const { SchemaDirectiveVisitor } = require('apollo-server');
const { GraphQLScalarType, GraphQLNonNull, defaultFieldResolver } = require('graphql');
class RegexDirective extends SchemaDirectiveVisitor {
visitInputFieldDefinition(field) {
this.wrapType(field);
}
visitFieldDefinition(field) {
this.wrapType(field);
}
wrapType(field) {
const { resolve = defaultFieldResolver } = field;
field.resolve = async function (source, args, context, info) {
if (info.operation.operation === 'mutation') {
if (source[field.name] === 'error') {
throw new Error(`Find error: ${field.name}`);
}
}
return await resolve.call(this, source, args, context, info);
};
if (
field.type instanceof GraphQLNonNull
&& field.type.ofType instanceof GraphQLScalarType
) {
field.type = new GraphQLNonNull(
new RegexType(field.type.ofType),
);
} else if (field.type instanceof GraphQLScalarType) {
field.type = new RegexType(field.type);
} else {
// throw new Error(`Not a scalar type: ${field.type}`);
}
}
}
class RegexType extends GraphQLScalarType {
constructor(type) {
super({
name: 'RegexScalar',
serialize(value) {
return type.serialize(value);
},
parseValue(value) {
return type.parseValue(value);
},
parseLiteral(ast) {
const result = type.parseLiteral(ast);
return result;
},
});
}
}
module.exports = RegexDirective;

Display backend error message after Create call

In my controller I have the following code - The problem is when it is error, I want to display exact error that is being passed from backend. But in my error handling function I never get any data. What is wrong here?
Controller.js
var token = null;
$.ajax({
url: sServiceURl,
type: "GET",
async: true,
beforeSend: function(xhr) {
sap.ui.core.BusyIndicator.show(0);
xhr.setRequestHeader("X-CSRF-Token", "Fetch");
},
complete: function(xhr) {
token = xhr.getResponseHeader("X-CSRF-Token");
oContext.OdataModel.create("/materialsSet", oContext.Data, null, oContext.submitSuccess.bind(oContext), oContext.submitError.bind(oContext));
}
});
submitSuccess: function(data, response, oContext) {
// works fine
},
submitError: function(oError) {
// I never get anything in oError, so the below code is useless.
try {
if (oError.responseText) {
obj = JSON.parse(oError.responseText);
message = obj.error.message.value;
} else if (oError.response.body) {
var errorModel = new sap.ui.model.xml.XMLModel();
errorModel.setXML(oError.response.body);
//Read message node
if (errorModel.getProperty("/0/message") !== "") {
message = errorModel.getProperty("/0/message");
} else {
message = message1;
}
} else {
message = message1;
}
} catch (error) {
message = message1;
}
sap.m.MessageToast.show(message);
},
Hope this will help you, first of all check backend response. I have use the below code for error handling.
submitError: function(responseBody) {
try {
var body = JSON.parse(responseBody);
var errorDetails = body.error.innererror.errordetails;
if (errorDetails) {
if (errorDetails.length > 0) {
for (i = 0; i < errorDetails.length; i++) {
console.log(errorDetails[i].message);
}
} else
console.log(body.error.message.value);
} else
console.log(body.error.message.value);
} catch (err) {
try {
//the error is in xml format. Technical error by framework
switch (typeof responseBody) {
case "string": // XML or simple text
if (responseBody.indexOf("<?xml") > -1) {
var oXML = jQuery.parseXML(responseBody);
var oXMLMsg = oXML.querySelector("message");
if (oXMLMsg)
console.log(oXMLMsg.textContent);
} else
console.log(responseBody);
break;
case "object": // Exception
console.log(responseBody.toString());
break;
}
} catch (err) {
console.log("common error message");
}
}
}

sinon stub is not working

I'm quiet new into testing and I don't seem to succeed to succesfully stub a function. I'm trying to stub the connection to the database, but it keep's contacting it, instead of using the result from the stub:
Here's the function:
var self = module.exports = {
VerifyAuthentication: function (data){
var deferred = q.defer()
if(typeof(data.email)=='undefined'){
deferred.reject({data:{},errorcode:"",errormessage:"param 'email' is mandatory in input object"})
}else{
if(typeof(data.password)=='undefined'){
deferred.reject({data:{},errorcode:"",errormessage:"param 'password' is mandatory in input object"})
}else{
var SqlString = "select id, mail, password, origin from tbl_user where mail = ?"
var param = [data.email]
self.ExecuteSingleQuery(SqlString, param).then(function(results){
if(results.length > 0)
{
if (results[0].password == data.password)
{
deferred.resolve({data:{"sessionId":results[0].id},errorcode:"",errormessage:""})
}else{
deferred.reject({data:{},errorcode:"",errormessage:"bad password"})
}
}else{
deferred.reject({data:{},errorcode:"",errormessage:"unknown user"})
}
})
}
}
return deferred.promise
},
ExecuteSingleQuery: function (queryString, parameters){
var deferred = q.defer()
var connection = connect()
connection.query(queryString, parameters, function (error, results, fields){
if(error){ deferred.reject(error)};
deferred.resolve(results)
});
return deferred.promise
},
And here's the test:
var dbconnection = require('../lib/dbConnection.js')
describe("VerifyAuthentication", function(){
it("_Returns DbResult object when user name and password match", function(){
var expectedResult = {data:{"sessionKey":"b12ac0a5-967e-40f3-8c4d-aac0f98328b2"},errorcode:"",errormessage:""}
stub = sinon.stub(dbconnection, 'ExecuteSingleQuery').returns(Promise.resolve(expectedResult))
return dbconnection.VerifyAuthentication({email:"correct#adres.com",password:"gtffr"}).then((result)=>{
expect(result.data.sessionId).to.not.be.undefined
expect(result.errorcode).to.not.be.undefined
expect(result.errormessage).to.not.be.undefined
stub.restore()
})
})
})
I always got an error 'unknown user', which is normal, because the user is indeed not in the database. However, I want to stub the 'ExecuteSingleQuery' function, avoiding it to connect to DB.
I have fixed a couple of issues in your code and posting the corrected files below.
dbConnection.js
var self = module.exports = {
VerifyAuthentication: function (data) {
var deferred = q.defer();
if (typeof (data.email) == 'undefined') {
deferred.reject({
data: {},
errorcode: '',
errormessage: "param 'email' is mandatory in input object"
});
} else {
if (typeof (data.password) == 'undefined') {
deferred.reject({
data: {},
errorcode: '',
errormessage: "param 'password' is mandatory in input object"
});
} else {
var SqlString = 'select id, mail, password, origin from tbl_user where mail = ?';
var param = [data.email];
self.ExecuteSingleQuery(SqlString, param).then(function (results) {
if (results.length > 0) {
if (results[0].password === data.password) {
deferred.resolve({
data: {
'sessionId': results[0].id
},
errorcode: '',
errormessage: ''
});
} else {
deferred.reject({
data: {},
errorcode: '',
errormessage: 'bad password'
});
}
} else {
deferred.reject({
data: {},
errorcode: '',
errormessage: 'unknown user'
});
}
});
}
}
return deferred.promise;
},
ExecuteSingleQuery: function (queryString, parameters) {
var deferred = q.defer();
var connection = connect();
connection.query(queryString, parameters, function (error, results, fields) {
if (error) {
deferred.reject(error);
}
deferred.resolve(results);
});
return deferred.promise;
}
};
dbConnection.test.js
describe('VerifyAuthentication', function () {
it('Returns DbResult object when user name and password match', function () {
var expectedResult = [{
id: '123',
password: 'gtffr'
}];
const stub = sinon.stub(dbconnection, 'ExecuteSingleQuery').resolves(expectedResult);
return dbconnection.VerifyAuthentication({
email: 'correct#adres.com',
password: 'gtffr'
}).then((result) => {
expect(result.data.sessionId).to.not.be.undefined;
expect(result.errorcode).to.not.be.undefined;
expect(result.errormessage).to.not.be.undefined;
stub.restore();
});
});
});
I am outlining the problematic parts below:
The expectedResult variable had a wrong type of value. In the
self.ExecuteSingleQuery() implementation you check for an array with length > 0. The fixed result returned by the stub, was an object instead of an array and this is why it returned the unknown user exception
The array should contain an object with { id: 'xxx', password: 'gtffr' } attributes. Password is validated against the one used by the dbconnection.VerifyAuthentication({email:"correct#adres.com",password:"gtffr"}) call
Finally, I have changed the stub statement to resolve instead of return as shown here const stub = sinon.stub(dbconnection, 'ExecuteSingleQuery').resolves(expectedResult); - this is the preferred method of resolving a promise

Node JS code not running in order

I have no idea why the code do not run as I expected.
When the UserExist is called, it should either console.log one of the statements that I set in my function code.
But the result is like the following the picture. Apreciate that if somebody can help!!
Console
var sql = require('mssql');
var config = require('./configuration/sqlconfig');
var Username = "Testing";
sql.connect(config);
console.log("Connected to DB");
if (!UserExist(Username)) {
InsertNewRecord(Username);
}
function isEmptyObject(obj) {
return !Object.keys(obj).length;
}
// This should work both there and elsewhere.
function isEmptyObject(obj) {
for (var key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) {
return false;
}
}
return true;
}
function UserExist(Username) {
console.log('Checking whether user exists or not... ');
new sql.Request().query("SELECT * FROM dbo.DB_Users WHERE Username = '" + Username + "';")
.then(function (recordset) {
if (isEmptyObject(recordset)) {
console.log("The User does not exist, ready to insert");
return true;
} else {
console.log("The user is existed already.");
return false;
}
}).catch(function (err) {
//When errors come
});
}
function InsertNewRecord(Username) {
console.log('Attempting to Insert records...');
new sql.Request().query("INSERT INTO dbo.Embright_Users (Username) VALUES ('" + Username + "');");
console.log("Added one new record");
}
The callbacks are not chained correctly. The InsertNewRecord() should be passed as callback to UserExist() function to make sure the execute in sequence. eg:
// Calling UserExist with a callback instead of 'if' statement
UserExist(Username, InsertNewRecord)
function UserExist(Username, callback) {
console.log('Checking whether user exists or not... ');
new sql.Request().query("SELECT * FROM dbo.DB_Users WHERE Username = '" + Username + "';")
.then(function (recordset) {
if (isEmptyObject(recordset)) {
console.log("The User does not exist, ready to insert");
// Calling InsertNewRecord with the username passed
callback(Username);
} else {
console.log("The user is existed already.");
// Do nothing
}
}).catch(function (err) {
//When errors come
});
}

Get password from input using node.js

How to get password from input using node.js? Which means you should not output password entered in console.
You can use the read module (disclosure: written by me) for this:
In your shell:
npm install read
Then in your JS:
var read = require('read')
read({ prompt: 'Password: ', silent: true }, function(er, password) {
console.log('Your password is: %s', password)
})
Update 2015 Dec 13: readline has replaced process.stdin and node_stdio was removed from Node 0.5.10.
var BACKSPACE = String.fromCharCode(127);
// Probably should use readline
// https://nodejs.org/api/readline.html
function getPassword(prompt, callback) {
if (prompt) {
process.stdout.write(prompt);
}
var stdin = process.stdin;
stdin.resume();
stdin.setRawMode(true);
stdin.resume();
stdin.setEncoding('utf8');
var password = '';
stdin.on('data', function (ch) {
ch = ch.toString('utf8');
switch (ch) {
case "\n":
case "\r":
case "\u0004":
// They've finished typing their password
process.stdout.write('\n');
stdin.setRawMode(false);
stdin.pause();
callback(false, password);
break;
case "\u0003":
// Ctrl-C
callback(true);
break;
case BACKSPACE:
password = password.slice(0, password.length - 1);
process.stdout.clearLine();
process.stdout.cursorTo(0);
process.stdout.write(prompt);
process.stdout.write(password.split('').map(function () {
return '*';
}).join(''));
break;
default:
// More passsword characters
process.stdout.write('*');
password += ch;
break;
}
});
}
getPassword('Password: ', (ok, password) => { console.log([ok, password]) } );
To do this I found this excellent Google Group post
Which contains the following snippet:
var stdin = process.openStdin()
, stdio = process.binding("stdio")
stdio.setRawMode()
var password = ""
stdin.on("data", function (c) {
c = c + ""
switch (c) {
case "\n": case "\r": case "\u0004":
stdio.setRawMode(false)
console.log("you entered: "+password)
stdin.pause()
break
case "\u0003":
process.exit()
break
default:
password += c
break
}
})
Here is my tweaked version of nailer's from above, updated to get a callback and for node 0.8 usage:
/**
* Get a password from stdin.
*
* Adapted from <http://stackoverflow.com/a/10357818/122384>.
*
* #param prompt {String} Optional prompt. Default 'Password: '.
* #param callback {Function} `function (cancelled, password)` where
* `cancelled` is true if the user aborted (Ctrl+C).
*
* Limitations: Not sure if backspace is handled properly.
*/
function getPassword(prompt, callback) {
if (callback === undefined) {
callback = prompt;
prompt = undefined;
}
if (prompt === undefined) {
prompt = 'Password: ';
}
if (prompt) {
process.stdout.write(prompt);
}
var stdin = process.stdin;
stdin.resume();
stdin.setRawMode(true);
stdin.resume();
stdin.setEncoding('utf8');
var password = '';
stdin.on('data', function (ch) {
ch = ch + "";
switch (ch) {
case "\n":
case "\r":
case "\u0004":
// They've finished typing their password
process.stdout.write('\n');
stdin.setRawMode(false);
stdin.pause();
callback(false, password);
break;
case "\u0003":
// Ctrl-C
callback(true);
break;
default:
// More passsword characters
process.stdout.write('*');
password += ch;
break;
}
});
}
How to use read without a callback
With async/await, we can get rid of the annoying callback with the following standard pattern:
const readCb = require('read')
async function read(opts) {
return new Promise((resolve, reject) => {
readCb(opts, (err, line) => {
if (err) {
reject(err)
} else {
resolve(line)
}
})
})
}
;(async () => {
const password = await read({ prompt: 'Password: ', silent: true })
console.log(password)
})()
The annoyance is that then you have to propagate async/await to the entire call stack, but it is generally the way to go, as it clearly marks what is async or not.
Tested on "read": "1.0.7", Node.js v14.17.0.
TODO how to prevent EAGAIN error if you try to use stdin again later with fs.readFileSync(0)?
Both read and https://stackoverflow.com/a/10357818/895245 cause future attempts to read from stdin with fs.readFileSync(0) to break with EAGAIN. Not sure how to fix that. Reproduction:
const fs = require('fs')
const readCb = require('read')
async function read(opts) {
return new Promise((resolve, reject) => {
readCb(opts, (err, line) => {
resolve([err, line])
})
})
}
;(async () => {
const [err, password] = await read({ prompt: 'Password: ', silent: true })
console.log(password)
console.log(fs.readFileSync(0).toString())
})()
or:
#!/usr/bin/env node
const fs = require('fs')
var BACKSPACE = String.fromCharCode(127);
// Probably should use readline
// https://nodejs.org/api/readline.html
function getPassword(prompt, callback) {
if (prompt) {
process.stdout.write(prompt);
}
var stdin = process.stdin;
stdin.resume();
stdin.setRawMode(true);
stdin.resume();
stdin.setEncoding('utf8');
var password = '';
stdin.on('data', function (ch) {
ch = ch.toString('utf8');
switch (ch) {
case "\n":
case "\r":
case "\u0004":
// They've finished typing their password
process.stdout.write('\n');
stdin.setRawMode(false);
stdin.pause();
callback(false, password);
break;
case "\u0003":
// Ctrl-C
callback(true);
break;
case BACKSPACE:
password = password.slice(0, password.length - 1);
process.stdout.clearLine();
process.stdout.cursorTo(0);
process.stdout.write(prompt);
process.stdout.write(password.split('').map(function () {
return '*';
}).join(''));
break;
default:
// More passsword characters
process.stdout.write('*');
password += ch;
break;
}
});
}
async function read(opts) {
return new Promise((resolve, reject) => {
getPassword(opts, (err, line) => {
resolve([err, line])
})
})
}
;(async () => {
const [err, password] = await read('Password: ')
console.log(password)
console.log(fs.readFileSync(0).toString())
})()
Error:
fs.js:614
handleErrorFromBinding(ctx);
^
Error: EAGAIN: resource temporarily unavailable, read
at Object.readSync (fs.js:614:3)
at tryReadSync (fs.js:383:20)
at Object.readFileSync (fs.js:420:19)
at /home/ciro/test/main.js:70:18
at processTicksAndRejections (internal/process/task_queues.js:95:5) {
errno: -11,
syscall: 'read',
code: 'EAGAIN'
}
Asked at: https://github.com/npm/read/issues/39