001 // Copyright 2011 The Apache Software Foundation 002 // 003 // Licensed under the Apache License, Version 2.0 (the "License"); 004 // you may not use this file except in compliance with the License. 005 // You may obtain a copy of the License at 006 // 007 // http://www.apache.org/licenses/LICENSE-2.0 008 // 009 // Unless required by applicable law or agreed to in writing, software 010 // distributed under the License is distributed on an "AS IS" BASIS, 011 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 012 // See the License for the specific language governing permissions and 013 // limitations under the License. 014 015 package org.apache.tapestry5.kaptcha.components; 016 017 import org.apache.tapestry5.*; 018 import org.apache.tapestry5.annotations.*; 019 import org.apache.tapestry5.corelib.base.AbstractField; 020 import org.apache.tapestry5.internal.TapestryInternalUtils; 021 import org.apache.tapestry5.ioc.Messages; 022 import org.apache.tapestry5.ioc.annotations.Inject; 023 import org.apache.tapestry5.services.FieldValidatorSource; 024 import org.apache.tapestry5.services.Request; 025 026 /** 027 * Field paired with a {@link KaptchaImage} to ensure that the user has provided 028 * the correct value. 029 * 030 * @since 5.3 031 */ 032 @SupportsInformalParameters 033 @Import(stylesheet = "kaptcha.css") 034 public class KaptchaField extends AbstractField 035 { 036 037 /** 038 * The image output for this field. The image will display a distorted text 039 * string. The user must decode the distorted text and enter the same value. 040 */ 041 @Parameter(required = true, defaultPrefix = BindingConstants.COMPONENT) 042 private KaptchaImage image; 043 044 @Inject 045 private Request request; 046 047 @Inject 048 private Messages messages; 049 050 @Inject 051 private ComponentResources resources; 052 053 @Environmental 054 private ValidationTracker validationTracker; 055 056 @Inject 057 private FieldValidatorSource fieldValidatorSource; 058 059 @Override 060 public boolean isRequired() 061 { 062 return true; 063 } 064 065 @Override 066 protected void processSubmission(String controlName) 067 { 068 String userValue = request.getParameter(controlName); 069 070 if (TapestryInternalUtils.isEqual(image.getCaptchaText(), userValue)) 071 return; 072 073 validationTracker.recordError(this, messages.get("tapestry-incorrect-captcha")); 074 } 075 076 @SuppressWarnings("rawtypes") 077 @BeginRender 078 boolean begin(MarkupWriter writer) 079 { 080 081 writer.element("input", 082 083 "type", "password", 084 085 "id", getClientId(), 086 087 "name", getControlName(), 088 089 "value", ""); 090 091 resources.renderInformalParameters(writer); 092 093 FieldValidator fieldValidator = fieldValidatorSource 094 .createValidator(this, "required", null); 095 096 fieldValidator.render(writer); 097 098 writer.end(); 099 100 return false; 101 } 102 }