/**
 * Provides a service class with some methods that integrate the Person domain class and Acegi security.
 *
 */
class AuthService {

    boolean transactional = false

    def authenticateService

    /**
    * Get the current user in a safe way to avoid a null userDomain.
    * @returns The current user or the 'system' person (Person #1) if userDomain() is not active.
    */
    def getCurrentUser() {
        if(authenticateService.userDomain()) {
            return Person.get(authenticateService.userDomain().id)
        }
        else {
            log.warn "userDomain not active, attempting to return Person #1."
            return Person.get(1)
        }
    }

    /**
    * Convenience wrapper around authenticateService.encodePassword().
    * @param passClearText The clear text password to encode.
    * @returns The encoded password.
    */
    def encodePassword(passClearText) {
        authenticateService.encodePassword(passClearText)
    }

    /**
    * Generate a random password.
    * @returns The generated password.
    */
    def getRandomPassword() {
        def passwd = ""
        def pool = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_"
        def rand = new Random(System.currentTimeMillis())

        for(i in 0..10)
            passwd += pool[rand.nextInt(pool.length())]

        return passwd
    }

}
