grails: how to check field value's validity specifically - grails

getFieldError("user_name").rejectedValue
If I have a field as above where I've set constraints as follows:
user_name(blank: false, unique: true, email: true)
how can I check for violations specifically in each case so as to customize the error message in each case? Currently I have the following but that only works in the first case if I try to submit the form with an empty field:
def errorVal = createdUser.errors.getFieldError("user_name").rejectedValue
if (errorVal == null)
render(contentType: 'text/json') {["message": 'Username cannot be blank!']}
else if (errorVal == invalid)
render(contentType: 'text/json') {["message": 'Username must be an e-mail address!']}
else if (errorVal == unique)
render(contentType: 'text/json') {["message": 'Username already exists for picked institution!']}
If I try to test the second case by putting something in the field which is a non-email address, I get this error in the console:
No such property: invalid for class: com.twc.fatcaone.AdminController

Like the great answers others have posted, I would recommend following built in framework guidelines, however, if you want you can use the EmailValidator class to check for valid e-mail addresses. Uniqueness is already check for you but if you have additional custom criteria then you can search the database using AND on your different criteria and if the result is positive you know its not unique. Again, this may not always be the best solution.

Related

Is it possible to have a few passwords in authlogic gem?

Right now we have phone_number as login, and sms code (4 digits) as password.
When user wants to login:
- user enters phone number
- we generate code
- we save code to user password field
- we send code to user via sms
- user uses this sms code to login in
We want to be able to have last 3 generated codes (password) be valid for login:
- we started to save generated codes in separate table
And here is the question: How do I connect this to authlogic? Is the any callback that turns off default password check and give me ability to add my custom logic for password checking?
I found a solution which helped me to tune password validation logic.
My authlogic version 3.5.6 and I has method called validate_by_password in following implementation.
I copied first part of it to save blank fields and logic checks. And overwrote invalid password check in way I need.
class Client::Session < Authlogic::Session::Base
...
def validate_by_password
# copy paste from gem
self.invalid_password = false
# check for blank fields
errors.add(login_field, I18n.t('error_messages.login_blank', default: 'cannot be blank')) if send(login_field).blank?
errors.add(password_field, I18n.t('error_messages.password_blank', default: 'cannot be blank')) if send("protected_#{password_field}").blank?
return if errors.count > 0
# check for unknown login
self.attempted_record = search_for_record(find_by_login_method, send(login_field))
if attempted_record.blank?
generalize_credentials_error_messages? ?
add_general_credentials_error :
errors.add(login_field, I18n.t('error_messages.login_not_found', default: 'is not valid'))
return
end
# custom check for invalid password
...
end
end

Google Form/Sheet - Skip blank email google script

