001    /**
002     * Copyright (c) 2000-2013 Liferay, Inc. All rights reserved.
003     *
004     * This library is free software; you can redistribute it and/or modify it under
005     * the terms of the GNU Lesser General Public License as published by the Free
006     * Software Foundation; either version 2.1 of the License, or (at your option)
007     * any later version.
008     *
009     * This library is distributed in the hope that it will be useful, but WITHOUT
010     * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
011     * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
012     * details.
013     */
014    
015    package com.liferay.portal.security.pwd;
016    
017    import com.liferay.portal.UserPasswordException;
018    import com.liferay.portal.kernel.exception.PortalException;
019    import com.liferay.portal.kernel.log.Log;
020    import com.liferay.portal.kernel.log.LogFactoryUtil;
021    import com.liferay.portal.kernel.util.GetterUtil;
022    import com.liferay.portal.kernel.util.PropsKeys;
023    import com.liferay.portal.model.PasswordPolicy;
024    import com.liferay.portal.util.PropsUtil;
025    import com.liferay.util.PwdGenerator;
026    
027    /**
028     * @author Brian Wing Shun Chan
029     */
030    public class RegExpToolkit extends BasicToolkit {
031    
032            public RegExpToolkit() {
033                    _pattern = PropsUtil.get(PropsKeys.PASSWORDS_REGEXPTOOLKIT_PATTERN);
034                    _charset = PropsUtil.get(PropsKeys.PASSWORDS_REGEXPTOOLKIT_CHARSET);
035                    _length = GetterUtil.getInteger(
036                            PropsUtil.get(PropsKeys.PASSWORDS_REGEXPTOOLKIT_LENGTH));
037            }
038    
039            @Override
040            public String generate(PasswordPolicy passwordPolicy) {
041                    return PwdGenerator.getPassword(_charset, _length);
042            }
043    
044            @Override
045            public void validate(
046                            long userId, String password1, String password2,
047                            PasswordPolicy passwordPolicy)
048                    throws PortalException {
049    
050                    boolean value = password1.matches(_pattern);
051    
052                    if (!value) {
053                            if (_log.isWarnEnabled()) {
054                                    _log.warn("User " + userId + " attempted an invalid password");
055                            }
056    
057                            throw new UserPasswordException(
058                                    UserPasswordException.PASSWORD_INVALID);
059                    }
060            }
061    
062            private static Log _log = LogFactoryUtil.getLog(RegExpToolkit.class);
063    
064            private String _charset;
065            private int _length;
066            private String _pattern;
067    
068    }