Subversion Repositories SmartDukaan

Rev

Rev 35956 | View as "text/plain" | Blame | Compare with Previous | Last modification | View Log | RSS feed

package com.spice.profitmandi.service;

import com.google.common.hash.Hashing;
import com.spice.profitmandi.common.exception.ProfitMandiBusinessException;
import com.spice.profitmandi.common.util.Utils;
import com.spice.profitmandi.dao.entity.auth.AuthUser;
import com.spice.profitmandi.dao.entity.dtr.User;
import com.spice.profitmandi.dao.entity.user.Promoter;
import com.spice.profitmandi.dao.repository.auth.AuthRepository;
import com.spice.profitmandi.dao.repository.dtr.UserRepository;
import com.spice.profitmandi.dao.repository.user.PromoterRepository;
import com.spice.profitmandi.service.mail.MailOutboxService;
import com.spice.profitmandi.service.user.UserService;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Component
public class AuthServiceImpl implements AuthService {

    // private static final String RESET_PASSWORD_BODY = "Dear %s, your password has
    // been reset. Please click this <a href=\"%s\">link</a> to reset your
    // password.\n\nRegards\nSmartdukaan";
    private static final String RESET_PASSWORD_BODY = "Dear %s, \nyour password has been reset to %s. \n\nRegards\nSmartdukaan";
    private static final String RESET_PASSWORD_SUBJECT = "Password Reset request";

    private static final Logger LOGGER = LogManager.getLogger(AuthServiceImpl.class);

    @Autowired
    AuthRepository authRepository;

    @Autowired
    JavaMailSender gmailRelaySender;

    @Autowired
    MailOutboxService mailOutboxService;

    @Autowired
    PromoterRepository promoterRepository;

    @Autowired
    UserRepository userRepository;

    @Autowired
    UserService userService;

    private String getHash256(String originalString) {
        return Hashing.sha256().hashString(originalString, StandardCharsets.UTF_8).toString();
    }

    @Override
    public List<Integer> getDirectReportees(int authId) {
        List<AuthUser> authUsers = authRepository.selectAllByManagerAuthId(authId);
        List<Integer> authIds = authUsers.stream().map(x -> x.getId()).collect(Collectors.toList());
        LOGGER.info("Auth Id == {}, All Reportees === {}", authId, authIds);
        return authIds;
    }
    @Override
    public List<AuthUser> getAllManagers(int authId) {
        AuthUser authUser = authRepository.selectById(authId);
        List<AuthUser> managersHierarchy = new ArrayList<>();

        // To prevent infinite loops due to circular references
        Set<Integer> visitedIds = new HashSet<>();
        visitedIds.add(authId);

        while (authUser != null && authUser.getManagerId() != 0) {
            int managerId = authUser.getManagerId();

            if (visitedIds.contains(managerId)) {
                LOGGER.warn("Circular reference detected: authId {} -> managerId {}", authUser.getId(), managerId);
                break;
            }

            AuthUser manager = authRepository.selectById(managerId);
            if (manager == null) {
                LOGGER.warn("Manager with ID {} not found for user {}", managerId, authUser.getId());
                break;
            }

            managersHierarchy.add(manager);
            visitedIds.add(managerId);

            authUser = manager;
        }

        LOGGER.info("managersHierarchy {}", managersHierarchy);
        return managersHierarchy;
    }

    public List<Integer> getAllReportees(int authId) {
        return getAllReportees(authId, new HashSet<>());  // call helper with visited set
    }

    private List<Integer> getAllReportees(int authId, Set<Integer> visited) {
        List<Integer> allReportees = new ArrayList<>();

        List<Integer> directReporteeIds = this.getDirectReportees(authId);

        for (int directReporteeId : directReporteeIds) {
            if (!visited.contains(directReporteeId)) {
                visited.add(directReporteeId); // mark visited
                allReportees.add(directReporteeId);

                // recursively get sub-reportees
                allReportees.addAll(getAllReportees(directReporteeId, visited));
            }
        }
        return allReportees;
    }

    @Override
    public boolean authenticate(String emailOrMobile, String password) {
        return authRepository.authenticate(emailOrMobile, getHash256(password));
    }

    @Override
    public void resetPassword(String emailOrMobile) throws ProfitMandiBusinessException {
        AuthUser authUser = authRepository.selectByEmailOrMobile(emailOrMobile);
        String password = getRandomString();
        try {
            mailOutboxService.queueMail(authUser.getEmailId(), null, RESET_PASSWORD_SUBJECT,
                    String.format(RESET_PASSWORD_BODY, authUser.getFirstName(), password), "AuthServiceImpl.resetPassword");
        } catch (Exception e) {
            throw new ProfitMandiBusinessException("Password Reset Email", emailOrMobile,
                    "Could not send password reset mail. Password Could not be reset");
        }
        userService.resetPassword(emailOrMobile, password);
        authUser.setPassword(getHash256(password));
    }

    @Override
    public void resetPassword(String emailOrMobile, String password) throws ProfitMandiBusinessException {
        try {
            AuthUser authUser = authRepository.selectByEmailOrMobile(emailOrMobile);
            authUser.setPassword(getHash256(password));
            userService.resetPassword(emailOrMobile, password);
        } catch (ProfitMandiBusinessException e) {
            userService.resetPassword(emailOrMobile, password);
        }
    }

    @Override
    public void changePassword(String emailOrMobile, String oldPassword, String newPassword) throws ProfitMandiBusinessException {
        if (authRepository.authenticate(emailOrMobile, getHash256(oldPassword))) {
            AuthUser authUser = authRepository.selectByEmailOrMobile(emailOrMobile);
            authUser.setPassword(getHash256(newPassword));
            userService.resetPassword(authUser.getEmailId(), newPassword);
        } else {
            throw new ProfitMandiBusinessException("Authentication", "Credentials", "Invalid email/mobile or password");
        }
    }

    @Override
    public void addAuthUser(AuthUser authUser) throws ProfitMandiBusinessException {
        try {
            authRepository.selectByEmailOrMobile(authUser.getEmailId());
        } catch (ProfitMandiBusinessException pbse) {
            try {
                authRepository.selectByEmailOrMobile(authUser.getMobileNumber());
            } catch (ProfitMandiBusinessException e) {
                authRepository.persist(authUser);
                this.resetPassword(authUser.getEmailId());
                return;
            }
            throw new ProfitMandiBusinessException("Mobile", authUser.getMobileNumber(), "Mobile number already exist");
        }
        throw new ProfitMandiBusinessException("Email", authUser.getEmailId(), "Email Id already exist");

    }

    private String getRandomString() {
        int length = 10;
        boolean useLetters = true;
        boolean useNumbers = false;
        String generatedString = RandomStringUtils.random(length, useLetters, useNumbers);
        return generatedString;
    }

    @Override
    public String getNameByEmailId(String email) {
        AuthUser authUser = authRepository.selectByGmailId(email);
        String userName = null;

        if (authUser != null) {
            userName = authUser.getFirstName() + " " + authUser.getLastName();
        } else {
            if (promoterRepository.selectMappedByEmailId(email) != null) {
                Promoter promoter = promoterRepository.selectMappedByEmailId(email);
                userName = promoter.getName();

            } else if (userRepository.isExistBySecondryEmailId(email)) {
                try {
                    User user = userRepository.selectBySecondryEmailId(email);
                    userName = user.getFirstName() + " " + user.getLastName();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        LOGGER.info("User Name from getNameByEmailId({}) is {}", email, userName);
        return userName;
    }

}