This is a similar question to this link, but slightly different:
Skipping blank emails in Google Apps Script Mail Merge
I have a form/sheet set up that, when the users fills out the form, it generates a receipt email (does not contain the form contents as some receipts do) that is then sent to the recipient. However when the user leaves this field blank I get a form trigger error, which is understandable why the script didn't finish. I am trying to figure out how to keep the script from attempting to send an email when the recipient/email field is blank. Unfortunately, making the email field required on the form is not an option since, oddly, not everyone would have an email address (if this were an option I would certainly just require an email address to be entered).
I have tried the following code snippet based on the link provided above.
// Send Email to recipient(s) declared above in #var sendEmail
if (e.values[11] != null) {
var sendEmail = e.values[11]; //email field column
var subject = "subject message";
var body = "body message";
MailApp.sendEmail(sendEmail, subject, body, {
name: "Community Home Health Care",
body: body,
noReply: true,
})
I have also tried instead of
(e.values[11] != null)
using
(e.values[11] != "")
The remaining code I have omitted (goes above what I have shown) simply takes the form field responses and generates a document converted to a PDF which works as expected. The email section also works, just trying to eliminate the failed script emails I get occasionally.
Thanks
First is an assumption that 12 items are passed (0 through 11) and the email is the last item to be passed. If that is the case, then test that the item is defined with:
if(typeof e.values[11] !== 'undefined')
If you are using the Mail Merge Tutorial linked to in the post you linked to, and using the getRowsData() function to get your form responses, you should be able to use the Header of the column containing the email address such as e.values.emailAddress and get:
if(typeof e.values.emailAddress !== 'undefined')
This may vary based on how your data is defined.

How to know which user answered a Jenkins-Pipeline input step?

I have a Jenkinsfile script that tests for the possibility to perform an SVN merge and then asks the user for the permission to commit the merge.
I would like to know the username that answers the "input" step in order to write it into the commit message.
Is this possibile?
This is what hypothetically I would like to do:
outcome = input message: 'Merge trunk into branch?', ok: 'Merge'
echo "User that allowed merge: ${outcome.user}"
The input step got an optional submitterParameter, which allows to specify the key of the returned Map that should contain the user who's submitting the input dialog:
If specified, this is the name of the return value that will contain the ID of the user that approves this input.
The return value will be handled in a fashion similar to the parameters value.
Type: String
This looks then as follows:
def feedback = input(submitterParameter: 'submitter', ...)
echo "It was ${feedback.submitter} who submitted the dialog."
P.S: If anybody is interested in a full-fledged code snippet returning the user both for positive and negative feedback to the dialog (and timeout as well), I kindly point to our pipeline library.
It is not currently possible, for now only entry parameters are returned in the input step answer, as mentionned in source code :
// TODO: perhaps we should return a different object to allow the workflow to look up
// who approved it, etc?
switch (mapResult.size()) {
case 0:
return null; // no value if there's no parameter
case 1:
return mapResult.values().iterator().next();
default:
return mapResult;
}
If you'd like to restrict which user(s) can approve the input step, you can however use the submitter parameter, e.g. :
input message: 'Approve ?', submitter: 'authorized-submitter'
EDIT
Since January 2017 it is now possible to request additional parameters to be sent. Please see StephenKing answer above.
If you are not asking for any parameters on the input, then adding the submitterParameter kind of worked. It didn't add it as a parameter on the return object, instead, it turned the returned object into a string with the username in it.
def feedback = input(submitterParameter: 'submitter')
echo "It was ${feedback} who submitted the dialog."
You can do this for exceptions if you turn off the groovy-sandbox:
try {
'Deploy to production?'
node {
sh 'echo deploying'
}
} catch(e) {
def user = e.getCauses()[0].getUser()
echo "Production deployment aborted by:\n ${user}"
}

Manually Invoking email verification

We've been using django-allauth for quite some time now in production. We can enable account email verification which works great. But we now have a REST api that allows users to register through the API and the workflow doesn't go through django-allauth. Is it possible to manually invoke the django-allauth email verification feature or do we need to use a custom solution?
I'll just post my answer here as I've been searching for adding email verification with Django Built-in Authentication (And using a Custom Auth Model), I used the method mentioned by Marcus, I'll just add all the other stuff around it for anyone who wants to do the same.
First: Install django-allauth as described here
Second: Add your email configurations in the settings.py file :
EMAIL_USE_TLS = True
EMAIL_HOST = 'smtp.gmail.com' #I used gmail in my case
EMAIL_HOST_USER = <Your Email>
EMAIL_HOST_PASSWORD = <Your Password>
EMAIL_PORT = 587
DEFAULT_FROM_EMAIL = <Default Sender name and email>
Third: Add configurations for verification and default login url, you'll find the documentation of all config parameters here, note that in my example I'm using a custom user model as mentioned, that's why I'm setting ACCOUNT_EMAIL_REQUIRED to True & ACCOUNT_USER_MODEL_USERNAME_FIELD and ACCOUNT_USERNAME_REQUIRED to False, also the LOGIN_URL,ACCOUNT_EMAIL_CONFIRMATION_AUTHENTICATED_REDIRECT_URL andLOGIN_REDIRECT_URL parameters are used after the user clicks on the confirmation link sent by email to him
ACCOUNT_EMAIL_VERIFICATION='mandatory'
ACCOUNT_CONFIRM_EMAIL_ON_GET=True
ACCOUNT_EMAIL_REQUIRED=True
ACCOUNT_USER_MODEL_USERNAME_FIELD = None
ACCOUNT_USERNAME_REQUIRED = False
ACCOUNT_AUTHENTICATION_METHOD = 'email'
LOGIN_URL='app:login_user'
LOGIN_REDIRECT_URL='app:login_user'
ACCOUNT_EMAIL_CONFIRMATION_AUTHENTICATED_REDIRECT_URL='app:login_user'
Fourth: After your signup form, save the user instance with is_active parameter set to False, then call the method:
from allauth.account.utils import *
send_email_confirmation(request, user, True)
Finally: Receive the signal after the user confirms his email, and set is_active to True
from allauth.account.signals import email_confirmed
from django.dispatch import receiver
# Signal sent to activate user upon confirmation
#receiver(email_confirmed)
def email_confirmed_(request, email_address, **kwargs):
user = MyUser.objects.get(email=email_address.email)
user.is_active = True
user.save()
Finally, you would want to change the default site name from Django Admin as it will be included in the email sent.
I had the same problem, and the solution I've found was to call the original send_email_confirmation method from allauth. I am using DRF3 for my API.
from allauth.account.utils import send_email_confirmation
...
def some_view(request):
user = ...
...
#using request._request to avoid TypeError on change made in DRF3 (from HTTPRequest to Request object)
send_email_confirmation(request._request, user)
...
I hope this helps you.

Best way to handle errors in Grails domain class validation

We have an API command like "student/create" to create a new student object. The code looks like this:
def student = new Student(firstName: firstName, lastName: lastName, email: email)
if (! student.validate()) {
response.error = "UNKNOWN_ERROR" // in case we can't find anything better
student.errors.allErrors.each { error ->
// set response.error to an appropriate value
println error
}
} else {
student.save()
}
Our goal is to give a reasonable error message like "EMAIL_DUPLICATE" or "FIRSTNAME_LENGTH" on a validation fail, so we want to test the errors we get against a set of expected errors so we can respond like that.
Here's what we get from that println:
Field error in object 'com.example.Student' on field 'email': rejected value [student#example.com]; codes [com.example.Student.email.unique.error.com.example.Student.email,com.example.Student.email.unique.error.email,com.example.Student.email.unique.error.java.lang.String,com.example.Student.email.unique.error,student.email.unique.error.com.example.Student.email,student.email.unique.error.email,student.email.unique.error.java.lang.String,student.email.unique.error,com.example.Student.email.unique.com.example.Student.email,com.example.Student.email.unique.email,com.example.Student.email.unique.java.lang.String,com.example.Student.email.unique,student.email.unique.com.example.Student.email,student.email.unique.email,student.email.unique.java.lang.String,student.email.unique,unique.com.example.Student.email,unique.email,unique.java.lang.String,unique]; arguments [email,class com.example.Student,student#example.com.org]; default message [Property [{0}] of class [{1}] with value [{2}] must be unique]
How can I figure out that this means the email is already used in the database so that I can tell the API user that?
(to be clear, I want to give a computer-readable message like "EMAIL_DUPLICATE" instead of something like "Property email of class Student with value student#example.com must be unique")
Not sure it would work in more situations than just this one, but does:
println "${error.objectName}_${error.codes[-1]}".toUpperCase()
Get you anywhere near?

Resources