Skip to content

Commit

Permalink
add java code to auth example
Browse files Browse the repository at this point in the history
  • Loading branch information
tipsy committed Jan 2, 2024
1 parent 39db901 commit 981c171
Show file tree
Hide file tree
Showing 5 changed files with 116 additions and 0 deletions.
8 changes: 8 additions & 0 deletions javalin6/javalin-auth-example/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,14 @@
<jvmTarget>11</jvmTarget>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>16</source>
<target>16</target>
</configuration>
</plugin>
</plugins>
</build>

Expand Down
35 changes: 35 additions & 0 deletions javalin6/javalin-auth-example/src/main/java/AuthJ.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import io.javalin.http.Context;
import io.javalin.http.Header;
import io.javalin.http.UnauthorizedResponse;

import java.util.List;
import java.util.Map;
import java.util.Optional;

public class AuthJ {

public static void handleAccess(Context ctx) {
var permittedRoles = ctx.routeRoles();
if (permittedRoles.contains(RoleJ.ANYONE)) {
return; // anyone can access
}
if (userRoles(ctx).stream().anyMatch(permittedRoles::contains)) {
return; // user has role required to access
}
ctx.header(Header.WWW_AUTHENTICATE, "Basic");
throw new UnauthorizedResponse();
}

public static List<RoleJ> userRoles(Context ctx) {
return Optional.ofNullable(ctx.basicAuthCredentials())
.map(credentials -> userRolesMap.getOrDefault(new Pair(credentials.getUsername(), credentials.getPassword()), List.of()))
.orElse(List.of());
}

record Pair(String a, String b) {}
private static final Map<Pair, List<RoleJ>> userRolesMap = Map.of(
new Pair("alice", "weak-1234"), List.of(RoleJ.USER_READ),
new Pair("bob", "weak-123456"), List.of(RoleJ.USER_READ, RoleJ.USER_WRITE)
);

}
26 changes: 26 additions & 0 deletions javalin6/javalin-auth-example/src/main/java/Main.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import io.javalin.Javalin;
import static io.javalin.apibuilder.ApiBuilder.*;

public class Main {

public static void main(String[] args) {

Javalin app = Javalin.create(config -> {
config.router.mount(router -> {
router.beforeMatched(AuthJ::handleAccess);
}).apiBuilder(() -> {
get("/", ctx -> ctx.redirect("/users"), RoleJ.ANYONE);
path("users", () -> {
get(UserControllerJ::getAllUserIds, RoleJ.ANYONE);
post(UserControllerJ::createUser, RoleJ.USER_WRITE);
path("{userId}", () -> {
get(UserControllerJ::getUser, RoleJ.USER_READ);
patch(UserControllerJ::updateUser, RoleJ.USER_WRITE);
delete(UserControllerJ::deleteUser, RoleJ.USER_WRITE);
});
});
});
}).start(7070);

}
}
3 changes: 3 additions & 0 deletions javalin6/javalin-auth-example/src/main/java/RoleJ.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import io.javalin.security.RouteRole;

public enum RoleJ implements RouteRole { ANYONE, USER_READ, USER_WRITE }
44 changes: 44 additions & 0 deletions javalin6/javalin-auth-example/src/main/java/UserControllerJ.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import io.javalin.http.Context;
import java.util.*;

public class UserControllerJ {

public record User(String name, String email) {}

private static final Map<String, User> users;

static {
var tempMap = Map.of(
randomId(), new User("Alice", "[email protected]"),
randomId(), new User("Bob", "[email protected]"),
randomId(), new User("Carol", "[email protected]"),
randomId(), new User("Dave", "[email protected]")
);
users = new HashMap<>(tempMap);
}

public static void getAllUserIds(Context ctx) {
ctx.json(users.keySet());
}

public static void createUser(Context ctx) {
users.put(randomId(), ctx.bodyAsClass(User.class));
}

public static void getUser(Context ctx) {
ctx.json(users.get(ctx.pathParam("userId")));
}

public static void updateUser(Context ctx) {
users.put(ctx.pathParam("userId"), ctx.bodyAsClass(User.class));
}

public static void deleteUser(Context ctx) {
users.remove(ctx.pathParam("userId"));
}

private static String randomId() {
return UUID.randomUUID().toString();
}

}

0 comments on commit 981c171

Please sign in to comment.