Subversion Repositories SmartDukaan

Rev

Rev 32367 | Go to most recent revision | Show entire file | Ignore whitespace | Details | Blame | Last modification | View Log | RSS feed

Rev 32367 Rev 32440
Line 1... Line 1...
1
package com.spice.profitmandi.web.controller;
1
package com.spice.profitmandi.web.controller;
2
 
2
 
3
import java.security.Key;
3
import java.security.Key;
-
 
4
import java.time.LocalDate;
4
import java.security.NoSuchAlgorithmException;
5
import java.time.LocalDateTime;
5
import java.security.SecureRandom;
6
import java.time.ZoneId;
-
 
7
import java.time.format.DateTimeFormatter;
6
import java.util.Date;
8
import java.util.Arrays;
7
import java.util.HashMap;
9
import java.util.HashMap;
-
 
10
import java.util.List;
8
import java.util.Map;
11
import java.util.Map;
9
 
12
 
10
import javax.servlet.http.HttpServletRequest;
13
import javax.servlet.http.HttpServletRequest;
11
 
14
 
-
 
15
import org.apache.http.Header;
-
 
16
import org.apache.http.HttpResponse;
12
import org.apache.http.conn.HttpHostConnectException;
17
import org.apache.http.conn.HttpHostConnectException;
13
import org.apache.logging.log4j.LogManager;
18
import org.apache.logging.log4j.LogManager;
14
import org.apache.logging.log4j.Logger;
19
import org.apache.logging.log4j.Logger;
-
 
20
import org.json.JSONObject;
15
import org.springframework.beans.factory.annotation.Autowired;
21
import org.springframework.beans.factory.annotation.Autowired;
16
import org.springframework.beans.factory.annotation.Value;
22
import org.springframework.beans.factory.annotation.Value;
17
import org.springframework.http.MediaType;
23
import org.springframework.http.MediaType;
18
import org.springframework.http.ResponseEntity;
24
import org.springframework.http.ResponseEntity;
19
import org.springframework.stereotype.Controller;
25
import org.springframework.stereotype.Controller;
Line 21... Line 27...
21
import org.springframework.web.bind.annotation.RequestBody;
27
import org.springframework.web.bind.annotation.RequestBody;
22
import org.springframework.web.bind.annotation.RequestMapping;
28
import org.springframework.web.bind.annotation.RequestMapping;
23
import org.springframework.web.bind.annotation.RequestMethod;
29
import org.springframework.web.bind.annotation.RequestMethod;
24
import org.springframework.web.bind.annotation.RequestParam;
30
import org.springframework.web.bind.annotation.RequestParam;
25
 
31
 
26
import com.auth0.jwt.interfaces.Signature;
32
import com.google.gson.Gson;
27
import com.spice.profitmandi.common.exception.ProfitMandiBusinessException;
33
import com.spice.profitmandi.common.exception.ProfitMandiBusinessException;
28
import com.spice.profitmandi.common.web.client.RestClient;
34
import com.spice.profitmandi.common.web.client.RestClient;
29
import com.spice.profitmandi.common.web.util.ResponseSender;
35
import com.spice.profitmandi.common.web.util.ResponseSender;
-
 
36
import com.spice.profitmandi.dao.entity.fofo.Campaign;
30
import com.spice.profitmandi.dao.entity.fofo.Customer;
37
import com.spice.profitmandi.dao.entity.fofo.Customer;
-
 
38
import com.spice.profitmandi.dao.entity.fofo.ThriweMembers;
31
import com.spice.profitmandi.dao.model.thriwe.benefit.BenefitGroup;
39
import com.spice.profitmandi.dao.model.thriwe.benefit.BenefitGroup;
-
 
40
import com.spice.profitmandi.dao.model.thriwe.benefit.BenefitResponse;
-
 
41
import com.spice.profitmandi.dao.model.thriwe.benefitConfiguration.BenefitConfigurationResponse;
-
 
42
import com.spice.profitmandi.dao.repository.fofo.CampaignRepository;
32
import com.spice.profitmandi.dao.repository.fofo.CustomerRepository;
43
import com.spice.profitmandi.dao.repository.fofo.CustomerRepository;
-
 
44
import com.spice.profitmandi.dao.repository.fofo.ThriweMemberRepository;
33
 
45
 
-
 
46
import io.jsonwebtoken.Jwts;
-
 
47
import io.jsonwebtoken.security.Keys;
34
import io.swagger.annotations.ApiImplicitParam;
48
import io.swagger.annotations.ApiImplicitParam;
35
import io.swagger.annotations.ApiImplicitParams;
49
import io.swagger.annotations.ApiImplicitParams;
36
import io.swagger.annotations.ApiOperation;
50
import io.swagger.annotations.ApiOperation;
37
 
51
 
38
@Controller
52
@Controller
Line 41... Line 55...
41
 
55
 
42
    @Autowired
56
    @Autowired
43
    private ResponseSender<?> responseSender;
57
    private ResponseSender<?> responseSender;
44
 
58
 
45
    @Autowired
59
    @Autowired
46
    RestClient restClient;
60
    private CustomerRepository customerRepository;
47
 
61
 
-
 
62
    @Autowired
-
 
63
    RestClient restClient;
48
 
64
 
49
    @Value("${thriwe.account.token}")
65
   // @Value("${thriwe.account.token}")
50
    private String token;
66
    private String token;
51
 
67
 
52
    @Autowired
68
    @Autowired
-
 
69
    CampaignRepository campaignRepository;
-
 
70
 
-
 
71
    @Autowired
53
    private CustomerRepository customerRepository;
72
    private ThriweMemberRepository thriweMemberRepository;
-
 
73
 
-
 
74
    @Autowired
-
 
75
    private Gson gson;
54
 
76
 
55
 
77
 
56
    private static final Logger LOGGER = LogManager.getLogger(ThriweController.class);
78
    private static final Logger LOGGER = LogManager.getLogger(ThriweController.class);
57
 
79
 
58
 
80
 
59
    @RequestMapping(value = "/thriwe/validate/customer", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
81
    @RequestMapping(value = "/thriwe/validate/customer", method = RequestMethod.GET)
60
    @ApiImplicitParams({@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header")})
-
 
61
    @ApiOperation(value = "")
-
 
62
    public ResponseEntity<?> validateCustomer(HttpServletRequest request) throws HttpHostConnectException, ProfitMandiBusinessException {
82
    public ResponseEntity<?> validateCustomer(HttpServletRequest request) throws HttpHostConnectException, ProfitMandiBusinessException {
63
 
83
 
64
        Map<String, String> params = new HashMap<String, String>();
84
        List<Campaign> campaigns = campaignRepository.selectAll();
-
 
85
        String memberShipId = null;
-
 
86
        if (!campaigns.isEmpty()) {
65
 
87
 
-
 
88
            Campaign campaign = campaigns.get(0);
66
        Customer customer = customerRepository.selectById(32697);
89
            Customer customer = customerRepository.selectById(32697);
67
 
90
 
-
 
91
            Map<String, String> params = new HashMap<String, String>();
68
        // String authToken = this.getToken(customer);
92
            String userName = customer.getId() + "-" + campaign.getId();
-
 
93
            LOGGER.info("token {}", token);
69
 
94
 
70
        Map<String, String> headers = new HashMap<String, String>();
-
 
71
 
95
 
-
 
96
            String secretKey = "smartdukan@thriwe_123smartdukaan";
72
 
97
 
-
 
98
            JSONObject jsonObject = new JSONObject();
-
 
99
            jsonObject.put("exp", LocalDateTime.now().plusDays(4).atZone(ZoneId.systemDefault()).toInstant().toEpochMilli() / 1000);
-
 
100
            jsonObject.put("iat", LocalDateTime.now().atZone(ZoneId.systemDefault()).toInstant().toEpochMilli() / 1000);
73
        headers.put("token", token);
101
            jsonObject.put("userName", userName);
74
        // headers.put("X-Auth-Token", authToken);
102
            jsonObject.put("email", customer.getEmailId());
-
 
103
            jsonObject.put("mobileNumber", customer.getMobileNumber());
75
        headers.put("Project-Code", "SMART_DUKAAN");
104
            jsonObject.put("firstName", customer.getFirstName());
-
 
105
            jsonObject.put("lastName", customer.getLastName());
-
 
106
            jsonObject.put("expiryDate", LocalDate.now().plusDays(4).format(DateTimeFormatter.ofPattern("dd/MM/yyyy")));
76
 
107
 
77
      /*  Key key = Keys.secretKeyFor(SignatureAlgorithm.HS256);
108
            LOGGER.info("jsonObject {}", jsonObject.toString());
78
 
109
 
79
        // JSON data as a Map (Key-Value pairs)
-
 
80
        Map<String, Object> jsonData = new HashMap<>();
110
            Map<String, Object> headersjwt = new HashMap<>();
81
        jsonData.put("exp", 1675145552L);
111
            headersjwt.put("alg", "HS256");
82
        jsonData.put("iat", 1674540752L);
-
 
83
        jsonData.put("userName", "75gtf-765dvy-atd6-ffdfa");
-
 
84
        jsonData.put("firstName", "Ishaan");
-
 
85
        jsonData.put("lastName", "Sharma");
112
            headersjwt.put("typ", "JWT");
86
        jsonData.put("email", "ishaan.sharma@thriwe.com");
-
 
87
        jsonData.put("mobile", "9560998243");
-
 
88
        jsonData.put("validTill", "12-May-2024");
-
 
89
 
-
 
90
        // Create the JWT
-
 
91
        String jwt = Jwts.builder()
-
 
92
                .setClaims(jsonData)
-
 
93
                .signWith(key)
-
 
94
                .compact();
-
 
95
 
-
 
96
        System.out.println("Generated JWT: " + jwt);*/
-
 
97
 
-
 
98
       // String secretKey = "your-secret-key"; // Replace with your actual secret key
-
 
99
 
-
 
100
  //      String token = Jwts.builder().setPayload(jsonData).signWith(SignatureAlgorithm.HS256, secretKey).compact();
-
 
101
 
-
 
102
    //    System.out.println("Generated JWT: " + token);
-
 
103
        
-
 
104
        // JSON data as a string
-
 
105
        // Generate the JWT
-
 
106
      // Create the JWT
-
 
107
 
113
 
108
        String url = "http://localhost:8083/validate-user";
-
 
109
        String response = restClient.get(url, params, headers);
114
            Key key = Keys.hmacShaKeyFor(secretKey.getBytes());
110
 
115
 
111
        LOGGER.info("response {}", response);
116
            String jwt = Jwts.builder().setHeaderParam("alg", "HS256").setHeaderParam("typ", "JWT").setPayload(jsonObject.toString()).signWith(key).compact();
112
 
117
 
113
        return responseSender.ok(true);
118
            LOGGER.info("jwt {}", jwt);
114
    }
-
 
115
 
119
 
116
 
120
 
117
    private static Key generateSecretKey() throws NoSuchAlgorithmException {
121
            Map<String, String> headers = new HashMap<String, String>();
118
        SecureRandom secureRandom = new SecureRandom();
122
            headers.put("Project-Code", "SMART_DUKAAN");
119
        byte[] bytes = new byte[32]; // 256 bits
123
            headers.put("X-Auth-Token", jwt);
-
 
124
            String url = "https://staging-india-api-gateway.thriwe.com/validate-user";
-
 
125
            HttpResponse response = restClient.getResponse(url, params, headers);
120
        secureRandom.nextBytes(bytes);
126
            LOGGER.info("response {}", response);
-
 
127
 
-
 
128
 
121
        return new javax.crypto.spec.SecretKeySpec(bytes, "HmacSHA256");
129
            Header[] authToken = response.getHeaders("Authorization");
-
 
130
            LOGGER.info("authToken {}", Arrays.asList(authToken).get(0).getValue());
122
    }
131
 
-
 
132
            ThriweMembers thriweMember = thriweMemberRepository.selectByUsername(userName, campaign.getStartDate(), campaign.getEndDate());
-
 
133
            LOGGER.info("thriweMembers {}", thriweMember);
123
 
134
 
-
 
135
            if (thriweMember != null) {
124
 
136
 
-
 
137
                thriweMember.setAuthToken(Arrays.asList(authToken).get(0).getValue());
-
 
138
 
-
 
139
                try {
-
 
140
                    String responseString = restClient.toString(response.getEntity().getContent());
-
 
141
                    LOGGER.info("responseString {}", new JSONObject(responseString).get("membershipId"));
-
 
142
                    JSONObject responseJson = new JSONObject(responseString);
-
 
143
                    String membershipId = responseJson.getString("membershipId");
-
 
144
                    thriweMember.setMembershipId(membershipId);
-
 
145
                    memberShipId = thriweMember.getMembershipId();
-
 
146
                } catch (Exception e) {
-
 
147
                    // TODO: handle exception
-
 
148
                }
-
 
149
 
-
 
150
 
-
 
151
            }
-
 
152
        }
-
 
153
 
-
 
154
        return responseSender.ok(memberShipId);
-
 
155
    }
-
 
156
 
125
    @RequestMapping(value = "/thriwe/benefitConfiguration", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
157
    @RequestMapping(value = "/thriwe/benefit-configs", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
126
    @ApiImplicitParams({@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header")})
158
    @ApiImplicitParams({@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header")})
127
    @ApiOperation(value = "")
159
    @ApiOperation(value = "")
128
    public ResponseEntity<?> benefitConfiguration(HttpServletRequest request) throws HttpHostConnectException, ProfitMandiBusinessException {
160
    public ResponseEntity<?> benefitConfigs(HttpServletRequest request, @RequestParam String membershipId) throws HttpHostConnectException, ProfitMandiBusinessException {
129
 
161
 
130
        Map<String, String> params = new HashMap<String, String>();
-
 
131
 
162
 
132
        Map<String, String> headers = new HashMap<String, String>();
163
        ThriweMembers thriweMember = thriweMemberRepository.selectByMembershipId(membershipId);
133
 
164
 
-
 
165
        Map<String, String> params = new HashMap<String, String>();
134
        headers.put("token", token);
166
        Map<String, String> headers = new HashMap<String, String>();
135
 
167
 
-
 
168
        headers.put("Authorization", thriweMember.getAuthToken());
136
        headers.put("Project-Code", "SMART_DUKAAN");
169
        headers.put("Project-Code", "SMART_DUKAAN");
137
 
170
 
138
        String url = "https://staging-india-api-gateway.thriwe.com/client/benefit-configs";
171
        String url = "https://staging-india-api-gateway.thriwe.com/client/benefit-configs";
139
        String response = restClient.get(url, params, headers);
-
 
140
 
172
 
-
 
173
        String response = restClient.get(url, params, headers);
141
        LOGGER.info("response {}", response);
174
        LOGGER.info("response {}", response);
142
 
175
 
143
        return responseSender.ok(true);
176
        BenefitConfigurationResponse benefitConfigurationResponse = gson.fromJson(response, BenefitConfigurationResponse.class);
144
    }
-
 
145
 
177
 
-
 
178
        LOGGER.info("benefitConfigurationResponse {}", benefitConfigurationResponse);
-
 
179
 
-
 
180
        return responseSender.ok(benefitConfigurationResponse);
-
 
181
    }
146
 
182
 
147
    @RequestMapping(value = "/thriwe/benefits", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
183
    @RequestMapping(value = "/thriwe/benefits", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
148
    @ApiImplicitParams({@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header")})
184
    @ApiImplicitParams({@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header")})
149
    @ApiOperation(value = "")
185
    @ApiOperation(value = "")
150
    public ResponseEntity<?> benefits(HttpServletRequest request, @RequestParam String configId) throws HttpHostConnectException, ProfitMandiBusinessException {
186
    public ResponseEntity<?> benefits(HttpServletRequest request, @RequestParam String membershipId, @RequestParam String configId) throws HttpHostConnectException, ProfitMandiBusinessException {
-
 
187
 
-
 
188
        ThriweMembers thriweMember = thriweMemberRepository.selectByMembershipId(membershipId);
151
 
189
 
152
        Map<String, String> params = new HashMap<String, String>();
190
        Map<String, String> params = new HashMap<String, String>();
153
 
191
 
154
        params.put("configId", configId);
192
        params.put("configId", configId);
155
 
193
 
156
        Map<String, String> headers = new HashMap<String, String>();
194
        Map<String, String> headers = new HashMap<String, String>();
157
 
195
 
158
        headers.put("token", token);
196
        headers.put("Authorization", thriweMember.getAuthToken());
159
        headers.put("Project-Code", "SMART_DUKAAN");
197
        headers.put("Project-Code", "SMART_DUKAAN");
160
 
198
 
161
        String url = "https://staging-india-api-gateway.thriwe.com/client/benefit-configs";
199
        String url = "https://staging-india-api-gateway.thriwe.com/client/benefit-items";
162
        String response = restClient.get(url, params, headers);
200
        String response = restClient.get(url, params, headers);
163
 
201
 
-
 
202
        BenefitResponse benefitResponse = gson.fromJson(response, BenefitResponse.class);
-
 
203
 
164
        LOGGER.info("response {}", response);
204
        LOGGER.info("benefitResponse {}", benefitResponse);
-
 
205
 
-
 
206
        return responseSender.ok(benefitResponse);
165
 
207
 
166
        return responseSender.ok(true);
-
 
167
    }
208
    }
168
 
209
 
169
 
210
 
170
    @RequestMapping(value = "/thriwe/createBooking", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
211
    @RequestMapping(value = "/thriwe/createBooking", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
171
    @ApiImplicitParams({@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header")})
212
    @ApiImplicitParams({@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header")})
172
    @ApiOperation(value = "")
213
    @ApiOperation(value = "")
173
    public ResponseEntity<?> createBooking(HttpServletRequest request, @RequestBody BenefitGroup benefitGroup) throws HttpHostConnectException, ProfitMandiBusinessException {
214
    public ResponseEntity<?> createBooking(HttpServletRequest request, @RequestBody BenefitGroup benefitGroup) throws HttpHostConnectException, ProfitMandiBusinessException {
174
 
215
 
-
 
216
        ThriweMembers thriweMember = thriweMemberRepository.selectByMembershipId(benefitGroup.getMembershipId());
175
 
217
 
176
        Map<String, String> headers = new HashMap<String, String>();
218
        Map<String, String> headers = new HashMap<String, String>();
177
 
219
 
178
        headers.put("token", token);
220
        headers.put("token", token);
179
        headers.put("Project-Code", "SMART_DUKAAN");
221
        headers.put("Project-Code", "SMART_DUKAAN");