Keycloak Script base authenticator same error message on failure - javascript

Need to send a custom error message in keycloak script based authenticator.
On failure it showing same error message Incorrect email or password. Please check and try again. How to send a custom error message?
Code:
function authenticate(context) {
var username = user ? user.username : "anonymous";
var authShouldFail = false;
if (username=="anonymous") {
context.failure(AuthenticationFlowError.INVALID_CLIENT_CREDENTIALS);
return;
}
context.success();
}

I searched source code of keycloak repository and finally came up with a solution. The answer is to use setError method to show custom error messages and use context.failureChallenge function instead of context.failure like the following code:
// import the required Java classes
AuthenticationFlowError = Java.type("org.keycloak.authentication.AuthenticationFlowError");
Response = Java.type("javax.ws.rs.core.Response");
Errors = Java.type("org.keycloak.events.Errors");
function authenticate(context) {
var showCustomError = true; // you need to make your own controls to set this property
if (showCustomError) {
var errorMessage = "this is custom error message"; // set your custom error message
context.getEvent().error(Errors.IDENTITY_PROVIDER_ERROR);
var challengeResponse = context.form().setError(errorMessage, []).createErrorPage(Response.Status.INTERNAL_SERVER_ERROR);
context.failureChallenge(AuthenticationFlowError.IDENTITY_PROVIDER_ERROR, challengeResponse);
return;
}
context.success();
}

Related

list errors shows in console but only one error shows in div

I am using express-validator for form validation and using axios to send the data to to the server. Once the validation is done I send a response back. I can loop over the errors and display them all in console, one under another but in my error div where I want to show the errors to the user, it only shows one, instead of all of them like in console.
Controller:
if (!errors.isEmpty()) {
return res.status(422).json({error: errors.array()});
}
Display errors to user:
const errorLoop = error.response.data.error;
for (const errMsg of errorLoop) {
console.log(errMsg.msg);
const showError = document.querySelector('.error');
showError.classList.add("notification");
showError.innerHTML = errMsg.msg;
}
You are setting the innerHTML for each error. Thus you are replacing it and will only ever see the last error.
Try this:
let errorMessages = ""
for(const errMsg of errorLoop){
errorMessages += errMsg.msg + "<br>"
}
const showError = document.querySelector('.error')
showError.classList.add("notification")
showError.innerHTML = errorMessages
(The <br> will insert a new line for visual purposes)

Roles with Meteor and React

I am currently working on a project for a client. I'm trying to assign roles to users at the time they sign up for an account.
handleSubmit(e){
e.preventDefault();
this.setState({message:'',messageClass:'hidden'});
var that = this;
var first_name = ReactDOM.findDOMNode(this.refs.first_name).value.trim();
var last_name = ReactDOM.findDOMNode(this.refs.last_name).value.trim();
var email = ReactDOM.findDOMNode(this.refs.email).value.trim();
var password = ReactDOM.findDOMNode(this.refs.password).value.trim();
var type = 'fan';
var user = {email:email,password:password,profile:{fullname:(first_name + last_name).toLowerCase(),firsname:first_name,lastname:last_name,avatar:'http://placehold.it/150x150',friends:[],type:type}};
Accounts.createUser(user,function(e){
if (e) {
Materialize.toast(e.reason, 5000);
} else {
FlowRouter.go('/dashboard');
}
})
}
Above is my handle submit event for the signup form. Below is the hook that I added to assign the role to the user after the user is inserted.
Meteor.users.after.insert(function (userId, doc) {
if (doc.profile.type === "fan") {
Roles.addUsersToRoles(doc._id, [ROLES.Fan])
}
});
What I'm finding is that the user gets created but instead of being redirected to the dashboard, the user remains on the signup page and receives an error in the toaster message stating internal server error. When I go into the console to find the user that was created, the profile type is assigned but the user is missing their email address.
This is the error I'm getting in my terminal window:
Exception while invoking method 'createUser' ReferenceError: ROLES is
not defined I20160402-16:04:42.482(-4)? at Object.
(both/collection_hooks/hooks.jsx:3:35) I20160402-16:04:42.482(-4)?
at packages/matb33_collection-hooks/insert.js:35:1
I20160402-16:04:42.482(-4)? at Array.forEach
(packages/es5-shim/.npm/package/node_modules/es5-shim/es5-shim.js:417:1)
I20160402-16:04:42.483(-4)? at Function..each..forEach
(packages/underscore/underscore.js:105:1) I20160402-16:04:42.483(-4)?
at after (packages/matb33_collection-hooks/insert.js:34:1)
I20160402-16:04:42.483(-4)? at
Object.CollectionHooks.defineAdvice.self
(packages/matb33_collection-hooks/insert.js:49:1)
I20160402-16:04:42.485(-4)? at Object.collection.(anonymous
function) [as insert]
(packages/matb33_collection-hooks/collection-hooks.js:117:1)
I20160402-16:04:42.485(-4)? at [object
Object].Mongo.Collection.(anonymous function) [as insert]
(packages/mongo/collection.js:590:1) I20160402-16:04:42.485(-4)?
at AccountsServer.Ap.insertUserDoc (accounts_server.js:1248:25)
I20160402-16:04:42.486(-4)? at createUser
(password_server.js:980:25)
Does anyone have any idea what exactly is happening?
The variable ROLES isn't defined in the context of your hook. It's either not a global or you're using Meteor 1.3 and you haven't exported it from the file you've defined it in and imported it into the file where you defined your hook.

Meteor "TypeError: Cannot read property '0' of undefined"

