Subversion Repositories SmartDukaan

Rev

Rev 35198 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
24330 amit.gupta 1
package com.spice.profitmandi.service;
2
 
3
import com.google.common.hash.Hashing;
4
import com.spice.profitmandi.common.exception.ProfitMandiBusinessException;
5
import com.spice.profitmandi.common.util.Utils;
6
import com.spice.profitmandi.dao.entity.auth.AuthUser;
24479 amit.gupta 7
import com.spice.profitmandi.dao.entity.dtr.User;
8
import com.spice.profitmandi.dao.entity.user.Promoter;
24330 amit.gupta 9
import com.spice.profitmandi.dao.repository.auth.AuthRepository;
24479 amit.gupta 10
import com.spice.profitmandi.dao.repository.dtr.UserRepository;
11
import com.spice.profitmandi.dao.repository.user.PromoterRepository;
35956 amit 12
import com.spice.profitmandi.service.mail.MailOutboxService;
34794 vikas.jang 13
import com.spice.profitmandi.service.user.UserService;
32559 amit.gupta 14
import org.apache.commons.lang.RandomStringUtils;
15
import org.apache.logging.log4j.LogManager;
16
import org.apache.logging.log4j.Logger;
17
import org.springframework.beans.factory.annotation.Autowired;
18
import org.springframework.mail.javamail.JavaMailSender;
19
import org.springframework.stereotype.Component;
24330 amit.gupta 20
 
32559 amit.gupta 21
import java.nio.charset.StandardCharsets;
22
import java.util.ArrayList;
35026 amit 23
import java.util.HashSet;
29269 manish 24
import java.util.List;
35026 amit 25
import java.util.Set;
29269 manish 26
import java.util.stream.Collectors;
27
 
