Skip to content

Instantly share code, notes, and snippets.

@eldermoraes
Created December 13, 2018 15:04
Show Gist options
  • Save eldermoraes/19574225db50991d971858a0dceb768c to your computer and use it in GitHub Desktop.
Save eldermoraes/19574225db50991d971858a0dceb768c to your computer and use it in GitHub Desktop.
@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) {
//If user already logged, then get it token
Optional<String> key = authSession.getToken(login, password);
if (key.isPresent()) {
return Response.ok(key.get()).build();
}
//Validade login and password on data source
if (!authSession.getDataSource().containsKey(login)
|| !authSession.getDataSource()
.get(login)
.getPassword()
.equals(password)) {
return Response.status(Response.Status.UNAUTHORIZED).build();
}
String token = TokenUtils.generateToken();
//Persist the information of authentication on AuthSession
authSession.putAuthenticated(token, new Auth(login, password, new Date()));
return Response.ok(token).build();
}
@HEAD
@Path("/{token}")
public Response checkAuthentication(@PathParam("token") String token) {
if (authSession.getAuthenticated().containsKey(token)) {
return Response.ok().build();
}
return Response.status(Response.Status.UNAUTHORIZED).build();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment