Grails test user account creation manually - grails

I am working in grails application, I was been asked to create a test user for our site. I did write the code in admin controller and gave the link in his page. The code worked and also I can see the details of this test user. But when I try to login using test user details, I am not able to login.
def createTestUser = {
String timeStr = System.currentTimeMillis() + ''
//def user = userService.createQuickUser(timeStr + '#test.supjam.com', timeStr, 'test-user') // TODO requires supajam-domain 2011.12.5.1
def user = userService.createQuickUser(timeStr + '#test.supajam.com', 'test-user')
user.passwd = timeStr
user.dailyNews = false
user.offers = false
user.emailConfirmed = true
user.enabled = true
user.save(failOnError: true)
}
This was the code. If anybody can please help, I would be thankful to them.

This similar question has some debugging tips:
Grails spring security login issue: /auth?login_error=1
i liked putting log.debug() statements in the authfail() if blocks.
if (exception instanceof AccountExpiredException) {
msg = SpringSecurityUtils.securityConfig.errors.login.expired
log.debug "exception - ${msg}" // added this
}

Related

How to resolve 'groovy.lang.MissingMethodException' ...Possible solutions: notify(), render(java.lang.String)

I am very new to Groovy and this is an old application where the author is no longer with our organization. None of the previous questions that look similar offered any help. The application needs to send a simple message to the user to warn they are missing an entry before they con continue on.
I have made no fewer than 20 changes from flash.message to confirm. Flash causes the application to jump all the way to the user login function. This confirm is giving a crash message: Error 500: Executing action [submitrequest] of controller [SdrmController] caused exception: Runtime error executing action
def submitrequest = {
def testChecker
testChecker = [params.fullExpName].flatten().findAll { it != null }
log.info('testChecker.size = ' + testChecker.size)
if (testChecker.size > 0) {
if (!confirm('Submitting can not be undone, are you sure?')) return
} else {
if (!confirm('You have to pick an expedition. Please return to your Request and pick at least one expedition.')) return
} else {
return
}
}
// rest of long time working code here
}
Expected Result is a simple message to screen tell the user to pick an "Expedition" from a list and then the code returns to the same point so the user can make the change then hit the submit again.
Then full message:
No signature of method: SdrmController.confirm() is applicable for argument types: (java.lang.String) values: [You have to pick an expedition. Please return to your Request and pick at least one expedition.] Possible solutions: notify(), render(java.lang.String)
-- flash.message worked for our situation.
`legChecker = [params.programLeg].flatten().findAll{it!=null}
if(requestInstance.futurePast == "future" && expChecker.size<1) {
flash.message = " you must select a future expedition "
render(view: 'stepstart', model: [....])
return
}`

Can admin role get other users permissions in Spring-security ACL Grails

I am trying to make a proof of concept application that allows the user with administration permission to grant and revoke permissions of other users. While granting and revoking works with only username (unique identifier) getting the permission to display in the UI proves to be out of my reach. Is it possible to get a list of other user's permissions from within a service method?
I've tried to search the web but I couldn't find any solution that would apply to my problem. I have tried using SwitchUserAuthorityChanger, RunAsManager and aclService.readAclsById. None of those worked.
I am using Grails 3.3.2 with Spring-Security 3.2.0 and ACL 3.2.0.
Cheers folks!
I ended up solving this myself. I'll post the answer here in case some poor soul would run into a similar problem.
After digging a bit in the ACL database tables, I created a separate service in which I get AclObjectIdentity by its id, I get users sid. Using these variables I find all related variables from AclEntry. After that its just a matter of getting permissions by their mask.
Here is the method in case it might help anyone:
def getPermissions(Object domainObject, String sid) {
Map<String, String> returnValue = [
"status": "success"
]
def aclObject = AclObjectIdentity.findByObjectId(domainObject.id)
def userAclSid = AclSid.findBySid(sid)
if (null == userAclSid || null == aclObject) {
returnValue["status"] = "failed"
return returnValue
}
def aclEntries = AclEntry.findAllBySidAndAclObjectIdentity(userAclSid, aclObject)
returnValue["permissions"] = []
def tempMap = [:]
if (null == aclEntries) {
returnValue["permissions"] = "null"
return returnValue
}
def counter = 0
for (entry in aclEntries) {
int mask = entry.mask
BasePermission permission
for (BasePermission perm in PermissionEnum.toList()) {
int test = 1 << mask
if (perm.getMask() == test) {
permission = perm
break;
}
}
def permString = PermissionEnum.getPermission(permission)
tempMap["$counter"] = permString
counter++
}
returnValue["permissions"] = tempMap
return returnValue
}

login date in spring security plugin for Grails

