package com.tneciv.poseidon.security;

import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

import static java.util.Collections.emptyList;

public class TokenAuthenticationService {

    private static final long EXPIRATIONTIME = 864000000L; // 10 days
    private static final String SECRET = "Poseidon";
    private static final String TOKEN_PREFIX = "Bearer";
    private static final String HEADER_STRING = "Authorization";

    public static void addAuthentication(HttpServletResponse res, String username) {

        String JWT = Jwts.builder()
                .setSubject(username)
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRATIONTIME))
                .signWith(SignatureAlgorithm.HS512, SECRET)
                .compact();

        res.addHeader(HEADER_STRING, TOKEN_PREFIX + " " + JWT);
    }

    public static Authentication getAuthentication(HttpServletRequest request) {

        String token = request.getHeader(HEADER_STRING);

        if (token != null) {
            // parse the token.
            String user = Jwts.parser()
                    .setSigningKey(SECRET)
                    .parseClaimsJws(token.replace(TOKEN_PREFIX, ""))
                    .getBody()
                    .getSubject();

            return user != null ?
                    new UsernamePasswordAuthenticationToken(user, null, emptyList()) :
                    null;
        }
        
        return null;
    }
}
@@ -32,16 +32,68 @@
 urity;%0A%0A
+import com.fasterxml.jackson.databind.ObjectMapper;%0A
 import i
@@ -411,17 +411,71 @@
 ava.
-util.Date
+io.IOException;%0Aimport java.util.Date;%0Aimport java.util.HashMap
 ;%0A%0Ai
@@ -893,18 +893,151 @@
 ername) 
-%7B%0A
+throws IOException %7B%0A        res.setCharacterEncoding(%22UTF-8%22);%0A        res.setContentType(%22application/json; charset=utf-8%22);%0A        
 %0A       
@@ -1044,19 +1044,24 @@
  String 
-JWT
+jwtToken
  = Jwts.
@@ -1278,24 +1278,32 @@
 .compact();%0A
+        
 %0A        res
@@ -1303,61 +1303,285 @@
     
-res.addHeader(HEADER_STRING, TOKEN_PREFIX + %22 %22 + JWT
+ObjectMapper mapper = new ObjectMapper();%0A        HashMap%3CString, String%3E hashMap = new HashMap%3C%3E();%0A        hashMap.put(%22username%22, username);%0A        hashMap.put(%22token%22, jwtToken);%0A        String json = mapper.writeValueAsString(hashMap);%0A        res.getWriter().append(json
 );%0A 
@@ -2163,24 +2163,16 @@
       %7D%0A
-        
 %0A       

return token in res body