24389 amit.gupta 28
@Component
24330 amit.gupta 29
public class AuthServiceImpl implements AuthService {
30
 
34077 tejus.loha 31
    // private static final String RESET_PASSWORD_BODY = "Dear %s, your password has
32
    // been reset. Please click this <a href=\"%s\">link</a> to reset your
33
    // password.\n\nRegards\nSmartdukaan";
34
    private static final String RESET_PASSWORD_BODY = "Dear %s, \nyour password has been reset to %s. \n\nRegards\nSmartdukaan";
35
    private static final String RESET_PASSWORD_SUBJECT = "Password Reset request";
24330 amit.gupta 36
 
34077 tejus.loha 37
    private static final Logger LOGGER = LogManager.getLogger(AuthServiceImpl.class);
24330 amit.gupta 38
 
34077 tejus.loha 39
    @Autowired
40
    AuthRepository authRepository;
24330 amit.gupta 41
 
34077 tejus.loha 42
    @Autowired
43
    JavaMailSender mailSender;
29282 amit.gupta 44
 
34077 tejus.loha 45
    @Autowired
35956 amit 46
    MailOutboxService mailOutboxService;
47
 
48
    @Autowired
34077 tejus.loha 49
    PromoterRepository promoterRepository;
29282 amit.gupta 50
 
34077 tejus.loha 51
    @Autowired
52
    UserRepository userRepository;
24330 amit.gupta 53
 
34794 vikas.jang 54
    @Autowired
55
    UserService userService;
56
 
34077 tejus.loha 57
    private String getHash256(String originalString) {
58
        return Hashing.sha256().hashString(originalString, StandardCharsets.UTF_8).toString();
59
    }
29282 amit.gupta 60
 
34077 tejus.loha 61
    @Override
62
    public List<Integer> getDirectReportees(int authId) {
63
        List<AuthUser> authUsers = authRepository.selectAllByManagerAuthId(authId);
64
        List<Integer> authIds = authUsers.stream().map(x -> x.getId()).collect(Collectors.toList());
65
        LOGGER.info("Auth Id == {}, All Reportees === {}", authId, authIds);
66
        return authIds;
67
    }
68
    @Override
69
    public List<AuthUser> getAllManagers(int authId) {
70
        AuthUser authUser = authRepository.selectById(authId);
71
        List<AuthUser> managersHierarchy = new ArrayList<>();
35198 ranu 72
 
73
        // To prevent infinite loops due to circular references
74
        Set<Integer> visitedIds = new HashSet<>();
75
        visitedIds.add(authId);
76
 
77
        while (authUser != null && authUser.getManagerId() != 0) {
78
            int managerId = authUser.getManagerId();
79
 
80
            if (visitedIds.contains(managerId)) {
81
                LOGGER.warn("Circular reference detected: authId {} -> managerId {}", authUser.getId(), managerId);
82
                break;
83
            }
84
 
85
            AuthUser manager = authRepository.selectById(managerId);
86
            if (manager == null) {
87
                LOGGER.warn("Manager with ID {} not found for user {}", managerId, authUser.getId());
88
                break;
89
            }
90
 
91
            managersHierarchy.add(manager);
92
            visitedIds.add(managerId);
93
 
94
            authUser = manager;
34077 tejus.loha 95
        }
35198 ranu 96
 
97
        LOGGER.info("managersHierarchy {}", managersHierarchy);
34077 tejus.loha 98
        return managersHierarchy;
99
    }
29282 amit.gupta 100
 
34077 tejus.loha 101
    public List<Integer> getAllReportees(int authId) {
35026 amit 102
        return getAllReportees(authId, new HashSet<>());  // call helper with visited set
103
    }
29282 amit.gupta 104
 
35026 amit 105
    private List<Integer> getAllReportees(int authId, Set<Integer> visited) {
34077 tejus.loha 106
        List<Integer> allReportees = new ArrayList<>();
24330 amit.gupta 107
 
34077 tejus.loha 108
        List<Integer> directReporteeIds = this.getDirectReportees(authId);
35026 amit 109
 
34077 tejus.loha 110
        for (int directReporteeId : directReporteeIds) {
35026 amit 111
            if (!visited.contains(directReporteeId)) {
112
                visited.add(directReporteeId); // mark visited
113
                allReportees.add(directReporteeId);
114
 
115
                // recursively get sub-reportees
116
                allReportees.addAll(getAllReportees(directReporteeId, visited));
117
            }
34077 tejus.loha 118
        }
119
        return allReportees;
120
    }
24330 amit.gupta 121
 
34077 tejus.loha 122
    @Override
123
    public boolean authenticate(String emailOrMobile, String password) {
124
        return authRepository.authenticate(emailOrMobile, getHash256(password));
125
    }
24330 amit.gupta 126
 
34077 tejus.loha 127
    @Override
128
    public void resetPassword(String emailOrMobile) throws ProfitMandiBusinessException {
129
        AuthUser authUser = authRepository.selectByEmailOrMobile(emailOrMobile);
130
        String password = getRandomString();
131
        try {
35956 amit 132
            mailOutboxService.queueMail(authUser.getEmailId(), null, RESET_PASSWORD_SUBJECT,
133
                    String.format(RESET_PASSWORD_BODY, authUser.getFirstName(), password), "AuthServiceImpl.resetPassword");
34077 tejus.loha 134
        } catch (Exception e) {
135
            throw new ProfitMandiBusinessException("Password Reset Email", emailOrMobile,
136
                    "Could not send password reset mail. Password Could not be reset");
137
        }
34794 vikas.jang 138
        userService.resetPassword(emailOrMobile, password);
34077 tejus.loha 139
        authUser.setPassword(getHash256(password));
140
    }
24330 amit.gupta 141
 
34077 tejus.loha 142
    @Override
34794 vikas.jang 143
    public void resetPassword(String emailOrMobile, String password) throws ProfitMandiBusinessException {
34815 vikas 144
        try {
145
            AuthUser authUser = authRepository.selectByEmailOrMobile(emailOrMobile);
146
            authUser.setPassword(getHash256(password));
147
            userService.resetPassword(emailOrMobile, password);
148
        } catch (ProfitMandiBusinessException e) {
149
            userService.resetPassword(emailOrMobile, password);
150
        }
34794 vikas.jang 151
    }
152
 
153
    @Override
154
    public void changePassword(String emailOrMobile, String oldPassword, String newPassword) throws ProfitMandiBusinessException {
34077 tejus.loha 155
        if (authRepository.authenticate(emailOrMobile, getHash256(oldPassword))) {
156
            AuthUser authUser = authRepository.selectByEmailOrMobile(emailOrMobile);
157
            authUser.setPassword(getHash256(newPassword));
34794 vikas.jang 158
            userService.resetPassword(authUser.getEmailId(), newPassword);
34077 tejus.loha 159
        } else {
160
            throw new ProfitMandiBusinessException("Authentication", "Credentials", "Invalid email/mobile or password");
161
        }
162
    }
24389 amit.gupta 163
 
34077 tejus.loha 164
    @Override
165
    public void addAuthUser(AuthUser authUser) throws ProfitMandiBusinessException {
166
        try {
167
            authRepository.selectByEmailOrMobile(authUser.getEmailId());
168
        } catch (ProfitMandiBusinessException pbse) {
169
            try {
170
                authRepository.selectByEmailOrMobile(authUser.getMobileNumber());
171
            } catch (ProfitMandiBusinessException e) {
172
                authRepository.persist(authUser);
173
                this.resetPassword(authUser.getEmailId());
174
                return;
175
            }
176
            throw new ProfitMandiBusinessException("Mobile", authUser.getMobileNumber(), "Mobile number already exist");
177
        }
178
        throw new ProfitMandiBusinessException("Email", authUser.getEmailId(), "Email Id already exist");
24330 amit.gupta 179
 
34077 tejus.loha 180
    }
24330 amit.gupta 181
 
34077 tejus.loha 182
    private String getRandomString() {
183
        int length = 10;
184
        boolean useLetters = true;
185
        boolean useNumbers = false;
186
        String generatedString = RandomStringUtils.random(length, useLetters, useNumbers);
187
        return generatedString;
188
    }
29282 amit.gupta 189
 
34077 tejus.loha 190
    @Override
191
    public String getNameByEmailId(String email) {
192
        AuthUser authUser = authRepository.selectByGmailId(email);
193
        String userName = null;
29282 amit.gupta 194
 
34077 tejus.loha 195
        if (authUser != null) {
196
            userName = authUser.getFirstName() + " " + authUser.getLastName();
197
        } else {
198
            if (promoterRepository.selectMappedByEmailId(email) != null) {
199
                Promoter promoter = promoterRepository.selectMappedByEmailId(email);
200
                userName = promoter.getName();
24479 amit.gupta 201
 
34077 tejus.loha 202
            } else if (userRepository.isExistBySecondryEmailId(email)) {
203
                try {
204
                    User user = userRepository.selectBySecondryEmailId(email);
205
                    userName = user.getFirstName() + " " + user.getLastName();
206
                } catch (Exception e) {
207
                    e.printStackTrace();
208
                }
209
            }
210
        }
211
        LOGGER.info("User Name from getNameByEmailId({}) is {}", email, userName);
212
        return userName;
213
    }
214
 
24330 amit.gupta 215
}