i'm using spring security plugin , i want to save the user's login date in the DB so i wrote the below in the config file :
grails.plugin.springsecurity.useSecurityEventListener = true
grails.plugin.springsecurity.onAuthenticationSuccessEvent= { e, appCtx ->
com.app.utils.UserActivity.withTransaction {
def user = com.app.utils.UserActivity.findByUser(com.app.security.Users.get(appCtx.springSecurityService.principal.id))
if (!user)
{
new com.app.utils.UserActivity(user:user,userLoggedIn:new Date(),userLoggedOut: null).save(failOnError:true)
}
else
{
user.userLoggedIn= new Date()
user.userLoggedOut=null
user.save(failOnError:true)
}
}
}
the issue is that appCtx.springSecurityService.principal.id is always returning null , and are there any events for the logout action.
The correct way to get the pricipal is from the authentication event like this:
e.getAuthentication().getPrincipal()

Grails channel security causing a redirect loop

I am new to Grails and I am working on an exisiting application. I am trying to force the anyone using our website to allways be on https. I added the Spring Security Core plugin
//BuildConfig.groovy
compile "org.grails.plugins:spring-security-core:2.0.0"
and I just added
///Config.groovy
grails.plugin.springsecurity.secureChannel.definition = [
'/**': 'REQUIRES_SECURE_CHANNEL'
When I try to go on localhost:8080/myapp, it redirects me to https://localhost:8443/myapp, but I get a "This webpage has a redirect loop ERR_TOO_MANY_REDIRECTS" message.
I added print statements in my SecurityFilters.groovy, and I can see the infinite loop going
baseFilter(controller: "*", action: "*")
{
before = {
println "baseFilter"
// If auth controller then ok to continue
if (controllerName.equals("auth"))
{
return true;
}
// If no subject (user) and not auth controller then user must authenticate
if (!session.subject && !(controllerName.equals("auth")))
{
params.targetUri = request.forwardURI - request.contextPath
if (params.action=="profile") {
params.targetUri=params.targetUri + "?page=" + params?.page
}
else if (params.action=="results") {
params.targetUri="/home"
}
println "baseFilter: Redirecting: PARAMS = $params"
redirect(controller:'auth', action:'login', params: params)
return false;
}
}
}
It's just:
baseFilter
baseFilter: Redirecting: PARAMS = [action:auth, format:null, controller:login, targetUri:/login/auth]
Over and over.
I've tried many other things I found on Stackoverflow and other websites, but they either do not work, or are too complicated.
Thank you.
Ok, so this isn't the answer to the question, but I managed to achieve what I was trying to do, which was to force SLL, and redirect any attempts to use http. I did this by using the shiro plugin, which was already being used by my application. In the Buildconfig.groovy, just add compile ":shiro:1.2.1" to you plugins. In the config.groovy I added the following properties:
security {
shiro {
filter {
loginUrl = "/login"
successUrl = "/"
unauthorizedUrl = "/unauthorized"
filterChainDefinitions = """
/** = ssl[443]
"""
}
}
}
You can modify your filterChainDefinitions to only force ssl on certain urls. I just used /** because I always want SSL.

How to check whether user is following me not using TweetSharp.TwitterService.ListFollowers()

Is there some function in TweetSharp that could be used in a similar way to my 'IsFollowingMe' below?
I'd like to check whether a user is following me before I attempt to send some private message.
TweetSharp.TwitterService service;
string screenName = "#some_one";
string someMessage = "Some Message";
if (service.IsFollowingMe(screenName))
{
service.SendDirectMessage(screenName, someMessage);
else
NotifyThatSendingNotPossible();
}
First option to such approach is to use:
TweetSharp.TwitterService service;
TwitterCursorList<TwitterUser> followers = service.ListFollowers();
and then iterate through the result to find out if user is following my account. But this will eventually be ineffective when there are a lot of followers.
Another option is to execute service.SendDirectMessage and then check if the result is null or not. I tested such approach with success - however my application logic prefers to check in advance if sending is possible and based on this information should do different actions.
The answer is as follows:
TweetSharp.TwitterService service;
string fromUser = "#mr_sender";
string toUser = "#some_one";
string someMessage = "Some Message";
TweetSharp.TwitterFriendship friendship =
service.GetFriendshipInfo(fromUser, toUser);
if (friendship.Relationship.Source.CanDirectMessage.HasValue &&
friendship.Relationship.Source.CanDirectMessage.Value)
{
service.SendDirectMessage(screenName, someMessage);
}
else
{
NotifyThatSendingNotPossible();
}
I could able to solve this using below way.
var twitterFriendship = service.GetFriendshipInfo(new GetFriendshipInfoOptions() { SourceScreenName = "source_name", TargetScreenName = "target_name"});
After that, you can check like below
if(twitterFriendship.Relationship.Source.Following && twitterFriendship.Relationship.Target.FollowedBy)
{
service.SendDirectMessage(new SendDirectMessageOptions() { ScreenName="target_name",Text="message"})
}

Resources