I'm new to Meteor.
What I'm trying to do is send an email to someone when they are invited to join the service (done) but I want that email to dynamically be populated with the user who invited them to join's details. This is the code I have:
Meteor.publish('profile', function() {
return Meteor.users.find(this.userId);
});
var emailData = {
existingUser: 'currentUser().profile.displayName',
existingOrganisation: 'currentUser().profile.organisation',
existingEmail: Meteor.users.emails[0].address
};
//Code taken from Meteor Docs to customise content of enrollment email
Accounts.emailTemplates.siteName = "Amendd";
Accounts.emailTemplates.from = "Amendd <no-reply#amendd.com>";
Accounts.emailTemplates.enrollAccount.subject = function (user) {
return "Welcome to Amendd";
};
Accounts.emailTemplates.enrollAccount.html = function (user, url) {
return SSR.render('enrollAccountEmail', emailData) + url;
};
Where enrollAccount.html is a seperate file in my '/private' folder. I have put the ' -- ' in place after my existingUser and existingOrganisation variables, while I focus on getting the email field to work.
The error message that I'm getting thrown up when I save and run the project in Terminal is
TypeError: Cannot read property '0' of undefined"
where it points me to the [0] in the existingEmail variable.
Can anyone shed any light on the issue I'm having?
UPDATE
The fix for this was moving the emailData object within the function:
SSR.compileTemplate('enrollAccountEmail', Assets.getText('enrollAccountEmail.html'));
Accounts.emailTemplates.siteName = "Amendd";
Accounts.emailTemplates.from = "Amendd <no-reply#amendd.com>";
Accounts.emailTemplates.enrollAccount.subject = function (user) {
return "Welcome to Amendd , " + user.email;
};
Accounts.emailTemplates.enrollAccount.html = function (user, url) {
var emailData = {
existingUser: Meteor.user().profile.displayName,
existingOrganisation: Meteor.user().profile.organisation,
existingEmail: Meteor.user().emails[0].address
};
return SSR.render('enrollAccountEmail', emailData) + url;
};
I don't believe currentUser() works on the server. Try using Meteor.user(), it will work anywhere but a publish function.
Meteor.user().emails[0].address
http://docs.meteor.com/#/full/meteor_user

Parse function suddenly returning invalid json

since a couple of hours ago all my parse functions have been returning invalid json. Nothing to do with the cloud code... I even tried rolling it back. I'm on the android platform and haven't made any game breaking changes to it..
For example,
I have a login function...
Parse.Cloud.define("loginuser", function(request, response){
var useremail = request.params.useremail;
var userpassword = request.params.userpassword;
var usersource = request.params.usersource;
Parse.User.logIn(useremail, userpassword,{
success:function(user){
// Sets either candidate or business to be true depending on condition
if (usersource == "candidate"){
user.set("candidate", true);
} else if (usersource == "business"){
user.set("business", true);
}
user.save(null, {
// login success & return
success: function(user){
response.success(user);
}, error: function(error){
response.error(error);
}
});
},
error:function(user, error){
// login failure
response.error(user, error);
}
});
});
With no change to it... it suddenly starts throwing error:
01-05 22:37:30.175 1052-1052/recruitr.recruitr E/Login error: com.parse.ParseRequest$ParseRequestException: bad json response
01-05 22:37:46.045 1052-1052/recruitr.recruitr E/Signup Error: com.parse.ParseRequest$ParseRequestException: bad json response
Does anyone know why?
EDIT:
Ran debugger and it pops this out when the error message shows up:
this = {LoginActivity$4#4619}
cancel = {boolean[1]#4623}
logincredentials = {HashMap#4624} size = 3
parseUser = null
e = {ParseRequest$ParseRequestException#4625} "com.parse.ParseRequest$ParseRequestException: bad json response"
isPermanentFailure = false
code = 100
cause = {JSONException#4630} "org.json.JSONException: Value <html> of type java.lang.String cannot be converted to JSONObject"
cause = {JSONException#4630} "org.json.JSONException: Value <html> of type java.lang.String cannot be converted to JSONObject"
detailMessage = {String#4638} "Value <html> of type java.lang.String cannot be converted to JSONObject"
stackState = {long[34]#4639}
stackTrace = {StackTraceElement[0]#4633}
suppressedExceptions = {Collections$EmptyList#4634} size = 0
shadow$_klass_ = {Class#497} "class org.json.JSONException"
shadow$_monitor_ = -1960135782
detailMessage = {String#4631} "bad json response"
stackState = {long[30]#4632}
stackTrace = {StackTraceElement[0]#4633}
suppressedExceptions = {Collections$EmptyList#4634} size = 0
shadow$_klass_ = {Class#4592} "class com.parse.ParseRequest$ParseRequestException"
shadow$_monitor_ = -2123277170
Found the problem:
The Android Parse SDK was having problems with a new update. Parse was not actually initializing in the code at all (keys weren't working/initialization was not working)
Fix the error by changing the dependency:
compile 'com.parse:parse-android:1.+'
to
compile 'com.parse:parse-android:1.12.0'
or
compile 'com.parse:parse-android:1.10.0'
Both seem to work flawlessly as of this moment in time.

Showing Pop up message if error occured while creating folder [Windows Store Javascript App]

I am trying to show a pop up error message to user if folder creation fails because it already exists, but access Denied exception is thrown on msg.showAsync()
sf.getFolderAsync(KorN_Name).then(function (kn) {
return kn.createFolderAsync(username, Windows.Storage.CreationCollisionOption.failIfExists)
}).done(function (user) {
//some code
},
function (error) {
var md = Windows.UI.Popups.MessageDialog;
var msg = new md("User already exists", "Ooops!");
msg.showAsync();
});
How to fix it?
Try this code. It might be failing because you initialized the messageBox differently:
var msg = new Windows.UI.Popups.MessageDialog("User already exists","Oops!");
msg.showAsync();
See this link if you have not already done so.

Categories