Chetan
Chetan

Reputation: 1707

Tenant based unique username in grails application

I am working on a application which has several companies as our clients and multiple users under each company which access our application.

So I have structured the table of users to save users of all companies in same table and have the company_id as a column-

class User {
    String username
    String password

    static belongsTo = [company:Company]

    static constraints = {
        username blank: false
        password blank: false
    }
}

In this app I have customised the spring security to authenticate the user based on 3 fields- username, password and comapany. So if there are two users ABC in company Org1 and Org2 they will be identified properly.

Now if I apply the constraint of unique: true on username the constraint is applied on whole table and it does not allow me to save two users ABC, no matter if they are on two different companies. (PS- I understand constraint is based on table, kindly read further).

Now the main problem is that I want to make the username unique based on the company not based on User table. How to do that? Is there a predefined constraint that can be used to check if the username is present in the company? Or will have to check it each time while registering, if the username already exits in a company?

Upvotes: 2

Views: 108

Answers (1)

Simon Tarplin
Simon Tarplin

Reputation: 196

You could try to use a multi-column constraint (see http://www.grails.org/doc/latest/ref/Constraints/unique.html)

Your username constraint would look something like this:

 username blank: false, unique: 'company'

Upvotes: 4

Related Questions