views:

339

answers:

2

I am using a string "username" as the primary-key of a table,

But when saving and getting the column with the username id I want the case to be ignored so that new users can't try to impersonate another user.

e.g. When registering a new user

  • username = Daxon
  • username = DaXoN //this should not be allowed

When getting the unique username it can be typed in any case and still be obtained. Youtube do this with their usernames.

e.g.

  • youtube.com/user/Daxon
  • youtube.com/user/DaXoN //Should go to the same profile of 'Daxon' anyway

Domain Class This uses username as the primary key

class User {
  String username
  String password

  static constraints = {
  }

  static mapping = {
    id generator: 'assigned', name: "username", type: 'string'
  }
}

I then scaffold the controllers and views, so can anyone help me on saving and getting unique usernames with case ignored?

+1  A: 

You can modify your save and get methods of the generated controler to do string comparrisons. Before inserting a username you could do an HQL query that does a case insensitive comparrison on the user name you want to insert to make sure that no user name already exists. See the "HQL And Case Sensitivity" section of the following link. http://dev.wavemaker.com/wiki/bin/view/Dev/HqlTutorial#HCaseInsensitiveQuery

Jared
+1  A: 

One way you can prevent the second user from registering a name that differs only in case is to create a case insensitive unique index on username at the database layer. If you try to save a name that case-insensitively matches an existing one, you'll get a database exception. This is the default with mysql, but for other databases, something like the following should do it:

create unique index username_csunique_idx on user(lower(username));

I'm not aware of any way to specify that kind of index in the domain class DSL.

To find the objects, query by username case insensitively. For example, User.findByUsernameIlike(userName), or User.find("from User as u where lower(u.username) = ?", [userName.toLowerCase()]) if you prefer HQL.

ataylor
I figured out the "Ilike" dynamic method, works a treat.I also never knew about the case-insensitive index, i'll try it out
Daxon