<commit_before>package net.davidvoid.thor.lightning.service.security;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import net.davidvoid.thor.lightning.config.RootConfig;
import net.davidvoid.thor.lightning.entity.User;
import net.davidvoid.thor.lightning.exception.AuthenticationException;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Date;

@RunWith(SpringJUnit4ClassRunner.class)
@ActiveProfiles("test")
@ContextConfiguration(classes = { RootConfig.class })
public class JwtAuthenticationServiceTest {

    @Autowired
    JwtAuthenticationService service = new JwtAuthenticationService();

    @Test
    public void getToken_willReturnAValidToken_WichContainsSubjectAndUidAndIssueAtFields() {
        User user = new User();
        user.setName("david");
        user.setPassword("<PASSWORD>");
        user.setId(123);

        String token = service.getToken(user);
        String key = load_key("config/key.hmac");

        Jws<Claims> claims = Jwts.parser().setSigningKey(key).parseClaimsJws(token);
        assertEquals("david", claims.getBody().getSubject());
        assertEquals(123, claims.getBody().get("uid"));
        // the issue time should be no more than 5 seconds before now
        assertTrue((new Date().getTime() - claims.getBody().getIssuedAt().getTime()) < 5000);
    }

    private String load_key(String filename) {
        ClassLoader loader = this.getClass().getClassLoader();

        try (BufferedReader reader = new BufferedReader(new InputStreamReader(loader.getResourceAsStream(filename)))) {
            return reader.readLine();
        } catch (IOException e) {
            throw new RuntimeException("failed to load key");
        }
    }

    @Test
    public void Authenticate_GivenInvalidToken_WillThrow() {
        try {
            service.authenticate("<KEY>");
            fail("should throw");
        } catch (AuthenticationException e) {}
    }

    @Test
    public void Authenticate_GivenValid_WillSuccess() {
        User user = new User();
        user.setName("david");
        user.setId(1);

        String jwtToken = service.getToken(user);
        Authentication auth = service.authenticate(jwtToken);
        assertEquals("david", auth.getName());
        assertEquals("david", auth.getPrincipal());
        assertEquals("", auth.getCredentials());
        assertEquals(1, auth.getAuthorities().size());
        GrantedAuthority role = (GrantedAuthority) auth.getAuthorities().toArray()[0];
        assertEquals("USER", role.toString());
        assertEquals(true, auth.isAuthenticated());
    }

}<commit_msg>add test that the ThorAuthentication will have id field<commit_after>package net.davidvoid.thor.lightning.service.security;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import net.davidvoid.thor.lightning.config.RootConfig;
import net.davidvoid.thor.lightning.entity.User;
import net.davidvoid.thor.lightning.exception.AuthenticationException;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Date;

@RunWith(SpringJUnit4ClassRunner.class)
@ActiveProfiles("test")
@ContextConfiguration(classes = { RootConfig.class })
public class JwtAuthenticationServiceTest {

    @Autowired
    JwtAuthenticationService service = new JwtAuthenticationService();

    @Test
    public void getToken_willReturnAValidToken_WichContainsSubjectAndUidAndIssueAtFields() {
        User user = new User();
        user.setName("david");
        user.setPassword("<PASSWORD>");
        user.setId(123);

        String token = service.getToken(user);
        String key = load_key("config/key.hmac");

        Jws<Claims> claims = Jwts.parser().setSigningKey(key).parseClaimsJws(token);
        assertEquals("david", claims.getBody().getSubject());
        assertEquals(123, claims.getBody().get("uid"));
        // the issue time should be no more than 5 seconds before now
        assertTrue((new Date().getTime() - claims.getBody().getIssuedAt().getTime()) < 5000);
    }

    private String load_key(String filename) {
        ClassLoader loader = this.getClass().getClassLoader();

        try (BufferedReader reader = new BufferedReader(new InputStreamReader(loader.getResourceAsStream(filename)))) {
            return reader.readLine();
        } catch (IOException e) {
            throw new RuntimeException("failed to load key");
        }
    }

    @Test
    public void Authenticate_GivenInvalidToken_WillThrow() {
        try {
            service.authenticate("<KEY>7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ");
            fail("should throw");
        } catch (AuthenticationException e) {}
    }

    @Test
    public void Authenticate_GivenValid_WillSuccess() {
        User user = new User();
        user.setName("david");
        user.setId(1);

        String jwtToken = service.getToken(user);
        ThorAuthentication auth = (ThorAuthentication) service.authenticate(jwtToken);
        assertEquals("david", auth.getName());
        assertEquals("david", auth.getPrincipal());
        assertEquals("", auth.getCredentials());
        assertEquals(1, auth.getAuthorities().size());
        GrantedAuthority role = (GrantedAuthority) auth.getAuthorities().toArray()[0];
        assertEquals("USER", role.toString());
        assertEquals(true, auth.isAuthenticated());
        assertEquals(1, auth.getId());
    }

}
{'fraction_non_alphanumeric': 0.1156060606060606, 'fraction_numerical': 0.006060606060606061, 'mean_word_length': 3.9224459358687547, 'pattern_counts': {'":': 0, '<': 11, '<?xml version=': 0, '>': 9, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2149028', 'n_tokens_mistral': 1866, 'n_tokens_neox': 1820, 'n_words': 343}