Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package startupdemo.controller;
- import java.sql.Connection;
- import java.sql.ResultSet;
- import java.sql.Statement;
- import javax.annotation.Resource;
- import java.util.concurrent.locks.ReentrantLock;
- import org.jboss.logging.Logger;
- import org.springframework.ui.Model;
- import org.springframework.web.bind.annotation.RequestMapping;
- import org.springframework.web.bind.annotation.RequestMethod;
- import org.springframework.web.bind.annotation.RequestParam;
- import org.springframework.web.bind.annotation.RestController;
- import org.springframework.web.servlet.mvc.support.RedirectAttributes;
- import startupdemo.service.MysqlService;
- import startupdemo.service.UserService;
- @RestController
- @RequestMapping("/login")
- public class LoginController
- {
- private static Logger LOG = Logger.getLogger(LoginController.class);
- private static String REDIRECT_PREFIX = "redirect:";
- @Resource(name = "userService")
- private UserService userService;
- @Resource(name = "mysqlService")
- private MysqlService mysqlService;
- private final ReentrantLock lock = new ReentrantLock();
- private String firstname;
- @RequestMapping(method = RequestMethod.GET)
- public String getLoginPage()
- {
- return "login";
- }
- @RequestMapping(method = RequestMethod.POST)
- public String loginUser(@RequestParam(value = "username", required = true) final String username,
- @RequestParam(value = "password", required = true) final String password,
- final Model model, final RedirectAttributes redirectAttributes)
- {
- final boolean loginsuccess = authenticateUser(username, password);
- if (loginsuccess)
- {
- // SUD-14 add customer greeting
- redirectAttributes.addFlashAttribute("message", "Welcome to startupdemo, " + firstname + "!");
- LOG.info("Login successful. Redirecting user to main application.");
- return REDIRECT_PREFIX + "/startupdemo";
- }
- LOG.info("Login failed.");
- model.addAttribute("errorMessage", "Could not login user " + username + ". Invalid username or password.");
- return "login";
- }
- private boolean authenticateUser(final String username, final String password)
- {
- boolean result = false;
- try
- {
- lock.lock();
- final Connection connection = mysqlService.openMysqlConnection();
- final Statement s = connection.createStatement();
- final String q = "SELECT * FROM users WHERE username = '" + username + "' AND password = '" + password + "'";
- final ResultSet rs = s.executeQuery(q);
- if (rs.next())
- {
- result = true;
- userService.setCurrentUser(username);
- firstname = rs.getString("firstname");
- }
- rs.close();
- s.close();
- mysqlService.closeMysqlConnection();
- lock.unlock();
- }
- catch (final Exception e)
- {
- LOG.error("Error happened while authenticating user.");
- }
- return result;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement