Spring Security Plugin Authentication Failure Issue - grails

EDITED HEADER: more related with the actual problem
I'm trying to setup spring security for my test application
i installed the plugin , created User and Role classes ;
put this to UrlMappings.groovy;
"/login/$action?"(controller: "login")
"/logout/$action?"(controller: "logout")
then I put a user in the bootstrap as follows,
import org.project.auth.Role
import org.project.auth.User
import org.project.auth.UserRole;
class BootStrap {
def springSecurityService
def init = { servletContext ->
def userRole = Role.findByAuthority('ROLE_USER') ?: new Role(authority: 'ROLE_USER').save(failOnError: true,flush:true)
def adminRole = Role.findByAuthority('ROLE_ADMIN') ?: new Role(authority: 'ROLE_ADMIN').save(failOnError: true,flush:true)
def adminUser = User.findByUsername('admin') ?: new User(
username: 'admin',
password: springSecurityService.encodePassword('admin'),
enabled: true).save(failOnError: true,flush:true)
print User.count()
if (!adminUser.authorities.contains(adminRole)) {
print "TEST"
UserRole.create adminUser, adminRole,true
}
}
def destroy = {
}
}
this print User.count() returns 1 so i know the user is created , print "TEST" works as well so i know that it goes into the if block but when i run the server it fails with
Sorry, we were not able to find a user with that username and password.
I use Grails 2.0.0.M1 , do you think it might be the issue?

