Skip to content

Commit

Permalink
hotfix editprofile, header.html, gửi email sau khi paypal, jasypt app…
Browse files Browse the repository at this point in the history
….prop, check info trống khi checkout
  • Loading branch information
jackytank committed Dec 7, 2022
1 parent 46a114a commit 85d24fb
Show file tree
Hide file tree
Showing 12 changed files with 82 additions and 54 deletions.
7 changes: 7 additions & 0 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,19 @@
<groupId>com.edu</groupId>
<artifactId>graduation-project</artifactId>
<version>0.0.1-SNAPSHOT</version>
<!-- <packaging>war</packaging> -->
<name>graduation-project</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>17</java.version>
</properties>
<dependencies>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,13 +18,15 @@
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.edu.graduationproject.entity.Order;
import com.edu.graduationproject.model.EPaypalPaymentIntent;
import com.edu.graduationproject.model.EPaypalPaymentMethod;
import com.edu.graduationproject.service.OrderService;
import com.edu.graduationproject.service.PaypalService;
import com.edu.graduationproject.utils.CommonUtils;
import com.edu.graduationproject.utils.URLUtils;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.paypal.api.payments.Links;
import com.paypal.api.payments.Payment;
import com.paypal.base.rest.PayPalRESTException;
Expand All @@ -40,6 +42,8 @@ public class PaypalController {
public static final String CHECKOUT_PAGE_URL = "/order/checkout";
public static final String HOMEPAGE_URL = "/order/checkout";
private static JsonNode orderJsonNode;
private static HttpServletRequest request;
private static ObjectMapper mapper = new ObjectMapper();

@Autowired
private PaypalService paypalService;
Expand All @@ -51,10 +55,11 @@ public class PaypalController {
@ResponseBody
public ResponseEntity<Object> pay(
@RequestBody JsonNode orderData,
HttpServletRequest request, ModelMap model)
HttpServletRequest _request, ModelMap model)
throws IOException {
HashMap<String, String> map = new HashMap<>();
orderJsonNode = orderData;
request = _request;
Double _total = CommonUtils.convertCurrency("VND", "USD", orderData.get("total").asDouble());
if (_total == 0.0) {
return ResponseEntity.ok(CHECKOUT_PAGE_URL);
Expand Down Expand Up @@ -99,8 +104,12 @@ public ModelAndView successPay(ModelMap model, @RequestParam("paymentId") String
try {
Payment payment = paypalService.executePayment(paymentId, payerId);
if (payment.getState().equals("approved")) {
orderService.create(orderJsonNode);
model.addAttribute("message", "You have successfully completed the payment!");
Order createdOrder = orderService.create(orderJsonNode);
JsonNode tmpOrderJsonNode = mapper.convertValue(createdOrder, JsonNode.class);

orderService.sendEmailReceipt(tmpOrderJsonNode, request);
model.addAttribute("message",
"Bạn đã thanh toán Paypal thành công, chúng tôi đã gửi email hóa đơn vào hòm thư của bạn!");
model.addAttribute("isPaymentSuccess", true);
return new ModelAndView("redirect:/", model);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -88,17 +88,6 @@ public ResponseEntity<User> update(@PathVariable("idOrUsername") Optional<Object
if (!existingUser.isPresent()) {
existingUser = userService.findById(Integer.valueOf((String) idOrUsername.get()));
}
if (!existingUser.get().getProvider().equals(EAuthProvider.DATABASE)) {
return ResponseEntity.badRequest().body(user);
}
if (user.getEnabled() == null) {
user.setEnabled(true);
}
if (user.getProvider() != EAuthProvider.DATABASE) {
user.setProvider(EAuthProvider.DATABASE);
}
user.setUpdatedAt(new Date());
user.setPassword(existingUser.get().getPassword());
User savedUser = userService.update(user);
return ResponseEntity.ok(savedUser);
} catch (NoSuchElementException e) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,8 @@
import com.edu.graduationproject.service.PersonalAccessTokenService;
import com.edu.graduationproject.service.ProductService;
import com.edu.graduationproject.service.UserService;
import com.edu.graduationproject.utils.CommonUtils;
import com.edu.graduationproject.utils.DateUtils;
import com.edu.graduationproject.utils.URLUtils;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
Expand Down Expand Up @@ -86,7 +86,7 @@ public void sendEmailReceipt(JsonNode orderData, HttpServletRequest request) {
// create accessToken
String randomStr = RandomString.make(30);
String abilities = "DOWNLOAD";
String downloadLink = CommonUtils.getSiteURL(request) + "/rest/orders/download-invoice?accessToken="
String downloadLink = URLUtils.getBaseURl(request) + "/rest/orders/download-invoice?accessToken="
+ randomStr + "&orderId=" + order.getId();
accessTokenService.create(new PersonalAccessToken(randomStr, abilities));

Expand Down Expand Up @@ -125,7 +125,6 @@ public void sendEmailReceipt(JsonNode orderData, HttpServletRequest request) {
downloadLink);
mailInfo.setBody(content);
mailerService.queue(mailInfo);

}

@Override
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package com.edu.graduationproject.service.impl;

import java.util.Date;
import java.util.List;
import java.util.Optional;

Expand Down Expand Up @@ -66,15 +67,28 @@ public User save(User user) {

@Override
public User update(User user) {
Optional<User> findUser = userRepo.findByUsername(user.getUsername());
if (findUser.isPresent()) {
if (user.getPassword().equals(String.valueOf(findUser.get().getPassword()))) {
user.setPassword((user.getPassword()));
} else if (!encoder.matches(user.getPassword(), findUser.get().getPassword())) {
user.setPassword(encoder.encode(user.getPassword()));
}
}
return userRepo.save(user);
Optional<User> findUser = userRepo.findByUsername(user.getUsername());
if (findUser.isPresent()) {
if (user.getEnabled() == null) {
user.setEnabled(true);
}
if (findUser.get().getProvider().equals(EAuthProvider.FACEBOOK)) {
user.setPassword(null);
user.setProvider(EAuthProvider.FACEBOOK);
} else if (findUser.get().getProvider().equals(EAuthProvider.GOOGLE)) {
user.setPassword(null);
user.setProvider(EAuthProvider.GOOGLE);
} else if (findUser.get().getProvider().equals(EAuthProvider.DATABASE)) {
user.setProvider(EAuthProvider.DATABASE);
} else if (findUser.get().getProvider() == null || user.getProvider() == null) {
user.setProvider(EAuthProvider.DATABASE);
}
if (findUser.get().getPassword() != null || findUser.get().getPassword() != "") {
user.setPassword((findUser.get().getPassword()));
}
user.setUpdatedAt(new Date());
}
return userRepo.save(user);
}

@Override
Expand Down
7 changes: 2 additions & 5 deletions src/main/resources/application.properties
Original file line number Diff line number Diff line change
Expand Up @@ -44,8 +44,8 @@ spring.security.oauth2.client.registration.github.scope=user:email,read:user
# For Mail
spring.mail.host=smtp.gmail.com
spring.mail.port=587
spring.mail.username=[email protected]
spring.mail.password=kvzgzfliinljxnug
spring.mail.username=ENC(Y5t9L5007g231OuDoPnIh19q4y/ICObTAj7OJZty9K4=)
spring.mail.password=ENC(0UfJRnRcwqE7wIMv20Dcvyc7olB34CadSiK9AqZDHuY=)
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true

Expand All @@ -57,6 +57,3 @@ paypal.client.secret=EBWG-ni6c47OZYBwpYCJUJu5GST_On7dupA0Ise4JkQXDxf6uHYPZEXsR-u
# For Exchange Rate apikey
apilayer.apikey=6h7fgfiZtBDuie6LxtyKp5cqVxwjaKnV

# JWT App Properties
bezkoder.app.jwtSecret=bezKoderSecretKey
bezkoder.app.jwtExpirationMs=86400000
27 changes: 21 additions & 6 deletions src/main/resources/static/assets/js/cart.controller.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
app.controller("shopping-cart-ctrl", favoriteCtrl);
app.controller("shopping-cart-ctrl", shoppingCartCtrl);

function favoriteCtrl($scope, $http) {
function shoppingCartCtrl($scope, $http, $window) {

$scope.userPrincipal = {};
$scope.cartOrderType = '';
Expand All @@ -14,18 +14,31 @@ function favoriteCtrl($scope, $http) {
$scope.get_user_pricipal = function () {
$http.get("/rest/users/principal").then(resp => {
$scope.userPrincipal = resp.data;
if ($window.location.pathname === '/order/checkout') {
if (resp.data.address === null || resp.data.phone === null || resp.data.fullname === null) {
alert('Cần cung cấp thông tin địa chỉ, họ tên và SDT để tiến hành thanh toán!');
$window.location.href = '/account/editprofile';
}
}
// localStorage.setItem("user", JSON.stringify(resp.data.id));
}).catch(error => {
console.log("Error", error);
});
};



$scope.initialize = function () {
if ($window.location.pathname === '/order/checkout') {
if ($scope.cart.items.length === 0) {
alert('Giỏ hàng bạn đang trống!');
$window.location.href = '/';
}
}

$scope.get_user_pricipal();
};

$scope.initialize();

$scope.cart = {
items: [],
//Thêm
Expand Down Expand Up @@ -168,15 +181,15 @@ function favoriteCtrl($scope, $http) {
if ($scope.cart.count === 0) {
alert("Error creating order or your cart is empty! Please try again!");
} else {
if (order.payment_method == "paypal") {
if (order.payment_method === "paypal") {
$http.post('/paypal', order).then(res => {
$scope.cart.clear();
location.href = res.data.returned_url;
}).catch(err => {
alert("Error creating order or your cart is empty! Please try again!");
console.log(err);
});
} else if (order.payment_method == "cod") {
} else if (order.payment_method === "cod") {
$http.post('/rest/orders', order).then(res => {
alert("Đặt hàng thành công, chúng tôi sẽ gửi mail hóa đơn vào địa chỉ email của bạn!");
$scope.semdEmailReceipt(res.data);
Expand All @@ -191,5 +204,7 @@ function favoriteCtrl($scope, $http) {
}
};

$scope.initialize();


}
1 change: 0 additions & 1 deletion src/main/resources/static/assets/js/script.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@

// change classname on mouse hover
function changeClassName(element, oldClass, newClass) {
console.log(element);
if (element.className == oldClass) {
element.className = newClass;
} else {
Expand Down
8 changes: 4 additions & 4 deletions src/main/resources/templates/account/edit_profile.html
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,10 @@
<div class="form-group mb-3">
<label for="customFile">Ảnh:</label>
<figure>
<img ng-src="{{ (form.image_url.startsWith('upload')?'/upload/images/':'/assets/images/') + (form.image_url || 'default-user.jpg') }}"
<img ng-src="{{ (form.image_url.startsWith('upload')?'/upload/images/':(form.image_url.startsWith('https://')?'':'/assets/images/')) + (form.image_url || 'default-user.jpg') }}"
class="img-fluid img-thumbnail" width="120" height="120">
</figure>
<input ng-model="form.image_url" onchange="angular.element(this).scope().imageChanged(this.files)" type="file" class="form-control"
<input ng-hide="form.image_url.startsWith('https://')" ng-model="form.image_url" onchange="angular.element(this).scope().imageChanged(this.files)" type="file" class="form-control"
id="customFile" />
</div>
<div class="row">
Expand All @@ -42,7 +42,7 @@
</div>
<div class="form-group col-6 mb-2">
<label for="email">Email </label>
<input ng-model="form.email" type="text" name="txtEmail" class="form-control" placeholder="[email protected]" required>
<input ng-model="form.email" type="text" name="txtEmail" class="form-control" placeholder="[email protected]" ng-disabled="form.image_url.startsWith('https://')" required>
<label ng-show="myform.txtEmail.$invalid" class="badge badge-danger my-2 p-2">Xin hãy nhập email! </label>
</div>
</div>
Expand All @@ -66,7 +66,7 @@
<i class="fas fa-save"></i> Lưu
</button>
<button ng-click="reset()" type="submit" class="btn btn-danger">
Hủy
Xóa hết
</button>
</div>
</div>
Expand Down
7 changes: 3 additions & 4 deletions src/main/resources/templates/account/reset_password_form.html
Original file line number Diff line number Diff line change
Expand Up @@ -18,13 +18,13 @@
<div>
<h2>Đặt lại mật khẩu</h2>
</div>

<form class="needs-validation" novalidate="true" th:action="@{/reset_password}" method="post">
<form class="needs-validation" novalidate th:action="@{/reset_password}" method="post">
<div class="mb-3">
<input type="hidden" name="token" th:value="${token}" />
<div class="form-floating">
<input class="form-control rounded-3" type="password" name="password" id="password">
<input class="form-control rounded-3" type="password" name="password" id="password" min="6" required>
<label>Nhập mật khẩu mới</label>
<div class="invalid-feedback">Hãy nhập mật khẩu</div>
</div>
</div>
<div class="mb-3">
Expand All @@ -33,7 +33,6 @@ <h2>Đặt lại mật khẩu</h2>
<label>Xác nhận mật khẩu mới</label>
</div>
<hr class="my-4">

</div>
<div class="d-grid gap-2 mb-4">
<button type="submit" id="submit" class="btn btn-lg rounded-3 btn-success">Gửi xác nhận</button>
Expand Down
4 changes: 2 additions & 2 deletions src/main/resources/templates/components/_header.html
Original file line number Diff line number Diff line change
Expand Up @@ -86,8 +86,8 @@
<th:block th:if="${#request.remoteUser}">
<!-- <span sec:authentication="authorities"></span> -->
<!-- if user log in with OAuth2 GG and FB then hide Edit profile -->
<li
sec:authorize="hasAnyRole('ROLE_ADMIN', 'ROLE_USER', 'ROLE_STAFF') and !hasAuthority('SCOPE_openid') and !hasAuthority('SCOPE_email') and !hasAuthority('SCOPE_public_profile')">
<!-- and !hasAuthority('SCOPE_openid') and !hasAuthority('SCOPE_email') and !hasAuthority('SCOPE_public_profile') -->
<li sec:authorize="hasAnyRole('ROLE_ADMIN', 'ROLE_USER', 'ROLE_STAFF')">
<a class="dropdown-item" th:href="@{/account/editprofile}">Chỉnh sửa tài khoản</a>
</li>
<li>
Expand Down
Loading

0 comments on commit 85d24fb

Please sign in to comment.