Skip to content

Instantly share code, notes, and snippets.

View eldermoraes's full-sized avatar
🤓
Coding

Elder Moraes eldermoraes

🤓
Coding
View GitHub Profile
public class TokenUtils {
public static String generateToken() {
SecureRandom random = new SecureRandom();
long longToken = Math.abs(random.nextLong());
return Long.toString(new Date().getTime()) + Long.toString(longToken, 16);
}
}
public class Auth {
private String login;
private String password;
private Date loginDate;
public Auth() {
}
@ApplicationScoped
public class AuthSession {
private Map<String, Auth> authenticated;
private Map<String, Auth> dataSource;
@PostConstruct
public void init() {
@HEAD
@Path("/{token}")
public Response checkAuthentication(@PathParam("token") String token) {
if (authSession.getAuthenticated().containsKey(token)) {
return Response.ok().build();
}
@POST
@Consumes("application/x-www-form-urlencoded")
public Response login(@FormParam("login") String login, @FormParam("password") String password) {
//If user already logged, then get it token
Optional<String> key = authSession.getToken(login, password);
if (key.isPresent()) {
return Response.ok(key.get()).build();
@Path("auth")
public class AuthenticationResource {
@Inject
private AuthSession authSession;
@POST
@Consumes("application/x-www-form-urlencoded")
public Response login(@FormParam("login") String login, @FormParam("password") String password) {
private JsonObject asJsonObject(Book book, URI bookUri,
URI authorUri) {
return Json.createObjectBuilder()
.add("isbn", book.isbn)
.add("title", book.title)
.add("_links", Json.createObjectBuilder()
.add("self", Json.createObjectBuilder()
.add("href", bookUri.toString()))
.add("author", Json.createObjectBuilder()
.add("href",
URI authorUri = createAuthorResourceUri(book
.authorId, uriInfo);
static URI createAuthorResourceUri(Integer authorId,
UriInfo uriInfo) {
return uriInfo.getBaseUriBuilder()
.path(HateosResource.class)
.path(HateosResource.class, "author")
.path(AuthorResource.class, "author")
.build(authorId);
}
@GET
@Path("/{isbn}")
public Response book(@PathParam("isbn") String isbn) {
Book book = books.get(isbn);
URI bookUri = createBookResourceUri(isbn, uriInfo);
URI authorUri = createAuthorResourceUri(book
.authorId, uriInfo);
return null;
}