Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package ru.pochta.abon.ui.view;
- import com.google.i18n.phonenumbers.AsYouTypeFormatter;
- import com.google.i18n.phonenumbers.NumberParseException;
- import com.google.i18n.phonenumbers.PhoneNumberUtil;
- import com.google.i18n.phonenumbers.Phonenumber;
- import com.vaadin.data.validator.RegexpValidator;
- import com.vaadin.event.MouseEvents;
- import com.vaadin.event.ShortcutAction;
- import com.vaadin.navigator.View;
- import com.vaadin.navigator.ViewChangeListener;
- import com.vaadin.server.Page;
- import com.vaadin.spring.annotation.SpringView;
- import com.vaadin.ui.*;
- import org.apache.commons.lang3.StringUtils;
- import org.apache.commons.lang3.exception.ExceptionUtils;
- import org.apache.log4j.Logger;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.context.MessageSource;
- import org.springframework.core.env.Environment;
- import ru.pochta.abon.container.Container;
- import ru.pochta.abon.ldap.AuthorizationException;
- import ru.pochta.abon.ldap.LdapUser;
- import ru.pochta.abon.ldap.LdapUserAuthorizationService;
- import ru.pochta.abon.ldap.LdapUserRepo;
- import ru.pochta.abon.library.dto.abonClient.dto.EmployeeRole;
- import ru.pochta.abon.library.dto.abonClient.dto.EmployeeWrapper;
- import ru.pochta.abon.library.dto.abonClient.enumeration.EmployeeRoleEnum;
- import ru.pochta.abon.library.service.abonClient.ServiceManager;
- import ru.pochta.abon.service.AuthenticationService;
- import ru.pochta.abon.ui.notification.AbonNotification;
- import ru.pochta.abon.util.VariousUtils;
- import javax.annotation.PostConstruct;
- import java.time.ZoneId;
- import java.util.Locale;
- import java.util.Objects;
- import java.util.regex.Matcher;
- import java.util.regex.Pattern;
- @SpringView(name = LoginView.VIEW_NAME)
- public class LoginView extends VerticalLayout implements View {
- public static final String VIEW_NAME = "login";
- private static final Logger LOG = Logger.getLogger(LoginView.class);
- @Autowired
- private Environment environment;
- @Autowired
- private AuthenticationService authenticationService;
- @Autowired
- private LdapUserRepo ldapUserRepo;
- @Autowired
- private LdapUserAuthorizationService ldapUserAuthorizationService;
- @Autowired
- private ServiceManager serviceManager;
- @Autowired
- private Container container;
- @Autowired
- private MessageSource messageSource;
- private Label singInLabel;
- private TextField loginTextField;
- private PasswordField passwordTextField;
- private Button forgotLink;
- private Button singInButton;
- private String enableOwnAuthentication;
- @PostConstruct
- void init() {
- //in case ldap is not working or you want to login as operator set 'login.enableOwnAuthentication' = 'true'
- enableOwnAuthentication = environment.getProperty("login.enableOwnAuthentication");
- }
- @Override
- public void enter(ViewChangeListener.ViewChangeEvent viewChangeEvent) {
- setSizeFull();
- setSpacing(true);
- initComponents();
- setTexts();
- }
- private void initComponents() {
- VerticalLayout loginLayout = new VerticalLayout();
- loginLayout.setSpacing(true);
- loginLayout.setWidthUndefined();
- addComponent(loginLayout);
- setComponentAlignment(loginLayout, Alignment.MIDDLE_CENTER);
- singInLabel = new Label();
- singInLabel.setStyleName("h2");
- loginTextField = new TextField();
- passwordTextField = new PasswordField();
- HorizontalLayout actionBlock = new HorizontalLayout();
- actionBlock.setSpacing(true);
- actionBlock.setWidth(100, Unit.PERCENTAGE);
- forgotLink = new Button();
- forgotLink.setStyleName("link");
- this.forgotLink.addClickListener(clickEvent -> {
- Notification.show(messageSource.getMessage("login.forgotNotification", null, getLocale()));
- });
- singInButton = new Button();
- singInButton.setClickShortcut(ShortcutAction.KeyCode.ENTER);
- singInButton.setStyleName("primary");
- actionBlock.addComponents(forgotLink, singInButton);
- actionBlock.setComponentAlignment(forgotLink, Alignment.MIDDLE_LEFT);
- actionBlock.setComponentAlignment(singInButton, Alignment.MIDDLE_RIGHT);
- this.singInButton.addClickListener(clickEvent -> {
- if (StringUtils.isNotBlank(loginTextField.getValue()) &&
- (StringUtils.isNotBlank(passwordTextField.getValue()) || enableOwnAuthentication.equalsIgnoreCase("true"))) {
- if (authenticateLdap(loginTextField.getValue(), passwordTextField.getValue())) {
- EmployeeWrapper employeeWrapper = authorizeOwn(loginTextField.getValue());
- if (Objects.nonNull(employeeWrapper)) {
- ZoneId officesZoneId = VariousUtils.getZoneIdForPostOffice(employeeWrapper.getPostOffice(), serviceManager);
- if (officesZoneId != null) {
- container.setOfficesZoneId(officesZoneId);
- LOG.debug("Saved office's time zone is " + officesZoneId.toString());
- }
- container.setEmployeeWrapper(employeeWrapper);
- setUpAuthorizationFlags(employeeWrapper);
- } else {
- LOG.error("Failed to authorize user via ldap: " + loginTextField.getValue());
- showFailedAuthorizationNotification();
- }
- } else if (enableOwnAuthentication.equalsIgnoreCase("true") && authenticateOwn(loginTextField.getValue(), passwordTextField.getValue())) {
- EmployeeWrapper employeeWrapper = authorizeOwn(loginTextField.getValue());
- if (Objects.nonNull(employeeWrapper)) {
- ZoneId officesZoneId = VariousUtils.getZoneIdForPostOffice(employeeWrapper.getPostOffice(), serviceManager);
- if (officesZoneId != null) {
- container.setOfficesZoneId(officesZoneId);
- LOG.debug("Saved office's time zone is " + officesZoneId.toString());
- }
- container.setEmployeeWrapper(employeeWrapper);
- setUpAuthorizationFlags(employeeWrapper);
- } else {
- LOG.error("Failed to authorize user via own system: " + loginTextField.getValue());
- showFailedAuthorizationNotification();
- }
- } else {
- showFailedAuthenticationNotification();
- }
- } else {
- showFailedAuthenticationNotification();
- }
- });
- loginLayout.addComponents(singInLabel, loginTextField, passwordTextField, actionBlock);
- }
- private void setTexts() {
- Locale locale = getLocale();
- singInLabel.setValue(messageSource.getMessage("login.singInLabel", null, locale));
- loginTextField.setCaption(messageSource.getMessage("login.login", null, locale));
- loginTextField.setValue("Ext-N.Ovcharenko");
- passwordTextField.setCaption(messageSource.getMessage("login.password", null, locale));
- forgotLink.setCaption(messageSource.getMessage("login.forgot", null, locale));
- singInButton.setCaption(messageSource.getMessage("login.singIn", null, locale));
- TextField phoneNumberField = new TextField("phone number");
- String patternPhoneExtended = "^\\+7 \\d{3} \\d{3}-\\d{2}-\\d{2}$";
- Pattern patternPhoneSimple = Pattern.compile("^(8|\\+?7)\\d{10}$");
- phoneNumberField.addValidator(new RegexpValidator(patternPhoneExtended, messageSource.getMessage("fieldPhoneFormat", null, locale)));
- phoneNumberField.addTextChangeListener(textChangeEvent -> {
- String eventString = textChangeEvent.getText();
- String val = phoneNumberField.getValue();
- System.out.println("txt val/event: " + val + " / " + eventString);
- phoneNumberField.setValue(eventString.replaceAll("[\\+ ()-]", ""));
- int delta = countCursorOffset(eventString, phoneNumberField.getCursorPosition());
- System.out.print("cursor: " + phoneNumberField.getCursorPosition() + " -> ");
- phoneNumberField.setCursorPosition(phoneNumberField.getCursorPosition() + delta);
- System.out.println(phoneNumberField.getCursorPosition());
- });
- phoneNumberField.addValueChangeListener(valueChangeEvent -> {
- String val = phoneNumberField.getValue();
- Matcher m = patternPhoneSimple.matcher(val);
- if (m.matches()) {
- PhoneNumberUtil phoneNumberUtil = PhoneNumberUtil.getInstance();
- try {
- Phonenumber.PhoneNumber phoneNumber = phoneNumberUtil.parse(val, "RU");
- String formattedPhone = phoneNumberUtil.format(phoneNumber, PhoneNumberUtil.PhoneNumberFormat.INTERNATIONAL);
- phoneNumberField.setValue(formattedPhone);
- } catch (NumberParseException e) {
- LOG.error(ExceptionUtils.getStackTrace(e));
- }
- }
- });
- addComponent(phoneNumberField);
- }
- private int countCursorOffset(String number, int currPos) {
- String formattedPrefix, originalPrefix, formatted, original;
- int len;
- if (number.contains(" ")) {
- //then it's already formatted. if we got here then we need to count cursor offset to the left
- formattedPrefix = number.substring(0, currPos);
- //System.out.println("prefix: " + formattedPrefix);
- originalPrefix = formattedPrefix.replaceAll("[\\+ ()-]", "");
- //System.out.println("short : " + formattedShort);
- len = formattedPrefix.length() - originalPrefix.length();
- System.out.println("delta : " + len);
- } else {
- //else convert original to formatted. and add (formatted - origin) prefix to cursor offset
- len = 1;
- }
- return len;
- }
- private String formatPhoneNumber(String number) {
- String prefix = "(\\+?[78])";
- String code = "(\\d{3})";
- String number1 = "(\\d{3})";
- String number2 = "(\\d{2})";
- String extra = "\\d";
- Pattern p = Pattern.compile(
- "(^" + prefix + ")?(" + code + ")?(" + number1 + ")?(" + number2 + ")?(" + number2 + ")?(" + extra + ")*");
- System.out.println("in : " + number);
- number = number.replaceAll("[\\+ ()-]", "");
- System.out.println("out: " + number);
- Matcher m = p.matcher(number);
- StringBuilder sb = new StringBuilder();
- try {
- if (m.find()) {
- if (null != m.group(2)) sb.append("+7 ");
- if (null != m.group(4)) sb.append("(" + m.group(4) + ") ");
- if (null != m.group(6)) sb.append(m.group(6) + "-");
- if (null != m.group(8)) sb.append(m.group(8) + "-");
- if (null != m.group(10)) sb.append(m.group(10));
- if (null != m.group(11)) sb.append(m.group(11));
- return sb.toString();
- }
- } catch (Exception e) {}
- return "+" + number;
- }
- private boolean authenticateLdap(String login, String password) {
- boolean authenticated;
- try {
- authenticated = ldapUserRepo.authenticate(login, password);
- } catch (Exception e) {
- authenticated = false;
- LOG.error("LDAP authentication failed!");
- LOG.error(ExceptionUtils.getStackTrace(e));
- }
- return authenticated;
- }
- private EmployeeWrapper authorizeLdap(String login) throws AuthorizationException {
- LdapUser ldapUser = ldapUserRepo.findByLogin(login);
- return ldapUserAuthorizationService.authorize(ldapUser);
- }
- private boolean authenticateOwn(String login, String password) {
- return authenticationService.authenticate(login, password);
- }
- private EmployeeWrapper authorizeOwn(String login) {
- return authenticationService.authorize(login);
- }
- private void setUpAuthorizationFlags(EmployeeWrapper employeeWrapper) {
- EmployeeRole role = employeeWrapper.getEmployeeRole();
- if (Objects.nonNull(role)) {
- if (role.isAdmin()) {
- container.setAdmin(true);
- container.setCoul(false);
- if (role.isAdminPostamtAndUFPS()) {
- container.setAdminPostamtAndUFPS(true);
- } else {
- container.setAdminPostamtAndUFPS(false);
- }
- getUI().getNavigator().navigateTo(AdminHomeView.VIEW_NAME);
- } else if (role.getEntityId().equals(EmployeeRoleEnum.OPERATOR_COUL.getId())) {
- container.setCoul(true);
- container.setAdmin(false);
- container.setAdminPostamtAndUFPS(false);
- getUI().getNavigator().navigateTo(PostOfficeCardView.VIEW_NAME);
- } else if (role.getEntityId().equals(EmployeeRoleEnum.OPERATOR.getId())) {
- // operators must use plugin for EAS, authorization of Operators occurs in AbonUI.class
- if (enableOwnAuthentication.equalsIgnoreCase("true")) {
- container.setAdmin(false);
- container.setCoul(false);
- container.setAdminPostamtAndUFPS(false);
- container.setLoggedViaEASOPS(true);
- getUI().getNavigator().navigateTo(PostOfficeCardView.VIEW_NAME);
- } else {
- showFailedAuthorizationNotification();
- }
- }
- } else {
- showFailedAuthorizationNotification();
- }
- }
- private void showFailedAuthenticationNotification() {
- Notification notification = AbonNotification.getAbonErrorNotification(
- messageSource.getMessage("login.failed.caption", null, getLocale()),
- messageSource.getMessage("login.authentication.failedNotification", null, getLocale()));
- notification.show(Page.getCurrent());
- }
- private void showFailedAuthorizationNotification() {
- Notification notification = AbonNotification.getAbonErrorNotification(
- messageSource.getMessage("login.failed.caption", null, getLocale()),
- messageSource.getMessage("login.authorization.failedNotification", null, getLocale()));
- notification.show(Page.getCurrent());
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment