Subversion Repositories SmartDukaan

Rev

Rev 32560 | Rev 34815 | Go to most recent revision | 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 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.List;
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 mailSender;

    @Autowired
    PromoterRepository promoterRepository;

    @Autowired
    UserRepository userRepository;

    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<>();
        while (authUser.getManagerId() != 0) {
            AuthUser authUser1 = authRepository.selectById(authUser.getManagerId());
            managersHierarchy.add(authUser1);
            authUser = authUser1;
        }
        return managersHierarchy;
    }

    public List<Integer> getAllReportees(int authId) {

        List<Integer> allReportees = new ArrayList<>();

        List<Integer> directReporteeIds = this.getDirectReportees(authId);
        allReportees.addAll(directReporteeIds);
        for (int directReporteeId : directReporteeIds) {
            allReportees.addAll(this.getAllReportees(directReporteeId));
        }
        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 {
            Utils.sendMailWithAttachments(mailSender, authUser.getEmailId(), null, RESET_PASSWORD_SUBJECT,
                    String.format(RESET_PASSWORD_BODY, authUser.getFirstName(), password), null);
        } catch (Exception e) {
            throw new ProfitMandiBusinessException("Password Reset Email", emailOrMobile,
                    "Could not send password reset mail. Password Could not be reset");
        }
        authUser.setPassword(getHash256(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));
        } 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;
    }

}