Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
package com.library.controller.admin.user;

import com.library.factory.ServiceFactory;
import com.library.service.TrackingUserService;
import com.library.service.UserService;
import com.library.util.SessionTracker;
import java.io.IOException;
Expand Down Expand Up @@ -32,8 +33,9 @@ public class LogaoutAllUser extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

userService.logoutAllUser();
TrackingUserService.clear();
HttpSession session = request.getSession();
session.setAttribute("logAll", "logout all users done!");
response.sendRedirect(request.getContextPath() + "/admin/user-manager");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
public class LogoutUserController extends HttpServlet {

UserDao userDao = new UserDaoImpl();

private final TrackingUserService trackService = ServiceFactory.getTrackingUserService();
private final UserService userService = ServiceFactory.getUserService();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@
*/
@WebServlet(name = "ManagerUserController", urlPatterns = {"/admin/user-borrowing-record"})
public class UserBorrowingRecordController extends HttpServlet {

private final UserService userService = ServiceFactory.getUserService();

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -76,15 +76,14 @@ protected void doPost(HttpServletRequest request, HttpServletResponse response)
String hashedPassword = userService.getHashedPassword(account);
if (HashPassword.checkPassword(pass, hashedPassword)) {
session.setAttribute("account", account);
session.setAttribute("user", user);
TrackingUserService.add(account);
activityService.ActivityUser(1, account);
userService.setOnlineUser(account);
int userID = userDao.findUserID(account);
trackService.updateData(session.getId(), userID);
SessionTracker.addSessionToServer(session.getId(), session);

session.setAttribute("user", user);
SessionTracker.addSessionToServer(session.getId(), session);
if (user.getRole().equals("user")) {
TrackingUserService.add(account);
activityService.ActivityUser(1, account);
userService.setOnlineUser(account);
int userID = userDao.findUserID(account);
trackService.updateData(session.getId(), userID);
response.sendRedirect(request.getContextPath() + "/book/list");
return;
} else {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ public void doFilter(ServletRequest servletRequest, ServletResponse servletRespo

String[] publicPaths = {
"/login", "/register", "/book/list",
"/resource/", "/images/", ".css", ".js", ".png", ".jpg"
"/resource/", "/images/", ".css", ".js", ".png", ".jpg", "/user/forgot-password"
};
for (String p : publicPaths) {
if (path.contains(p)) {
Expand Down
4 changes: 2 additions & 2 deletions src/java/com/library/controller/user/ForgotPassword.java
Original file line number Diff line number Diff line change
Expand Up @@ -51,10 +51,10 @@ protected void doPost(HttpServletRequest request, HttpServletResponse response)
Validator.requireNotEmpty(account);
userService.isAccountExist(account);
String tmp = RandomPassword.generatePassword();
String subject = "Password Recovery - Library System";
String title = "Password Recovery - Library System";
String message = "<p>Your New Pass : <b>" + tmp + "</b> </p>";
userService.updatePassword(account, HashPassword.hash(tmp));
MailService.send(account, subject, message);
MailService.send(account, title, message);
session.setAttribute("message", "we have sent your password via email");
response.sendRedirect(request.getContextPath() + "/user/forgot-password");
} catch (ValidationException e) {
Expand Down
68 changes: 32 additions & 36 deletions src/java/com/library/controller/user/RegisterController.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
* Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
* Click nbfs://nbhost/SystemFileSystem/Templates/JSP_Servlet/Servlet.java to edit this template
*/

package com.library.controller.user;

import java.io.IOException;
Expand All @@ -14,61 +13,58 @@
import jakarta.servlet.http.HttpServletResponse;
import com.library.dao.UserDao;
import com.library.dao.UserDaoImpl;
import com.library.exception.AccountHasExistedException;
import com.library.exception.AccountNotExistException;
import com.library.exception.ValidationException;

import com.library.factory.ServiceFactory;
import com.library.service.UserService;
import com.library.util.HashPassword;
import com.library.util.Validator;
import jakarta.servlet.http.HttpSession;


/**
*
* @author hieuchu
* @author hieuchu
*/
@WebServlet(name="RegisterController", urlPatterns={"/user/register"})
@WebServlet(name = "RegisterController", urlPatterns = {"/user/register"})
public class RegisterController extends HttpServlet {
UserDao userDao = new UserDaoImpl();


private final UserService userService = ServiceFactory.getUserService();

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
throws ServletException, IOException {
HttpSession session = request.getSession();
String error = (String) session.getAttribute("error");
request.setAttribute("error", error);
session.removeAttribute("error");
request.getRequestDispatcher("/WEB-INF/views/user/register.jsp").forward(request, response);
}
request.getRequestDispatcher("/WEB-INF/views/user/register.jsp").forward(request, response);
}

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
throws ServletException, IOException {
HttpSession session = request.getSession();
String userName = request.getParameter("username");
String pass = request.getParameter("password");
String account = request.getParameter("account");
if(userName.trim().isEmpty()){
session.setAttribute("error", "Vui lòng nhập họ và tên!");
response.sendRedirect(request.getContextPath() + "/user/register");
return;
}
else if(pass.trim().isEmpty()){
session.setAttribute("error", "Vui lòng nhập mật khẩu!");
response.sendRedirect(request.getContextPath() + "/user/register");
return;
}
else if(account.trim().isEmpty()){
session.setAttribute("error", "Vui lòng nhập tên đăng nhập!");
String account = request.getParameter("account");
try {
Validator.validateUserInput(account, pass);
userService.hasAccountExisted(account);
String hashedPassword = HashPassword.hash(pass);
userService.addUser(userName, account, hashedPassword);
session.setAttribute("success", "Resgiter Done !!!");
response.sendRedirect(request.getContextPath() + "/user/login");
} catch (AccountHasExistedException s) {
session.setAttribute("error", "account has existed !!!");
response.sendRedirect(request.getContextPath() + "/user/register");
return;
}

if(userDao.checkUserExistence(account)){
session.setAttribute("error", "Tên đăng nhập đã được sử dụng!");
} catch (ValidationException s1) {
session.setAttribute("error", s1.getMessage());
response.sendRedirect(request.getContextPath() + "/user/register");
return;
}
else{
String hashedPassword = HashPassword.hash(pass);
userDao.addNewUser(userName, account, hashedPassword);
session.setAttribute("success", "Bạn đã đăng kí thành công!");
response.sendRedirect(request.getContextPath() + "/user/login");
return;

}
}


}
20 changes: 5 additions & 15 deletions src/java/com/library/controller/user/SettingController.java
Original file line number Diff line number Diff line change
Expand Up @@ -33,29 +33,19 @@ public class SettingController extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

HttpSession session = request.getSession(false);
// if (session == null || session.getAttribute("account") == null) {
// response.sendRedirect(request.getContextPath() + "/user/login");
// return;
// }
HttpSession session = request.getSession(false);
String account = (String) session.getAttribute("account");
try {
UserProfileDTO dto = userService.getProfileUserByAccount(account);

UserProfileDTO dto = userService.getProfileUserByAccount(account);
String error = (String) session.getAttribute("changePasswordError");
String success = (String) session.getAttribute("changePasswordSuccess");

String success = (String) session.getAttribute("changePasswordSuccess");
request.setAttribute("error", error);
request.setAttribute("success", success);

request.setAttribute("success", success);
session.removeAttribute("changePasswordError");
session.removeAttribute("changePasswordSuccess");
session.setAttribute("user", dto);

session.setAttribute("user", dto);
request.getRequestDispatcher("/WEB-INF/views/user/setting.jsp").forward(request, response);
return;

} catch (UserNotFoundException u) {
response.sendError(404, "User not found");
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -83,13 +83,13 @@ protected void doPost(HttpServletRequest request, HttpServletResponse response)

boolean checkUpdate = userService.updateProfileUser(account, avatar, fullName, userID);
if (checkUpdate) {
request.setAttribute("isUpdated", "You have updated your profile successfully!");
request.setAttribute("isUpdated", "You have updated your profile successfully!");
session.removeAttribute("user");
u.setNewProfile(fullName, account, avatar);
session.setAttribute("user", u);
activityService.ActivityUser(2, account);
} else {
request.setAttribute("isUpdated", " Failed to update your profile. Please try again!");
request.setAttribute("isUpdated", " Failed to update your profile");
}
request.getRequestDispatcher("/WEB-INF/views/user/setting.jsp").forward(request, response);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,18 +25,14 @@
public class UserDashBoardController extends HttpServlet {

BookDao bookDao = new BookDaoImpl();
BorrowingDao borrowDao = new BorrowingDaoImpl();
BorrowingDao borrowDao = new BorrowingDaoImpl();

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
int totalBook = bookDao.totalBook();
HttpSession session = request.getSession(false); //get available session
HttpSession session = request.getSession(false);

// check if the session is null or if the user has not logged in yet
if(session == null || session.getAttribute("account") == null){
response.sendRedirect(request.getContextPath() + "/user/login");
return ;
}
// take current user account
String account = (String)session.getAttribute("account");

Expand Down
2 changes: 1 addition & 1 deletion src/java/com/library/dao/BookDaoImpl.java
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ public List<Book> getAllBook(){
b.setCoverImage(rs.getString("cover_image"));

Category category = new Category();
category.setCategoryID(rs.getInt("category_ID"));
category.setCategoryID(rs.getInt("category_ID"));
category.setType(BookType.convert(rs.getString("category_name")));
b.setCategory(category);
list.add(b);
Expand Down
2 changes: 1 addition & 1 deletion src/java/com/library/dao/UserDao.java
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ public interface UserDao {

boolean checkUserExistence(String username);

void addNewUser(String username,String account,String password);
boolean addNewUser(String username,String account,String password);

boolean checkAdminLogin(String username,String pass);

Expand Down
6 changes: 4 additions & 2 deletions src/java/com/library/dao/UserDaoImpl.java
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ public boolean checkUserExistence(String username) {
}

@Override
public void addNewUser(String username, String account, String password) {
public boolean addNewUser(String username, String account, String password) {
String sql = "insert into users(fullname, account, password, role, avatar) values (?, ?, ?, ?, ?)";
String role = "user";
String avatar = "ava.jpg";
Expand All @@ -82,10 +82,12 @@ public void addNewUser(String username, String account, String password) {
ps.setString(3, password);
ps.setString(4, role);
ps.setString(5, avatar);
ps.executeUpdate();
int tmp = ps.executeUpdate();
if(tmp > 0 ) return true ;
} catch (SQLException e) {
e.printStackTrace();;
}
return false ;
}

@Override
Expand Down
2 changes: 1 addition & 1 deletion src/java/com/library/dao/UserSessionDao.java
Original file line number Diff line number Diff line change
Expand Up @@ -17,5 +17,5 @@ public interface UserSessionDao {
void updateData(String sessionID , int userID);
String getSessionID(int userID);
public void deleteUserFromSessions(Connection conn, int userId);

List<String> getSessionIDUser();
}
23 changes: 20 additions & 3 deletions src/java/com/library/dao/UserSessionDaoImpl.java
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ public void updateData(String sessionID, int userID) {
public void deleteUserFromSessions(Connection conn, int userId) {
String sql = "DELETE FROM user_sessions WHERE user_id = ?";
try (
PreparedStatement ps = conn.prepareStatement(sql)) {
PreparedStatement ps = conn.prepareStatement(sql)) {
ps.setInt(1, userId);
int tmp = ps.executeUpdate();
} catch (SQLException e) {
Expand All @@ -89,7 +89,24 @@ public void deleteUserFromSessions(Connection conn, int userId) {

}



@Override
public List<String> getSessionIDUser() {
List<String> listSession = new ArrayList<>();
String sql = " SELECT user_sessions.session_id\n"
+ " FROM users\n"
+ " JOIN user_sessions ON user_sessions.user_id = users.user_id\n"
+ " WHERE users.role = 'user' ";

try (
Connection conn = DBConnection.getInstance().getConnection(); PreparedStatement ps = conn.prepareStatement(sql); ResultSet rs = ps.executeQuery();) {
while (rs.next()) {
listSession.add(rs.getString("session_id"));
}
} catch (SQLException e) {
e.printStackTrace();
}

return listSession;
}

}
17 changes: 17 additions & 0 deletions src/java/com/library/exception/AccountHasExistedException.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
/*
* Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
* Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template
*/
package com.library.exception;

/**
*
* @author hieuchu
*/
public class AccountHasExistedException extends LibraryException{

public AccountHasExistedException(String message) {
super(message);
}

}
5 changes: 3 additions & 2 deletions src/java/com/library/factory/ServiceFactory.java
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
* @author hieuchu
*/
public final class ServiceFactory {

private static ActivityService activityService;
private static BookService bookService;
private static BorrowingService borrowService;
Expand Down Expand Up @@ -56,7 +56,7 @@ public static BookService getBookService() {
return bookService;
}

public static BorrowingService getBorrowService() {
public static BorrowingService getBorrowService() {
if (borrowService == null) {
borrowService = new BorrowingService(
DaoFactory.getBorrowingDao(),
Expand Down Expand Up @@ -98,6 +98,7 @@ public static ReturnService getReturnService() {
return returnService;
}


public static TrackingUserService getTrackingUserService() {
if (trackService == null) {
trackService = new TrackingUserService(
Expand Down
4 changes: 2 additions & 2 deletions src/java/com/library/service/ActivityService.java
Original file line number Diff line number Diff line change
Expand Up @@ -64,10 +64,10 @@ public void BookActivityOfUser(String account, int actionID, int bookID) {
String actionName = this.actionDao.getNameByID(actionID);
String detail = "";
if (actionName.equalsIgnoreCase("borrow book")) {
detail = account + "has just borrowed " + getBookTitle(bookID);
detail = account + " has just borrowed " + getBookTitle(bookID);
}
if (actionName.equalsIgnoreCase("return book")) {
detail = account + "has just returned " + getBookTitle(bookID);
detail = account + " has just returned " + getBookTitle(bookID);
}
this.activityDao.insertData(userID, actionID, detail, LocalDateTime.now());

Expand Down
Loading