How to exclude specific keywords from UrlMapping in Grails?
Asked Answered
P

3

5

I use the following url mapping in Grails:

"/$id"{
  controller = "user"
  action = "show"
}       

to map urls like mydomain.com/someusername

How do I attach constrains to the url mapping to exclude keywords like "login", "logout",...

I.e., mydomain.com/someusername should route to mydomain.com/user/show/someusername, mydomain.com/login should not route to mydomain.com/user/show/login.

Poltroon answered 9/6, 2013 at 12:21 Comment(2)
What did you mean by user/show/login? Is login an action?Cowberry
mydomain.com/someusername should route to mydomain.com/user/show/someusername, mydomain.com/login should not route to mydomain.com/user/show/login.Poltroon
G
14

You can use contrainsts for this mapping:

"/$id"{
  controller = "user"
  action = "show"
  constraints {
    //add a validator for $id from url mapping
    id(validator: {
        return !(it in ['login', 'logout'])
    })
  }
}    
Galvani answered 9/6, 2013 at 15:59 Comment(0)
I
2

Use a filter, and redirect from it.

class UrlMappingFilters {
    def filters = {
        filterUrlKeywords(controller: '*', action: '*') {
            def keywords = ['login', 'logout']
            before = {
                if (params.id in keywords) {
                    // redirect to start, or render error...
                    redirect(uri: '/')
                    return false
                }
            }
        }
    }
}

If you want to make it specific to a controller or action, use its name instead of the '*'.

Read more:

Ineffaceable answered 9/6, 2013 at 13:59 Comment(0)
U
1

I have done this type of thing for REST based endpoints numerous times, and Grails is smart enough to figure out what you want. Note that ordering in the UrlMappings file may be important.

For example, you can define this:

class UrlMappings {
    static mappings = {
        "/login" { controller: 'auth', action: 'login' }
        "/logout" { controller: 'auth', action: 'logout' }
        "/$id" { controller: 'user', action: 'view' }
    }
}

Then when you hit "/login" you will go in the auth:login method, but when you hit "/userid" you will be sent to user:view:userid as expected.

Uterine answered 22/1, 2016 at 16:30 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.