Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.github.sobolewskikamil.soa.service.rest;
- import com.github.sobolewskikamil.soa.persistence.api.remote.LoggedOwnerDao;
- import javax.annotation.security.RolesAllowed;
- import javax.ejb.EJB;
- import javax.servlet.ServletException;
- import javax.servlet.http.HttpServletRequest;
- import javax.ws.rs.*;
- import javax.ws.rs.core.Context;
- import javax.ws.rs.core.MediaType;
- import javax.ws.rs.core.Response;
- import java.sql.Timestamp;
- import java.time.Instant;
- @Consumes(value = {MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
- @Produces(value = {MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
- @Path("auth")
- public class Authentication {
- @EJB(mappedName = "java:global/soa-project-persistence-server/LoggedOwnerDao!com.github.sobolewskikamil.soa.persistence.api.remote.LoggedOwnerDao")
- private LoggedOwnerDao loggedOwnerDao;
- @Context
- private HttpServletRequest httpRequest;
- @POST
- public Response login(Credentials credentials) {
- try {
- String username = credentials.getUsername();
- String password = credentials.getPassword();
- if (loggedOwnerDao.isOwnerLogged(username)) {
- if (shouldTimeoutSession(username, httpRequest.getSession().getMaxInactiveInterval())) {
- loggedOwnerDao.logoutOwner(username);
- } else {
- return Response.status(401).type("text/plain").entity("User is logged in a different session").build();
- }
- }
- httpRequest.login(username, password);
- loggedOwnerDao.logOwnerByName(username, httpRequest.getSession().getId());
- return Response.ok(httpRequest.getSession().getId()).build();
- } catch (ServletException e) {
- return Response.status(401).type("text/plain").entity("Credentials are invalid").build();
- }
- }
- @DELETE
- @RolesAllowed({"Admin", "User"})
- public Response logout() {
- try {
- String login = httpRequest.getUserPrincipal().getName();
- loggedOwnerDao.logoutOwner(login);
- httpRequest.logout();
- return Response.ok().build();
- } catch (ServletException e) {
- return Response.status(500).build();
- }
- }
- private boolean shouldTimeoutSession(String ownerName, int maxInactiveInterval) {
- Timestamp lastRequestTime = loggedOwnerDao.getLastRequestTime(ownerName);
- Timestamp now = Timestamp.from(Instant.now());
- long lastRequestTimeMillis = lastRequestTime.getTime();
- long nowMillis = now.getTime();
- long diffInSeconds = (nowMillis - lastRequestTimeMillis) / 1000;
- return diffInSeconds > maxInactiveInterval;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement