Skip to content

Commit

Permalink
add and fix the tests
Browse files Browse the repository at this point in the history
  • Loading branch information
ChaimaaeROUAI committed Dec 9, 2024
1 parent abdd2c9 commit b65178d
Show file tree
Hide file tree
Showing 4 changed files with 80 additions and 133 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@
import io.micronaut.session.annotation.SessionValue;
import org.reactivestreams.Publisher;
import reactor.core.publisher.Flux;
import io.micronaut.http.filter.FilterPatternStyle;

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

Expand All @@ -45,10 +45,8 @@
* @author Graeme Rocher
* @since 1.0
*/

@Filter(patternStyle = FilterPatternStyle.REGEX, value = "${http.session.filter.regex-pattern:/.*}")
@Filter("${micronaut.session.filter.exclude-pattern:/**}")
public class HttpSessionFilter implements HttpServerFilter {

/**
* The order of the filter.
*/
Expand All @@ -58,24 +56,24 @@ public class HttpSessionFilter implements HttpServerFilter {
* Constant for Micronaut SESSION attribute.
*/
public static final CharSequence SESSION_ATTRIBUTE = "micronaut.SESSION";
private final HttpSessionFilterConfiguration config;

private final SessionStore<Session> sessionStore;
private final HttpSessionIdResolver[] resolvers;
private final HttpSessionIdEncoder[] encoders;
private final HttpSessionFilterConfiguration configuration;

/**
* Constructor.
*
* @param sessionStore The session store
* @param resolvers The HTTP session id resolvers
* @param encoders The HTTP session id encoders
* @param config the configuration for the HttpSessionFilter
*/
public HttpSessionFilter(SessionStore<Session> sessionStore, HttpSessionIdResolver[] resolvers, HttpSessionIdEncoder[] encoders, HttpSessionFilterConfiguration config) {
public HttpSessionFilter(SessionStore<Session> sessionStore, HttpSessionIdResolver[] resolvers, HttpSessionIdEncoder[] encoders, HttpSessionFilterConfiguration configuration) {
this.sessionStore = sessionStore;
this.resolvers = resolvers;
this.encoders = encoders;
this.config = config;
this.configuration = configuration;
}

@Override
Expand All @@ -85,9 +83,6 @@ public int getOrder() {

@Override
public Publisher<MutableHttpResponse<?>> doFilter(HttpRequest<?> request, ServerFilterChain chain) {
if (!request.getUri().getPath().matches(config.getRegexPattern())) {
return chain.proceed(request);
}
request.setAttribute(HttpSessionFilter.class.getName(), true);
try {
for (HttpSessionIdResolver resolver : resolvers) {
Expand All @@ -96,11 +91,11 @@ public Publisher<MutableHttpResponse<?>> doFilter(HttpRequest<?> request, Server
String id = ids.get(0);
Publisher<Optional<Session>> sessionLookup = Publishers.fromCompletableFuture(() -> sessionStore.findSession(id));
Flux<MutableHttpResponse<?>> storeSessionInAttributes = Flux
.from(sessionLookup)
.switchMap(session -> {
session.ifPresent(entries -> request.getAttributes().put(SESSION_ATTRIBUTE, entries));
return chain.proceed(request);
});
.from(sessionLookup)
.switchMap(session -> {
session.ifPresent(entries -> request.getAttributes().put(SESSION_ATTRIBUTE, entries));
return chain.proceed(request);
});
return encodeSessionId(request, storeSessionInAttributes);
}
}
Expand Down Expand Up @@ -140,7 +135,7 @@ private Publisher<MutableHttpResponse<?>> encodeSessionId(HttpRequest<?> request
if (opt.isPresent()) {
Session session = opt.get();
if (sessionAttr != null) {
session.put(sessionAttr, body.get());
session.put(sessionAttr, body.get());
}

if (session.isNew() || session.isModified()) {
Expand All @@ -151,8 +146,8 @@ private Publisher<MutableHttpResponse<?>> encodeSessionId(HttpRequest<?> request
Session newSession = sessionStore.newSession();
newSession.put(sessionAttr, body.get());
return Flux
.from(Publishers.fromCompletableFuture(() -> sessionStore.save(newSession)))
.map(s -> new SessionAndResponse(Optional.of(s), response));
.from(Publishers.fromCompletableFuture(() -> sessionStore.save(newSession)))
.map(s -> new SessionAndResponse(Optional.of(s), response));
}
return Flux.just(new SessionAndResponse(opt, response));
});
Expand Down
Original file line number Diff line number Diff line change
@@ -1,59 +1,16 @@
/*
* Copyright 2017-2024 original authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.micronaut.session.http;

import io.micronaut.context.annotation.ConfigurationProperties;
import io.micronaut.core.annotation.Internal;

/**
* Configuration properties for the HttpSessionFilter.
*
* This class contains settings for the session filter, including
* a regex pattern to define which paths should have session handling applied.
*/
@Internal
@ConfigurationProperties("http.session.filter")
public class HttpSessionFilterConfiguration {
@ConfigurationProperties("micronaut.session.filter")
public class HttpSessionFilterConfiguration {
private String excludePattern = "/**";

/**
* The regex pattern for filtering paths that should have session handling.
*/
private String regexPattern = "/.*";

/**
* Gets the regex pattern for filtering paths that should have session handling.
*
* Subclasses may override this method to provide a different regex pattern.
* However, care should be taken to ensure that the new pattern remains compatible
* with the intended usage of session handling.
*
* @return The regex pattern for filtering paths.
*/
public String getRegexPattern() {
return regexPattern;
public String getExcludePattern() {
return excludePattern;
}

/**
* Sets the regex pattern for filtering paths that should have session handling.
*
* @param regexPattern The regex pattern to apply for filtering paths.
* Default is "/.*", which matches all paths.
*/
public void setRegexPattern(String regexPattern) {
this.regexPattern = (regexPattern != null) ? regexPattern : "/.*";

public void setExcludePattern(String excludePattern) {
this.excludePattern = excludePattern;
}
}
Original file line number Diff line number Diff line change
@@ -1,35 +1,77 @@

package io.micronaut.session;
import io.micronaut.session.http.HttpSessionFilterConfiguration;


import io.micronaut.context.annotation.Property;
import io.micronaut.session.http.HttpSessionFilterConfiguration;
import io.micronaut.test.extensions.junit5.annotation.MicronautTest;
import jakarta.inject.Inject;
import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assertions.*;

@MicronautTest
class HttpSessionFilterConfigurationTest {

@Inject
HttpSessionFilterConfiguration configuration;

@Test
void testRegexPatternDefault() {
HttpSessionFilterConfiguration config = new HttpSessionFilterConfiguration();
assertEquals("/.*", config.getRegexPattern(), "Default regex pattern should match all paths.");
void testDefaultConfiguration() {
assertEquals("/**", configuration.getExcludePattern(),
"Default exclude pattern should be '/**'");
}

@Test
void testSetRegexPattern() {
HttpSessionFilterConfiguration config = new HttpSessionFilterConfiguration();
config.setRegexPattern("/assets/.*");
assertEquals("/assets/.*", config.getRegexPattern(), "Regex pattern should be updated correctly.");
@Property(name = "micronaut.session.filter.exclude-pattern", value = "/static/**,/public/**")
void testMultipleExclusionPatterns() {
assertEquals("/static/**,/public/**", configuration.getExcludePattern());
assertTrue(matchesExcludePattern("/static/image.jpg"), "Static path should be excluded");
assertTrue(matchesExcludePattern("/public/script.js"), "Public path should be excluded");
assertFalse(matchesExcludePattern("/api/users"), "API path shouldn't be excluded");
assertFalse(matchesExcludePattern("/login"), "Login path shouldn't be excluded");
}

@Test
void testSetRegexPatternToNull() {
HttpSessionFilterConfiguration config = new HttpSessionFilterConfiguration();
config.setRegexPattern(null);
assertEquals("/.*", config.getRegexPattern(), "If set to null, regex pattern should revert to the default.");
@Property(name = "micronaut.session.filter.exclude-pattern", value = "/admin/**")
void testSingleExclusionPattern() {
assertEquals("/admin/**", configuration.getExcludePattern());

assertTrue(matchesExcludePattern("/admin/users"), "Admin path should be excluded");
assertTrue(matchesExcludePattern("/admin/settings"), "Admin path should be excluded");
assertFalse(matchesExcludePattern("/user/profile"), "User path shouldn't be excluded");
}

@Test
void testSetRegexPatternToEmptyString() {
HttpSessionFilterConfiguration config = new HttpSessionFilterConfiguration();
config.setRegexPattern("");
assertEquals("", config.getRegexPattern(), "Regex pattern should accept an empty string if explicitly set.");
@Property(name = "micronaut.session.filter.exclude-pattern", value = "")
void testEmptyExclusionPattern() {
assertEquals("", configuration.getExcludePattern());
assertFalse(matchesExcludePattern("/any/path"), "No path should match empty pattern");
}


private boolean matchesExcludePattern(String path) {
if (configuration.getExcludePattern() == null || configuration.getExcludePattern().isEmpty()) {
return false;
}

String[] patterns = configuration.getExcludePattern().split(",");
for (String pattern : patterns) {
if (pathMatches(pattern.trim(), path)) {
return true;
}
}
return false;
}

private boolean pathMatches(String pattern, String path) {
if (pattern.isEmpty()) {
return false;
}

String regex = "^" + pattern
.replace(".", "\\.")
.replace("**", ".*")
.replace("*", "[^/]*") + "$";
return path.matches(regex);
}
}

This file was deleted.

0 comments on commit b65178d

Please sign in to comment.