The User domain class in the 1.2 version of the plugin encrypts the password for you. So older code like this that uses the springSecurityService double-encodes. Change password: springSecurityService.encodePassword('admin') to password: 'admin' and it should work.
If not, turn up the debugging and you should see a message about why it's failing. Add this to Config.groovy in the log4j block:
debug 'org.springframework.security'
Also to be safe I'd change
if (!adminUser.authorities.contains(adminRole)) { to if (!UserRole.findByUserAndRole(adminUser, adminRole)) {
`

I ma facing the same problem but after some searching came across this. http://jira.grails.org/browse/GPSPRINGSECURITYUI-33
and http://jira.grails.org/browse/GPSPRINGSECURITYUI-27
Hope this helps. But i am unable to find the next stable version where this problem is fixed.

Related

Rails Devise token generator with service objects

I am working on a fairly large Rails app which due to large no of activities uses service objects (& light-services gem). Typically actions are performed in steps in the services, with many of the functions/objects used in these steps instantiated in the model it is working with (Customer.rb) in this case.
In one step I am trying to generate a Devise reset_password_token, but hit a glitch
Customer.rb
def self.generate_token
Devise.token_generator
end
and then in service object reset_password.rb
def generate_token
raw, hashed = Devise.token_generator.generate(Customer, :reset_password_token)
producer.reset_password_token = hashed
producer.reset_password_token_sent_at = Time.now.utc
#token = raw
end
All that goes in to db is the timestamp, and a nil, nil for token although token gets put in to the url endpoint so is being generated
If anyone encountered this scenario before, tips more than welcome!
Here is rest of code, not setting the token in DB properly.
def validate_producer_email
self.valid_email = EmailValidator.valid?(producer.email)
end
# #return [TrueClass, FalseClass]
def validate_token
self.producer.reset_password_token = reset_password_token, params['reset_password_token']
customer = Customer.producer.find_by(reset_password_token: reset_password_token)
# true if customer.email && Devise.secure_compare(reset_password_token, params[:reset_password_token])
customer.present?
end
def update_producer
return if ask_underwriter?
Producer::Update
.with(self)
.run(
producer: producer,
force: current_administrator.blank?,
params: {
customer: {
reset_password_token: reset_password_token
}
}
)
end
If anyone has any tips on how to fix?
Thanks

Jenkins Pipeline Get Rejecter Name instead of user id

I have followed below link to reject /approve deployment request. But if i reject deployment i can only get user id. How can i get user name?
def user = err.getCauses()[0].getUser()
https://support.cloudbees.com/hc/en-us/articles/226554067-Pipeline-How-to-add-an-input-step-with-timeout-that-continues-if-timeout-is-reached-using-a-default-value?mobile_site=true
Try this:
import hudson.model.Cause
import hudson.tasks.Mailer
import hudson.model.User
def name = cause.getUserName()
println "name is ${name}"
def jenkins_id = cause.getUserId()
println "jenkins_id is ${jenkins_id}"
User u = User.get(jenkins_id)
def umail = u.getProperty(Mailer.UserProperty.class)
def email = umail.getAddress()
println "email is ${email}"
You may want to read the JavaDocs of the User class to see if the name is available.
I found solution to this as below
def user = err.getCauses()[0].getUser().getDisplayName()

createLink in ApplicationTagLib from service

I am trying to learn about creating the link using createLink from ApplicationTagLib called from the service.
Grails : 3.2.8
Code :
def applicationTag = new ApplicationTagLib()
def abc = application.Tag.createLink(controller:"accomodate", action:"menu", id:4)
Error :
org.grails.taglib.GrailsTagException: Tag [createLink] does not exist.
No corresponding tag library found.
I am very new to this version. I will be really thankful if you help me in finding out what sort of mistake is my code having.
try this:
import grails.core.support.GrailsApplicationAware
import grails.core.GrailsApplication
import grails.web.mapping.LinkGenerator
class MyService implements GrailsApplicationAware{
GrailsApplication grailsApplication
def config
LinkGenerator grailsLinkGenerator
def myMethod() {
def url = hostname+grailsLinkGenerator.link(controller: 'someController', action: 'something', params:[token:something], absolute: 'false')
}
void setGrailsApplication(GrailsApplication ga) {
config = ga.config
}
}
...
String hostname=grailsApplication.config.myApp?.hostName
def url=hostname+grailsLinkGenerator.link(controller: 'someController', action: 'something', params:[token:something], absolute: 'false')
or
def url=grailsLinkGenerator.link(controller: 'someController', action: 'something', params:[token:something], absolute: true)
ED2A
If you must
I have applicationTag lib working this way:
import grails.util.Holders
import org.grails.plugins.web.taglib.ApplicationTagLib
class SomeService {
def g = Holders.grailsApplication.mainContext.getBean(ApplicationTagLib)
def someMethod() {
def aa = g.createLink('something')
}
}
The problem with doing things this way is if you start hitting presentation layer references then you may get No thread-bound request found. Specially from quartz jobs and anything that is called outside of the scope of a real user. You can get around all of this using this example. But why go through all that when the grailsLinkGenerator example above won't hit any of the issues that may arise otherwise
I came here because I just wanted a link created in a regular service class, and V H's answer^ helped me; thank you! :D
But for those looking for the same thing I was, this is what is sufficient for us to work (Grails version 4.0.4):
import grails.web.mapping.LinkGenerator
and in the service method:
def link = grailsLinkGenerator.link(
controller: 'controlerName',
action: 'actionName',
params: [uuid: "uuidExample"]
)
Thank you once more, V H! :)

Rails Facebook Omniauth get user address

I'm tryig to get the user address from facebook with Omniauth but did not work.
i added their address on update callback after login.
If i removed their address from omniauth the app did not update their address.
Someone have any idea how to get their address and why the app did not edit and update their address after the login?
thank's
def omniauth_callback
auth_hash = request.env['omniauth.auth']
user = User.find_by_uid(auth_hash[:uid])
if user.nil? && auth_hash[:info][:email]
user = User.find_by_email(auth_hash[:info][:email])
end
if user.nil?
email_domain = ''
email_domain = '#facebook.com' if auth_hash[:provider] == 'facebook'
user = User.new(email: auth_hash[:info][:email] || auth_hash[:info][:nickname] + email_domain, name: auth_hash[:info][:first_name] || '', surname: auth_hash[:info][:last_name] || '', gender: 'I')
user.password_digest = ''
user.save!(validate: false)
end
user.update_attribute(:login_at, Time.zone.now)
user.update_attribute(:address)
user.update_attribute(:neighborhood)
user.update_attribute(:postal_code)
user.update_attribute(:ip_address, request.remote_ip)
user.update_attribute(:provider, auth_hash[:provider])
user.update_attribute(:uid, auth_hash[:uid])
user.update_attribute(:oauth_token, auth_hash[:credentials][:token])
user.update_attribute(:oauth_expires_at, Time.at(auth_hash[:credentials][:expires_at]))
cookies[:auth_token] = { value: user.oauth_token, expires: user.oauth_expires_at}
redirect_to root_url
end
One reason your code will not work is because this
user.update_attribute(:address)
Doesn't do anything - except raise an error. You have to pass a value into update_attribute as well as specify the field.
Also as #mysmallidea points out, you'd be better advised to use update as that will allow you to update multiple fields in one database action.
If present, the address data will be within the auth_hash. So I suggest that you first work out the structure of that hash. In your development environment, add the following:
Rails.logger.info auth_hash.inspect
That will output the current auth_hash to logs/development.log. Use that to determine where in the hash the address data is. You'll then be able to do something like:
user.update address: auth_hash[:info][:address]
However, you may find that the address is not included in the data returned by the facebook oauth system. In which case you will need to return to their documentation to see if this is possible.

Grails GORM MissingMethodException

new to groovy and stuck on this for quite some time.
Heres the method in question.
protected User currentUser() {
def user = springSecurityService.currentUser
println "In currentUser Method"
println "Is userId null?"
println user.id == null
println user.id instanceof Long
User.get(user.id)
}
And User.get is a method in the GORM package
D get(Serializable id) {
execute({ Session session ->
session.retrieve(persistentClass, id)
} as SessionCallback)
}
Im getting the error
No signature of method: User.get() is applicable for argument types: () values: []
What I dont understand is that through the println statements I verified that
user.id is not null
user.id is instanceof Long , which implements the Serializable interface.
Any idea whats happening here?
Thank you.
A possible solution could be that you have an invalid import statement. User is a very common class name so maybe you (or your IDE) have imported a different User class than you expect. The imported class might not have a get(id) method.

Resources