package net.isammoc.gbj.auth

class UserController {
	def scaffold = User
	
	def register = { UserRegistrationCommand urc ->
		if (!params.register) return

		// Copied from the 'save' action of the register controller
		// generated by the Spring Security plugin (with some substantial
		// modifications).
		def role = Role.findByAuthority("ROLE_USER")
		if (!role) {
			urc.password = null
			urc.passwordRepeat = null
			flash.message = 'Default Role not found.'
			return [ userDetails: urc ]
		}

		if (!urc.hasErrors()) {
			def props = urc.properties
			def user = new User(username:urc.username, password:urc.password)

			// We've validated the user - now it's time to save it.
			if (!user.save()) {
				urc.password = null
				urc.passwordRepeat = null
				flash.message = "Error registering user"
				return [ userDetails: user ]
			}

			UserRole.create user, role
			flash.message = "Successfully registered user - you can now log in"
			redirect(uri: '/')
		}
		else {
			urc.password = null
			urc.passwordRepeat = null
			flash.message = "Error registering user"
			return [ userDetails: urc ]
		}
	}
}


class UserRegistrationCommand {

	String username
	String password
	String passwordRepeat

	static constraints = {
		username(blank: false, size: 3..20, validator: { username, urc, errors ->
			if (username && User.findByUsername(username)) {
				errors.rejectValue(
						"userId",
						"error.user.exists",
						[ username ] as Object[],
						"User ${username} already exists")
			}
		})

		// Ensure password does not match username
		password(size: 6..30, blank: false,
				 validator: { passwd, urc ->
					return passwd != urc.username
				})
		passwordRepeat(nullable: false,
				validator: { passwd2, urc ->
					return passwd2 == urc.password
				})
	}
}
