Grails validate a password - grails

In a controller how can i validate a password so it contains at least 1 letter, 1 number, 1 special character and is at least 8 digits long. The code i am trying to use is as follows:
boolean validatePassword(String password) {
System.out.println("In validate")
def pattern = /^.*(?=.{7,})(?=.*\d)(?=.*[a-zA-Z])(?=.*[!##$%*&+()]).*$/
def matcher = password =~ pattern
System.out.println("HERERERE")
return matcher.getCount() ? true : false
}
This does not work if says everything is invalid.
I have spring security ui plug in installed. Is there a way I can use its validation features?
I know i can use it to encode the password.

Rather than trying to do everything in one regex I'd split up the tests. Since in Groovy a Matcher coerces to boolean by calling find(), the following should work, and makes the intent clearer.
boolean validatePassword(String pass) {
return (pass) && (pass.length() > 7) && (pass =~ /\p{Alpha}/) &&
(pass =~ /\p{Digit}/) && (pass =~ /[!##$%*&+()]/)
}

There is also a nice java library called vtpassword for this purpose if you need something more sophisticated
http://code.google.com/p/vt-middleware/wiki/vtpassword

Related

2 expect blocks in Spock?

I have the following Spock test, which passes:
def "test"() {
given:
def name = "John"
expect:
name.length() == 4
when:
name = name.concat(name)
then:
name.length() == 8
}
But when I modify the last then block and make it an expect block...
// previous part same
expect:
name.length() == 8
I am getting:
Groovy-Eclipse: Groovy:'expect' is not allowed here; instead, use one of: [and, then]
Is it because multiple expect blocks are not allowed in a single test? If so, is this documented anywhere? There is a similar test here written with given - expect - when - then but it is not clear why a second expect was not used, although what is being asserted is same, just being flipped.
when-expect is simply a syntax error with regard to Spock's specification DSL. The compiler message already tells you how to solve your problem. After when you need then (or and first, if you want to structure your when block into multiple sections). In contrast, expect is a kind of when-then contracted into a single block, because both the stimulus and verifying the response in a condition appear together. Block labels and how to use them is documented here.
Under Specifications as Documentation, you learn more about why you might want to use and and block labels. Under Invocation Order you learn about what you can achieve by using multiple then blocks in contrast to then-and.
You can use multiple expect blocks within one feature, no problem. But you do need to make sure that your when-then (if any) is complete, before you can use another expect.
For example, this is a valid feature:
def "my feature"() {
given: true
and: true
and: true
expect: true
when: true
and: true
then: true
and: true
then: true
expect: true
and: true
cleanup: true
}

Jenkinsfile (Groovy) URI validator

I'm fairly new to Groovy and Jenkins, so hopefully this question is coherent.
I have a Jenkinsfile written in Groovy and would like to validate one of the params as a valid URI. Without writing my own regex check, is there a library I could easily invoke during Jenkins startup?
You can try this:
try {
def foo = new java.net.URL("yourURI").openStream()
if (foo.getClass() == sun.net.www.protocol.http.HttpURLConnection$HttpInputStream) {
println 'valid'
foo.close()
}
}
catch (java.io.FileNotFoundException e) {
println 'not valid'
return
}
Unfortunately URL.toUri is not allowed at least in our setup. (It could possibly be allowed with a separate config.) Apparently opening the url (trying to connect to the host) could be possible, but that feels like it could cause other problems.
I ended up with this:
// Validation URLs in Jenkins script is hard (URL.toUri is banned). This regex roughly matches the subset of
// URLs we might want to use (and some invalid but harmless URLs). You can get a rough sense what
// this matches with a generation tool like https://www.browserling.com/tools/text-from-regex .
def saneUrlPattern = ~/^https:\/\/[-\w]{1,32}(\.[-\w]{1,32}){0,4}(:[0-9]{1,5})?(\/|(\/[-\w]{1,32}){1,10})?(\?([-\w]{1,32}=[-\w]{0,40}(&[-\w]{1,32}=[-\w]{0,40}){1,8})?)?(#[-\w]{0,40})?$/
if (!(params.sourceUrl =~ saneUrlPattern)) {
return [error: "Invalid url ${params.sourceUrl}. A simple https URL is expected."]
}
I realise that trying to validate URLs with a regular expression is difficult. I tried to strike a balance between strict and correct enough validation and a regular expression that has some hope of being understood by looking at it and being reasonably convinced as to what it actually matches.

Grails test failing on view

I'm a pretty raw Grails newb but I know some Groovy and I have a Java background. This is an ancient test app I'm updating to Java 8 from Java 6.
Context: Grails 2.3.9 / Java 1.8.0_101
The test that is failing is:
#TestFor(PillsController)
#Mock(Pills)
class PillsControllerTests {
...
void testUpdate() {
controller.update()
assert flash.message != null
assert response.redirectedUrl == '/somethingPills/list'
response.reset()
populateValidParams(params)
def somethingPills = new SomethingPills(params)
assert somethingPills.save() != null
params.id = somethingPills.id
controller.update()
assert view == "/somethingPills/edit" //<--- FAILS HERE. VIEW IS NULL.
assert model.somethingPillsInstance != null
somethingPills.clearErrors()
populateValidParams(params)
controller.update()
assert response.redirectedUrl == "/somethingPills/show/$somethingPills.id"
assert flash.message != null
response.reset()
somethingPills.clearErrors()
populateValidParams(params)
params.id = somethingPills.id
params.version = -1
controller.update()
assert view == "/somethingPills/edit"
assert model.somethingPillsInstance != null
assert model.somethingPillsInstance.errors.getFieldError('version')
assert flash.message != null
}
}
I assume "view" is a reference to some codified variant of Model/View/Controller.
I found the update at the top confusing. Update what if nothing has been saved? I tried moving populate and SomethingPills declaration above update. The result was that view was still null. How can I predict what view will be?
Another thing I noticed. If I click on the update method, I see that there are two parameters. I'm assuming that Groovy allows you pass no parameters by default or I would be seeing an error about that. I don't know if this is how it is supposed to work but if I pull the ID & version from SomethingPills and pass them then I get /somethingPills/show/1" instead of null but still not "/somethingPills/edit".
[EDIT] I've found this: http://docs.grails.org/2.3.9/guide/scaffolding.html
Go to your PillsController.groovy file and find the update() method.
See if you have a statement like
render view:'/somethingPills/edit', ....
In the unit test, view refers to the path of the gsp file that the controller renders.
I am pretty sure there would be some logic in the update() method, which you need to post if the unit test still fails. Form the unit test, it looks like as if some condition matches, then it renders the gsp template otherwise it redirects.

Validating call arguments with a closure when stubbing return value

I have a question about validating arguments in a mock call with a closure. Sometimes I do this:
customerRepository.save({ Customer customer ->
assert ...
assert ...
}) >> { ... some return value ... }
etc. i.e. multiple (but not too many) asserts in the closure, and also want to stub the call to return something. What I found out is that the code above doesn't work, I need to return a truthy value from the closure, otherwise the object I want to return is not returned and the test will fail somewhere else.
I don't think this is documented, could anybody say what the rules here are exactly?
Edit: actually, I've just checked and I need to return a truthy value even if I don't stub the return value.
So far i know two options for validating arguments. Either match the arguments in-place which does not require asserts:
then:
1 * customerRepository.save({ it.id == 1 && it.name == "joe" }) >> returnValue
However, this will give you "too few invocations" if the validation fails which I find misleading in some cases and usually harder to debug.
Alternatively, match all arguments and assert in the implementation:
then:
1 * customerRepository.save(_) >> { Customer customer ->
assert customer.id == 1
assert customer.name == "joe"
return returnValue
}
This will give you very descriptive assertion errors.

Grails <where> returns DetachedCriteria with all entries

Domain.where {
1 == 0
}.count()
This returned all the elements of the domain class. The more general case:
Domain.where {
false
}.count()
Will return all elements; if I use one of the fields and make a false condition, the result is as expected.
My question is why does this happen (the first case) ? If it is a too naive question, please just suggest some reading material. Thanks!
The version of grails that I use is 2.3.6 (it may be different in newer versions?)
I'm not sure what you are trying to achieve, but here is an explanation (maybe a bit general because of that :).
What you pass to the where method is actually a DSL for specifying SQL criterias, it just uses normal Groovy syntax to pretend to be more natural. But when you do someProperty != 5 && someOtherProperty == 6 that is not evaluated directly, but transformed to end up in an SQL query as select * from Domain where some_property != 5 and some_other_property = 6.
Since you are not passing any reference to a property in your criteria (1 == 0), it gets ignored by the detached criteria DSL evaluator, thus returning the result of select * from domain. You can try to do for example id != id to see how you get an empty list as the result. If you again examine the resulting query, you'll see that a where id<>id is included.
You can learn more about the where method: https://grails.github.io/grails-doc/latest/guide/GORM.html#whereQueries
Bear in mind that what you pass to the where method is a Closure, so the code inside is not executed upfront, and is not necessarily evaluated in the context where it was declared. You can learn more about Groovy Closures. Also about creating DSLs with Groovy, though is a bit of an advanced topic.
(I simplified the SQL queries to make them more undestandable, if you activate the query log of Hibernate or MySQL/other DB you are using, you'll see they are bigger).
To illustrate Deigote's explanation, here's a very crude implementation of a WHERE query builder (actually just the WHERE clause) using the criteria criteria format:
class WhereBuilder {
def conditions = []
def eq(column, value) {
conditions << [
column: column,
operator: '=',
value: value]
}
def ne(column, value) {
conditions << [
column: column,
operator: '!=',
value: value]
}
String toString() {
'WHERE ' <<
conditions.collect {
"${it.column} ${it.operator} '${it.value}'"
}.join(' AND ')
}
}
def builder = new WhereBuilder()
builder.with {
1 == 0
false
eq 'firstName', 'John'
ne 'lastName', 'Smith'
}
assert builder.toString() == "WHERE firstName = 'John' AND lastName != 'Smith'"
As you can see, the expressions 1 == 0 and false have no effect.

Resources