mirror of
https://github.com/scm-manager/scm-manager.git
synced 2025-11-10 07:25:44 +01:00
Merge with 2.0.0-m3
This commit is contained in:
@@ -0,0 +1,26 @@
|
|||||||
|
package sonia.scm.api.v2.resources;
|
||||||
|
|
||||||
|
import java.lang.annotation.Documented;
|
||||||
|
import java.lang.annotation.ElementType;
|
||||||
|
import java.lang.annotation.Retention;
|
||||||
|
import java.lang.annotation.RetentionPolicy;
|
||||||
|
import java.lang.annotation.Target;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Annotation to specify the source of an enricher.
|
||||||
|
*
|
||||||
|
* @author Sebastian Sdorra
|
||||||
|
* @since 2.0.0
|
||||||
|
*/
|
||||||
|
@Documented
|
||||||
|
@Target(ElementType.TYPE)
|
||||||
|
@Retention(RetentionPolicy.RUNTIME)
|
||||||
|
public @interface Enrich {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Source mapping class.
|
||||||
|
*
|
||||||
|
* @return source mapping class
|
||||||
|
*/
|
||||||
|
Class<?> value();
|
||||||
|
}
|
||||||
@@ -3,7 +3,7 @@ package sonia.scm.api.v2.resources;
|
|||||||
import de.otto.edison.hal.HalRepresentation;
|
import de.otto.edison.hal.HalRepresentation;
|
||||||
import org.mapstruct.Mapping;
|
import org.mapstruct.Mapping;
|
||||||
|
|
||||||
public abstract class BaseMapper<T, D extends HalRepresentation> implements InstantAttributeMapper {
|
public abstract class BaseMapper<T, D extends HalRepresentation> extends LinkAppenderMapper implements InstantAttributeMapper {
|
||||||
|
|
||||||
@Mapping(target = "attributes", ignore = true) // We do not map HAL attributes
|
@Mapping(target = "attributes", ignore = true) // We do not map HAL attributes
|
||||||
public abstract D map(T modelObject);
|
public abstract D map(T modelObject);
|
||||||
|
|||||||
10
scm-core/src/main/java/sonia/scm/api/v2/resources/Index.java
Normal file
10
scm-core/src/main/java/sonia/scm/api/v2/resources/Index.java
Normal file
@@ -0,0 +1,10 @@
|
|||||||
|
package sonia.scm.api.v2.resources;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The {@link Index} object can be used to register a {@link LinkEnricher} for the index resource.
|
||||||
|
*
|
||||||
|
* @author Sebastian Sdorra
|
||||||
|
* @since 2.0.0
|
||||||
|
*/
|
||||||
|
public final class Index {
|
||||||
|
}
|
||||||
@@ -0,0 +1,47 @@
|
|||||||
|
package sonia.scm.api.v2.resources;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The {@link LinkAppender} can be used within an {@link LinkEnricher} to append hateoas links to a json response.
|
||||||
|
*
|
||||||
|
* @author Sebastian Sdorra
|
||||||
|
* @since 2.0.0
|
||||||
|
*/
|
||||||
|
public interface LinkAppender {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Appends one link to the json response.
|
||||||
|
*
|
||||||
|
* @param rel name of relation
|
||||||
|
* @param href link uri
|
||||||
|
*/
|
||||||
|
void appendOne(String rel, String href);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Returns a builder which is able to append an array of links to the resource.
|
||||||
|
*
|
||||||
|
* @param rel name of link relation
|
||||||
|
* @return multi link builder
|
||||||
|
*/
|
||||||
|
LinkArrayBuilder arrayBuilder(String rel);
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Builder for link arrays.
|
||||||
|
*/
|
||||||
|
interface LinkArrayBuilder {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Append an link to the array.
|
||||||
|
*
|
||||||
|
* @param name name of link
|
||||||
|
* @param href link target
|
||||||
|
* @return {@code this}
|
||||||
|
*/
|
||||||
|
LinkArrayBuilder append(String name, String href);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Builds the array and appends the it to the json response.
|
||||||
|
*/
|
||||||
|
void build();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
package sonia.scm.api.v2.resources;
|
||||||
|
|
||||||
|
import com.google.common.annotations.VisibleForTesting;
|
||||||
|
|
||||||
|
import javax.inject.Inject;
|
||||||
|
|
||||||
|
public class LinkAppenderMapper {
|
||||||
|
|
||||||
|
@Inject
|
||||||
|
private LinkEnricherRegistry registry;
|
||||||
|
|
||||||
|
@VisibleForTesting
|
||||||
|
void setRegistry(LinkEnricherRegistry registry) {
|
||||||
|
this.registry = registry;
|
||||||
|
}
|
||||||
|
|
||||||
|
protected void appendLinks(LinkAppender appender, Object source, Object... contextEntries) {
|
||||||
|
// null check is only their to not break existing tests
|
||||||
|
if (registry != null) {
|
||||||
|
|
||||||
|
Object[] ctx = new Object[contextEntries.length + 1];
|
||||||
|
ctx[0] = source;
|
||||||
|
for (int i = 0; i < contextEntries.length; i++) {
|
||||||
|
ctx[i + 1] = contextEntries[i];
|
||||||
|
}
|
||||||
|
|
||||||
|
LinkEnricherContext context = LinkEnricherContext.of(ctx);
|
||||||
|
|
||||||
|
Iterable<LinkEnricher> enrichers = registry.allByType(source.getClass());
|
||||||
|
for (LinkEnricher enricher : enrichers) {
|
||||||
|
enricher.enrich(context, appender);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
package sonia.scm.api.v2.resources;
|
||||||
|
|
||||||
|
import sonia.scm.plugin.ExtensionPoint;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A {@link LinkEnricher} can be used to append hateoas links to a specific json response.
|
||||||
|
* To register an enricher use the {@link Enrich} annotation or the {@link LinkEnricherRegistry} which is available
|
||||||
|
* via injection.
|
||||||
|
*
|
||||||
|
* <b>Warning:</b> enrichers are always registered as singletons.
|
||||||
|
*
|
||||||
|
* @author Sebastian Sdorra
|
||||||
|
* @since 2.0.0
|
||||||
|
*/
|
||||||
|
@ExtensionPoint
|
||||||
|
@FunctionalInterface
|
||||||
|
public interface LinkEnricher {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Enriches the response with hateoas links.
|
||||||
|
*
|
||||||
|
* @param context contains the source for the json mapping and related objects
|
||||||
|
* @param appender can be used to append links to the json response
|
||||||
|
*/
|
||||||
|
void enrich(LinkEnricherContext context, LinkAppender appender);
|
||||||
|
}
|
||||||
@@ -0,0 +1,72 @@
|
|||||||
|
package sonia.scm.api.v2.resources;
|
||||||
|
|
||||||
|
import com.google.common.collect.ImmutableMap;
|
||||||
|
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.NoSuchElementException;
|
||||||
|
import java.util.Optional;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Context object for the {@link LinkEnricher}. The context holds the source object for the json and all related
|
||||||
|
* objects, which can be useful for the link creation.
|
||||||
|
*
|
||||||
|
* @author Sebastian Sdorra
|
||||||
|
* @since 2.0.0
|
||||||
|
*/
|
||||||
|
public final class LinkEnricherContext {
|
||||||
|
|
||||||
|
private final Map<Class, Object> instanceMap;
|
||||||
|
|
||||||
|
private LinkEnricherContext(Map<Class,Object> instanceMap) {
|
||||||
|
this.instanceMap = instanceMap;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Creates a context with the given entries
|
||||||
|
*
|
||||||
|
* @param instances entries of the context
|
||||||
|
*
|
||||||
|
* @return context of given entries
|
||||||
|
*/
|
||||||
|
public static LinkEnricherContext of(Object... instances) {
|
||||||
|
ImmutableMap.Builder<Class, Object> builder = ImmutableMap.builder();
|
||||||
|
for (Object instance : instances) {
|
||||||
|
builder.put(instance.getClass(), instance);
|
||||||
|
}
|
||||||
|
return new LinkEnricherContext(builder.build());
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Returns the registered object from the context. The method will return an empty optional, if no object with the
|
||||||
|
* given type was registered.
|
||||||
|
*
|
||||||
|
* @param type type of instance
|
||||||
|
* @param <T> type of instance
|
||||||
|
* @return optional instance
|
||||||
|
*/
|
||||||
|
public <T> Optional<T> oneByType(Class<T> type) {
|
||||||
|
Object instance = instanceMap.get(type);
|
||||||
|
if (instance != null) {
|
||||||
|
return Optional.of(type.cast(instance));
|
||||||
|
}
|
||||||
|
return Optional.empty();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Returns the registered object from the context, but throws an {@link NoSuchElementException} if the type was not
|
||||||
|
* registered.
|
||||||
|
*
|
||||||
|
* @param type type of instance
|
||||||
|
* @param <T> type of instance
|
||||||
|
* @return instance
|
||||||
|
*/
|
||||||
|
public <T> T oneRequireByType(Class<T> type) {
|
||||||
|
Optional<T> instance = oneByType(type);
|
||||||
|
if (instance.isPresent()) {
|
||||||
|
return instance.get();
|
||||||
|
} else {
|
||||||
|
throw new NoSuchElementException("No instance for given type present");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
package sonia.scm.api.v2.resources;
|
||||||
|
|
||||||
|
import com.google.common.collect.HashMultimap;
|
||||||
|
import com.google.common.collect.Multimap;
|
||||||
|
import sonia.scm.plugin.Extension;
|
||||||
|
|
||||||
|
import javax.inject.Singleton;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The {@link LinkEnricherRegistry} is responsible for binding {@link LinkEnricher} instances to their source types.
|
||||||
|
*
|
||||||
|
* @author Sebastian Sdorra
|
||||||
|
* @since 2.0.0
|
||||||
|
*/
|
||||||
|
@Extension
|
||||||
|
@Singleton
|
||||||
|
public final class LinkEnricherRegistry {
|
||||||
|
|
||||||
|
private final Multimap<Class, LinkEnricher> enrichers = HashMultimap.create();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Registers a new {@link LinkEnricher} for the given source type.
|
||||||
|
*
|
||||||
|
* @param sourceType type of json mapping source
|
||||||
|
* @param enricher link enricher instance
|
||||||
|
*/
|
||||||
|
public void register(Class sourceType, LinkEnricher enricher) {
|
||||||
|
enrichers.put(sourceType, enricher);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Returns all registered {@link LinkEnricher} for the given type.
|
||||||
|
*
|
||||||
|
* @param sourceType type of json mapping source
|
||||||
|
* @return all registered enrichers
|
||||||
|
*/
|
||||||
|
public Iterable<LinkEnricher> allByType(Class sourceType) {
|
||||||
|
return enrichers.get(sourceType);
|
||||||
|
}
|
||||||
|
}
|
||||||
10
scm-core/src/main/java/sonia/scm/api/v2/resources/Me.java
Normal file
10
scm-core/src/main/java/sonia/scm/api/v2/resources/Me.java
Normal file
@@ -0,0 +1,10 @@
|
|||||||
|
package sonia.scm.api.v2.resources;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The {@link Me} object can be used to register a {@link LinkEnricher} for the me resource.
|
||||||
|
*
|
||||||
|
* @author Sebastian Sdorra
|
||||||
|
* @since 2.0.0
|
||||||
|
*/
|
||||||
|
public final class Me {
|
||||||
|
}
|
||||||
@@ -30,26 +30,25 @@
|
|||||||
*/
|
*/
|
||||||
package sonia.scm.security;
|
package sonia.scm.security;
|
||||||
|
|
||||||
import java.util.Map;
|
|
||||||
import sonia.scm.plugin.ExtensionPoint;
|
import sonia.scm.plugin.ExtensionPoint;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Validates the claims of a jwt token. The validator is called durring authentication
|
* Validates an {@link AccessToken}. The validator is called during authentication
|
||||||
* with a jwt token.
|
* with an {@link AccessToken}.
|
||||||
*
|
*
|
||||||
* @author Sebastian Sdorra
|
* @author Sebastian Sdorra
|
||||||
* @since 2.0.0
|
* @since 2.0.0
|
||||||
*/
|
*/
|
||||||
@ExtensionPoint
|
@ExtensionPoint
|
||||||
public interface TokenClaimsValidator {
|
public interface AccessTokenValidator {
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Returns {@code true} if the claims is valid. If the token is not valid and the
|
* Returns {@code true} if the {@link AccessToken} is valid. If the token is not valid and the
|
||||||
* method returns {@code false}, the authentication is treated as failed.
|
* method returns {@code false}, the authentication is treated as failed.
|
||||||
*
|
*
|
||||||
* @param claims token claims
|
* @param token the access token to verify
|
||||||
*
|
*
|
||||||
* @return {@code true} if the claims is valid
|
* @return {@code true} if the token is valid
|
||||||
*/
|
*/
|
||||||
boolean validate(Map<String, Object> claims);
|
boolean validate(AccessToken token);
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,74 @@
|
|||||||
|
package sonia.scm.api.v2.resources;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.BeforeEach;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.junit.jupiter.api.extension.ExtendWith;
|
||||||
|
import org.mockito.Mock;
|
||||||
|
import org.mockito.junit.jupiter.MockitoExtension;
|
||||||
|
|
||||||
|
import java.util.Optional;
|
||||||
|
|
||||||
|
import static org.mockito.Mockito.verify;
|
||||||
|
|
||||||
|
@ExtendWith(MockitoExtension.class)
|
||||||
|
class LinkAppenderMapperTest {
|
||||||
|
|
||||||
|
@Mock
|
||||||
|
private LinkAppender appender;
|
||||||
|
|
||||||
|
private LinkEnricherRegistry registry;
|
||||||
|
private LinkAppenderMapper mapper;
|
||||||
|
|
||||||
|
@BeforeEach
|
||||||
|
void beforeEach() {
|
||||||
|
registry = new LinkEnricherRegistry();
|
||||||
|
mapper = new LinkAppenderMapper();
|
||||||
|
mapper.setRegistry(registry);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void shouldAppendSimpleLink() {
|
||||||
|
registry.register(String.class, (ctx, appender) -> appender.appendOne("42", "https://hitchhiker.com"));
|
||||||
|
|
||||||
|
mapper.appendLinks(appender, "hello");
|
||||||
|
|
||||||
|
verify(appender).appendOne("42", "https://hitchhiker.com");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void shouldCallMultipleEnrichers() {
|
||||||
|
registry.register(String.class, (ctx, appender) -> appender.appendOne("42", "https://hitchhiker.com"));
|
||||||
|
registry.register(String.class, (ctx, appender) -> appender.appendOne("21", "https://scm.hitchhiker.com"));
|
||||||
|
|
||||||
|
mapper.appendLinks(appender, "hello");
|
||||||
|
|
||||||
|
verify(appender).appendOne("42", "https://hitchhiker.com");
|
||||||
|
verify(appender).appendOne("21", "https://scm.hitchhiker.com");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void shouldAppendLinkByUsingSourceFromContext() {
|
||||||
|
registry.register(String.class, (ctx, appender) -> {
|
||||||
|
Optional<String> rel = ctx.oneByType(String.class);
|
||||||
|
appender.appendOne(rel.get(), "https://hitchhiker.com");
|
||||||
|
});
|
||||||
|
|
||||||
|
mapper.appendLinks(appender, "42");
|
||||||
|
|
||||||
|
verify(appender).appendOne("42", "https://hitchhiker.com");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void shouldAppendLinkByUsingMultipleContextEntries() {
|
||||||
|
registry.register(Integer.class, (ctx, appender) -> {
|
||||||
|
Optional<Integer> rel = ctx.oneByType(Integer.class);
|
||||||
|
Optional<String> href = ctx.oneByType(String.class);
|
||||||
|
appender.appendOne(String.valueOf(rel.get()), href.get());
|
||||||
|
});
|
||||||
|
|
||||||
|
mapper.appendLinks(appender, Integer.valueOf(42), "https://hitchhiker.com");
|
||||||
|
|
||||||
|
verify(appender).appendOne("42", "https://hitchhiker.com");
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
package sonia.scm.api.v2.resources;
|
||||||
|
|
||||||
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
import java.util.NoSuchElementException;
|
||||||
|
|
||||||
|
class LinkEnricherContextTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void shouldCreateContextFromSingleObject() {
|
||||||
|
LinkEnricherContext context = LinkEnricherContext.of("hello");
|
||||||
|
assertThat(context.oneByType(String.class)).contains("hello");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void shouldCreateContextFromMultipleObjects() {
|
||||||
|
LinkEnricherContext context = LinkEnricherContext.of("hello", Integer.valueOf(42), Long.valueOf(21L));
|
||||||
|
assertThat(context.oneByType(String.class)).contains("hello");
|
||||||
|
assertThat(context.oneByType(Integer.class)).contains(42);
|
||||||
|
assertThat(context.oneByType(Long.class)).contains(21L);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void shouldReturnEmptyOptionalForUnknownTypes() {
|
||||||
|
LinkEnricherContext context = LinkEnricherContext.of();
|
||||||
|
assertThat(context.oneByType(String.class)).isNotPresent();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void shouldReturnRequiredObject() {
|
||||||
|
LinkEnricherContext context = LinkEnricherContext.of("hello");
|
||||||
|
assertThat(context.oneRequireByType(String.class)).isEqualTo("hello");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void shouldThrowAnNoSuchElementExceptionForUnknownTypes() {
|
||||||
|
LinkEnricherContext context = LinkEnricherContext.of();
|
||||||
|
assertThrows(NoSuchElementException.class, () -> context.oneRequireByType(String.class));
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -0,0 +1,60 @@
|
|||||||
|
package sonia.scm.api.v2.resources;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.BeforeEach;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
|
||||||
|
class LinkEnricherRegistryTest {
|
||||||
|
|
||||||
|
private LinkEnricherRegistry registry;
|
||||||
|
|
||||||
|
@BeforeEach
|
||||||
|
void setUpObjectUnderTest() {
|
||||||
|
registry = new LinkEnricherRegistry();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void shouldRegisterTheEnricher() {
|
||||||
|
SampleLinkEnricher enricher = new SampleLinkEnricher();
|
||||||
|
registry.register(String.class, enricher);
|
||||||
|
|
||||||
|
Iterable<LinkEnricher> enrichers = registry.allByType(String.class);
|
||||||
|
assertThat(enrichers).containsOnly(enricher);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void shouldRegisterMultipleEnrichers() {
|
||||||
|
SampleLinkEnricher one = new SampleLinkEnricher();
|
||||||
|
registry.register(String.class, one);
|
||||||
|
|
||||||
|
SampleLinkEnricher two = new SampleLinkEnricher();
|
||||||
|
registry.register(String.class, two);
|
||||||
|
|
||||||
|
Iterable<LinkEnricher> enrichers = registry.allByType(String.class);
|
||||||
|
assertThat(enrichers).containsOnly(one, two);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void shouldRegisterEnrichersForDifferentTypes() {
|
||||||
|
SampleLinkEnricher one = new SampleLinkEnricher();
|
||||||
|
registry.register(String.class, one);
|
||||||
|
|
||||||
|
SampleLinkEnricher two = new SampleLinkEnricher();
|
||||||
|
registry.register(Integer.class, two);
|
||||||
|
|
||||||
|
Iterable<LinkEnricher> enrichers = registry.allByType(String.class);
|
||||||
|
assertThat(enrichers).containsOnly(one);
|
||||||
|
|
||||||
|
enrichers = registry.allByType(Integer.class);
|
||||||
|
assertThat(enrichers).containsOnly(two);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static class SampleLinkEnricher implements LinkEnricher {
|
||||||
|
@Override
|
||||||
|
public void enrich(LinkEnricherContext context, LinkAppender appender) {
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -2,12 +2,7 @@
|
|||||||
import React from "react";
|
import React from "react";
|
||||||
import { translate } from "react-i18next";
|
import { translate } from "react-i18next";
|
||||||
import type { Links } from "@scm-manager/ui-types";
|
import type { Links } from "@scm-manager/ui-types";
|
||||||
import {
|
import { apiClient, SubmitButton, Loading, ErrorNotification } from "../";
|
||||||
apiClient,
|
|
||||||
SubmitButton,
|
|
||||||
Loading,
|
|
||||||
ErrorNotification
|
|
||||||
} from "../";
|
|
||||||
|
|
||||||
type RenderProps = {
|
type RenderProps = {
|
||||||
readOnly: boolean,
|
readOnly: boolean,
|
||||||
@@ -20,10 +15,10 @@ type Props = {
|
|||||||
render: (props: RenderProps) => any, // ???
|
render: (props: RenderProps) => any, // ???
|
||||||
|
|
||||||
// context props
|
// context props
|
||||||
t: (string) => string
|
t: string => string
|
||||||
};
|
};
|
||||||
|
|
||||||
type ConfigurationType = {
|
type ConfigurationType = {
|
||||||
_links: Links
|
_links: Links
|
||||||
} & Object;
|
} & Object;
|
||||||
|
|
||||||
@@ -32,6 +27,7 @@ type State = {
|
|||||||
fetching: boolean,
|
fetching: boolean,
|
||||||
modifying: boolean,
|
modifying: boolean,
|
||||||
contentType?: string,
|
contentType?: string,
|
||||||
|
configChanged: boolean,
|
||||||
|
|
||||||
configuration?: ConfigurationType,
|
configuration?: ConfigurationType,
|
||||||
modifiedConfiguration?: ConfigurationType,
|
modifiedConfiguration?: ConfigurationType,
|
||||||
@@ -43,12 +39,12 @@ type State = {
|
|||||||
* synchronizing the configuration with the backend.
|
* synchronizing the configuration with the backend.
|
||||||
*/
|
*/
|
||||||
class Configuration extends React.Component<Props, State> {
|
class Configuration extends React.Component<Props, State> {
|
||||||
|
|
||||||
constructor(props: Props) {
|
constructor(props: Props) {
|
||||||
super(props);
|
super(props);
|
||||||
this.state = {
|
this.state = {
|
||||||
fetching: true,
|
fetching: true,
|
||||||
modifying: false,
|
modifying: false,
|
||||||
|
configChanged: false,
|
||||||
valid: false
|
valid: false
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@@ -56,7 +52,8 @@ class Configuration extends React.Component<Props, State> {
|
|||||||
componentDidMount() {
|
componentDidMount() {
|
||||||
const { link } = this.props;
|
const { link } = this.props;
|
||||||
|
|
||||||
apiClient.get(link)
|
apiClient
|
||||||
|
.get(link)
|
||||||
.then(this.captureContentType)
|
.then(this.captureContentType)
|
||||||
.then(response => response.json())
|
.then(response => response.json())
|
||||||
.then(this.loadConfig)
|
.then(this.loadConfig)
|
||||||
@@ -119,19 +116,39 @@ class Configuration extends React.Component<Props, State> {
|
|||||||
|
|
||||||
this.setState({ modifying: true });
|
this.setState({ modifying: true });
|
||||||
|
|
||||||
const {modifiedConfiguration} = this.state;
|
const { modifiedConfiguration } = this.state;
|
||||||
|
|
||||||
apiClient.put(this.getModificationUrl(), modifiedConfiguration, this.getContentType())
|
apiClient
|
||||||
.then(() => this.setState({ modifying: false }))
|
.put(
|
||||||
|
this.getModificationUrl(),
|
||||||
|
modifiedConfiguration,
|
||||||
|
this.getContentType()
|
||||||
|
)
|
||||||
|
.then(() => this.setState({ modifying: false, configChanged: true, valid: false }))
|
||||||
.catch(this.handleError);
|
.catch(this.handleError);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
renderConfigChangedNotification = () => {
|
||||||
|
if (this.state.configChanged) {
|
||||||
|
return (
|
||||||
|
<div className="notification is-primary">
|
||||||
|
<button
|
||||||
|
className="delete"
|
||||||
|
onClick={() => this.setState({ configChanged: false })}
|
||||||
|
/>
|
||||||
|
{this.props.t("config-form.submit-success-notification")}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
};
|
||||||
|
|
||||||
render() {
|
render() {
|
||||||
const { t } = this.props;
|
const { t } = this.props;
|
||||||
const { fetching, error, configuration, modifying, valid } = this.state;
|
const { fetching, error, configuration, modifying, valid } = this.state;
|
||||||
|
|
||||||
if (error) {
|
if (error) {
|
||||||
return <ErrorNotification error={error}/>;
|
return <ErrorNotification error={error} />;
|
||||||
} else if (fetching || !configuration) {
|
} else if (fetching || !configuration) {
|
||||||
return <Loading />;
|
return <Loading />;
|
||||||
} else {
|
} else {
|
||||||
@@ -144,19 +161,21 @@ class Configuration extends React.Component<Props, State> {
|
|||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<form onSubmit={this.modifyConfiguration}>
|
<>
|
||||||
{ this.props.render(renderProps) }
|
{this.renderConfigChangedNotification()}
|
||||||
<hr/>
|
<form onSubmit={this.modifyConfiguration}>
|
||||||
<SubmitButton
|
{this.props.render(renderProps)}
|
||||||
label={t("config-form.submit")}
|
<hr />
|
||||||
disabled={!valid || readOnly}
|
<SubmitButton
|
||||||
loading={modifying}
|
label={t("config-form.submit")}
|
||||||
/>
|
disabled={!valid || readOnly}
|
||||||
</form>
|
loading={modifying}
|
||||||
|
/>
|
||||||
|
</form>
|
||||||
|
</>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export default translate("config")(Configuration);
|
export default translate("config")(Configuration);
|
||||||
|
|||||||
@@ -7,17 +7,19 @@ type Props = {
|
|||||||
options: string[],
|
options: string[],
|
||||||
optionSelected: string => void,
|
optionSelected: string => void,
|
||||||
preselectedOption?: string,
|
preselectedOption?: string,
|
||||||
className: any
|
className: any,
|
||||||
|
disabled?: boolean
|
||||||
};
|
};
|
||||||
|
|
||||||
class DropDown extends React.Component<Props> {
|
class DropDown extends React.Component<Props> {
|
||||||
render() {
|
render() {
|
||||||
const { options, preselectedOption, className } = this.props;
|
const { options, preselectedOption, className, disabled } = this.props;
|
||||||
return (
|
return (
|
||||||
<div className={classNames(className, "select")}>
|
<div className={classNames(className, "select")}>
|
||||||
<select
|
<select
|
||||||
value={preselectedOption ? preselectedOption : ""}
|
value={preselectedOption ? preselectedOption : ""}
|
||||||
onChange={this.change}
|
onChange={this.change}
|
||||||
|
disabled={disabled}
|
||||||
>
|
>
|
||||||
<option key="" />
|
<option key="" />
|
||||||
{options.map(option => {
|
{options.map(option => {
|
||||||
|
|||||||
@@ -2,60 +2,81 @@
|
|||||||
import React from "react";
|
import React from "react";
|
||||||
import { translate } from "react-i18next";
|
import { translate } from "react-i18next";
|
||||||
import PrimaryNavigationLink from "./PrimaryNavigationLink";
|
import PrimaryNavigationLink from "./PrimaryNavigationLink";
|
||||||
|
import type { Links } from "@scm-manager/ui-types";
|
||||||
|
import { binder, ExtensionPoint } from "@scm-manager/ui-extensions";
|
||||||
|
|
||||||
type Props = {
|
type Props = {
|
||||||
t: string => string,
|
t: string => string,
|
||||||
repositoriesLink: string,
|
links: Links,
|
||||||
usersLink: string,
|
|
||||||
groupsLink: string,
|
|
||||||
configLink: string,
|
|
||||||
logoutLink: string
|
|
||||||
};
|
};
|
||||||
|
|
||||||
class PrimaryNavigation extends React.Component<Props> {
|
class PrimaryNavigation extends React.Component<Props> {
|
||||||
render() {
|
|
||||||
const { t, repositoriesLink, usersLink, groupsLink, configLink, logoutLink } = this.props;
|
|
||||||
|
|
||||||
const links = [
|
createNavigationAppender = (navigationItems) => {
|
||||||
repositoriesLink ? (
|
const { t, links } = this.props;
|
||||||
<PrimaryNavigationLink
|
|
||||||
to="/repos"
|
return (to: string, match: string, label: string, linkName: string) => {
|
||||||
match="/(repo|repos)"
|
const link = links[linkName];
|
||||||
label={t("primary-navigation.repositories")}
|
if (link) {
|
||||||
key={"repositoriesLink"}
|
const navigationItem = (
|
||||||
/>): null,
|
<PrimaryNavigationLink
|
||||||
usersLink ? (
|
to={to}
|
||||||
<PrimaryNavigationLink
|
match={match}
|
||||||
to="/users"
|
label={t(label)}
|
||||||
match="/(user|users)"
|
key={linkName}
|
||||||
label={t("primary-navigation.users")}
|
/>)
|
||||||
key={"usersLink"}
|
;
|
||||||
/>) : null,
|
navigationItems.push(navigationItem);
|
||||||
groupsLink ? (
|
}
|
||||||
<PrimaryNavigationLink
|
};
|
||||||
to="/groups"
|
};
|
||||||
match="/(group|groups)"
|
|
||||||
label={t("primary-navigation.groups")}
|
appendLogout = (navigationItems, append) => {
|
||||||
key={"groupsLink"}
|
const { t, links } = this.props;
|
||||||
/>) : null,
|
|
||||||
configLink ? (
|
const props = {
|
||||||
<PrimaryNavigationLink
|
links,
|
||||||
to="/config"
|
label: t("primary-navigation.logout")
|
||||||
label={t("primary-navigation.config")}
|
};
|
||||||
key={"configLink"}
|
|
||||||
/>) : null,
|
if (binder.hasExtension("primary-navigation.logout", props)) {
|
||||||
logoutLink ? (
|
navigationItems.push(
|
||||||
<PrimaryNavigationLink
|
<ExtensionPoint name="primary-navigation.logout" props={props} />
|
||||||
to="/logout"
|
);
|
||||||
label={t("primary-navigation.logout")}
|
} else {
|
||||||
key={"logoutLink"}
|
append("/logout", "/logout", "primary-navigation.logout", "logout");
|
||||||
/>) : null
|
}
|
||||||
];
|
};
|
||||||
|
|
||||||
|
createNavigationItems = () => {
|
||||||
|
const navigationItems = [];
|
||||||
|
|
||||||
|
const append = this.createNavigationAppender(navigationItems);
|
||||||
|
append("/repos", "/(repo|repos)", "primary-navigation.repositories", "repositories");
|
||||||
|
append("/users", "/(user|users)", "primary-navigation.users", "users");
|
||||||
|
append("/groups", "/(group|groups)", "primary-navigation.groups", "groups");
|
||||||
|
append("/config", "/config", "primary-navigation.config", "config");
|
||||||
|
|
||||||
|
navigationItems.push(
|
||||||
|
<ExtensionPoint
|
||||||
|
name="primary-navigation"
|
||||||
|
renderAll={true}
|
||||||
|
props={{links: this.props.links}}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
|
||||||
|
this.appendLogout(navigationItems, append);
|
||||||
|
|
||||||
|
return navigationItems;
|
||||||
|
};
|
||||||
|
|
||||||
|
render() {
|
||||||
|
const navigationItems = this.createNavigationItems();
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<nav className="tabs is-boxed">
|
<nav className="tabs is-boxed">
|
||||||
<ul>
|
<ul>
|
||||||
{links}
|
{navigationItems}
|
||||||
</ul>
|
</ul>
|
||||||
</nav>
|
</nav>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -22,7 +22,8 @@
|
|||||||
"error-notification": {
|
"error-notification": {
|
||||||
"prefix": "Error",
|
"prefix": "Error",
|
||||||
"loginLink": "You can login here again.",
|
"loginLink": "You can login here again.",
|
||||||
"timeout": "The session has expired."
|
"timeout": "The session has expired.",
|
||||||
|
"wrong-login-credentials": "Invalid credentials"
|
||||||
},
|
},
|
||||||
"loading": {
|
"loading": {
|
||||||
"alt": "Loading ..."
|
"alt": "Loading ..."
|
||||||
|
|||||||
@@ -10,6 +10,7 @@
|
|||||||
},
|
},
|
||||||
"config-form": {
|
"config-form": {
|
||||||
"submit": "Submit",
|
"submit": "Submit",
|
||||||
|
"submit-success-notification": "Configuration changed successfully!",
|
||||||
"no-permission-notification": "Please note: You do not have the permission to edit the config!"
|
"no-permission-notification": "Please note: You do not have the permission to edit the config!"
|
||||||
},
|
},
|
||||||
"proxy-settings": {
|
"proxy-settings": {
|
||||||
|
|||||||
@@ -23,7 +23,8 @@ type State = {
|
|||||||
error: {
|
error: {
|
||||||
loginAttemptLimitTimeout: boolean,
|
loginAttemptLimitTimeout: boolean,
|
||||||
loginAttemptLimit: boolean
|
loginAttemptLimit: boolean
|
||||||
}
|
},
|
||||||
|
changed: boolean
|
||||||
};
|
};
|
||||||
|
|
||||||
class ConfigForm extends React.Component<Props, State> {
|
class ConfigForm extends React.Component<Props, State> {
|
||||||
@@ -59,7 +60,8 @@ class ConfigForm extends React.Component<Props, State> {
|
|||||||
error: {
|
error: {
|
||||||
loginAttemptLimitTimeout: false,
|
loginAttemptLimitTimeout: false,
|
||||||
loginAttemptLimit: false
|
loginAttemptLimit: false
|
||||||
}
|
},
|
||||||
|
changed: false
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -75,6 +77,9 @@ class ConfigForm extends React.Component<Props, State> {
|
|||||||
|
|
||||||
submit = (event: Event) => {
|
submit = (event: Event) => {
|
||||||
event.preventDefault();
|
event.preventDefault();
|
||||||
|
this.setState({
|
||||||
|
changed: false
|
||||||
|
});
|
||||||
this.props.submitForm(this.state.config);
|
this.props.submitForm(this.state.config);
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -156,7 +161,9 @@ class ConfigForm extends React.Component<Props, State> {
|
|||||||
<SubmitButton
|
<SubmitButton
|
||||||
loading={loading}
|
loading={loading}
|
||||||
label={t("config-form.submit")}
|
label={t("config-form.submit")}
|
||||||
disabled={!configUpdatePermission || this.hasError()}
|
disabled={
|
||||||
|
!configUpdatePermission || this.hasError() || !this.state.changed
|
||||||
|
}
|
||||||
/>
|
/>
|
||||||
</form>
|
</form>
|
||||||
);
|
);
|
||||||
@@ -172,7 +179,8 @@ class ConfigForm extends React.Component<Props, State> {
|
|||||||
error: {
|
error: {
|
||||||
...this.state.error,
|
...this.state.error,
|
||||||
[name]: !isValid
|
[name]: !isValid
|
||||||
}
|
},
|
||||||
|
changed: true
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -34,7 +34,19 @@ type Props = {
|
|||||||
t: string => string
|
t: string => string
|
||||||
};
|
};
|
||||||
|
|
||||||
class GlobalConfig extends React.Component<Props> {
|
type State = {
|
||||||
|
configChanged: boolean
|
||||||
|
};
|
||||||
|
|
||||||
|
class GlobalConfig extends React.Component<Props, State> {
|
||||||
|
constructor(props: Props) {
|
||||||
|
super(props);
|
||||||
|
|
||||||
|
this.state = {
|
||||||
|
configChanged: false
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
componentDidMount() {
|
componentDidMount() {
|
||||||
this.props.configReset();
|
this.props.configReset();
|
||||||
this.props.fetchConfig(this.props.configLink);
|
this.props.fetchConfig(this.props.configLink);
|
||||||
@@ -42,6 +54,22 @@ class GlobalConfig extends React.Component<Props> {
|
|||||||
|
|
||||||
modifyConfig = (config: Config) => {
|
modifyConfig = (config: Config) => {
|
||||||
this.props.modifyConfig(config);
|
this.props.modifyConfig(config);
|
||||||
|
this.setState({ configChanged: true });
|
||||||
|
};
|
||||||
|
|
||||||
|
renderConfigChangedNotification = () => {
|
||||||
|
if (this.state.configChanged) {
|
||||||
|
return (
|
||||||
|
<div className="notification is-primary">
|
||||||
|
<button
|
||||||
|
className="delete"
|
||||||
|
onClick={() => this.setState({ configChanged: false })}
|
||||||
|
/>
|
||||||
|
{this.props.t("config-form.submit-success-notification")}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return null;
|
||||||
};
|
};
|
||||||
|
|
||||||
render() {
|
render() {
|
||||||
@@ -64,6 +92,7 @@ class GlobalConfig extends React.Component<Props> {
|
|||||||
return (
|
return (
|
||||||
<div>
|
<div>
|
||||||
<Title title={t("global-config.title")} />
|
<Title title={t("global-config.title")} />
|
||||||
|
{this.renderConfigChangedNotification()}
|
||||||
<ConfigForm
|
<ConfigForm
|
||||||
submitForm={config => this.modifyConfig(config)}
|
submitForm={config => this.modifyConfig(config)}
|
||||||
config={config}
|
config={config}
|
||||||
|
|||||||
@@ -19,15 +19,11 @@ import {
|
|||||||
Footer,
|
Footer,
|
||||||
Header
|
Header
|
||||||
} from "@scm-manager/ui-components";
|
} from "@scm-manager/ui-components";
|
||||||
import type { Me } from "@scm-manager/ui-types";
|
import type { Links, Me } from "@scm-manager/ui-types";
|
||||||
import {
|
import {
|
||||||
getConfigLink,
|
|
||||||
getFetchIndexResourcesFailure,
|
getFetchIndexResourcesFailure,
|
||||||
getGroupsLink,
|
getLinks,
|
||||||
getLogoutLink,
|
|
||||||
getMeLink,
|
getMeLink,
|
||||||
getRepositoriesLink,
|
|
||||||
getUsersLink,
|
|
||||||
isFetchIndexResourcesPending
|
isFetchIndexResourcesPending
|
||||||
} from "../modules/indexResource";
|
} from "../modules/indexResource";
|
||||||
|
|
||||||
@@ -36,11 +32,7 @@ type Props = {
|
|||||||
authenticated: boolean,
|
authenticated: boolean,
|
||||||
error: Error,
|
error: Error,
|
||||||
loading: boolean,
|
loading: boolean,
|
||||||
repositoriesLink: string,
|
links: Links,
|
||||||
usersLink: string,
|
|
||||||
groupsLink: string,
|
|
||||||
configLink: string,
|
|
||||||
logoutLink: string,
|
|
||||||
meLink: string,
|
meLink: string,
|
||||||
|
|
||||||
// dispatcher functions
|
// dispatcher functions
|
||||||
@@ -63,22 +55,14 @@ class App extends Component<Props> {
|
|||||||
loading,
|
loading,
|
||||||
error,
|
error,
|
||||||
authenticated,
|
authenticated,
|
||||||
t,
|
links,
|
||||||
repositoriesLink,
|
t
|
||||||
usersLink,
|
|
||||||
groupsLink,
|
|
||||||
configLink,
|
|
||||||
logoutLink
|
|
||||||
} = this.props;
|
} = this.props;
|
||||||
|
|
||||||
let content;
|
let content;
|
||||||
const navigation = authenticated ? (
|
const navigation = authenticated ? (
|
||||||
<PrimaryNavigation
|
<PrimaryNavigation
|
||||||
repositoriesLink={repositoriesLink}
|
links={links}
|
||||||
usersLink={usersLink}
|
|
||||||
groupsLink={groupsLink}
|
|
||||||
configLink={configLink}
|
|
||||||
logoutLink={logoutLink}
|
|
||||||
/>
|
/>
|
||||||
) : (
|
) : (
|
||||||
""
|
""
|
||||||
@@ -95,7 +79,7 @@ class App extends Component<Props> {
|
|||||||
/>
|
/>
|
||||||
);
|
);
|
||||||
} else {
|
} else {
|
||||||
content = <Main authenticated={authenticated} />;
|
content = <Main authenticated={authenticated} links={links} />;
|
||||||
}
|
}
|
||||||
return (
|
return (
|
||||||
<div className="App">
|
<div className="App">
|
||||||
@@ -120,22 +104,14 @@ const mapStateToProps = state => {
|
|||||||
isFetchMePending(state) || isFetchIndexResourcesPending(state);
|
isFetchMePending(state) || isFetchIndexResourcesPending(state);
|
||||||
const error =
|
const error =
|
||||||
getFetchMeFailure(state) || getFetchIndexResourcesFailure(state);
|
getFetchMeFailure(state) || getFetchIndexResourcesFailure(state);
|
||||||
const repositoriesLink = getRepositoriesLink(state);
|
const links = getLinks(state);
|
||||||
const usersLink = getUsersLink(state);
|
|
||||||
const groupsLink = getGroupsLink(state);
|
|
||||||
const configLink = getConfigLink(state);
|
|
||||||
const logoutLink = getLogoutLink(state);
|
|
||||||
const meLink = getMeLink(state);
|
const meLink = getMeLink(state);
|
||||||
return {
|
return {
|
||||||
authenticated,
|
authenticated,
|
||||||
me,
|
me,
|
||||||
loading,
|
loading,
|
||||||
error,
|
error,
|
||||||
repositoriesLink,
|
links,
|
||||||
usersLink,
|
|
||||||
groupsLink,
|
|
||||||
configLink,
|
|
||||||
logoutLink,
|
|
||||||
meLink
|
meLink
|
||||||
};
|
};
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -15,7 +15,8 @@ import {
|
|||||||
InputField,
|
InputField,
|
||||||
SubmitButton,
|
SubmitButton,
|
||||||
ErrorNotification,
|
ErrorNotification,
|
||||||
Image
|
Image,
|
||||||
|
UNAUTHORIZED_ERROR
|
||||||
} from "@scm-manager/ui-components";
|
} from "@scm-manager/ui-components";
|
||||||
import classNames from "classnames";
|
import classNames from "classnames";
|
||||||
import { getLoginLink } from "../modules/indexResource";
|
import { getLoginLink } from "../modules/indexResource";
|
||||||
@@ -92,13 +93,22 @@ class Login extends React.Component<Props, State> {
|
|||||||
return !this.isValid();
|
return !this.isValid();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
areCredentialsInvalid() {
|
||||||
|
const { t, error } = this.props;
|
||||||
|
if (error === UNAUTHORIZED_ERROR) {
|
||||||
|
return new Error(t("error-notification.wrong-login-credentials"));
|
||||||
|
} else {
|
||||||
|
return error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
renderRedirect = () => {
|
renderRedirect = () => {
|
||||||
const { from } = this.props.location.state || { from: { pathname: "/" } };
|
const { from } = this.props.location.state || { from: { pathname: "/" } };
|
||||||
return <Redirect to={from} />;
|
return <Redirect to={from} />;
|
||||||
};
|
};
|
||||||
|
|
||||||
render() {
|
render() {
|
||||||
const { authenticated, loading, error, t, classes } = this.props;
|
const { authenticated, loading, t, classes } = this.props;
|
||||||
|
|
||||||
if (authenticated) {
|
if (authenticated) {
|
||||||
return this.renderRedirect();
|
return this.renderRedirect();
|
||||||
@@ -119,7 +129,7 @@ class Login extends React.Component<Props, State> {
|
|||||||
alt={t("login.logo-alt")}
|
alt={t("login.logo-alt")}
|
||||||
/>
|
/>
|
||||||
</figure>
|
</figure>
|
||||||
<ErrorNotification error={error} />
|
<ErrorNotification error={this.areCredentialsInvalid()} />
|
||||||
<form onSubmit={this.handleSubmit}>
|
<form onSubmit={this.handleSubmit}>
|
||||||
<InputField
|
<InputField
|
||||||
placeholder={t("login.username-placeholder")}
|
placeholder={t("login.username-placeholder")}
|
||||||
|
|||||||
@@ -2,6 +2,7 @@
|
|||||||
import React from "react";
|
import React from "react";
|
||||||
|
|
||||||
import { Redirect, Route, Switch, withRouter } from "react-router-dom";
|
import { Redirect, Route, Switch, withRouter } from "react-router-dom";
|
||||||
|
import type {Links} from "@scm-manager/ui-types";
|
||||||
|
|
||||||
import Overview from "../repos/containers/Overview";
|
import Overview from "../repos/containers/Overview";
|
||||||
import Users from "../users/containers/Users";
|
import Users from "../users/containers/Users";
|
||||||
@@ -9,6 +10,8 @@ import Login from "../containers/Login";
|
|||||||
import Logout from "../containers/Logout";
|
import Logout from "../containers/Logout";
|
||||||
|
|
||||||
import { ProtectedRoute } from "@scm-manager/ui-components";
|
import { ProtectedRoute } from "@scm-manager/ui-components";
|
||||||
|
import { ExtensionPoint } from "@scm-manager/ui-extensions";
|
||||||
|
|
||||||
import AddUser from "../users/containers/AddUser";
|
import AddUser from "../users/containers/AddUser";
|
||||||
import SingleUser from "../users/containers/SingleUser";
|
import SingleUser from "../users/containers/SingleUser";
|
||||||
import RepositoryRoot from "../repos/containers/RepositoryRoot";
|
import RepositoryRoot from "../repos/containers/RepositoryRoot";
|
||||||
@@ -22,12 +25,13 @@ import Config from "../config/containers/Config";
|
|||||||
import Profile from "./Profile";
|
import Profile from "./Profile";
|
||||||
|
|
||||||
type Props = {
|
type Props = {
|
||||||
authenticated?: boolean
|
authenticated?: boolean,
|
||||||
|
links: Links
|
||||||
};
|
};
|
||||||
|
|
||||||
class Main extends React.Component<Props> {
|
class Main extends React.Component<Props> {
|
||||||
render() {
|
render() {
|
||||||
const { authenticated } = this.props;
|
const { authenticated, links } = this.props;
|
||||||
return (
|
return (
|
||||||
<div className="main">
|
<div className="main">
|
||||||
<Switch>
|
<Switch>
|
||||||
@@ -112,6 +116,12 @@ class Main extends React.Component<Props> {
|
|||||||
component={Profile}
|
component={Profile}
|
||||||
authenticated={authenticated}
|
authenticated={authenticated}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
|
<ExtensionPoint
|
||||||
|
name="main.route"
|
||||||
|
renderAll={true}
|
||||||
|
props={{authenticated, links}}
|
||||||
|
/>
|
||||||
</Switch>
|
</Switch>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -12,11 +12,12 @@ import {
|
|||||||
ChangesetDiff,
|
ChangesetDiff,
|
||||||
AvatarWrapper,
|
AvatarWrapper,
|
||||||
AvatarImage,
|
AvatarImage,
|
||||||
changesets,
|
changesets
|
||||||
} from "@scm-manager/ui-components";
|
} from "@scm-manager/ui-components";
|
||||||
|
|
||||||
import classNames from "classnames";
|
import classNames from "classnames";
|
||||||
import type { Tag } from "@scm-manager/ui-types";
|
import type { Tag } from "@scm-manager/ui-types";
|
||||||
|
import { ExtensionPoint } from "@scm-manager/ui-extensions";
|
||||||
|
|
||||||
const styles = {
|
const styles = {
|
||||||
spacing: {
|
spacing: {
|
||||||
@@ -38,9 +39,9 @@ class ChangesetDetails extends React.Component<Props> {
|
|||||||
const description = changesets.parseDescription(changeset.description);
|
const description = changesets.parseDescription(changeset.description);
|
||||||
|
|
||||||
const id = (
|
const id = (
|
||||||
<ChangesetId repository={repository} changeset={changeset} link={false}/>
|
<ChangesetId repository={repository} changeset={changeset} link={false} />
|
||||||
);
|
);
|
||||||
const date = <DateFromNow date={changeset.date}/>;
|
const date = <DateFromNow date={changeset.date} />;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div>
|
<div>
|
||||||
@@ -54,7 +55,7 @@ class ChangesetDetails extends React.Component<Props> {
|
|||||||
</AvatarWrapper>
|
</AvatarWrapper>
|
||||||
<div className="media-content">
|
<div className="media-content">
|
||||||
<p>
|
<p>
|
||||||
<ChangesetAuthor changeset={changeset}/>
|
<ChangesetAuthor changeset={changeset} />
|
||||||
</p>
|
</p>
|
||||||
<p>
|
<p>
|
||||||
<Interpolate
|
<Interpolate
|
||||||
@@ -66,16 +67,22 @@ class ChangesetDetails extends React.Component<Props> {
|
|||||||
</div>
|
</div>
|
||||||
<div className="media-right">{this.renderTags()}</div>
|
<div className="media-right">{this.renderTags()}</div>
|
||||||
</article>
|
</article>
|
||||||
<p>
|
<ExtensionPoint
|
||||||
{description.message.split("\n").map((item, key) => {
|
name="changesets.changeset.description"
|
||||||
return (
|
props={{ changeset, description }}
|
||||||
<span key={key}>
|
renderAll={true}
|
||||||
{item}
|
>
|
||||||
<br/>
|
<p>
|
||||||
</span>
|
{description.message.split("\n").map((item, key) => {
|
||||||
);
|
return (
|
||||||
})}
|
<span key={key}>
|
||||||
</p>
|
{item}
|
||||||
|
<br />
|
||||||
|
</span>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</p>
|
||||||
|
</ExtensionPoint>
|
||||||
</div>
|
</div>
|
||||||
<div>
|
<div>
|
||||||
<ChangesetDiff changeset={changeset} />
|
<ChangesetDiff changeset={changeset} />
|
||||||
@@ -95,7 +102,7 @@ class ChangesetDetails extends React.Component<Props> {
|
|||||||
return (
|
return (
|
||||||
<div className="level-item">
|
<div className="level-item">
|
||||||
{tags.map((tag: Tag) => {
|
{tags.map((tag: Tag) => {
|
||||||
return <ChangesetTag key={tag.name} tag={tag}/>;
|
return <ChangesetTag key={tag.name} tag={tag} />;
|
||||||
})}
|
})}
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -9,7 +9,12 @@ import classNames from "classnames";
|
|||||||
import RepositoryAvatar from "./RepositoryAvatar";
|
import RepositoryAvatar from "./RepositoryAvatar";
|
||||||
|
|
||||||
const styles = {
|
const styles = {
|
||||||
overlay: {
|
overlayFullColumn: {
|
||||||
|
position: "absolute",
|
||||||
|
height: "calc(120px - 0.5rem)",
|
||||||
|
width: "calc(100% - 1.5rem)"
|
||||||
|
},
|
||||||
|
overlayHalfColumn: {
|
||||||
position: "absolute",
|
position: "absolute",
|
||||||
height: "calc(120px - 1.5rem)",
|
height: "calc(120px - 1.5rem)",
|
||||||
width: "calc(50% - 3rem)"
|
width: "calc(50% - 3rem)"
|
||||||
@@ -80,6 +85,9 @@ class RepositoryEntry extends React.Component<Props> {
|
|||||||
const { repository, classes, fullColumnWidth } = this.props;
|
const { repository, classes, fullColumnWidth } = this.props;
|
||||||
const repositoryLink = this.createLink(repository);
|
const repositoryLink = this.createLink(repository);
|
||||||
const halfColumn = fullColumnWidth ? "is-full" : "is-half";
|
const halfColumn = fullColumnWidth ? "is-full" : "is-half";
|
||||||
|
const overlayLinkClass = fullColumnWidth
|
||||||
|
? classes.overlayFullColumn
|
||||||
|
: classes.overlayHalfColumn;
|
||||||
return (
|
return (
|
||||||
<div
|
<div
|
||||||
className={classNames(
|
className={classNames(
|
||||||
@@ -90,12 +98,12 @@ class RepositoryEntry extends React.Component<Props> {
|
|||||||
halfColumn
|
halfColumn
|
||||||
)}
|
)}
|
||||||
>
|
>
|
||||||
<Link className={classNames(classes.overlay)} to={repositoryLink} />
|
<Link className={classNames(overlayLinkClass)} to={repositoryLink} />
|
||||||
<article className={classNames("media", classes.inner)}>
|
<article className={classNames("media", classes.inner)}>
|
||||||
<figure className={classNames(classes.centerImage, "media-left")}>
|
<figure className={classNames(classes.centerImage, "media-left")}>
|
||||||
<RepositoryAvatar repository={repository} />
|
<RepositoryAvatar repository={repository} />
|
||||||
</figure>
|
</figure>
|
||||||
<div className="media-content">
|
<div className={classNames("media-content", "text-box")}>
|
||||||
<div className="content">
|
<div className="content">
|
||||||
<p className="is-marginless">
|
<p className="is-marginless">
|
||||||
<strong>{repository.name}</strong>
|
<strong>{repository.name}</strong>
|
||||||
|
|||||||
@@ -92,8 +92,8 @@ export default function reducer(
|
|||||||
): any {
|
): any {
|
||||||
if (action.itemId && action.type === FETCH_SOURCES_SUCCESS) {
|
if (action.itemId && action.type === FETCH_SOURCES_SUCCESS) {
|
||||||
return {
|
return {
|
||||||
[action.itemId]: action.payload,
|
...state,
|
||||||
...state
|
[action.itemId]: action.payload
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
return state;
|
return state;
|
||||||
|
|||||||
@@ -112,14 +112,12 @@ $fa-font-path: "webfonts";
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
.media {
|
.text-box {
|
||||||
.media-content {
|
width: calc(50% - 0.75rem);
|
||||||
width: calc(50% - 0.75rem);
|
.shorten-text {
|
||||||
.shorten-text {
|
overflow: hidden;
|
||||||
overflow: hidden;
|
text-overflow: ellipsis;
|
||||||
text-overflow: ellipsis;
|
white-space: nowrap;
|
||||||
white-space: nowrap;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -4,10 +4,8 @@ import org.slf4j.Logger;
|
|||||||
import org.slf4j.LoggerFactory;
|
import org.slf4j.LoggerFactory;
|
||||||
import org.slf4j.MDC;
|
import org.slf4j.MDC;
|
||||||
import sonia.scm.api.v2.resources.ErrorDto;
|
import sonia.scm.api.v2.resources.ErrorDto;
|
||||||
import sonia.scm.api.v2.resources.ExceptionWithContextToErrorDtoMapper;
|
|
||||||
import sonia.scm.web.VndMediaType;
|
import sonia.scm.web.VndMediaType;
|
||||||
|
|
||||||
import javax.inject.Inject;
|
|
||||||
import javax.ws.rs.core.Response;
|
import javax.ws.rs.core.Response;
|
||||||
import javax.ws.rs.ext.ExceptionMapper;
|
import javax.ws.rs.ext.ExceptionMapper;
|
||||||
import javax.ws.rs.ext.Provider;
|
import javax.ws.rs.ext.Provider;
|
||||||
@@ -20,16 +18,9 @@ public class FallbackExceptionMapper implements ExceptionMapper<Exception> {
|
|||||||
|
|
||||||
private static final String ERROR_CODE = "CmR8GCJb31";
|
private static final String ERROR_CODE = "CmR8GCJb31";
|
||||||
|
|
||||||
private final ExceptionWithContextToErrorDtoMapper mapper;
|
|
||||||
|
|
||||||
@Inject
|
|
||||||
public FallbackExceptionMapper(ExceptionWithContextToErrorDtoMapper mapper) {
|
|
||||||
this.mapper = mapper;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public Response toResponse(Exception exception) {
|
public Response toResponse(Exception exception) {
|
||||||
logger.debug("map {} to status code 500", exception);
|
logger.warn("mapping unexpected {} to status code 500", exception.getClass().getName(), exception);
|
||||||
ErrorDto errorDto = new ErrorDto();
|
ErrorDto errorDto = new ErrorDto();
|
||||||
errorDto.setMessage("internal server error");
|
errorDto.setMessage("internal server error");
|
||||||
errorDto.setContext(Collections.emptyList());
|
errorDto.setContext(Collections.emptyList());
|
||||||
|
|||||||
@@ -0,0 +1,35 @@
|
|||||||
|
package sonia.scm.api;
|
||||||
|
|
||||||
|
import org.slf4j.Logger;
|
||||||
|
import org.slf4j.LoggerFactory;
|
||||||
|
import org.slf4j.MDC;
|
||||||
|
import sonia.scm.api.v2.resources.ErrorDto;
|
||||||
|
import sonia.scm.web.VndMediaType;
|
||||||
|
|
||||||
|
import javax.ws.rs.NotFoundException;
|
||||||
|
import javax.ws.rs.core.Response;
|
||||||
|
import javax.ws.rs.ext.ExceptionMapper;
|
||||||
|
import javax.ws.rs.ext.Provider;
|
||||||
|
import java.util.Collections;
|
||||||
|
|
||||||
|
@Provider
|
||||||
|
public class JaxNotFoundExceptionMapper implements ExceptionMapper<NotFoundException> {
|
||||||
|
|
||||||
|
private static final Logger logger = LoggerFactory.getLogger(JaxNotFoundExceptionMapper.class);
|
||||||
|
|
||||||
|
private static final String ERROR_CODE = "92RCCCMHO1";
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Response toResponse(NotFoundException exception) {
|
||||||
|
logger.debug(exception.getMessage());
|
||||||
|
ErrorDto errorDto = new ErrorDto();
|
||||||
|
errorDto.setMessage("path not found");
|
||||||
|
errorDto.setContext(Collections.emptyList());
|
||||||
|
errorDto.setErrorCode(ERROR_CODE);
|
||||||
|
errorDto.setTransactionId(MDC.get("transaction_id"));
|
||||||
|
return Response.status(Response.Status.NOT_FOUND)
|
||||||
|
.entity(errorDto)
|
||||||
|
.type(VndMediaType.ERROR_TYPE)
|
||||||
|
.build();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
package sonia.scm.api;
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.core.JsonParseException;
|
||||||
|
import org.slf4j.Logger;
|
||||||
|
import org.slf4j.LoggerFactory;
|
||||||
|
import org.slf4j.MDC;
|
||||||
|
import sonia.scm.api.v2.resources.ErrorDto;
|
||||||
|
import sonia.scm.web.VndMediaType;
|
||||||
|
|
||||||
|
import javax.ws.rs.core.Response;
|
||||||
|
import javax.ws.rs.ext.ExceptionMapper;
|
||||||
|
import javax.ws.rs.ext.Provider;
|
||||||
|
import java.util.Collections;
|
||||||
|
|
||||||
|
@Provider
|
||||||
|
public class JsonParseExceptionMapper implements ExceptionMapper<JsonParseException> {
|
||||||
|
|
||||||
|
private static final Logger logger = LoggerFactory.getLogger(JsonParseExceptionMapper.class);
|
||||||
|
|
||||||
|
private static final String ERROR_CODE = "2VRCrvpL71";
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Response toResponse(JsonParseException exception) {
|
||||||
|
logger.trace("got illegal json: {}", exception.getMessage());
|
||||||
|
ErrorDto errorDto = new ErrorDto();
|
||||||
|
errorDto.setMessage("illegal json content: " + exception.getMessage());
|
||||||
|
errorDto.setContext(Collections.emptyList());
|
||||||
|
errorDto.setErrorCode(ERROR_CODE);
|
||||||
|
errorDto.setTransactionId(MDC.get("transaction_id"));
|
||||||
|
return Response.status(Response.Status.BAD_REQUEST)
|
||||||
|
.entity(errorDto)
|
||||||
|
.type(VndMediaType.ERROR_TYPE)
|
||||||
|
.build();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -15,7 +15,7 @@ import static de.otto.edison.hal.Link.linkBuilder;
|
|||||||
import static de.otto.edison.hal.Links.linkingTo;
|
import static de.otto.edison.hal.Links.linkingTo;
|
||||||
|
|
||||||
@Mapper
|
@Mapper
|
||||||
public abstract class BranchToBranchDtoMapper {
|
public abstract class BranchToBranchDtoMapper extends LinkAppenderMapper {
|
||||||
|
|
||||||
@Inject
|
@Inject
|
||||||
private ResourceLinks resourceLinks;
|
private ResourceLinks resourceLinks;
|
||||||
@@ -24,12 +24,15 @@ public abstract class BranchToBranchDtoMapper {
|
|||||||
public abstract BranchDto map(Branch branch, @Context NamespaceAndName namespaceAndName);
|
public abstract BranchDto map(Branch branch, @Context NamespaceAndName namespaceAndName);
|
||||||
|
|
||||||
@AfterMapping
|
@AfterMapping
|
||||||
void appendLinks(@MappingTarget BranchDto target, @Context NamespaceAndName namespaceAndName) {
|
void appendLinks(Branch source, @MappingTarget BranchDto target, @Context NamespaceAndName namespaceAndName) {
|
||||||
Links.Builder linksBuilder = linkingTo()
|
Links.Builder linksBuilder = linkingTo()
|
||||||
.self(resourceLinks.branch().self(namespaceAndName, target.getName()))
|
.self(resourceLinks.branch().self(namespaceAndName, target.getName()))
|
||||||
.single(linkBuilder("history", resourceLinks.branch().history(namespaceAndName, target.getName())).build())
|
.single(linkBuilder("history", resourceLinks.branch().history(namespaceAndName, target.getName())).build())
|
||||||
.single(linkBuilder("changeset", resourceLinks.changeset().changeset(namespaceAndName.getNamespace(), namespaceAndName.getName(), target.getRevision())).build())
|
.single(linkBuilder("changeset", resourceLinks.changeset().changeset(namespaceAndName.getNamespace(), namespaceAndName.getName(), target.getRevision())).build())
|
||||||
.single(linkBuilder("source", resourceLinks.source().self(namespaceAndName.getNamespace(), namespaceAndName.getName(), target.getRevision())).build());
|
.single(linkBuilder("source", resourceLinks.source().self(namespaceAndName.getNamespace(), namespaceAndName.getName(), target.getRevision())).build());
|
||||||
|
|
||||||
|
appendLinks(new EdisonLinkAppender(linksBuilder), source, namespaceAndName);
|
||||||
|
|
||||||
target.add(linksBuilder.build());
|
target.add(linksBuilder.build());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -23,7 +23,7 @@ import static de.otto.edison.hal.Link.link;
|
|||||||
import static de.otto.edison.hal.Links.linkingTo;
|
import static de.otto.edison.hal.Links.linkingTo;
|
||||||
|
|
||||||
@Mapper
|
@Mapper
|
||||||
public abstract class ChangesetToChangesetDtoMapper implements InstantAttributeMapper {
|
public abstract class ChangesetToChangesetDtoMapper extends LinkAppenderMapper implements InstantAttributeMapper {
|
||||||
|
|
||||||
@Inject
|
@Inject
|
||||||
private RepositoryServiceFactory serviceFactory;
|
private RepositoryServiceFactory serviceFactory;
|
||||||
@@ -67,6 +67,9 @@ public abstract class ChangesetToChangesetDtoMapper implements InstantAttributeM
|
|||||||
.self(resourceLinks.changeset().self(repository.getNamespace(), repository.getName(), target.getId()))
|
.self(resourceLinks.changeset().self(repository.getNamespace(), repository.getName(), target.getId()))
|
||||||
.single(link("diff", resourceLinks.diff().self(namespace, name, target.getId())))
|
.single(link("diff", resourceLinks.diff().self(namespace, name, target.getId())))
|
||||||
.single(link("modifications", resourceLinks.modifications().self(namespace, name, target.getId())));
|
.single(link("modifications", resourceLinks.modifications().self(namespace, name, target.getId())));
|
||||||
|
|
||||||
|
appendLinks(new EdisonLinkAppender(linksBuilder), source, repository);
|
||||||
|
|
||||||
target.add(linksBuilder.build());
|
target.add(linksBuilder.build());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,49 @@
|
|||||||
|
package sonia.scm.api.v2.resources;
|
||||||
|
|
||||||
|
import de.otto.edison.hal.Link;
|
||||||
|
import de.otto.edison.hal.Links;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
class EdisonLinkAppender implements LinkAppender {
|
||||||
|
|
||||||
|
private final Links.Builder builder;
|
||||||
|
|
||||||
|
EdisonLinkAppender(Links.Builder builder) {
|
||||||
|
this.builder = builder;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void appendOne(String rel, String href) {
|
||||||
|
builder.single(Link.link(rel, href));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public LinkArrayBuilder arrayBuilder(String rel) {
|
||||||
|
return new EdisonLinkArrayBuilder(builder, rel);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static class EdisonLinkArrayBuilder implements LinkArrayBuilder {
|
||||||
|
|
||||||
|
private final Links.Builder builder;
|
||||||
|
private final String rel;
|
||||||
|
private final List<Link> linkArray = new ArrayList<>();
|
||||||
|
|
||||||
|
private EdisonLinkArrayBuilder(Links.Builder builder, String rel) {
|
||||||
|
this.builder = builder;
|
||||||
|
this.rel = rel;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public LinkArrayBuilder append(String name, String href) {
|
||||||
|
linkArray.add(Link.linkBuilder(rel, href).withName(name).build());
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void build() {
|
||||||
|
builder.array(linkArray);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -18,7 +18,7 @@ import java.util.stream.Collectors;
|
|||||||
import static de.otto.edison.hal.Link.link;
|
import static de.otto.edison.hal.Link.link;
|
||||||
|
|
||||||
@Mapper
|
@Mapper
|
||||||
public abstract class FileObjectToFileObjectDtoMapper implements InstantAttributeMapper {
|
public abstract class FileObjectToFileObjectDtoMapper extends LinkAppenderMapper implements InstantAttributeMapper {
|
||||||
|
|
||||||
@Inject
|
@Inject
|
||||||
private ResourceLinks resourceLinks;
|
private ResourceLinks resourceLinks;
|
||||||
@@ -39,6 +39,8 @@ public abstract class FileObjectToFileObjectDtoMapper implements InstantAttribut
|
|||||||
links.single(link("history", resourceLinks.fileHistory().self(namespaceAndName.getNamespace(), namespaceAndName.getName(), revision, path)));
|
links.single(link("history", resourceLinks.fileHistory().self(namespaceAndName.getNamespace(), namespaceAndName.getName(), revision, path)));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
appendLinks(new EdisonLinkAppender(links), fileObject, namespaceAndName, revision);
|
||||||
|
|
||||||
dto.add(links.build());
|
dto.add(links.build());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -31,6 +31,9 @@ public abstract class GroupToGroupDtoMapper extends BaseMapper<Group, GroupDto>
|
|||||||
if (GroupPermissions.modify(group).isPermitted()) {
|
if (GroupPermissions.modify(group).isPermitted()) {
|
||||||
linksBuilder.single(link("update", resourceLinks.group().update(target.getName())));
|
linksBuilder.single(link("update", resourceLinks.group().update(target.getName())));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
appendLinks(new EdisonLinkAppender(linksBuilder), group);
|
||||||
|
|
||||||
target.add(linksBuilder.build());
|
target.add(linksBuilder.build());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -14,7 +14,7 @@ import java.util.List;
|
|||||||
|
|
||||||
import static de.otto.edison.hal.Link.link;
|
import static de.otto.edison.hal.Link.link;
|
||||||
|
|
||||||
public class IndexDtoGenerator {
|
public class IndexDtoGenerator extends LinkAppenderMapper {
|
||||||
|
|
||||||
private final ResourceLinks resourceLinks;
|
private final ResourceLinks resourceLinks;
|
||||||
private final SCMContextProvider scmContextProvider;
|
private final SCMContextProvider scmContextProvider;
|
||||||
@@ -56,6 +56,8 @@ public class IndexDtoGenerator {
|
|||||||
builder.single(link("login", resourceLinks.authentication().jsonLogin()));
|
builder.single(link("login", resourceLinks.authentication().jsonLogin()));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
appendLinks(new EdisonLinkAppender(builder), new Index());
|
||||||
|
|
||||||
return new IndexDto(scmContextProvider.getVersion(), builder.build());
|
return new IndexDto(scmContextProvider.getVersion(), builder.build());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,45 @@
|
|||||||
|
package sonia.scm.api.v2.resources;
|
||||||
|
|
||||||
|
import org.slf4j.Logger;
|
||||||
|
import org.slf4j.LoggerFactory;
|
||||||
|
import sonia.scm.plugin.Extension;
|
||||||
|
|
||||||
|
import javax.inject.Inject;
|
||||||
|
import javax.servlet.ServletContextEvent;
|
||||||
|
import javax.servlet.ServletContextListener;
|
||||||
|
import java.util.Set;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Registers every {@link LinkEnricher} which is annotated with an {@link Enrich} annotation.
|
||||||
|
*/
|
||||||
|
@Extension
|
||||||
|
public class LinkEnricherAutoRegistration implements ServletContextListener {
|
||||||
|
|
||||||
|
private static final Logger LOG = LoggerFactory.getLogger(LinkEnricherAutoRegistration.class);
|
||||||
|
|
||||||
|
private final LinkEnricherRegistry registry;
|
||||||
|
private final Set<LinkEnricher> enrichers;
|
||||||
|
|
||||||
|
@Inject
|
||||||
|
public LinkEnricherAutoRegistration(LinkEnricherRegistry registry, Set<LinkEnricher> enrichers) {
|
||||||
|
this.registry = registry;
|
||||||
|
this.enrichers = enrichers;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void contextInitialized(ServletContextEvent sce) {
|
||||||
|
for (LinkEnricher enricher : enrichers) {
|
||||||
|
Enrich annotation = enricher.getClass().getAnnotation(Enrich.class);
|
||||||
|
if (annotation != null) {
|
||||||
|
registry.register(annotation.value(), enricher);
|
||||||
|
} else {
|
||||||
|
LOG.warn("found LinkEnricher extension {} without Enrich annotation", enricher.getClass());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void contextDestroyed(ServletContextEvent sce) {
|
||||||
|
// nothing todo
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -14,7 +14,7 @@ import static de.otto.edison.hal.Link.link;
|
|||||||
import static de.otto.edison.hal.Links.linkingTo;
|
import static de.otto.edison.hal.Links.linkingTo;
|
||||||
|
|
||||||
@Mapper
|
@Mapper
|
||||||
public abstract class MeToUserDtoMapper extends UserToUserDtoMapper{
|
public abstract class MeToUserDtoMapper extends UserToUserDtoMapper {
|
||||||
|
|
||||||
@Inject
|
@Inject
|
||||||
private UserManager userManager;
|
private UserManager userManager;
|
||||||
@@ -36,6 +36,9 @@ public abstract class MeToUserDtoMapper extends UserToUserDtoMapper{
|
|||||||
if (userManager.isTypeDefault(user)) {
|
if (userManager.isTypeDefault(user)) {
|
||||||
linksBuilder.single(link("password", resourceLinks.me().passwordChange()));
|
linksBuilder.single(link("password", resourceLinks.me().passwordChange()));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
appendLinks(new EdisonLinkAppender(linksBuilder), new Me(), user);
|
||||||
|
|
||||||
target.add(linksBuilder.build());
|
target.add(linksBuilder.build());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -67,6 +67,9 @@ public abstract class RepositoryToRepositoryDtoMapper extends BaseMapper<Reposit
|
|||||||
}
|
}
|
||||||
linksBuilder.single(link("changesets", resourceLinks.changeset().all(target.getNamespace(), target.getName())));
|
linksBuilder.single(link("changesets", resourceLinks.changeset().all(target.getNamespace(), target.getName())));
|
||||||
linksBuilder.single(link("sources", resourceLinks.source().selfWithoutRevision(target.getNamespace(), target.getName())));
|
linksBuilder.single(link("sources", resourceLinks.source().selfWithoutRevision(target.getNamespace(), target.getName())));
|
||||||
|
|
||||||
|
appendLinks(new EdisonLinkAppender(linksBuilder), repository);
|
||||||
|
|
||||||
target.add(linksBuilder.build());
|
target.add(linksBuilder.build());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -15,7 +15,7 @@ import static de.otto.edison.hal.Link.link;
|
|||||||
import static de.otto.edison.hal.Links.linkingTo;
|
import static de.otto.edison.hal.Links.linkingTo;
|
||||||
|
|
||||||
@Mapper
|
@Mapper
|
||||||
public abstract class TagToTagDtoMapper {
|
public abstract class TagToTagDtoMapper extends LinkAppenderMapper {
|
||||||
|
|
||||||
@Inject
|
@Inject
|
||||||
private ResourceLinks resourceLinks;
|
private ResourceLinks resourceLinks;
|
||||||
@@ -24,11 +24,14 @@ public abstract class TagToTagDtoMapper {
|
|||||||
public abstract TagDto map(Tag tag, @Context NamespaceAndName namespaceAndName);
|
public abstract TagDto map(Tag tag, @Context NamespaceAndName namespaceAndName);
|
||||||
|
|
||||||
@AfterMapping
|
@AfterMapping
|
||||||
void appendLinks(@MappingTarget TagDto target, @Context NamespaceAndName namespaceAndName) {
|
void appendLinks(Tag tag, @MappingTarget TagDto target, @Context NamespaceAndName namespaceAndName) {
|
||||||
Links.Builder linksBuilder = linkingTo()
|
Links.Builder linksBuilder = linkingTo()
|
||||||
.self(resourceLinks.tag().self(namespaceAndName.getNamespace(), namespaceAndName.getName(), target.getName()))
|
.self(resourceLinks.tag().self(namespaceAndName.getNamespace(), namespaceAndName.getName(), target.getName()))
|
||||||
.single(link("sources", resourceLinks.source().self(namespaceAndName.getNamespace(), namespaceAndName.getName(), target.getRevision())))
|
.single(link("sources", resourceLinks.source().self(namespaceAndName.getNamespace(), namespaceAndName.getName(), target.getRevision())))
|
||||||
.single(link("changeset", resourceLinks.changeset().self(namespaceAndName.getNamespace(), namespaceAndName.getName(), target.getRevision())));
|
.single(link("changeset", resourceLinks.changeset().self(namespaceAndName.getNamespace(), namespaceAndName.getName(), target.getRevision())));
|
||||||
|
|
||||||
|
appendLinks(new EdisonLinkAppender(linksBuilder), tag, namespaceAndName);
|
||||||
|
|
||||||
target.add(linksBuilder.build());
|
target.add(linksBuilder.build());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,5 @@
|
|||||||
package sonia.scm.api.v2.resources;
|
package sonia.scm.api.v2.resources;
|
||||||
|
|
||||||
import com.google.common.annotations.VisibleForTesting;
|
|
||||||
import de.otto.edison.hal.Links;
|
import de.otto.edison.hal.Links;
|
||||||
import org.mapstruct.AfterMapping;
|
import org.mapstruct.AfterMapping;
|
||||||
import org.mapstruct.Mapper;
|
import org.mapstruct.Mapper;
|
||||||
@@ -43,6 +42,9 @@ public abstract class UserToUserDtoMapper extends BaseMapper<User, UserDto> {
|
|||||||
linksBuilder.single(link("password", resourceLinks.user().passwordChange(target.getName())));
|
linksBuilder.single(link("password", resourceLinks.user().passwordChange(target.getName())));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
appendLinks(new EdisonLinkAppender(linksBuilder), user);
|
||||||
|
|
||||||
target.add(linksBuilder.build());
|
target.add(linksBuilder.build());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -34,6 +34,8 @@ package sonia.scm.plugin;
|
|||||||
//~--- non-JDK imports --------------------------------------------------------
|
//~--- non-JDK imports --------------------------------------------------------
|
||||||
|
|
||||||
import com.google.common.base.Function;
|
import com.google.common.base.Function;
|
||||||
|
import org.slf4j.Logger;
|
||||||
|
import org.slf4j.LoggerFactory;
|
||||||
|
|
||||||
//~--- JDK imports ------------------------------------------------------------
|
//~--- JDK imports ------------------------------------------------------------
|
||||||
|
|
||||||
@@ -52,17 +54,18 @@ import java.util.Set;
|
|||||||
public final class ExplodedSmp implements Comparable<ExplodedSmp>
|
public final class ExplodedSmp implements Comparable<ExplodedSmp>
|
||||||
{
|
{
|
||||||
|
|
||||||
|
private static final Logger logger = LoggerFactory.getLogger(ExplodedSmp.class);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Constructs ...
|
* Constructs ...
|
||||||
*
|
*
|
||||||
*
|
*
|
||||||
* @param path
|
* @param path
|
||||||
* @param pluginId
|
|
||||||
* @param dependencies
|
|
||||||
* @param plugin
|
* @param plugin
|
||||||
*/
|
*/
|
||||||
ExplodedSmp(Path path, Plugin plugin)
|
ExplodedSmp(Path path, Plugin plugin)
|
||||||
{
|
{
|
||||||
|
logger.trace("create exploded scm for plugin {} and dependencies {}", plugin.getInformation().getName(), plugin.getDependencies());
|
||||||
this.path = path;
|
this.path = path;
|
||||||
this.plugin = plugin;
|
this.plugin = plugin;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -175,6 +175,11 @@ public final class PluginNode
|
|||||||
this.wrapper = wrapper;
|
this.wrapper = wrapper;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String toString() {
|
||||||
|
return plugin.getPath().toString() + " -> " + children;
|
||||||
|
}
|
||||||
|
|
||||||
//~--- fields ---------------------------------------------------------------
|
//~--- fields ---------------------------------------------------------------
|
||||||
|
|
||||||
/** Field description */
|
/** Field description */
|
||||||
|
|||||||
@@ -162,34 +162,29 @@ public final class PluginProcessor
|
|||||||
|
|
||||||
Set<Path> archives = collect(pluginDirectory, new PluginArchiveFilter());
|
Set<Path> archives = collect(pluginDirectory, new PluginArchiveFilter());
|
||||||
|
|
||||||
if (logger.isDebugEnabled())
|
logger.debug("extract {} archives", archives.size());
|
||||||
{
|
|
||||||
logger.debug("extract {} archives", archives.size());
|
|
||||||
}
|
|
||||||
|
|
||||||
extract(archives);
|
extract(archives);
|
||||||
|
|
||||||
List<Path> dirs = collectPluginDirectories(pluginDirectory);
|
List<Path> dirs = collectPluginDirectories(pluginDirectory);
|
||||||
|
|
||||||
if (logger.isDebugEnabled())
|
logger.debug("process {} directories: {}", dirs.size(), dirs);
|
||||||
{
|
|
||||||
logger.debug("process {} directories", dirs.size());
|
|
||||||
}
|
|
||||||
|
|
||||||
List<ExplodedSmp> smps = Lists.transform(dirs, new PathTransformer());
|
List<ExplodedSmp> smps = Lists.transform(dirs, new PathTransformer());
|
||||||
|
|
||||||
logger.trace("start building plugin tree");
|
logger.trace("start building plugin tree");
|
||||||
|
|
||||||
List<PluginNode> rootNodes = new PluginTree(smps).getRootNodes();
|
PluginTree pluginTree = new PluginTree(smps);
|
||||||
|
|
||||||
|
logger.trace("build plugin tree: {}", pluginTree);
|
||||||
|
|
||||||
|
List<PluginNode> rootNodes = pluginTree.getRootNodes();
|
||||||
|
|
||||||
logger.trace("create plugin wrappers and build classloaders");
|
logger.trace("create plugin wrappers and build classloaders");
|
||||||
|
|
||||||
Set<PluginWrapper> wrappers = createPluginWrappers(classLoader, rootNodes);
|
Set<PluginWrapper> wrappers = createPluginWrappers(classLoader, rootNodes);
|
||||||
|
|
||||||
if (logger.isDebugEnabled())
|
logger.debug("collected {} plugins", wrappers.size());
|
||||||
{
|
|
||||||
logger.debug("collected {} plugins", wrappers.size());
|
|
||||||
}
|
|
||||||
|
|
||||||
return ImmutableSet.copyOf(wrappers);
|
return ImmutableSet.copyOf(wrappers);
|
||||||
}
|
}
|
||||||
@@ -208,6 +203,9 @@ public final class PluginProcessor
|
|||||||
ClassLoader classLoader, PluginNode node)
|
ClassLoader classLoader, PluginNode node)
|
||||||
throws IOException
|
throws IOException
|
||||||
{
|
{
|
||||||
|
if (node.getWrapper() != null) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
ExplodedSmp smp = node.getPlugin();
|
ExplodedSmp smp = node.getPlugin();
|
||||||
|
|
||||||
List<ClassLoader> parents = Lists.newArrayList();
|
List<ClassLoader> parents = Lists.newArrayList();
|
||||||
|
|||||||
@@ -112,14 +112,14 @@ public final class PluginTree
|
|||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
appendNode(rootNodes, dependencies, smp);
|
appendNode(smp);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
//J-
|
//J-
|
||||||
throw new PluginConditionFailedException(
|
throw new PluginConditionFailedException(
|
||||||
condition,
|
condition,
|
||||||
String.format(
|
String.format(
|
||||||
"could not load plugin %s, the plugin condition does not match",
|
"could not load plugin %s, the plugin condition does not match",
|
||||||
plugin.getInformation().getId()
|
plugin.getInformation().getId()
|
||||||
@@ -149,23 +149,20 @@ public final class PluginTree
|
|||||||
* Method description
|
* Method description
|
||||||
*
|
*
|
||||||
*
|
*
|
||||||
* @param nodes
|
|
||||||
* @param dependencies
|
|
||||||
* @param smp
|
* @param smp
|
||||||
*/
|
*/
|
||||||
private void appendNode(List<PluginNode> nodes, Set<String> dependencies,
|
private void appendNode(ExplodedSmp smp)
|
||||||
ExplodedSmp smp)
|
|
||||||
{
|
{
|
||||||
PluginNode child = new PluginNode(smp);
|
PluginNode child = new PluginNode(smp);
|
||||||
|
|
||||||
for (String dependency : dependencies)
|
for (String dependency : smp.getPlugin().getDependencies())
|
||||||
{
|
{
|
||||||
if (!appendNode(nodes, child, dependency))
|
if (!appendNode(rootNodes, child, dependency))
|
||||||
{
|
{
|
||||||
//J-
|
//J-
|
||||||
throw new PluginNotInstalledException(
|
throw new PluginNotInstalledException(
|
||||||
String.format(
|
String.format(
|
||||||
"dependency %s of %s is not installed",
|
"dependency %s of %s is not installed",
|
||||||
dependency,
|
dependency,
|
||||||
child.getId()
|
child.getId()
|
||||||
)
|
)
|
||||||
@@ -188,7 +185,7 @@ public final class PluginTree
|
|||||||
private boolean appendNode(List<PluginNode> nodes, PluginNode child,
|
private boolean appendNode(List<PluginNode> nodes, PluginNode child,
|
||||||
String dependency)
|
String dependency)
|
||||||
{
|
{
|
||||||
logger.debug("check for {} {}", dependency, child.getId());
|
logger.debug("check for {} as dependency of {}", dependency, child.getId());
|
||||||
|
|
||||||
boolean found = false;
|
boolean found = false;
|
||||||
|
|
||||||
@@ -196,29 +193,28 @@ public final class PluginTree
|
|||||||
{
|
{
|
||||||
if (node.getId().equals(dependency))
|
if (node.getId().equals(dependency))
|
||||||
{
|
{
|
||||||
logger.debug("add plugin {} as child of {}", child.getId(),
|
logger.debug("add plugin {} as child of {}", child.getId(), node.getId());
|
||||||
node.getId());
|
|
||||||
node.addChild(child);
|
node.addChild(child);
|
||||||
found = true;
|
found = true;
|
||||||
|
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
else
|
else if (appendNode(node.getChildren(), child, dependency))
|
||||||
{
|
{
|
||||||
if (appendNode(node.getChildren(), child, dependency))
|
found = true;
|
||||||
{
|
|
||||||
found = true;
|
|
||||||
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
|
|
||||||
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return found;
|
return found;
|
||||||
}
|
}
|
||||||
|
|
||||||
//~--- fields ---------------------------------------------------------------
|
@Override
|
||||||
|
public String toString() {
|
||||||
|
return "plugin tree: " + rootNodes.toString();
|
||||||
|
}
|
||||||
|
//~--- fields ---------------------------------------------------------------
|
||||||
|
|
||||||
/** Field description */
|
/** Field description */
|
||||||
private final List<PluginNode> rootNodes = Lists.newArrayList();
|
private final List<PluginNode> rootNodes = Lists.newArrayList();
|
||||||
|
|||||||
@@ -73,43 +73,39 @@ public final class UberClassLoader extends ClassLoader
|
|||||||
|
|
||||||
//~--- methods --------------------------------------------------------------
|
//~--- methods --------------------------------------------------------------
|
||||||
|
|
||||||
/**
|
|
||||||
* Method description
|
|
||||||
*
|
|
||||||
*
|
|
||||||
* @param name
|
|
||||||
*
|
|
||||||
* @return
|
|
||||||
*
|
|
||||||
* @throws ClassNotFoundException
|
|
||||||
*/
|
|
||||||
@Override
|
@Override
|
||||||
protected Class<?> findClass(String name) throws ClassNotFoundException
|
protected Class<?> findClass(String name) throws ClassNotFoundException
|
||||||
{
|
{
|
||||||
Class<?> clazz = getFromCache(name);
|
Class<?> clazz = getFromCache(name);
|
||||||
|
|
||||||
if (clazz == null)
|
if (clazz == null) {
|
||||||
{
|
clazz = findClassInPlugins(name);
|
||||||
for (PluginWrapper plugin : plugins)
|
cache.put(name, new WeakReference<>(clazz));
|
||||||
{
|
|
||||||
ClassLoader cl = plugin.getClassLoader();
|
|
||||||
|
|
||||||
// load class could be slow, perhaps we should call
|
|
||||||
// find class via reflection ???
|
|
||||||
clazz = cl.loadClass(name);
|
|
||||||
|
|
||||||
if (clazz != null)
|
|
||||||
{
|
|
||||||
cache.put(name, new WeakReference<Class<?>>(clazz));
|
|
||||||
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return clazz;
|
return clazz;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private Class<?> findClassInPlugins(String name) throws ClassNotFoundException {
|
||||||
|
for (PluginWrapper plugin : plugins) {
|
||||||
|
Class<?> clazz = findClass(plugin.getClassLoader(), name);
|
||||||
|
if (clazz != null) {
|
||||||
|
return clazz;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
throw new ClassNotFoundException("could not find class " + name + " in any of the installed plugins");
|
||||||
|
}
|
||||||
|
|
||||||
|
private Class<?> findClass(ClassLoader classLoader, String name) {
|
||||||
|
try {
|
||||||
|
// load class could be slow, perhaps we should call
|
||||||
|
// find class via reflection ???
|
||||||
|
return classLoader.loadClass(name);
|
||||||
|
} catch (ClassNotFoundException ex) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Method description
|
* Method description
|
||||||
*
|
*
|
||||||
|
|||||||
@@ -31,35 +31,20 @@
|
|||||||
|
|
||||||
package sonia.scm.security;
|
package sonia.scm.security;
|
||||||
|
|
||||||
//~--- non-JDK imports --------------------------------------------------------
|
|
||||||
|
|
||||||
import com.google.common.annotations.VisibleForTesting;
|
import com.google.common.annotations.VisibleForTesting;
|
||||||
|
|
||||||
import io.jsonwebtoken.Claims;
|
|
||||||
import io.jsonwebtoken.JwtException;
|
|
||||||
import io.jsonwebtoken.Jwts;
|
|
||||||
|
|
||||||
import org.apache.shiro.authc.AuthenticationException;
|
|
||||||
import org.apache.shiro.authc.AuthenticationInfo;
|
import org.apache.shiro.authc.AuthenticationInfo;
|
||||||
import org.apache.shiro.authc.AuthenticationToken;
|
import org.apache.shiro.authc.AuthenticationToken;
|
||||||
import org.apache.shiro.authc.credential.AllowAllCredentialsMatcher;
|
import org.apache.shiro.authc.credential.AllowAllCredentialsMatcher;
|
||||||
import org.apache.shiro.realm.AuthenticatingRealm;
|
import org.apache.shiro.realm.AuthenticatingRealm;
|
||||||
|
|
||||||
import sonia.scm.group.GroupDAO;
|
import sonia.scm.group.GroupDAO;
|
||||||
import sonia.scm.plugin.Extension;
|
import sonia.scm.plugin.Extension;
|
||||||
import sonia.scm.user.UserDAO;
|
import sonia.scm.user.UserDAO;
|
||||||
|
|
||||||
import static com.google.common.base.Preconditions.checkArgument;
|
|
||||||
|
|
||||||
import java.util.List;
|
|
||||||
import java.util.Set;
|
|
||||||
|
|
||||||
//~--- JDK imports ------------------------------------------------------------
|
|
||||||
|
|
||||||
import javax.inject.Inject;
|
import javax.inject.Inject;
|
||||||
import javax.inject.Singleton;
|
import javax.inject.Singleton;
|
||||||
import org.slf4j.Logger;
|
|
||||||
import org.slf4j.LoggerFactory;
|
import static com.google.common.base.Preconditions.checkArgument;
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Realm for authentication with {@link BearerToken}.
|
* Realm for authentication with {@link BearerToken}.
|
||||||
@@ -71,34 +56,29 @@ import org.slf4j.LoggerFactory;
|
|||||||
@Extension
|
@Extension
|
||||||
public class BearerRealm extends AuthenticatingRealm
|
public class BearerRealm extends AuthenticatingRealm
|
||||||
{
|
{
|
||||||
|
|
||||||
/**
|
|
||||||
* the logger for BearerRealm
|
|
||||||
*/
|
|
||||||
private static final Logger LOG = LoggerFactory.getLogger(BearerRealm.class);
|
|
||||||
|
|
||||||
/** realm name */
|
/** realm name */
|
||||||
@VisibleForTesting
|
@VisibleForTesting
|
||||||
static final String REALM = "BearerRealm";
|
static final String REALM = "BearerRealm";
|
||||||
|
|
||||||
//~--- constructors ---------------------------------------------------------
|
|
||||||
|
/** dao realm helper */
|
||||||
|
private final DAORealmHelper helper;
|
||||||
|
|
||||||
|
/** access token resolver **/
|
||||||
|
private final AccessTokenResolver tokenResolver;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Constructs ...
|
* Constructs ...
|
||||||
*
|
*
|
||||||
* @param helperFactory dao realm helper factory
|
* @param helperFactory dao realm helper factory
|
||||||
* @param resolver key resolver
|
* @param tokenResolver resolve access token from bearer
|
||||||
* @param validators token claims validators
|
|
||||||
*/
|
*/
|
||||||
@Inject
|
@Inject
|
||||||
public BearerRealm(
|
public BearerRealm(DAORealmHelperFactory helperFactory, AccessTokenResolver tokenResolver) {
|
||||||
DAORealmHelperFactory helperFactory, SecureKeyResolver resolver, Set<TokenClaimsValidator> validators
|
|
||||||
)
|
|
||||||
{
|
|
||||||
this.helper = helperFactory.create(REALM);
|
this.helper = helperFactory.create(REALM);
|
||||||
this.resolver = resolver;
|
this.tokenResolver = tokenResolver;
|
||||||
this.validators = validators;
|
|
||||||
|
|
||||||
setCredentialsMatcher(new AllowAllCredentialsMatcher());
|
setCredentialsMatcher(new AllowAllCredentialsMatcher());
|
||||||
setAuthenticationTokenClass(BearerToken.class);
|
setAuthenticationTokenClass(BearerToken.class);
|
||||||
}
|
}
|
||||||
@@ -106,71 +86,26 @@ public class BearerRealm extends AuthenticatingRealm
|
|||||||
//~--- methods --------------------------------------------------------------
|
//~--- methods --------------------------------------------------------------
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Validates the given jwt token and retrieves authentication data from
|
* Validates the given bearer token and retrieves authentication data from
|
||||||
* {@link UserDAO} and {@link GroupDAO}.
|
* {@link UserDAO} and {@link GroupDAO}.
|
||||||
*
|
*
|
||||||
*
|
*
|
||||||
* @param token jwt token
|
* @param token bearer token
|
||||||
*
|
*
|
||||||
* @return authentication data from user and group dao
|
* @return authentication data from user and group dao
|
||||||
*/
|
*/
|
||||||
@Override
|
@Override
|
||||||
protected AuthenticationInfo doGetAuthenticationInfo( AuthenticationToken token)
|
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) {
|
||||||
{
|
checkArgument(token instanceof BearerToken, "%s is required", BearerToken.class);
|
||||||
checkArgument(token instanceof BearerToken, "%s is required",
|
|
||||||
BearerToken.class);
|
|
||||||
|
|
||||||
BearerToken bt = (BearerToken) token;
|
BearerToken bt = (BearerToken) token;
|
||||||
Claims c = checkToken(bt);
|
AccessToken accessToken = tokenResolver.resolve(bt);
|
||||||
|
|
||||||
return helper.getAuthenticationInfo(c.getSubject(), bt.getCredentials(), Scopes.fromClaims(c));
|
return helper.getAuthenticationInfo(
|
||||||
|
accessToken.getSubject(),
|
||||||
|
bt.getCredentials(),
|
||||||
|
Scopes.fromClaims(accessToken.getClaims())
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Validates the jwt token.
|
|
||||||
*
|
|
||||||
*
|
|
||||||
* @param token jwt token
|
|
||||||
*
|
|
||||||
* @return claim
|
|
||||||
*/
|
|
||||||
private Claims checkToken(BearerToken token)
|
|
||||||
{
|
|
||||||
Claims claims;
|
|
||||||
|
|
||||||
try
|
|
||||||
{
|
|
||||||
//J-
|
|
||||||
claims = Jwts.parser()
|
|
||||||
.setSigningKeyResolver(resolver)
|
|
||||||
.parseClaimsJws(token.getCredentials())
|
|
||||||
.getBody();
|
|
||||||
//J+
|
|
||||||
|
|
||||||
// check all registered claims validators
|
|
||||||
validators.forEach((validator) -> {
|
|
||||||
if (!validator.validate(claims)) {
|
|
||||||
LOG.warn("token claims is invalid, marked by validator {}", validator.getClass());
|
|
||||||
throw new AuthenticationException("token claims is invalid");
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
catch (JwtException ex)
|
|
||||||
{
|
|
||||||
throw new AuthenticationException("signature is invalid", ex);
|
|
||||||
}
|
|
||||||
|
|
||||||
return claims;
|
|
||||||
}
|
|
||||||
|
|
||||||
//~--- fields ---------------------------------------------------------------
|
|
||||||
|
|
||||||
/** token claims validators **/
|
|
||||||
private final Set<TokenClaimsValidator> validators;
|
|
||||||
|
|
||||||
/** dao realm helper */
|
|
||||||
private final DAORealmHelper helper;
|
|
||||||
|
|
||||||
/** secure key resolver */
|
|
||||||
private final SecureKeyResolver resolver;
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -55,37 +55,48 @@ public final class JwtAccessTokenResolver implements AccessTokenResolver {
|
|||||||
private static final Logger LOG = LoggerFactory.getLogger(JwtAccessTokenResolver.class);
|
private static final Logger LOG = LoggerFactory.getLogger(JwtAccessTokenResolver.class);
|
||||||
|
|
||||||
private final SecureKeyResolver keyResolver;
|
private final SecureKeyResolver keyResolver;
|
||||||
private final Set<TokenClaimsValidator> validators;
|
private final Set<AccessTokenValidator> validators;
|
||||||
|
|
||||||
@Inject
|
@Inject
|
||||||
public JwtAccessTokenResolver(SecureKeyResolver keyResolver, Set<TokenClaimsValidator> validators) {
|
public JwtAccessTokenResolver(SecureKeyResolver keyResolver, Set<AccessTokenValidator> validators) {
|
||||||
this.keyResolver = keyResolver;
|
this.keyResolver = keyResolver;
|
||||||
this.validators = validators;
|
this.validators = validators;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public JwtAccessToken resolve(BearerToken bearerToken) {
|
public JwtAccessToken resolve(BearerToken bearerToken) {
|
||||||
Claims claims;
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
// parse and validate
|
String compact = bearerToken.getCredentials();
|
||||||
claims = Jwts.parser()
|
|
||||||
|
Claims claims = Jwts.parser()
|
||||||
.setSigningKeyResolver(keyResolver)
|
.setSigningKeyResolver(keyResolver)
|
||||||
.parseClaimsJws(bearerToken.getCredentials())
|
.parseClaimsJws(compact)
|
||||||
.getBody();
|
.getBody();
|
||||||
|
|
||||||
// check all registered claims validators
|
JwtAccessToken token = new JwtAccessToken(claims, compact);
|
||||||
validators.forEach((validator) -> {
|
validate(token);
|
||||||
if (!validator.validate(claims)) {
|
|
||||||
LOG.warn("token claims is invalid, marked by validator {}", validator.getClass());
|
return token;
|
||||||
throw new AuthenticationException("token claims is invalid");
|
|
||||||
}
|
|
||||||
});
|
|
||||||
} catch (JwtException ex) {
|
} catch (JwtException ex) {
|
||||||
throw new AuthenticationException("signature is invalid", ex);
|
throw new AuthenticationException("signature is invalid", ex);
|
||||||
}
|
}
|
||||||
|
}
|
||||||
return new JwtAccessToken(claims, bearerToken.getCredentials());
|
|
||||||
|
|
||||||
|
private void validate(AccessToken accessToken) {
|
||||||
|
validators.forEach(validator -> validate(validator, accessToken));
|
||||||
|
}
|
||||||
|
|
||||||
|
private void validate(AccessTokenValidator validator, AccessToken accessToken) {
|
||||||
|
if (!validator.validate(accessToken)) {
|
||||||
|
String msg = createValidationFailedMessage(validator, accessToken);
|
||||||
|
LOG.debug(msg);
|
||||||
|
throw new AuthenticationException(msg);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private String createValidationFailedMessage(AccessTokenValidator validator, AccessToken accessToken) {
|
||||||
|
return String.format("token %s is invalid, marked by validator %s", accessToken.getId(), validator.getClass());
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -47,7 +47,7 @@ import org.apache.shiro.authz.SimpleAuthorizationInfo;
|
|||||||
import org.apache.shiro.authz.permission.PermissionResolver;
|
import org.apache.shiro.authz.permission.PermissionResolver;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Utile methods for {@link Scope}.
|
* Util methods for {@link Scope}.
|
||||||
*
|
*
|
||||||
* @author Sebastian Sdorra
|
* @author Sebastian Sdorra
|
||||||
* @since 2.0.0
|
* @since 2.0.0
|
||||||
|
|||||||
@@ -44,7 +44,7 @@ import sonia.scm.util.HttpUtil;
|
|||||||
/**
|
/**
|
||||||
* Xsrf access token enricher will add an xsrf custom field to the access token. The enricher will only
|
* Xsrf access token enricher will add an xsrf custom field to the access token. The enricher will only
|
||||||
* add the xsrf field, if the authentication request is issued from the web interface and xsrf protection is
|
* add the xsrf field, if the authentication request is issued from the web interface and xsrf protection is
|
||||||
* enabled. The xsrf field will be validated on every request by the {@link XsrfTokenClaimsValidator}. Xsrf protection
|
* enabled. The xsrf field will be validated on every request by the {@link XsrfAccessTokenValidator}. Xsrf protection
|
||||||
* can be disabled with {@link ScmConfiguration#setEnabledXsrfProtection(boolean)}.
|
* can be disabled with {@link ScmConfiguration#setEnabledXsrfProtection(boolean)}.
|
||||||
*
|
*
|
||||||
* @see <a href="https://goo.gl/s67xO3">Issue 793</a>
|
* @see <a href="https://goo.gl/s67xO3">Issue 793</a>
|
||||||
|
|||||||
@@ -30,30 +30,23 @@
|
|||||||
*/
|
*/
|
||||||
package sonia.scm.security;
|
package sonia.scm.security;
|
||||||
|
|
||||||
import com.google.common.base.Strings;
|
import sonia.scm.plugin.Extension;
|
||||||
import java.util.Map;
|
|
||||||
import javax.inject.Inject;
|
import javax.inject.Inject;
|
||||||
import javax.inject.Provider;
|
import javax.inject.Provider;
|
||||||
import javax.servlet.http.HttpServletRequest;
|
import javax.servlet.http.HttpServletRequest;
|
||||||
import org.slf4j.Logger;
|
import java.util.Optional;
|
||||||
import org.slf4j.LoggerFactory;
|
|
||||||
import sonia.scm.plugin.Extension;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Validates xsrf protected token claims. The validator check if the current request contains an xsrf key which is
|
* Validates xsrf protected access tokens. The validator check if the current request contains an xsrf key which is
|
||||||
* equal to the token in the claims. If the claims does not contain a xsrf key, the check is passed by. The xsrf keys
|
* equal to the one in the access token. If the token does not contain a xsrf key, the check is passed by. The xsrf keys
|
||||||
* are added by the {@link XsrfTokenClaimsEnricher}.
|
* are added by the {@link XsrfAccessTokenEnricher}.
|
||||||
*
|
*
|
||||||
* @author Sebastian Sdorra
|
* @author Sebastian Sdorra
|
||||||
* @since 2.0.0
|
* @since 2.0.0
|
||||||
*/
|
*/
|
||||||
@Extension
|
@Extension
|
||||||
public class XsrfTokenClaimsValidator implements TokenClaimsValidator {
|
public class XsrfAccessTokenValidator implements AccessTokenValidator {
|
||||||
|
|
||||||
/**
|
|
||||||
* the logger for XsrfTokenClaimsEnricher
|
|
||||||
*/
|
|
||||||
private static final Logger LOG = LoggerFactory.getLogger(XsrfTokenClaimsValidator.class);
|
|
||||||
|
|
||||||
private final Provider<HttpServletRequest> requestProvider;
|
private final Provider<HttpServletRequest> requestProvider;
|
||||||
|
|
||||||
@@ -64,16 +57,16 @@ public class XsrfTokenClaimsValidator implements TokenClaimsValidator {
|
|||||||
* @param requestProvider http request provider
|
* @param requestProvider http request provider
|
||||||
*/
|
*/
|
||||||
@Inject
|
@Inject
|
||||||
public XsrfTokenClaimsValidator(Provider<HttpServletRequest> requestProvider) {
|
public XsrfAccessTokenValidator(Provider<HttpServletRequest> requestProvider) {
|
||||||
this.requestProvider = requestProvider;
|
this.requestProvider = requestProvider;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public boolean validate(Map<String, Object> claims) {
|
public boolean validate(AccessToken accessToken) {
|
||||||
String xsrfClaimValue = (String) claims.get(Xsrf.TOKEN_KEY);
|
Optional<String> xsrfClaim = accessToken.getCustom(Xsrf.TOKEN_KEY);
|
||||||
if (!Strings.isNullOrEmpty(xsrfClaimValue)) {
|
if (xsrfClaim.isPresent()) {
|
||||||
String xsrfHeaderValue = requestProvider.get().getHeader(Xsrf.HEADER_KEY);
|
String xsrfHeaderValue = requestProvider.get().getHeader(Xsrf.HEADER_KEY);
|
||||||
return xsrfClaimValue.equals(xsrfHeaderValue);
|
return xsrfClaim.get().equals(xsrfHeaderValue);
|
||||||
}
|
}
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
package sonia.scm.api.v2.resources;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.junit.jupiter.api.extension.ExtendWith;
|
||||||
|
import org.mockito.InjectMocks;
|
||||||
|
import org.mockito.junit.jupiter.MockitoExtension;
|
||||||
|
import sonia.scm.repository.Branch;
|
||||||
|
import sonia.scm.repository.NamespaceAndName;
|
||||||
|
|
||||||
|
import java.net.URI;
|
||||||
|
|
||||||
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
|
||||||
|
@ExtendWith(MockitoExtension.class)
|
||||||
|
class BranchToBranchDtoMapperTest {
|
||||||
|
|
||||||
|
private final URI baseUri = URI.create("https://hitchhiker.com");
|
||||||
|
|
||||||
|
@SuppressWarnings("unused") // Is injected
|
||||||
|
private final ResourceLinks resourceLinks = ResourceLinksMock.createMock(baseUri);
|
||||||
|
|
||||||
|
@InjectMocks
|
||||||
|
private BranchToBranchDtoMapperImpl mapper;
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void shouldAppendLinks() {
|
||||||
|
LinkEnricherRegistry registry = new LinkEnricherRegistry();
|
||||||
|
registry.register(Branch.class, (ctx, appender) -> {
|
||||||
|
NamespaceAndName namespaceAndName = ctx.oneRequireByType(NamespaceAndName.class);
|
||||||
|
Branch branch = ctx.oneRequireByType(Branch.class);
|
||||||
|
|
||||||
|
appender.appendOne("ka", "http://" + namespaceAndName.logString() + "/" + branch.getName());
|
||||||
|
});
|
||||||
|
mapper.setRegistry(registry);
|
||||||
|
|
||||||
|
Branch branch = new Branch("master", "42");
|
||||||
|
|
||||||
|
BranchDto dto = mapper.map(branch, new NamespaceAndName("hitchhiker", "heart-of-gold"));
|
||||||
|
assertThat(dto.getLinks().getLinkBy("ka").get().getHref()).isEqualTo("http://hitchhiker/heart-of-gold/master");
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -0,0 +1,43 @@
|
|||||||
|
package sonia.scm.api.v2.resources;
|
||||||
|
|
||||||
|
import de.otto.edison.hal.Link;
|
||||||
|
import de.otto.edison.hal.Links;
|
||||||
|
import org.junit.jupiter.api.BeforeEach;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
import static de.otto.edison.hal.Links.linkingTo;
|
||||||
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
|
||||||
|
class EdisonLinkAppenderTest {
|
||||||
|
|
||||||
|
private Links.Builder builder;
|
||||||
|
private EdisonLinkAppender appender;
|
||||||
|
|
||||||
|
@BeforeEach
|
||||||
|
void prepare() {
|
||||||
|
builder = linkingTo();
|
||||||
|
appender = new EdisonLinkAppender(builder);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void shouldAppendOneLink() {
|
||||||
|
appender.appendOne("self", "https://scm.hitchhiker.com");
|
||||||
|
|
||||||
|
Links links = builder.build();
|
||||||
|
assertThat(links.getLinkBy("self").get().getHref()).isEqualTo("https://scm.hitchhiker.com");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void shouldAppendMultipleLinks() {
|
||||||
|
appender.arrayBuilder("items")
|
||||||
|
.append("one", "http://one")
|
||||||
|
.append("two", "http://two")
|
||||||
|
.build();
|
||||||
|
|
||||||
|
List<Link> items = builder.build().getLinksBy("items");
|
||||||
|
assertThat(items).hasSize(2);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -71,6 +71,24 @@ public class FileObjectToFileObjectDtoMapperTest {
|
|||||||
assertThat(dto.getLinks().getLinkBy("self").get().getHref()).isEqualTo(expectedBaseUri.resolve("namespace/name/content/revision/foo/bar").toString());
|
assertThat(dto.getLinks().getLinkBy("self").get().getHref()).isEqualTo(expectedBaseUri.resolve("namespace/name/content/revision/foo/bar").toString());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void shouldAppendLinks() {
|
||||||
|
LinkEnricherRegistry registry = new LinkEnricherRegistry();
|
||||||
|
registry.register(FileObject.class, (ctx, appender) -> {
|
||||||
|
NamespaceAndName repository = ctx.oneRequireByType(NamespaceAndName.class);
|
||||||
|
FileObject fo = ctx.oneRequireByType(FileObject.class);
|
||||||
|
String rev = ctx.oneRequireByType(String.class);
|
||||||
|
|
||||||
|
appender.appendOne("hog", "http://" + repository.logString() + "/" + fo.getName() + "/" + rev);
|
||||||
|
});
|
||||||
|
mapper.setRegistry(registry);
|
||||||
|
|
||||||
|
FileObject fileObject = createFileObject();
|
||||||
|
FileObjectDto dto = mapper.map(fileObject, new NamespaceAndName("hitchhiker", "hog"), "42");
|
||||||
|
|
||||||
|
assertThat(dto.getLinks().getLinkBy("hog").get().getHref()).isEqualTo("http://hitchhiker/hog/foo/42");
|
||||||
|
}
|
||||||
|
|
||||||
private FileObject createDirectoryObject() {
|
private FileObject createDirectoryObject() {
|
||||||
FileObject fileObject = createFileObject();
|
FileObject fileObject = createFileObject();
|
||||||
fileObject.setDirectory(true);
|
fileObject.setDirectory(true);
|
||||||
|
|||||||
@@ -35,7 +35,7 @@ public class GroupToGroupDtoMapperTest {
|
|||||||
private URI expectedBaseUri;
|
private URI expectedBaseUri;
|
||||||
|
|
||||||
@Before
|
@Before
|
||||||
public void init() throws URISyntaxException {
|
public void init() {
|
||||||
initMocks(this);
|
initMocks(this);
|
||||||
expectedBaseUri = baseUri.resolve(GroupRootResource.GROUPS_PATH_V2 + "/");
|
expectedBaseUri = baseUri.resolve(GroupRootResource.GROUPS_PATH_V2 + "/");
|
||||||
subjectThreadState.bind();
|
subjectThreadState.bind();
|
||||||
@@ -89,6 +89,21 @@ public class GroupToGroupDtoMapperTest {
|
|||||||
assertEquals("http://example.com/base/v2/users/user0", actualMember.getLinks().getLinkBy("self").get().getHref());
|
assertEquals("http://example.com/base/v2/users/user0", actualMember.getLinks().getLinkBy("self").get().getHref());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void shouldAppendLinks() {
|
||||||
|
LinkEnricherRegistry registry = new LinkEnricherRegistry();
|
||||||
|
registry.register(Group.class, (ctx, appender) -> {
|
||||||
|
Group group = ctx.oneRequireByType(Group.class);
|
||||||
|
appender.appendOne("some", "http://" + group.getName());
|
||||||
|
});
|
||||||
|
mapper.setRegistry(registry);
|
||||||
|
|
||||||
|
Group group = createDefaultGroup();
|
||||||
|
GroupDto dto = mapper.map(group);
|
||||||
|
|
||||||
|
assertEquals("http://abc", dto.getLinks().getLinkBy("some").get().getHref());
|
||||||
|
}
|
||||||
|
|
||||||
private Group createDefaultGroup() {
|
private Group createDefaultGroup() {
|
||||||
Group group = new Group();
|
Group group = new Group();
|
||||||
group.setName("abc");
|
group.setName("abc");
|
||||||
|
|||||||
@@ -0,0 +1,64 @@
|
|||||||
|
package sonia.scm.api.v2.resources;
|
||||||
|
|
||||||
|
import com.google.common.collect.ImmutableSet;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
import java.util.Set;
|
||||||
|
|
||||||
|
import static org.assertj.core.api.Java6Assertions.assertThat;
|
||||||
|
|
||||||
|
class LinkEnricherAutoRegistrationTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void shouldRegisterAllAvailableLinkEnrichers() {
|
||||||
|
LinkEnricher one = new One();
|
||||||
|
LinkEnricher two = new Two();
|
||||||
|
LinkEnricher three = new Three();
|
||||||
|
LinkEnricher four = new Four();
|
||||||
|
Set<LinkEnricher> enrichers = ImmutableSet.of(one, two, three, four);
|
||||||
|
|
||||||
|
LinkEnricherRegistry registry = new LinkEnricherRegistry();
|
||||||
|
|
||||||
|
LinkEnricherAutoRegistration autoRegistration = new LinkEnricherAutoRegistration(registry, enrichers);
|
||||||
|
autoRegistration.contextInitialized(null);
|
||||||
|
|
||||||
|
assertThat(registry.allByType(String.class)).containsOnly(one, two);
|
||||||
|
assertThat(registry.allByType(Integer.class)).containsOnly(three);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Enrich(String.class)
|
||||||
|
public static class One implements LinkEnricher {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void enrich(LinkEnricherContext context, LinkAppender appender) {
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Enrich(String.class)
|
||||||
|
public static class Two implements LinkEnricher {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void enrich(LinkEnricherContext context, LinkAppender appender) {
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Enrich(Integer.class)
|
||||||
|
public static class Three implements LinkEnricher {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void enrich(LinkEnricherContext context, LinkAppender appender) {
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static class Four implements LinkEnricher {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void enrich(LinkEnricherContext context, LinkAppender appender) {
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -11,6 +11,7 @@ import org.mockito.InjectMocks;
|
|||||||
import org.mockito.Mock;
|
import org.mockito.Mock;
|
||||||
import sonia.scm.user.User;
|
import sonia.scm.user.User;
|
||||||
import sonia.scm.user.UserManager;
|
import sonia.scm.user.UserManager;
|
||||||
|
import sonia.scm.user.UserTestData;
|
||||||
|
|
||||||
import java.net.URI;
|
import java.net.URI;
|
||||||
|
|
||||||
@@ -124,6 +125,21 @@ public class MeToUserDtoMapperTest {
|
|||||||
assertThat(userDto.getPassword()).as("hide password for the me resource").isBlank();
|
assertThat(userDto.getPassword()).as("hide password for the me resource").isBlank();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void shouldAppendLinks() {
|
||||||
|
LinkEnricherRegistry registry = new LinkEnricherRegistry();
|
||||||
|
registry.register(Me.class, (ctx, appender) -> {
|
||||||
|
User user = ctx.oneRequireByType(User.class);
|
||||||
|
appender.appendOne("profile", "http://hitchhiker.com/users/" + user.getName());
|
||||||
|
});
|
||||||
|
mapper.setRegistry(registry);
|
||||||
|
|
||||||
|
User trillian = UserTestData.createTrillian();
|
||||||
|
UserDto dto = mapper.map(trillian);
|
||||||
|
|
||||||
|
assertEquals("http://hitchhiker.com/users/trillian", dto.getLinks().getLinkBy("profile").get().getHref());
|
||||||
|
}
|
||||||
|
|
||||||
private User createDefaultUser() {
|
private User createDefaultUser() {
|
||||||
User user = new User();
|
User user = new User();
|
||||||
user.setName("abc");
|
user.setName("abc");
|
||||||
|
|||||||
@@ -211,6 +211,19 @@ public class RepositoryToRepositoryDtoMapperTest {
|
|||||||
assertTrue(dto.getLinks().getLinksBy("protocol").isEmpty());
|
assertTrue(dto.getLinks().getLinksBy("protocol").isEmpty());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void shouldAppendLinks() {
|
||||||
|
LinkEnricherRegistry registry = new LinkEnricherRegistry();
|
||||||
|
registry.register(Repository.class, (ctx, appender) -> {
|
||||||
|
Repository repository = ctx.oneRequireByType(Repository.class);
|
||||||
|
appender.appendOne("id", "http://" + repository.getId());
|
||||||
|
});
|
||||||
|
mapper.setRegistry(registry);
|
||||||
|
|
||||||
|
RepositoryDto dto = mapper.map(createTestRepository());
|
||||||
|
assertEquals("http://1", dto.getLinks().getLinkBy("id").get().getHref());
|
||||||
|
}
|
||||||
|
|
||||||
private ScmProtocol mockProtocol(String type, String protocol) {
|
private ScmProtocol mockProtocol(String type, String protocol) {
|
||||||
return new MockScmProtocol(type, protocol);
|
return new MockScmProtocol(type, protocol);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,37 @@
|
|||||||
|
package sonia.scm.api.v2.resources;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.junit.jupiter.api.extension.ExtendWith;
|
||||||
|
import org.mockito.InjectMocks;
|
||||||
|
import org.mockito.junit.jupiter.MockitoExtension;
|
||||||
|
import sonia.scm.repository.NamespaceAndName;
|
||||||
|
import sonia.scm.repository.Tag;
|
||||||
|
|
||||||
|
import java.net.URI;
|
||||||
|
|
||||||
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
|
||||||
|
@ExtendWith(MockitoExtension.class)
|
||||||
|
class TagToTagDtoMapperTest {
|
||||||
|
|
||||||
|
@SuppressWarnings("unused") // Is injected
|
||||||
|
private final ResourceLinks resourceLinks = ResourceLinksMock.createMock(URI.create("https://hitchhiker.com"));
|
||||||
|
|
||||||
|
@InjectMocks
|
||||||
|
private TagToTagDtoMapperImpl mapper;
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void shouldAppendLinks() {
|
||||||
|
LinkEnricherRegistry registry = new LinkEnricherRegistry();
|
||||||
|
registry.register(Tag.class, (ctx, appender) -> {
|
||||||
|
NamespaceAndName repository = ctx.oneRequireByType(NamespaceAndName.class);
|
||||||
|
Tag tag = ctx.oneRequireByType(Tag.class);
|
||||||
|
appender.appendOne("yo", "http://" + repository.logString() + "/" + tag.getName());
|
||||||
|
});
|
||||||
|
mapper.setRegistry(registry);
|
||||||
|
|
||||||
|
TagDto dto = mapper.map(new Tag("1.0.0", "42"), new NamespaceAndName("hitchhiker", "hog"));
|
||||||
|
assertThat(dto.getLinks().getLinkBy("yo").get().getHref()).isEqualTo("http://hitchhiker/hog/1.0.0");
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -11,6 +11,7 @@ import org.mockito.InjectMocks;
|
|||||||
import org.mockito.Mock;
|
import org.mockito.Mock;
|
||||||
import sonia.scm.user.User;
|
import sonia.scm.user.User;
|
||||||
import sonia.scm.user.UserManager;
|
import sonia.scm.user.UserManager;
|
||||||
|
import sonia.scm.user.UserTestData;
|
||||||
|
|
||||||
import java.net.URI;
|
import java.net.URI;
|
||||||
import java.time.Instant;
|
import java.time.Instant;
|
||||||
@@ -149,4 +150,17 @@ public class UserToUserDtoMapperTest {
|
|||||||
assertEquals(expectedCreationDate, userDto.getCreationDate());
|
assertEquals(expectedCreationDate, userDto.getCreationDate());
|
||||||
assertEquals(expectedModificationDate, userDto.getLastModified());
|
assertEquals(expectedModificationDate, userDto.getLastModified());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void shouldAppendLink() {
|
||||||
|
User trillian = UserTestData.createTrillian();
|
||||||
|
|
||||||
|
LinkEnricherRegistry registry = new LinkEnricherRegistry();
|
||||||
|
registry.register(User.class, (ctx, appender) -> appender.appendOne("sample", "http://" + ctx.oneByType(User.class).get().getName()));
|
||||||
|
mapper.setRegistry(registry);
|
||||||
|
|
||||||
|
UserDto userDto = mapper.map(trillian);
|
||||||
|
|
||||||
|
assertEquals("http://trillian", userDto.getLinks().getLinkBy("sample").get().getHref());
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -29,271 +29,98 @@
|
|||||||
*
|
*
|
||||||
*/
|
*/
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
package sonia.scm.security;
|
package sonia.scm.security;
|
||||||
|
|
||||||
//~--- non-JDK imports --------------------------------------------------------
|
|
||||||
|
|
||||||
import com.google.common.collect.ImmutableList;
|
|
||||||
import com.google.common.collect.Sets;
|
|
||||||
import io.jsonwebtoken.Claims;
|
|
||||||
import io.jsonwebtoken.JwsHeader;
|
|
||||||
import io.jsonwebtoken.Jwts;
|
|
||||||
import io.jsonwebtoken.SignatureAlgorithm;
|
|
||||||
import org.apache.shiro.authc.AuthenticationException;
|
|
||||||
import org.apache.shiro.authc.AuthenticationInfo;
|
import org.apache.shiro.authc.AuthenticationInfo;
|
||||||
import org.apache.shiro.authc.UsernamePasswordToken;
|
import org.apache.shiro.authc.UsernamePasswordToken;
|
||||||
import org.apache.shiro.subject.PrincipalCollection;
|
import org.junit.jupiter.api.BeforeEach;
|
||||||
import org.hamcrest.Matchers;
|
import org.junit.jupiter.api.Test;
|
||||||
import org.junit.Before;
|
import org.junit.jupiter.api.extension.ExtendWith;
|
||||||
import org.junit.Rule;
|
|
||||||
import org.junit.Test;
|
|
||||||
import org.junit.rules.ExpectedException;
|
|
||||||
import org.junit.runner.RunWith;
|
|
||||||
import org.mockito.InjectMocks;
|
import org.mockito.InjectMocks;
|
||||||
import org.mockito.Mock;
|
import org.mockito.Mock;
|
||||||
import org.mockito.Mockito;
|
import org.mockito.invocation.InvocationOnMock;
|
||||||
import org.mockito.junit.MockitoJUnitRunner;
|
import org.mockito.junit.jupiter.MockitoExtension;
|
||||||
import sonia.scm.group.GroupDAO;
|
import org.mockito.stubbing.Answer;
|
||||||
import sonia.scm.user.User;
|
|
||||||
import sonia.scm.user.UserDAO;
|
|
||||||
import sonia.scm.user.UserTestData;
|
|
||||||
|
|
||||||
import javax.crypto.spec.SecretKeySpec;
|
import java.util.HashMap;
|
||||||
import java.util.Date;
|
|
||||||
import java.util.Set;
|
|
||||||
|
|
||||||
import static org.junit.Assert.assertEquals;
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
import static org.junit.Assert.assertNotNull;
|
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||||
import static org.junit.Assert.assertThat;
|
import static org.mockito.ArgumentMatchers.any;
|
||||||
import static org.junit.Assert.assertTrue;
|
import static org.mockito.ArgumentMatchers.anyString;
|
||||||
import static org.mockito.Mockito.any;
|
import static org.mockito.Mockito.mock;
|
||||||
import static org.mockito.Mockito.when;
|
import static org.mockito.Mockito.when;
|
||||||
import static sonia.scm.security.SecureKeyTestUtil.createSecureKey;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Unit tests for {@link BearerRealm}.
|
* Unit tests for {@link BearerRealm}.
|
||||||
*
|
*
|
||||||
* @author Sebastian Sdorra
|
* @author Sebastian Sdorra
|
||||||
*/
|
*/
|
||||||
@SuppressWarnings("unchecked")
|
@ExtendWith(MockitoExtension.class)
|
||||||
@RunWith(MockitoJUnitRunner.class)
|
class BearerRealmTest {
|
||||||
public class BearerRealmTest
|
|
||||||
{
|
|
||||||
|
|
||||||
@Rule
|
|
||||||
public ExpectedException expectedException = ExpectedException.none();
|
|
||||||
|
|
||||||
/**
|
@Mock
|
||||||
* Method description
|
private DAORealmHelperFactory realmHelperFactory;
|
||||||
*
|
|
||||||
*/
|
|
||||||
@Test
|
|
||||||
public void testDoGetAuthenticationInfo()
|
|
||||||
{
|
|
||||||
SecureKey key = createSecureKey();
|
|
||||||
|
|
||||||
User marvin = UserTestData.createMarvin();
|
@Mock
|
||||||
|
private DAORealmHelper realmHelper;
|
||||||
|
|
||||||
when(userDAO.get(marvin.getName())).thenReturn(marvin);
|
@Mock
|
||||||
|
private AccessTokenResolver accessTokenResolver;
|
||||||
|
|
||||||
resolveKey(key);
|
|
||||||
|
|
||||||
String compact = createCompactToken(marvin.getName(), key);
|
|
||||||
|
|
||||||
BearerToken token = BearerToken.valueOf(compact);
|
|
||||||
AuthenticationInfo info = realm.doGetAuthenticationInfo(token);
|
|
||||||
|
|
||||||
assertNotNull(info);
|
|
||||||
|
|
||||||
PrincipalCollection principals = info.getPrincipals();
|
|
||||||
|
|
||||||
assertEquals(marvin.getName(), principals.getPrimaryPrincipal());
|
|
||||||
assertEquals(marvin, principals.oneByType(User.class));
|
|
||||||
assertNotNull(principals.oneByType(Scope.class));
|
|
||||||
assertTrue(principals.oneByType(Scope.class).isEmpty());
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Test {@link BearerRealm#doGetAuthenticationInfo(AuthenticationToken)} with scope.
|
|
||||||
*
|
|
||||||
*/
|
|
||||||
@Test
|
|
||||||
public void testDoGetAuthenticationInfoWithScope()
|
|
||||||
{
|
|
||||||
SecureKey key = createSecureKey();
|
|
||||||
|
|
||||||
User marvin = UserTestData.createMarvin();
|
|
||||||
|
|
||||||
when(userDAO.get(marvin.getName())).thenReturn(marvin);
|
|
||||||
|
|
||||||
resolveKey(key);
|
|
||||||
|
|
||||||
String compact = createCompactToken(
|
|
||||||
marvin.getName(),
|
|
||||||
key,
|
|
||||||
new Date(System.currentTimeMillis() + 60000),
|
|
||||||
Scope.valueOf("repo:*", "user:*")
|
|
||||||
);
|
|
||||||
|
|
||||||
AuthenticationInfo info = realm.doGetAuthenticationInfo(BearerToken.valueOf(compact));
|
|
||||||
Scope scope = info.getPrincipals().oneByType(Scope.class);
|
|
||||||
assertThat(scope, Matchers.containsInAnyOrder("repo:*", "user:*"));
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Test {@link BearerRealm#doGetAuthenticationInfo(AuthenticationToken)} with a failed
|
|
||||||
* claims validation.
|
|
||||||
*/
|
|
||||||
@Test
|
|
||||||
public void testDoGetAuthenticationInfoWithInvalidClaims()
|
|
||||||
{
|
|
||||||
SecureKey key = createSecureKey();
|
|
||||||
User marvin = UserTestData.createMarvin();
|
|
||||||
|
|
||||||
resolveKey(key);
|
|
||||||
|
|
||||||
String compact = createCompactToken(marvin.getName(), key);
|
|
||||||
|
|
||||||
// treat claims as invalid
|
|
||||||
when(validator.validate(Mockito.anyMap())).thenReturn(false);
|
|
||||||
|
|
||||||
// expect exception
|
|
||||||
expectedException.expect(AuthenticationException.class);
|
|
||||||
expectedException.expectMessage(Matchers.containsString("claims"));
|
|
||||||
|
|
||||||
// kick authentication
|
|
||||||
realm.doGetAuthenticationInfo(BearerToken.valueOf(compact));
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Method description
|
|
||||||
*
|
|
||||||
*/
|
|
||||||
@Test(expected = AuthenticationException.class)
|
|
||||||
public void testDoGetAuthenticationInfoWithExpiredToken()
|
|
||||||
{
|
|
||||||
User trillian = UserTestData.createTrillian();
|
|
||||||
|
|
||||||
SecureKey key = createSecureKey();
|
|
||||||
|
|
||||||
resolveKey(key);
|
|
||||||
|
|
||||||
Date exp = new Date(System.currentTimeMillis() - 600l);
|
|
||||||
String compact = createCompactToken(trillian.getName(), key, exp, Scope.empty());
|
|
||||||
|
|
||||||
realm.doGetAuthenticationInfo(BearerToken.valueOf(compact));
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Method description
|
|
||||||
*
|
|
||||||
*/
|
|
||||||
@Test(expected = AuthenticationException.class)
|
|
||||||
public void testDoGetAuthenticationInfoWithInvalidSignature()
|
|
||||||
{
|
|
||||||
resolveKey(createSecureKey());
|
|
||||||
|
|
||||||
User trillian = UserTestData.createTrillian();
|
|
||||||
String compact = createCompactToken(trillian.getName(), createSecureKey());
|
|
||||||
|
|
||||||
realm.doGetAuthenticationInfo(BearerToken.valueOf(compact));
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Method description
|
|
||||||
*
|
|
||||||
*/
|
|
||||||
@Test(expected = AuthenticationException.class)
|
|
||||||
public void testDoGetAuthenticationInfoWithoutSignature()
|
|
||||||
{
|
|
||||||
String compact = Jwts.builder().setSubject("test").compact();
|
|
||||||
|
|
||||||
realm.doGetAuthenticationInfo(BearerToken.valueOf(compact));
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Method description
|
|
||||||
*
|
|
||||||
*/
|
|
||||||
@Test(expected = IllegalArgumentException.class)
|
|
||||||
public void testDoGetAuthenticationInfoWrongToken()
|
|
||||||
{
|
|
||||||
realm.doGetAuthenticationInfo(new UsernamePasswordToken("test", "test"));
|
|
||||||
}
|
|
||||||
|
|
||||||
//~--- set methods ----------------------------------------------------------
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Method description
|
|
||||||
*
|
|
||||||
*/
|
|
||||||
@Before
|
|
||||||
public void setUp()
|
|
||||||
{
|
|
||||||
when(validator.validate(Mockito.anyMap())).thenReturn(true);
|
|
||||||
Set<TokenClaimsValidator> validators = Sets.newHashSet(validator);
|
|
||||||
realm = new BearerRealm(helperFactory, keyResolver, validators);
|
|
||||||
}
|
|
||||||
|
|
||||||
//~--- methods --------------------------------------------------------------
|
|
||||||
|
|
||||||
private String createCompactToken(String subject, SecureKey key) {
|
|
||||||
return createCompactToken(subject, key, Scope.empty());
|
|
||||||
}
|
|
||||||
|
|
||||||
private String createCompactToken(String subject, SecureKey key, Scope scope) {
|
|
||||||
return createCompactToken(subject, key, new Date(System.currentTimeMillis() + 60000), scope);
|
|
||||||
}
|
|
||||||
|
|
||||||
private String createCompactToken(String subject, SecureKey key, Date exp, Scope scope) {
|
|
||||||
return Jwts.builder()
|
|
||||||
.claim(Scopes.CLAIMS_KEY, ImmutableList.copyOf(scope))
|
|
||||||
.setSubject(subject)
|
|
||||||
.setExpiration(exp)
|
|
||||||
.signWith(SignatureAlgorithm.HS256, key.getBytes())
|
|
||||||
.compact();
|
|
||||||
}
|
|
||||||
|
|
||||||
private void resolveKey(SecureKey key) {
|
|
||||||
when(
|
|
||||||
keyResolver.resolveSigningKey(
|
|
||||||
any(JwsHeader.class),
|
|
||||||
any(Claims.class)
|
|
||||||
)
|
|
||||||
)
|
|
||||||
.thenReturn(
|
|
||||||
new SecretKeySpec(
|
|
||||||
key.getBytes(),
|
|
||||||
SignatureAlgorithm.HS256.getJcaName()
|
|
||||||
)
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
//~--- fields ---------------------------------------------------------------
|
|
||||||
|
|
||||||
@InjectMocks
|
@InjectMocks
|
||||||
private DAORealmHelperFactory helperFactory;
|
|
||||||
|
|
||||||
@Mock
|
|
||||||
private LoginAttemptHandler loginAttemptHandler;
|
|
||||||
|
|
||||||
@Mock
|
|
||||||
private TokenClaimsValidator validator;
|
|
||||||
|
|
||||||
/** Field description */
|
|
||||||
@Mock
|
|
||||||
private GroupDAO groupDAO;
|
|
||||||
|
|
||||||
/** Field description */
|
|
||||||
@Mock
|
|
||||||
private SecureKeyResolver keyResolver;
|
|
||||||
|
|
||||||
/** Field description */
|
|
||||||
private BearerRealm realm;
|
private BearerRealm realm;
|
||||||
|
|
||||||
/** Field description */
|
|
||||||
@Mock
|
@Mock
|
||||||
private UserDAO userDAO;
|
private AuthenticationInfo authenticationInfo;
|
||||||
|
|
||||||
|
@BeforeEach
|
||||||
|
void prepareObjectUnderTest() {
|
||||||
|
when(realmHelperFactory.create(BearerRealm.REALM)).thenReturn(realmHelper);
|
||||||
|
realm = new BearerRealm(realmHelperFactory, accessTokenResolver);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void shouldDoGetAuthentication() {
|
||||||
|
BearerToken bearerToken = BearerToken.valueOf("__bearer__");
|
||||||
|
AccessToken accessToken = mock(AccessToken.class);
|
||||||
|
when(accessToken.getSubject()).thenReturn("trillian");
|
||||||
|
when(accessToken.getClaims()).thenReturn(new HashMap<>());
|
||||||
|
|
||||||
|
when(accessTokenResolver.resolve(bearerToken)).thenReturn(accessToken);
|
||||||
|
|
||||||
|
// we have to use answer, because we could not mock the result of Scopes
|
||||||
|
when(realmHelper.getAuthenticationInfo(
|
||||||
|
anyString(), anyString(), any(Scope.class)
|
||||||
|
)).thenAnswer(createAnswer("trillian", "__bearer__", true));
|
||||||
|
|
||||||
|
AuthenticationInfo result = realm.doGetAuthenticationInfo(bearerToken);
|
||||||
|
assertThat(result).isSameAs(authenticationInfo);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void shouldThrowIllegalArgumentExceptionForWrongTypeOfToken() {
|
||||||
|
assertThrows(IllegalArgumentException.class, () -> realm.doGetAuthenticationInfo(new UsernamePasswordToken()));
|
||||||
|
}
|
||||||
|
|
||||||
|
private Answer<AuthenticationInfo> createAnswer(String expectedSubject, String expectedCredentials, boolean scopeEmpty) {
|
||||||
|
return (iom) -> {
|
||||||
|
String subject = iom.getArgument(0);
|
||||||
|
assertThat(subject).isEqualTo(expectedSubject);
|
||||||
|
String credentials = iom.getArgument(1);
|
||||||
|
assertThat(credentials).isEqualTo(expectedCredentials);
|
||||||
|
Scope scope = iom.getArgument(2);
|
||||||
|
assertThat(scope.isEmpty()).isEqualTo(scopeEmpty);
|
||||||
|
|
||||||
|
return authenticationInfo;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private class MyAnswer implements Answer<AuthenticationInfo> {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public AuthenticationInfo answer(InvocationOnMock invocationOnMock) throws Throwable {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -40,26 +40,27 @@ import io.jsonwebtoken.Jwts;
|
|||||||
import io.jsonwebtoken.SignatureAlgorithm;
|
import io.jsonwebtoken.SignatureAlgorithm;
|
||||||
import io.jsonwebtoken.SignatureException;
|
import io.jsonwebtoken.SignatureException;
|
||||||
import io.jsonwebtoken.UnsupportedJwtException;
|
import io.jsonwebtoken.UnsupportedJwtException;
|
||||||
import java.security.SecureRandom;
|
|
||||||
import java.util.Date;
|
|
||||||
import java.util.Set;
|
|
||||||
import javax.crypto.spec.SecretKeySpec;
|
|
||||||
import org.apache.shiro.authc.AuthenticationException;
|
import org.apache.shiro.authc.AuthenticationException;
|
||||||
import org.hamcrest.Matchers;
|
import org.hamcrest.Matchers;
|
||||||
import org.junit.Test;
|
|
||||||
import static org.junit.Assert.*;
|
|
||||||
import static org.hamcrest.Matchers.*;
|
|
||||||
import org.junit.Before;
|
import org.junit.Before;
|
||||||
import org.junit.Rule;
|
import org.junit.Rule;
|
||||||
|
import org.junit.Test;
|
||||||
import org.junit.rules.ExpectedException;
|
import org.junit.rules.ExpectedException;
|
||||||
import org.junit.runner.RunWith;
|
import org.junit.runner.RunWith;
|
||||||
import org.mockito.Mock;
|
import org.mockito.Mock;
|
||||||
import org.mockito.Mockito;
|
import org.mockito.Mockito;
|
||||||
import static org.mockito.Mockito.*;
|
|
||||||
import static sonia.scm.security.SecureKeyTestUtil.createSecureKey;
|
|
||||||
|
|
||||||
import org.mockito.junit.MockitoJUnitRunner;
|
import org.mockito.junit.MockitoJUnitRunner;
|
||||||
|
|
||||||
|
import javax.crypto.spec.SecretKeySpec;
|
||||||
|
import java.util.Date;
|
||||||
|
import java.util.Set;
|
||||||
|
|
||||||
|
import static org.hamcrest.Matchers.instanceOf;
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
import static org.junit.Assert.assertThat;
|
||||||
|
import static org.mockito.Mockito.when;
|
||||||
|
import static sonia.scm.security.SecureKeyTestUtil.createSecureKey;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Unit tests for {@link JwtAccessTokenResolver}.
|
* Unit tests for {@link JwtAccessTokenResolver}.
|
||||||
*
|
*
|
||||||
@@ -70,14 +71,12 @@ public class JwtAccessTokenResolverTest {
|
|||||||
|
|
||||||
@Rule
|
@Rule
|
||||||
public ExpectedException expectedException = ExpectedException.none();
|
public ExpectedException expectedException = ExpectedException.none();
|
||||||
|
|
||||||
private final SecureRandom random = new SecureRandom();
|
|
||||||
|
|
||||||
@Mock
|
@Mock
|
||||||
private SecureKeyResolver keyResolver;
|
private SecureKeyResolver keyResolver;
|
||||||
|
|
||||||
@Mock
|
@Mock
|
||||||
private TokenClaimsValidator validator;
|
private AccessTokenValidator validator;
|
||||||
|
|
||||||
private JwtAccessTokenResolver resolver;
|
private JwtAccessTokenResolver resolver;
|
||||||
|
|
||||||
@@ -86,8 +85,8 @@ public class JwtAccessTokenResolverTest {
|
|||||||
*/
|
*/
|
||||||
@Before
|
@Before
|
||||||
public void prepareObjectUnderTest() {
|
public void prepareObjectUnderTest() {
|
||||||
Set<TokenClaimsValidator> validators = Sets.newHashSet(validator);
|
Set<AccessTokenValidator> validators = Sets.newHashSet(validator);
|
||||||
when(validator.validate(anyMap())).thenReturn(true);
|
when(validator.validate(Mockito.any(AccessToken.class))).thenReturn(true);
|
||||||
resolver = new JwtAccessTokenResolver(keyResolver, validators);
|
resolver = new JwtAccessTokenResolver(keyResolver, validators);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -115,11 +114,11 @@ public class JwtAccessTokenResolverTest {
|
|||||||
String compact = createCompactToken("marvin", secureKey);
|
String compact = createCompactToken("marvin", secureKey);
|
||||||
|
|
||||||
// prepare mock
|
// prepare mock
|
||||||
when(validator.validate(anyMap())).thenReturn(false);
|
when(validator.validate(Mockito.any(AccessToken.class))).thenReturn(false);
|
||||||
|
|
||||||
// expect exception
|
// expect exception
|
||||||
expectedException.expect(AuthenticationException.class);
|
expectedException.expect(AuthenticationException.class);
|
||||||
expectedException.expectMessage(Matchers.containsString("claims"));
|
expectedException.expectMessage(Matchers.containsString("token"));
|
||||||
|
|
||||||
BearerToken bearer = BearerToken.valueOf(compact);
|
BearerToken bearer = BearerToken.valueOf(compact);
|
||||||
resolver.resolve(bearer);
|
resolver.resolve(bearer);
|
||||||
|
|||||||
@@ -31,88 +31,90 @@
|
|||||||
|
|
||||||
package sonia.scm.security;
|
package sonia.scm.security;
|
||||||
|
|
||||||
import com.google.common.collect.Maps;
|
|
||||||
import java.util.Map;
|
|
||||||
import javax.servlet.http.HttpServletRequest;
|
|
||||||
import org.junit.Test;
|
|
||||||
import static org.junit.Assert.*;
|
|
||||||
import org.junit.Before;
|
import org.junit.Before;
|
||||||
|
import org.junit.Test;
|
||||||
import org.junit.runner.RunWith;
|
import org.junit.runner.RunWith;
|
||||||
import org.mockito.Mock;
|
import org.mockito.Mock;
|
||||||
import static org.mockito.Mockito.*;
|
|
||||||
import org.mockito.junit.MockitoJUnitRunner;
|
import org.mockito.junit.MockitoJUnitRunner;
|
||||||
|
|
||||||
|
import javax.servlet.http.HttpServletRequest;
|
||||||
|
import java.util.Optional;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertFalse;
|
||||||
|
import static org.junit.Assert.assertTrue;
|
||||||
|
import static org.mockito.Mockito.when;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Tests {@link XsrfTokenClaimsValidator}.
|
* Tests {@link XsrfAccessTokenValidator}.
|
||||||
*
|
*
|
||||||
* @author Sebastian Sdorra
|
* @author Sebastian Sdorra
|
||||||
*/
|
*/
|
||||||
@RunWith(MockitoJUnitRunner.class)
|
@RunWith(MockitoJUnitRunner.class)
|
||||||
public class XsrfTokenClaimsValidatorTest {
|
public class XsrfAccessTokenValidatorTest {
|
||||||
|
|
||||||
@Mock
|
@Mock
|
||||||
private HttpServletRequest request;
|
private HttpServletRequest request;
|
||||||
|
|
||||||
private XsrfTokenClaimsValidator validator;
|
@Mock
|
||||||
|
private AccessToken accessToken;
|
||||||
|
|
||||||
|
private XsrfAccessTokenValidator validator;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Prepare object under test.
|
* Prepare object under test.
|
||||||
*/
|
*/
|
||||||
@Before
|
@Before
|
||||||
public void prepareObjectUnderTest() {
|
public void prepareObjectUnderTest() {
|
||||||
validator = new XsrfTokenClaimsValidator(() -> request);
|
validator = new XsrfAccessTokenValidator(() -> request);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Tests {@link XsrfTokenClaimsValidator#validate(java.util.Map)}.
|
* Tests {@link XsrfAccessTokenValidator#validate(AccessToken)}.
|
||||||
*/
|
*/
|
||||||
@Test
|
@Test
|
||||||
public void testValidate() {
|
public void testValidate() {
|
||||||
// prepare
|
// prepare
|
||||||
Map<String, Object> claims = Maps.newHashMap();
|
when(accessToken.getCustom(Xsrf.TOKEN_KEY)).thenReturn(Optional.of("abc"));
|
||||||
claims.put(Xsrf.TOKEN_KEY, "abc");
|
|
||||||
when(request.getHeader(Xsrf.HEADER_KEY)).thenReturn("abc");
|
when(request.getHeader(Xsrf.HEADER_KEY)).thenReturn("abc");
|
||||||
|
|
||||||
// execute and assert
|
// execute and assert
|
||||||
assertTrue(validator.validate(claims));
|
assertTrue(validator.validate(accessToken));
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Tests {@link XsrfTokenClaimsValidator#validate(java.util.Map)} with wrong header.
|
* Tests {@link XsrfAccessTokenValidator#validate(AccessToken)} with wrong header.
|
||||||
*/
|
*/
|
||||||
@Test
|
@Test
|
||||||
public void testValidateWithWrongHeader() {
|
public void testValidateWithWrongHeader() {
|
||||||
// prepare
|
// prepare
|
||||||
Map<String, Object> claims = Maps.newHashMap();
|
when(accessToken.getCustom(Xsrf.TOKEN_KEY)).thenReturn(Optional.of("abc"));
|
||||||
claims.put(Xsrf.TOKEN_KEY, "abc");
|
|
||||||
when(request.getHeader(Xsrf.HEADER_KEY)).thenReturn("123");
|
when(request.getHeader(Xsrf.HEADER_KEY)).thenReturn("123");
|
||||||
|
|
||||||
// execute and assert
|
// execute and assert
|
||||||
assertFalse(validator.validate(claims));
|
assertFalse(validator.validate(accessToken));
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Tests {@link XsrfTokenClaimsValidator#validate(java.util.Map)} without header.
|
* Tests {@link XsrfAccessTokenValidator#validate(AccessToken)} without header.
|
||||||
*/
|
*/
|
||||||
@Test
|
@Test
|
||||||
public void testValidateWithoutHeader() {
|
public void testValidateWithoutHeader() {
|
||||||
// prepare
|
// prepare
|
||||||
Map<String, Object> claims = Maps.newHashMap();
|
when(accessToken.getCustom(Xsrf.TOKEN_KEY)).thenReturn(Optional.of("abc"));
|
||||||
claims.put(Xsrf.TOKEN_KEY, "abc");
|
|
||||||
|
|
||||||
// execute and assert
|
// execute and assert
|
||||||
assertFalse(validator.validate(claims));
|
assertFalse(validator.validate(accessToken));
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Tests {@link XsrfTokenClaimsValidator#validate(java.util.Map)} without claims key.
|
* Tests {@link XsrfAccessTokenValidator#validate(AccessToken)} without claims key.
|
||||||
*/
|
*/
|
||||||
@Test
|
@Test
|
||||||
public void testValidateWithoutClaimsKey() {
|
public void testValidateWithoutClaimsKey() {
|
||||||
// prepare
|
// prepare
|
||||||
Map<String, Object> claims = Maps.newHashMap();
|
when(accessToken.getCustom(Xsrf.TOKEN_KEY)).thenReturn(Optional.empty());
|
||||||
|
|
||||||
// execute and assert
|
// execute and assert
|
||||||
assertTrue(validator.validate(claims));
|
assertTrue(validator.validate(accessToken));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Reference in New Issue
Block a user