Skip to content
Snippets Groups Projects

Compare revisions

Changes are shown as if the source revision was being merged into the target revision. Learn more about comparing revisions.

Source

Select target project
No results found

Target

Select target project
  • arsnova/arsnova-backend
  • pcvl72/arsnova-backend
  • tksl38/arsnova-backend
3 results
Show changes
Showing
with 1964 additions and 404 deletions
package de.thm.arsnova.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.ChannelRegistration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;
import de.thm.arsnova.config.properties.MessageBrokerProperties;
import de.thm.arsnova.config.properties.SecurityProperties;
import de.thm.arsnova.websocket.handler.AuthChannelInterceptorAdapter;
@Configuration
@EnableWebSocketMessageBroker
@EnableConfigurationProperties(MessageBrokerProperties.class)
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
private static final String MESSAGING_PREFIX = "/backend";
private static final String[] DESTINATION_PREFIX = {"/exchange", "/topic", "/queue"};
private static final String USER_REGISTRY_BROADCAST = "/topic/log-user-registry";
private static final String USER_DESTINATION_BROADCAST = "/queue/log-unresolved-user";
private final MessageBrokerProperties.Relay relayProperties;
private final AuthChannelInterceptorAdapter authChannelInterceptorAdapter;
private String[] corsOrigins;
@Autowired
public WebSocketConfig(
final MessageBrokerProperties messageBrokerProperties,
final SecurityProperties securityProperties,
final AuthChannelInterceptorAdapter authChannelInterceptorAdapter) {
this.relayProperties = messageBrokerProperties.getRelay();
this.corsOrigins = securityProperties.getCorsOrigins().stream().toArray(String[]::new);
this.authChannelInterceptorAdapter = authChannelInterceptorAdapter;
}
@Override
public void configureMessageBroker(final MessageBrokerRegistry config) {
config.setApplicationDestinationPrefixes(MESSAGING_PREFIX);
if (relayProperties.isEnabled()) {
config
.enableStompBrokerRelay(DESTINATION_PREFIX)
.setUserRegistryBroadcast(USER_REGISTRY_BROADCAST)
.setUserDestinationBroadcast(USER_DESTINATION_BROADCAST)
.setRelayHost(relayProperties.getHost())
.setRelayPort(relayProperties.getPort())
.setClientLogin(relayProperties.getUsername())
.setClientPasscode(relayProperties.getPassword());
} else {
config.enableSimpleBroker(DESTINATION_PREFIX);
}
}
@Override
public void registerStompEndpoints(final StompEndpointRegistry registry) {
registry.addEndpoint("/ws").setAllowedOrigins(corsOrigins).withSockJS();
}
@Override
public void configureClientInboundChannel(final ChannelRegistration registration) {
registration.interceptors(authChannelInterceptorAdapter);
}
}
package de.thm.arsnova.config;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;
import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
import org.springframework.core.env.PropertiesPropertySource;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.support.DefaultPropertySourceFactory;
import org.springframework.core.io.support.EncodedResource;
public class YamlPropertySourceFactory extends DefaultPropertySourceFactory {
@Override
public PropertySource<?> createPropertySource(final String name, final EncodedResource resource)
throws IOException {
try {
final YamlPropertiesFactoryBean yamlPropertiesFactoryBean = new PrefixedYamlPropertiesFactoryBean();
yamlPropertiesFactoryBean.setResources(resource.getResource());
yamlPropertiesFactoryBean.afterPropertiesSet();
final Properties properties = yamlPropertiesFactoryBean.getObject();
return new PropertiesPropertySource(name != null ? name : resource.getResource().getFilename(), properties);
} catch (final IllegalStateException e) {
if (e.getCause() instanceof FileNotFoundException) {
throw (FileNotFoundException) e.getCause();
}
throw e;
}
}
}
/**
* Configuration of Spring's and ARSnova's components
* Configuration of Spring's and ARSnova's components.
*/
package de.thm.arsnova.config;
/*
* This file is part of ARSnova Backend.
* Copyright (C) 2012-2019 The ARSnova Team and Contributors
*
* ARSnova Backend is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* ARSnova Backend is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.thm.arsnova.config.properties;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.core.style.ToStringCreator;
@ConfigurationProperties(AuthenticationProviderProperties.PREFIX)
public class AuthenticationProviderProperties {
public static final String PREFIX = SecurityProperties.PREFIX + ".authentication-providers";
public abstract static class Provider {
public enum Role {
MODERATOR,
PARTICIPANT
}
private boolean enabled;
private String title;
private int order;
private Set<Role> allowedRoles;
public boolean isEnabled() {
return enabled;
}
public void setEnabled(final boolean enabled) {
this.enabled = enabled;
}
public String getTitle() {
return title;
}
public void setTitle(final String title) {
this.title = title;
}
public int getOrder() {
return order;
}
public void setOrder(final int order) {
this.order = order;
}
public Set<Role> getAllowedRoles() {
return allowedRoles;
}
public void setAllowedRoles(final Set<Role> allowedRoles) {
this.allowedRoles = allowedRoles;
}
}
public static class Registered extends Provider {
private List<String> allowedEmailDomains;
private String registrationMailSubject;
private String registrationMailBody;
private String resetPasswordMailSubject;
private String resetPasswordMailBody;
public List<String> getAllowedEmailDomains() {
return allowedEmailDomains;
}
public void setAllowedEmailDomains(final List<String> allowedEmailDomains) {
this.allowedEmailDomains = allowedEmailDomains;
}
public String getRegistrationMailSubject() {
return registrationMailSubject;
}
public void setRegistrationMailSubject(final String registrationMailSubject) {
this.registrationMailSubject = registrationMailSubject;
}
public String getRegistrationMailBody() {
return registrationMailBody;
}
public void setRegistrationMailBody(final String registrationMailBody) {
this.registrationMailBody = registrationMailBody;
}
public String getResetPasswordMailSubject() {
return resetPasswordMailSubject;
}
public void setResetPasswordMailSubject(final String resetPasswordMailSubject) {
this.resetPasswordMailSubject = resetPasswordMailSubject;
}
public String getResetPasswordMailBody() {
return resetPasswordMailBody;
}
public void setResetPasswordMailBody(final String resetPasswordMailBody) {
this.resetPasswordMailBody = resetPasswordMailBody;
}
}
public static class Guest extends Provider {
}
public static class Ldap extends Provider {
private String hostUrl;
private String userDnPattern;
private String userIdAttribute;
private String userSearchFilter;
private String userSearchBase;
private String managerUserDn;
private String managerPassword;
private int connectTimeout;
public String getHostUrl() {
return hostUrl;
}
public void setHostUrl(final String hostUrl) {
this.hostUrl = hostUrl;
}
public String getUserDnPattern() {
return userDnPattern;
}
public void setUserDnPattern(final String userDnPattern) {
this.userDnPattern = userDnPattern;
}
public String getUserIdAttribute() {
return userIdAttribute;
}
public void setUserIdAttribute(final String userIdAttribute) {
this.userIdAttribute = userIdAttribute;
}
public String getUserSearchFilter() {
return userSearchFilter;
}
public void setUserSearchFilter(final String userSearchFilter) {
this.userSearchFilter = userSearchFilter;
}
public String getUserSearchBase() {
return userSearchBase;
}
public void setUserSearchBase(final String userSearchBase) {
this.userSearchBase = userSearchBase;
}
public String getManagerUserDn() {
return managerUserDn;
}
public void setManagerUserDn(final String managerUserDn) {
this.managerUserDn = managerUserDn;
}
public String getManagerPassword() {
return managerPassword;
}
public void setManagerPassword(final String managerPassword) {
this.managerPassword = managerPassword;
}
public int getConnectTimeout() {
return connectTimeout;
}
public void setConnectTimeout(final int connectTimeout) {
this.connectTimeout = connectTimeout;
}
}
public static class Oidc extends Provider {
private String issuer;
private String clientId;
private String secret;
public String getIssuer() {
return issuer;
}
public void setIssuer(final String issuer) {
this.issuer = issuer;
}
public String getClientId() {
return clientId;
}
public void setClientId(final String clientId) {
this.clientId = clientId;
}
public String getSecret() {
return secret;
}
public void setSecret(final String secret) {
this.secret = secret;
}
}
public static class Saml extends Provider {
public static class Idp {
private String metaFile;
public String getMetaFile() {
return metaFile;
}
public void setMetaFile(final String metaFile) {
this.metaFile = metaFile;
}
}
public static class Sp {
private String metaFile;
private String entityId;
public String getMetaFile() {
return metaFile;
}
public void setMetaFile(final String metaFile) {
this.metaFile = metaFile;
}
public String getEntityId() {
return entityId;
}
public void setEntityId(final String entityId) {
this.entityId = entityId;
}
}
public static class Keystore {
private String file;
private String storePassword;
private String keyAlias;
private String keyPassword;
public String getFile() {
return file;
}
public void setFile(final String file) {
this.file = file;
}
public String getStorePassword() {
return storePassword;
}
public void setStorePassword(final String storePassword) {
this.storePassword = storePassword;
}
public String getKeyAlias() {
return keyAlias;
}
public void setKeyAlias(final String keyAlias) {
this.keyAlias = keyAlias;
}
public String getKeyPassword() {
return keyPassword;
}
public void setKeyPassword(final String keyPassword) {
this.keyPassword = keyPassword;
}
}
private boolean enabled;
private Idp idp;
private Sp sp;
private Keystore keystore;
private String userIdAttribute;
private int assertionConsumerServiceIndex;
private int maxAuthenticationLifetime;
@Override
public boolean isEnabled() {
return enabled;
}
@Override
public void setEnabled(final boolean enabled) {
this.enabled = enabled;
}
public Idp getIdp() {
return idp;
}
public void setIdp(final Idp idp) {
this.idp = idp;
}
public Sp getSp() {
return sp;
}
public void setSp(final Sp sp) {
this.sp = sp;
}
public Keystore getKeystore() {
return keystore;
}
public void setKeystore(final Keystore keystore) {
this.keystore = keystore;
}
public String getUserIdAttribute() {
return userIdAttribute;
}
public void setUserIdAttribute(final String userIdAttribute) {
this.userIdAttribute = userIdAttribute;
}
public int getAssertionConsumerServiceIndex() {
return assertionConsumerServiceIndex;
}
public void setAssertionConsumerServiceIndex(final int assertionConsumerServiceIndex) {
this.assertionConsumerServiceIndex = assertionConsumerServiceIndex;
}
public int getMaxAuthenticationLifetime() {
return maxAuthenticationLifetime;
}
public void setMaxAuthenticationLifetime(final int maxAuthenticationLifetime) {
this.maxAuthenticationLifetime = maxAuthenticationLifetime;
}
}
public static class Cas extends Provider {
private String hostUrl;
public String getHostUrl() {
return hostUrl;
}
public void setHostUrl(final String hostUrl) {
this.hostUrl = hostUrl;
}
}
public static class Oauth extends Provider {
private String key;
private String secret;
public String getKey() {
return key;
}
public void setKey(final String key) {
this.key = key;
}
public String getSecret() {
return secret;
}
public void setSecret(final String secret) {
this.secret = secret;
}
@Override
public String toString() {
return new ToStringCreator(this).append("enabled", isEnabled()).append("key", key).toString();
}
}
private Registered registered;
private Guest guest;
private List<Ldap> ldap;
private List<Oidc> oidc;
private Saml saml;
private Cas cas;
private Map<String, Oauth> oauth;
public Registered getRegistered() {
return registered;
}
public void setRegistered(final Registered registered) {
this.registered = registered;
}
public Guest getGuest() {
return guest;
}
public void setGuest(final Guest guest) {
this.guest = guest;
}
public List<Ldap> getLdap() {
return ldap;
}
public void setLdap(final List<Ldap> ldap) {
this.ldap = ldap;
}
public List<Oidc> getOidc() {
return oidc;
}
public void setOidc(final List<Oidc> oidc) {
this.oidc = oidc;
}
public Saml getSaml() {
return saml;
}
public void setSaml(final Saml saml) {
this.saml = saml;
}
public Cas getCas() {
return cas;
}
public void setCas(final Cas cas) {
this.cas = cas;
}
public Map<String, Oauth> getOauth() {
return oauth;
}
public void setOauth(final Map<String, Oauth> oauth) {
this.oauth = oauth;
}
}
/*
* This file is part of ARSnova Backend.
* Copyright (C) 2012-2019 The ARSnova Team and Contributors
*
* ARSnova Backend is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* ARSnova Backend is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.thm.arsnova.config.properties;
import org.springframework.boot.context.properties.ConfigurationProperties;
@ConfigurationProperties(CouchDbProperties.PREFIX)
public class CouchDbProperties {
public static final String PREFIX = SystemProperties.PREFIX + ".couchdb";
private String host;
private int port;
private String dbName;
private String username;
private String password;
private String migrateFrom;
public String getHost() {
return host;
}
public void setHost(final String host) {
this.host = host;
}
public int getPort() {
return port;
}
public void setPort(final int port) {
this.port = port;
}
public String getDbName() {
return dbName;
}
public void setDbName(final String dbName) {
this.dbName = dbName;
}
public String getUsername() {
return username;
}
public void setUsername(final String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(final String password) {
this.password = password;
}
public String getMigrateFrom() {
return migrateFrom;
}
public void setMigrateFrom(final String migrateFrom) {
this.migrateFrom = migrateFrom;
}
}
/*
* This file is part of ARSnova Backend.
* Copyright (C) 2012-2019 The ARSnova Team and Contributors
*
* ARSnova Backend is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* ARSnova Backend is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.thm.arsnova.config.properties;
import com.fasterxml.jackson.annotation.JsonView;
import org.springframework.boot.context.properties.ConfigurationProperties;
import de.thm.arsnova.model.serialization.View;
@ConfigurationProperties(FeatureProperties.PREFIX)
public class FeatureProperties {
public static final String PREFIX = "features";
public static class Contents {
private boolean enabled;
private int answerOptionLimit;
@JsonView(View.Public.class)
public boolean isEnabled() {
return enabled;
}
public void setEnabled(final boolean enabled) {
this.enabled = enabled;
}
@JsonView(View.Public.class)
public int getAnswerOptionLimit() {
return answerOptionLimit;
}
public void setAnswerOptionLimit(final int answerOptionLimit) {
this.answerOptionLimit = answerOptionLimit;
}
}
public static class Comments {
private boolean enabled;
@JsonView(View.Public.class)
public boolean isEnabled() {
return enabled;
}
public void setEnabled(final boolean enabled) {
this.enabled = enabled;
}
}
public static class LiveFeedback {
private boolean enabled;
private int resetInterval;
@JsonView(View.Public.class)
public boolean isEnabled() {
return enabled;
}
public void setEnabled(final boolean enabled) {
this.enabled = enabled;
}
public int getResetInterval() {
return resetInterval;
}
public void setResetInterval(final int resetInterval) {
this.resetInterval = resetInterval;
}
}
public static class ContentPool {
private boolean enabled;
@JsonView(View.Public.class)
public boolean isEnabled() {
return enabled;
}
public void setEnabled(final boolean enabled) {
this.enabled = enabled;
}
}
private Contents contents;
private Comments comments;
private LiveFeedback liveFeedback;
private ContentPool contentPool;
@JsonView(View.Public.class)
public Contents getContents() {
return contents;
}
public void setContents(final Contents contents) {
this.contents = contents;
}
@JsonView(View.Public.class)
public Comments getComments() {
return comments;
}
public void setComments(final Comments comments) {
this.comments = comments;
}
@JsonView(View.Public.class)
public LiveFeedback getLiveFeedback() {
return liveFeedback;
}
public void setLiveFeedback(final LiveFeedback liveFeedback) {
this.liveFeedback = liveFeedback;
}
@JsonView(View.Public.class)
public ContentPool getContentPool() {
return contentPool;
}
public void setContentPool(final ContentPool contentPool) {
this.contentPool = contentPool;
}
}
/*
* This file is part of ARSnova Backend.
* Copyright (C) 2012-2016 The ARSnova Team
* Copyright (C) 2012-2019 The ARSnova Team and Contributors
*
* ARSnova Backend is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
......@@ -15,49 +15,70 @@
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.thm.arsnova.events;
import de.thm.arsnova.entities.Question;
import de.thm.arsnova.entities.Session;
package de.thm.arsnova.config.properties;
import java.util.HashMap;
import org.springframework.boot.context.properties.ConfigurationProperties;
/**
* Fires whenever a peer instruction round is reset.
*/
public class PiRoundResetEvent extends SessionEvent {
@ConfigurationProperties(MessageBrokerProperties.PREFIX)
public class MessageBrokerProperties {
public static final String PREFIX = SystemProperties.PREFIX + ".message-broker";
private static final long serialVersionUID = 1L;
public static class Relay {
private boolean enabled;
private String host;
private int port;
private String username;
private String password;
private final String questionId;
private final String questionVariant;
public boolean isEnabled() {
return enabled;
}
public PiRoundResetEvent(Object source, Session session, Question question) {
super(source, session);
questionId = question.get_id();
questionVariant = question.getQuestionVariant();
}
public void setEnabled(final boolean enabled) {
this.enabled = enabled;
}
@Override
public void accept(NovaEventVisitor visitor) {
visitor.visit(this);
}
public String getHost() {
return host;
}
public String getQuestionId() {
return questionId;
}
public void setHost(final String host) {
this.host = host;
}
public String getQuestionVariant() {
return questionVariant;
}
public int getPort() {
return port;
}
public void setPort(final int port) {
this.port = port;
}
public HashMap<String, String> getPiRoundResetInformations() {
HashMap<String, String> map = new HashMap<String, String>();
public String getUsername() {
return username;
}
map.put("_id", getQuestionId());
map.put("variant", getQuestionVariant());
public void setUsername(final String username) {
this.username = username;
}
return map;
public String getPassword() {
return password;
}
public void setPassword(final String password) {
this.password = password;
}
}
private Relay relay;
public Relay getRelay() {
return relay;
}
public void setRelay(final Relay relay) {
this.relay = relay;
}
}
/*
* This file is part of ARSnova Backend.
* Copyright (C) 2012-2019 The ARSnova Team and Contributors
*
* ARSnova Backend is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* ARSnova Backend is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.thm.arsnova.config.properties;
import java.time.Duration;
import java.time.temporal.ChronoUnit;
import java.util.List;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.convert.DurationUnit;
@ConfigurationProperties(SecurityProperties.PREFIX)
public class SecurityProperties {
public static final String PREFIX = "security";
public static class Jwt {
private String serverId;
private String secret;
@DurationUnit(ChronoUnit.MINUTES)
private Duration validityPeriod;
public String getServerId() {
return serverId;
}
public void setServerId(final String serverId) {
this.serverId = serverId;
}
public String getSecret() {
return secret;
}
public void setSecret(final String secret) {
this.secret = secret;
}
public Duration getValidityPeriod() {
return validityPeriod;
}
public void setValidityPeriod(final Duration validityPeriod) {
this.validityPeriod = validityPeriod;
}
}
private Jwt jwt;
private List<String> adminAccounts;
private int loginTryLimit;
private List<String> corsOrigins;
public Jwt getJwt() {
return jwt;
}
public void setJwt(final Jwt jwt) {
this.jwt = jwt;
}
public List<String> getAdminAccounts() {
return adminAccounts;
}
public void setAdminAccounts(final List<String> adminAccounts) {
this.adminAccounts = adminAccounts;
}
public int getLoginTryLimit() {
return loginTryLimit;
}
public void setLoginTryLimit(final int loginTryLimit) {
this.loginTryLimit = loginTryLimit;
}
public List<String> getCorsOrigins() {
return corsOrigins;
}
public void setCorsOrigins(final List<String> corsOrigins) {
this.corsOrigins = corsOrigins;
}
}
/*
* This file is part of ARSnova Backend.
* Copyright (C) 2012-2019 The ARSnova Team and Contributors
*
* ARSnova Backend is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* ARSnova Backend is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.thm.arsnova.config.properties;
import org.springframework.boot.context.properties.ConfigurationProperties;
@ConfigurationProperties(SystemProperties.PREFIX)
public class SystemProperties {
public static final String PREFIX = "system";
public static class Api {
private String proxyPath;
private boolean indentResponseBody;
private boolean exposeErrorMessages;
public String getProxyPath() {
return proxyPath;
}
public void setProxyPath(final String proxyPath) {
this.proxyPath = proxyPath;
}
public boolean isIndentResponseBody() {
return indentResponseBody;
}
public void setIndentResponseBody(final boolean indentResponseBody) {
this.indentResponseBody = indentResponseBody;
}
public boolean isExposeErrorMessages() {
return exposeErrorMessages;
}
public void setExposeErrorMessages(final boolean exposeErrorMessages) {
this.exposeErrorMessages = exposeErrorMessages;
}
}
public static class Mail {
private String senderName;
private String senderAddress;
private String host;
public String getSenderName() {
return senderName;
}
public void setSenderName(final String senderName) {
this.senderName = senderName;
}
public String getSenderAddress() {
return senderAddress;
}
public void setSenderAddress(final String senderAddress) {
this.senderAddress = senderAddress;
}
public String getHost() {
return host;
}
public void setHost(final String host) {
this.host = host;
}
}
public static class LmsConnector {
private boolean enabled;
private String hostUrl;
private String username;
private String password;
public boolean isEnabled() {
return enabled;
}
public void setEnabled(final boolean enabled) {
this.enabled = enabled;
}
public String getHostUrl() {
return hostUrl;
}
public void setHostUrl(final String hostUrl) {
this.hostUrl = hostUrl;
}
public String getUsername() {
return username;
}
public void setUsername(final String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(final String password) {
this.password = password;
}
}
public static class Socketio {
private String bindAddress;
private int port;
private String proxyPath;
public String getBindAddress() {
return bindAddress;
}
public void setBindAddress(final String bindAddress) {
this.bindAddress = bindAddress;
}
public int getPort() {
return port;
}
public void setPort(final int port) {
this.port = port;
}
public String getProxyPath() {
return proxyPath;
}
public void setProxyPath(final String proxyPath) {
this.proxyPath = proxyPath;
}
}
private String rootUrl;
private Api api;
private Mail mail;
private LmsConnector lmsConnector;
private Socketio socketio;
public String getRootUrl() {
return rootUrl;
}
public void setRootUrl(final String rootUrl) {
this.rootUrl = rootUrl;
}
public Api getApi() {
return api;
}
public void setApi(final Api api) {
this.api = api;
}
public Mail getMail() {
return mail;
}
public void setMail(final Mail mail) {
this.mail = mail;
}
public LmsConnector getLmsConnector() {
return lmsConnector;
}
public void setLmsConnector(final LmsConnector lmsConnector) {
this.lmsConnector = lmsConnector;
}
public Socketio getSocketio() {
return socketio;
}
public void setSocketio(final Socketio socketio) {
this.socketio = socketio;
}
}
/*
* This file is part of ARSnova Backend.
* Copyright (C) 2012-2019 The ARSnova Team and Contributors
*
* ARSnova Backend is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* ARSnova Backend is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.thm.arsnova.config.properties;
import java.util.Map;
import org.springframework.boot.context.properties.ConfigurationProperties;
@ConfigurationProperties
public class UiProperties {
private Map<String, Object> ui;
public Map<String, Object> getUi() {
return ui;
}
public void setUi(final Map<String, Object> ui) {
this.ui = ui;
}
}
/*
* This file is part of ARSnova Backend.
* Copyright (C) 2012-2016 The ARSnova Team
* Copyright (C) 2012-2019 The ARSnova Team and Contributors
*
* ARSnova Backend is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
......@@ -15,6 +15,7 @@
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.thm.arsnova.controller;
/**
......
/*
* This file is part of ARSnova Backend.
* Copyright (C) 2012-2019 The ARSnova Team and Contributors
*
* ARSnova Backend is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* ARSnova Backend is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.thm.arsnova.controller;
import java.io.IOException;
import java.util.Collection;
import java.util.Map;
import java.util.Set;
import javax.naming.OperationNotSupportedException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PatchMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.util.UriComponentsBuilder;
import de.thm.arsnova.model.Entity;
import de.thm.arsnova.model.FindQuery;
import de.thm.arsnova.service.EntityService;
import de.thm.arsnova.service.FindQueryService;
import de.thm.arsnova.web.exceptions.NotFoundException;
/**
* Base type for Entity controllers which provides basic CRUD operations and supports Entity patching.
*
* @param <E> Entity type
* @author Daniel Gerhardt
*/
public abstract class AbstractEntityController<E extends Entity> {
public static final String MEDIATYPE_EMPTY = "application/x-empty";
private static final Logger logger = LoggerFactory.getLogger(AbstractEntityController.class);
protected static final String ENTITY_ID_HEADER = "Arsnova-Entity-Id";
protected static final String ENTITY_REVISION_HEADER = "Arsnova-Entity-Revision";
protected static final String DEFAULT_ROOT_MAPPING = "/";
protected static final String DEFAULT_ID_MAPPING = "/{id:[^~].*}";
protected static final String DEFAULT_ALIAS_MAPPING = "/~{alias}";
protected static final String DEFAULT_FIND_MAPPING = "/find";
protected static final String ALIAS_SUBPATH = "/{subPath:.+}";
protected static final String GET_MAPPING = DEFAULT_ID_MAPPING;
protected static final String GET_MULTIPLE_MAPPING = DEFAULT_ROOT_MAPPING;
protected static final String PUT_MAPPING = DEFAULT_ID_MAPPING;
protected static final String POST_MAPPING = DEFAULT_ROOT_MAPPING;
protected static final String PATCH_MAPPING = DEFAULT_ID_MAPPING;
protected static final String DELETE_MAPPING = DEFAULT_ID_MAPPING;
protected static final String FIND_MAPPING = DEFAULT_FIND_MAPPING;
protected final EntityService<E> entityService;
protected FindQueryService<E> findQueryService;
protected AbstractEntityController(final EntityService<E> entityService) {
this.entityService = entityService;
}
protected abstract String getMapping();
@GetMapping(GET_MAPPING)
public E get(@PathVariable final String id) {
return entityService.get(id);
}
@GetMapping(GET_MULTIPLE_MAPPING)
public Iterable<E> getMultiple(@RequestParam final Collection<String> ids) {
return entityService.get(ids);
}
@PutMapping(value = PUT_MAPPING, produces = MEDIATYPE_EMPTY)
public void putWithoutResponse(@RequestBody final E entity, final HttpServletResponse httpServletResponse) {
put(entity, httpServletResponse);
}
@PutMapping(PUT_MAPPING)
public E put(@RequestBody final E entity, final HttpServletResponse httpServletResponse) {
final E oldEntity = entityService.get(entity.getId());
entityService.update(oldEntity, entity);
httpServletResponse.setHeader(ENTITY_ID_HEADER, entity.getId());
httpServletResponse.setHeader(ENTITY_REVISION_HEADER, entity.getRevision());
return entity;
}
@PostMapping(value = POST_MAPPING, produces = MEDIATYPE_EMPTY)
@ResponseStatus(HttpStatus.CREATED)
public void postWithoutResponse(@RequestBody final E entity, final HttpServletResponse httpServletResponse) {
post(entity, httpServletResponse);
}
@PostMapping(POST_MAPPING)
@ResponseStatus(HttpStatus.CREATED)
public E post(@RequestBody final E entity, final HttpServletResponse httpServletResponse) {
entityService.create(entity);
final String uri = UriComponentsBuilder.fromPath(getMapping()).path(GET_MAPPING)
.buildAndExpand(entity.getId()).toUriString();
httpServletResponse.setHeader(HttpHeaders.LOCATION, uri);
httpServletResponse.setHeader(ENTITY_ID_HEADER, entity.getId());
httpServletResponse.setHeader(ENTITY_REVISION_HEADER, entity.getRevision());
return entity;
}
@PatchMapping(value = PATCH_MAPPING, produces = MEDIATYPE_EMPTY)
public void patchWithoutResponse(@PathVariable final String id, @RequestBody final Map<String, Object> changes,
final HttpServletResponse httpServletResponse) throws IOException {
patch(id, changes, httpServletResponse);
}
@PatchMapping(PATCH_MAPPING)
public E patch(@PathVariable final String id, @RequestBody final Map<String, Object> changes,
final HttpServletResponse httpServletResponse) throws IOException {
final E entity = entityService.get(id);
entityService.patch(entity, changes);
httpServletResponse.setHeader(ENTITY_ID_HEADER, entity.getId());
httpServletResponse.setHeader(ENTITY_REVISION_HEADER, entity.getRevision());
return entity;
}
@DeleteMapping(DELETE_MAPPING)
public void delete(@PathVariable final String id) {
final E entity = entityService.get(id);
entityService.delete(entity);
}
@PostMapping(FIND_MAPPING)
public Iterable<E> find(@RequestBody final FindQuery<E> findQuery) throws OperationNotSupportedException {
if (findQueryService != null) {
logger.debug("Resolving find query: {}", findQuery);
final Set<String> ids = findQueryService.resolveQuery(findQuery);
logger.debug("Resolved find query to IDs: {}", ids);
return entityService.get(ids);
} else {
throw new OperationNotSupportedException("Find is not supported for this entity type.");
}
}
@RequestMapping(value = {DEFAULT_ALIAS_MAPPING, DEFAULT_ALIAS_MAPPING + ALIAS_SUBPATH})
public void forwardAlias(@PathVariable final String alias, @PathVariable(required = false) final String subPath,
final HttpServletRequest httpServletRequest, final HttpServletResponse httpServletResponse)
throws ServletException, IOException {
final String targetPath = String.format(
"%s/%s%s", getMapping(), resolveAlias(alias), subPath != null ? "/" + subPath : "");
logger.debug("Forwarding alias request to {}", targetPath);
httpServletRequest.getRequestDispatcher(targetPath)
.forward(httpServletRequest, httpServletResponse);
}
protected String resolveAlias(final String alias) {
throw new NotFoundException("Aliases not supported for " + getMapping() + ".");
}
@Autowired(required = false)
public void setFindQueryService(final FindQueryService<E> findQueryService) {
this.findQueryService = findQueryService;
}
}
/*
* This file is part of ARSnova Backend.
* Copyright (C) 2012-2016 The ARSnova Team
* Copyright (C) 2012-2019 The ARSnova Team and Contributors
*
* ARSnova Backend is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
......@@ -15,32 +15,29 @@
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.thm.arsnova.events;
import de.thm.arsnova.entities.InterposedQuestion;
import de.thm.arsnova.entities.Session;
package de.thm.arsnova.controller;
/**
* Fires whenever an interposed question is deleted.
*/
public class DeleteInterposedQuestionEvent extends SessionEvent {
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
private static final long serialVersionUID = 1L;
import de.thm.arsnova.model.Answer;
import de.thm.arsnova.service.AnswerService;
private final InterposedQuestion question;
@RestController
@RequestMapping(AnswerController.REQUEST_MAPPING)
public class AnswerController extends AbstractEntityController<Answer> {
protected static final String REQUEST_MAPPING = "/answer";
public DeleteInterposedQuestionEvent(Object source, Session session, InterposedQuestion question) {
super(source, session);
this.question = question;
}
private AnswerService answerService;
@Override
public void accept(NovaEventVisitor visitor) {
visitor.visit(this);
public AnswerController(final AnswerService answerService) {
super(answerService);
this.answerService = answerService;
}
public InterposedQuestion getQuestion() {
return question;
@Override
protected String getMapping() {
return REQUEST_MAPPING;
}
}
/*
* This file is part of ARSnova Backend.
* Copyright (C) 2012-2016 The ARSnova Team
*
* ARSnova Backend is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* ARSnova Backend is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.thm.arsnova.controller;
import de.thm.arsnova.entities.InterposedReadingCount;
import de.thm.arsnova.entities.transport.InterposedQuestion;
import de.thm.arsnova.exceptions.BadRequestException;
import de.thm.arsnova.services.IQuestionService;
import de.thm.arsnova.web.DeprecatedApi;
import de.thm.arsnova.web.Pagination;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
/**
* Handles requests related to audience questions, which are also called interposed or feedback questions.
*/
@RestController
@RequestMapping("/audiencequestion")
@Api(value = "/audiencequestion", description = "the Audience Question API")
public class AudienceQuestionController extends PaginationController {
public static final Logger LOGGER = LoggerFactory.getLogger(AudienceQuestionController.class);
@Autowired
private IQuestionService questionService;
@ApiOperation(value = "Count all the questions in current session",
nickname = "getAudienceQuestionCount")
@RequestMapping(value = "/count", method = RequestMethod.GET)
@DeprecatedApi
@Deprecated
public int getInterposedCount(@ApiParam(value = "Session-Key from current session", required = true) @RequestParam final String sessionkey) {
return questionService.getInterposedCount(sessionkey);
}
@ApiOperation(value = "count all unread interposed questions",
nickname = "getUnreadInterposedCount")
@RequestMapping(value = "/readcount", method = RequestMethod.GET)
@DeprecatedApi
@Deprecated
public InterposedReadingCount getUnreadInterposedCount(@ApiParam(value = "Session-Key from current session", required = true) @RequestParam("sessionkey") final String sessionkey, String user) {
return questionService.getInterposedReadingCount(sessionkey, user);
}
@ApiOperation(value = "Retrieves all Interposed Questions for a Session",
nickname = "getInterposedQuestions")
@RequestMapping(value = "/", method = RequestMethod.GET)
@Pagination
public List<InterposedQuestion> getInterposedQuestions(@ApiParam(value = "Session-Key from current session", required = true) @RequestParam final String sessionkey) {
return InterposedQuestion.fromList(questionService.getInterposedQuestions(sessionkey, offset, limit));
}
@ApiOperation(value = "Retrieves an InterposedQuestion",
nickname = "getInterposedQuestion")
@RequestMapping(value = "/{questionId}", method = RequestMethod.GET)
public InterposedQuestion getInterposedQuestion(@ApiParam(value = "ID of the question that needs to be deleted", required = true) @PathVariable final String questionId) {
return new InterposedQuestion(questionService.readInterposedQuestion(questionId));
}
@ApiOperation(value = "Creates a new Interposed Question for a Session and returns the InterposedQuestion's data",
nickname = "postInterposedQuestion")
@ApiResponses(value = {
@ApiResponse(code = 400, message = HTML_STATUS_400)
})
@RequestMapping(value = "/", method = RequestMethod.POST)
@ResponseStatus(HttpStatus.CREATED)
public void postInterposedQuestion(
@ApiParam(value = "Session-Key from current session", required = true) @RequestParam final String sessionkey,
@ApiParam(value = "the body from the new question", required = true) @RequestBody final de.thm.arsnova.entities.InterposedQuestion question
) {
if (questionService.saveQuestion(question)) {
return;
}
throw new BadRequestException();
}
@ApiOperation(value = "Deletes an InterposedQuestion",
nickname = "deleteInterposedQuestion")
@RequestMapping(value = "/{questionId}", method = RequestMethod.DELETE)
public void deleteInterposedQuestion(@ApiParam(value = "ID of the question that needs to be deleted", required = true) @PathVariable final String questionId) {
questionService.deleteInterposedQuestion(questionId);
}
}
/*
* This file is part of ARSnova Backend.
* Copyright (C) 2012-2019 The ARSnova Team and Contributors
*
* ARSnova Backend is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* ARSnova Backend is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.thm.arsnova.controller;
import java.io.IOException;
import java.util.Arrays;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.pac4j.core.context.J2EContext;
import org.pac4j.oidc.client.OidcClient;
import org.pac4j.saml.client.SAML2Client;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.cas.web.CasAuthenticationEntryPoint;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.View;
import org.springframework.web.servlet.view.RedirectView;
import de.thm.arsnova.config.SecurityConfig;
import de.thm.arsnova.model.ClientAuthentication;
import de.thm.arsnova.model.LoginCredentials;
import de.thm.arsnova.model.UserProfile;
import de.thm.arsnova.security.LoginAuthenticationSucessHandler;
import de.thm.arsnova.service.UserService;
import de.thm.arsnova.web.exceptions.NotImplementedException;
@RestController
@RequestMapping("/auth")
public class AuthenticationController {
private UserService userService;
private OidcClient oidcClient;
private SAML2Client saml2Client;
private CasAuthenticationEntryPoint casEntryPoint;
public AuthenticationController(final UserService userService) {
this.userService = userService;
}
@Autowired(required = false)
public void setOidcClient(final OidcClient oidcClient) {
this.oidcClient = oidcClient;
}
@Autowired(required = false)
public void setSaml2Client(final SAML2Client saml2Client) {
this.saml2Client = saml2Client;
}
@Autowired(required = false)
public void setCasEntryPoint(final CasAuthenticationEntryPoint casEntryPoint) {
this.casEntryPoint = casEntryPoint;
}
@PostMapping("/login")
public ClientAuthentication login(@RequestParam(defaultValue = "false") final boolean refresh,
final HttpServletRequest request, final HttpServletResponse response) {
if (request.getCookies() != null && Arrays.stream(request.getCookies())
.anyMatch(c -> c.getName().equalsIgnoreCase(LoginAuthenticationSucessHandler.AUTH_COOKIE_NAME))) {
/* Delete cookie */
final Cookie cookie = new Cookie(LoginAuthenticationSucessHandler.AUTH_COOKIE_NAME, null);
cookie.setPath(request.getContextPath());
cookie.setMaxAge(0);
response.addCookie(cookie);
}
return userService.getCurrentClientAuthentication(refresh);
}
@PostMapping("/login/guest")
public ClientAuthentication loginGuest(final HttpServletRequest request) {
final ClientAuthentication currentAuthentication = userService.getCurrentClientAuthentication(false);
if (currentAuthentication != null
&& currentAuthentication.getAuthProvider() == UserProfile.AuthProvider.ARSNOVA_GUEST) {
return currentAuthentication;
}
userService.authenticate(new UsernamePasswordAuthenticationToken(null, null),
UserProfile.AuthProvider.ARSNOVA_GUEST, request.getRemoteAddr());
return userService.getCurrentClientAuthentication(false);
}
@PostMapping("/login/{providerId}")
public ClientAuthentication loginViaProvider(
@PathVariable final String providerId,
@RequestBody final LoginCredentials loginCredentials,
final HttpServletRequest request) {
switch (providerId) {
case "registered":
final String loginId = loginCredentials.getLoginId().toLowerCase();
userService.authenticate(new UsernamePasswordAuthenticationToken(
loginId, loginCredentials.getPassword()),
UserProfile.AuthProvider.ARSNOVA, request.getRemoteAddr());
return userService.getCurrentClientAuthentication(false);
case SecurityConfig.LDAP_PROVIDER_ID:
userService.authenticate(new UsernamePasswordAuthenticationToken(
loginCredentials.getLoginId(), loginCredentials.getPassword()),
UserProfile.AuthProvider.LDAP, request.getRemoteAddr());
return userService.getCurrentClientAuthentication(false);
default:
throw new IllegalArgumentException("Invalid provider ID.");
}
}
@GetMapping("/sso/{providerId}")
public View redirectToSso(@PathVariable final String providerId,
final HttpServletRequest request, final HttpServletResponse response) throws IOException, ServletException {
switch (providerId) {
case SecurityConfig.OIDC_PROVIDER_ID:
if (oidcClient == null) {
throw new IllegalArgumentException("Invalid provider ID.");
}
return new RedirectView(
oidcClient.getRedirectAction(new J2EContext(request, response)).getLocation());
case SecurityConfig.SAML_PROVIDER_ID:
if (saml2Client == null) {
throw new IllegalArgumentException("Invalid provider ID.");
}
return new RedirectView(
saml2Client.getRedirectAction(new J2EContext(request, response)).getLocation());
case SecurityConfig.CAS_PROVIDER_ID:
if (casEntryPoint == null) {
throw new IllegalArgumentException("Invalid provider ID.");
}
casEntryPoint.commence(request, response, null);
return null;
default:
throw new IllegalArgumentException("Invalid provider ID.");
}
}
@GetMapping(value = "/config/saml/sp-metadata.xml", produces = MediaType.APPLICATION_XML_VALUE)
public String samlSpMetadata() throws IOException {
if (saml2Client == null) {
throw new NotImplementedException("SAML authentication is disabled.");
}
return saml2Client.getServiceProviderMetadataResolver().getMetadata();
}
}
/*
* This file is part of ARSnova Backend.
* Copyright (C) 2012-2016 The ARSnova Team
* Copyright (C) 2012-2019 The ARSnova Team and Contributors
*
* ARSnova Backend is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
......@@ -15,32 +15,29 @@
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.thm.arsnova.events;
import de.thm.arsnova.entities.InterposedQuestion;
import de.thm.arsnova.entities.Session;
package de.thm.arsnova.controller;
/**
* Fires whenever a new interposed (aka. feedback or audience) question is added.
*/
public class NewInterposedQuestionEvent extends SessionEvent {
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
private static final long serialVersionUID = 1L;
import de.thm.arsnova.model.Comment;
import de.thm.arsnova.service.CommentService;
private final InterposedQuestion question;
@RestController
@RequestMapping(CommentController.REQUEST_MAPPING)
public class CommentController extends AbstractEntityController<Comment> {
protected static final String REQUEST_MAPPING = "/comment";
public NewInterposedQuestionEvent(Object source, Session session, InterposedQuestion question) {
super(source, session);
this.question = question;
}
private CommentService commentService;
public InterposedQuestion getQuestion() {
return question;
public CommentController(final CommentService commentService) {
super(commentService);
this.commentService = commentService;
}
@Override
public void accept(NovaEventVisitor visitor) {
visitor.visit(this);
protected String getMapping() {
return REQUEST_MAPPING;
}
}
/*
* This file is part of ARSnova Backend.
* Copyright (C) 2012-2016 The ARSnova Team
* Copyright (C) 2012-2019 The ARSnova Team and Contributors
*
* ARSnova Backend is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
......@@ -15,265 +15,90 @@
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.thm.arsnova.controller;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
package de.thm.arsnova.controller;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import de.thm.arsnova.config.SecurityConfig;
import de.thm.arsnova.config.properties.AuthenticationProviderProperties;
import de.thm.arsnova.config.properties.FeatureProperties;
import de.thm.arsnova.config.properties.UiProperties;
import de.thm.arsnova.model.AuthenticationProvider;
import de.thm.arsnova.model.Configuration;
@RestController
@RequestMapping(ConfigurationController.REQUEST_MAPPING)
@EnableConfigurationProperties(UiProperties.class)
public class ConfigurationController {
protected static final String REQUEST_MAPPING = "/configuration";
private AuthenticationProviderProperties providerProperties;
private UiProperties uiProperties;
private FeatureProperties featureProperties;
private List<AuthenticationProvider> authenticationProviders;
private Map<String, Object> featureConfig;
public ConfigurationController(
final AuthenticationProviderProperties authenticationProviderProperties,
final UiProperties uiProperties,
final FeatureProperties featureProperties) {
this.providerProperties = authenticationProviderProperties;
this.uiProperties = uiProperties;
this.featureProperties = featureProperties;
buildAuthenticationProviderConfig();
buildFeatureConfig();
}
/**
* The ConfigurationController provides frontend clients with information necessary to correctly interact with the
* backend and other frontends as well as settings for ARSnova. The the alternative /arsnova-config route is necessary
* in case the backend application is deployed as root context.
*/
@Controller
@RequestMapping({"/configuration", "/arsnova-config"})
public class ConfigurationController extends AbstractController {
public static final Logger LOGGER = LoggerFactory
.getLogger(ConfigurationController.class);
@Value("${api.path:}")
private String apiPath;
@Value("${socketio.proxy-path:}")
private String socketioPath;
@Value("${customization.path}")
private String customizationPath;
@Value("${mobile.path}")
private String mobilePath;
@Value("${presenter.path}")
private String presenterPath;
@Value("${links.overlay.url}")
private String overlayUrl;
@Value("${links.organization.url}")
private String organizationUrl;
@Value("${links.imprint.url}")
private String imprintUrl;
@Value("${links.blog.url:}")
private String blogUrl;
@Value("${links.privacy-policy.url}")
private String privacyPolicyUrl;
@Value("${links.documentation.url}")
private String documentationUrl;
@Value("${links.presenter-documentation.url}")
private String presenterDocumentationUrl;
@Value("${feedback.warning:5}")
private String feedbackWarningOffset;
@Value("${features.mathjax.enabled:true}")
private String mathJaxEnabled;
@Value("${features.mathjax.src:}")
private String mathJaxSrc;
@Value("${features.freetext-imageanswer.enabled:false}")
private String imageAnswerEnabled;
@Value("${features.question-format.grid-square.enabled:false}")
private String gridSquareEnabled;
@Value("${features.session-import-export.enabled:false}")
private String sessionImportExportEnabled;
@Value("${features.public-pool.enabled:false}")
private String publicPoolEnabled;
@Value("${question.answer-option-limit:8}")
private String answerOptionLimit;
@Value("${upload.filesize_b:}")
private String maxUploadFilesize;
@Value("${question.parse-answer-option-formatting:false}")
private String parseAnswerOptionFormatting;
@Value("${pp.subjects}")
private String ppSubjects;
@Value("${pp.licenses}")
private String ppLicenses;
@Value("${pp.logofilesize_b}")
private String ppLogoMaxFilesize;
@Value("${upload.filesize_b}")
private String gridImageMaxFileSize;
@Value("${tracking.provider}")
private String trackingProvider;
@Value("${tracking.tracker-url}")
private String trackingTrackerUrl;
@Value("${tracking.site-id}")
private String trackingSiteId;
@Value("${session.demo-id:}")
private String demoSessionKey;
@Value("${ui.slogan:}")
private String arsnovaSlogan;
@Value("${ui.splashscreen.logo-path:}")
private String splashscreenLogo;
@Value("${ui.splashscreen.slogan:}")
private String splashscreenSlogan;
@Value("${ui.splashscreen.slogan-color:}")
private String splashscreenSloganColor;
@Value("${ui.splashscreen.background-color:}")
private String splashscreenBgColor;
@Value("${ui.splashscreen.loading-ind-color:}")
private String splashscreenLoadingIndColor;
@Value("${ui.splashscreen.min-delay:}")
private String splashscreenDelay;
@Value("${pp.session-levels.de}")
private String ppLevelsDe;
@Value("${pp.session-levels.en}")
private String ppLevelsEn;
@RequestMapping(method = RequestMethod.GET)
@ResponseBody
public HashMap<String, Object> getConfiguration(HttpServletRequest request) {
HashMap<String, Object> config = new HashMap<String, Object>();
HashMap<String, Boolean> features = new HashMap<String, Boolean>();
HashMap<String, String> publicPool = new HashMap<String, String>();
HashMap<String, Object> splashscreen = new HashMap<String, Object>();
/* The API path could be unknown to the client in case the request was forwarded */
if ("".equals(apiPath)) {
apiPath = request.getContextPath();
}
config.put("apiPath", apiPath);
if (!"".equals(socketioPath)) {
config.put("socketioPath", socketioPath);
}
if (!"".equals(customizationPath)) {
config.put("customizationPath", customizationPath);
}
if (!"".equals(mobilePath)) {
config.put("mobilePath", mobilePath);
}
if (!"".equals(presenterPath)) {
config.put("presenterPath", presenterPath);
}
if (!"".equals(documentationUrl)) {
config.put("documentationUrl", documentationUrl);
}
if (!"".equals(blogUrl)) {
config.put("blogUrl", blogUrl);
}
if (!"".equals(presenterDocumentationUrl)) {
config.put("presenterDocumentationUrl", presenterDocumentationUrl);
}
if (!"".equals(overlayUrl)) {
config.put("overlayUrl", overlayUrl);
}
if (!"".equals(organizationUrl)) {
config.put("organizationUrl", organizationUrl);
}
if (!"".equals(imprintUrl)) {
config.put("imprintUrl", imprintUrl);
}
if (!"".equals(privacyPolicyUrl)) {
config.put("privacyPolicyUrl", privacyPolicyUrl);
}
if (!"".equals(demoSessionKey)) {
config.put("demoSessionKey", demoSessionKey);
}
if (!"".equals(arsnovaSlogan)) {
config.put("arsnovaSlogan", arsnovaSlogan);
}
if (!"".equals(maxUploadFilesize)) {
config.put("maxUploadFilesize", maxUploadFilesize);
}
if (!"".equals(mathJaxSrc) && "true".equals(mathJaxEnabled)) {
config.put("mathJaxSrc", mathJaxSrc);
}
config.put("answerOptionLimit", Integer.valueOf(answerOptionLimit));
config.put("feedbackWarningOffset", Integer.valueOf(feedbackWarningOffset));
config.put("parseAnswerOptionFormatting", Boolean.valueOf(parseAnswerOptionFormatting));
config.put("features", features);
features.put("mathJax", "true".equals(mathJaxEnabled));
/* Keep the markdown property for now since the frontend still depends on it */
features.put("markdown", true);
features.put("imageAnswer", "true".equals(imageAnswerEnabled));
features.put("gridSquare", "true".equals(gridSquareEnabled));
features.put("sessionImportExport", "true".equals(sessionImportExportEnabled));
features.put("publicPool", "true".equals(publicPoolEnabled));
// add public pool configuration on demand
if (features.get("publicPool")) {
config.put("publicPool", publicPool);
publicPool.put("subjects", ppSubjects);
publicPool.put("licenses", ppLicenses);
publicPool.put("logoMaxFilesize", ppLogoMaxFilesize);
publicPool.put("levelsDe", ppLevelsDe);
publicPool.put("levelsEn", ppLevelsEn);
}
@GetMapping
public Configuration get() {
final Configuration configuration = new Configuration();
configuration.setAuthenticationProviders(authenticationProviders);
configuration.setUi(uiProperties.getUi());
configuration.setFeatures(featureConfig);
config.put("splashscreen", splashscreen);
return configuration;
}
if (!"".equals(splashscreenLogo)) {
splashscreen.put("logo", splashscreenLogo);
private void buildAuthenticationProviderConfig() {
this.authenticationProviders = new ArrayList<>();
if (providerProperties.getGuest().isEnabled()) {
authenticationProviders.add(new AuthenticationProvider("guest", providerProperties.getGuest()));
}
if (!"".equals(splashscreenSlogan)) {
splashscreen.put("slogan", splashscreenSlogan);
if (providerProperties.getRegistered().isEnabled()) {
authenticationProviders.add(new AuthenticationProvider(
SecurityConfig.INTERNAL_PROVIDER_ID, providerProperties.getRegistered()));
}
if (!"".equals(splashscreenSloganColor)) {
splashscreen.put("sloganColor", splashscreenSloganColor);
if (!providerProperties.getLdap().isEmpty() && providerProperties.getLdap().get(0).isEnabled()) {
authenticationProviders.add(new AuthenticationProvider(
SecurityConfig.LDAP_PROVIDER_ID, providerProperties.getLdap().get(0)));
}
if (!"".equals(splashscreenBgColor)) {
splashscreen.put("bgcolor", splashscreenBgColor);
if (!providerProperties.getOidc().isEmpty() && providerProperties.getOidc().get(0).isEnabled()) {
authenticationProviders.add(new AuthenticationProvider(
SecurityConfig.OIDC_PROVIDER_ID, providerProperties.getOidc().get(0)));
}
if (!"".equals(splashscreenLoadingIndColor)) {
splashscreen.put("loadIndColor", splashscreenLoadingIndColor);
if (providerProperties.getSaml().isEnabled()) {
authenticationProviders.add(new AuthenticationProvider(
SecurityConfig.SAML_PROVIDER_ID, providerProperties.getSaml()));
}
if (!"".equals(splashscreenDelay)) {
splashscreen.put("minDelay", Integer.valueOf(splashscreenDelay));
if (providerProperties.getCas().isEnabled()) {
authenticationProviders.add(new AuthenticationProvider(
SecurityConfig.CAS_PROVIDER_ID, providerProperties.getCas()));
}
}
if (!"".equals(trackingTrackerUrl)) {
HashMap<String, String> tracking = new HashMap<String, String>();
config.put("tracking", tracking);
tracking.put("provider", trackingProvider);
tracking.put("trackerUrl", trackingTrackerUrl);
tracking.put("siteId", trackingSiteId);
}
config.put("grid", gridImageMaxFileSize);
return config;
private void buildFeatureConfig() {
this.featureConfig = new HashMap<>();
featureConfig.put("contents", featureProperties.getContents());
featureConfig.put("comments", featureProperties.getComments());
featureConfig.put("liveFeedback", featureProperties.getLiveFeedback());
featureConfig.put("contentPool", featureProperties.getContentPool());
}
}
/*
* This file is part of ARSnova Backend.
* Copyright (C) 2012-2019 The ARSnova Team and Contributors
*
* ARSnova Backend is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* ARSnova Backend is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.thm.arsnova.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import de.thm.arsnova.model.AnswerStatistics;
import de.thm.arsnova.model.Content;
import de.thm.arsnova.service.AnswerService;
import de.thm.arsnova.service.ContentService;
@RestController
@RequestMapping(ContentController.REQUEST_MAPPING)
public class ContentController extends AbstractEntityController<Content> {
protected static final String REQUEST_MAPPING = "/content";
private static final String GET_ANSWER_STATISTICS_MAPPING = DEFAULT_ID_MAPPING + "/stats";
private ContentService contentService;
private AnswerService answerService;
public ContentController(final ContentService contentService, final AnswerService answerService) {
super(contentService);
this.contentService = contentService;
this.answerService = answerService;
}
@Override
protected String getMapping() {
return REQUEST_MAPPING;
}
@GetMapping(GET_ANSWER_STATISTICS_MAPPING)
public AnswerStatistics getAnswerStatistics(@PathVariable final String id) {
return answerService.getAllStatistics(id);
}
}
/*
* This file is part of ARSnova Backend.
* Copyright (C) 2012-2016 The ARSnova Team
* Copyright (C) 2012-2019 The ARSnova Team and Contributors
*
* ARSnova Backend is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
......@@ -15,110 +15,152 @@
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.thm.arsnova.controller;
import de.thm.arsnova.exceptions.BadRequestException;
import de.thm.arsnova.exceptions.ForbiddenException;
import de.thm.arsnova.exceptions.NoContentException;
import de.thm.arsnova.exceptions.NotFoundException;
import de.thm.arsnova.exceptions.NotImplementedException;
import de.thm.arsnova.exceptions.PayloadTooLargeException;
import de.thm.arsnova.exceptions.PreconditionFailedException;
import de.thm.arsnova.exceptions.UnauthorizedException;
import java.util.Map;
import javax.naming.OperationNotSupportedException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.ektorp.DocumentNotFoundException;
import org.slf4j.event.Level;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.authentication.AuthenticationCredentialsNotFoundException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
import de.thm.arsnova.model.EntityValidationException;
import de.thm.arsnova.web.exceptions.BadRequestException;
import de.thm.arsnova.web.exceptions.ForbiddenException;
import de.thm.arsnova.web.exceptions.NoContentException;
import de.thm.arsnova.web.exceptions.NotFoundException;
import de.thm.arsnova.web.exceptions.NotImplementedException;
import de.thm.arsnova.web.exceptions.PayloadTooLargeException;
import de.thm.arsnova.web.exceptions.PreconditionFailedException;
import de.thm.arsnova.web.exceptions.UnauthorizedException;
/**
* Translates security/authentication related exceptions into HTTP status codes.
* Translates exceptions into HTTP status codes.
*/
@ControllerAdvice
public class SecurityExceptionControllerAdvice {
public class ControllerExceptionHandler extends ResponseEntityExceptionHandler {
private ControllerExceptionHelper helper;
@ExceptionHandler
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public Map<String, String> defaultExceptionHandler(
final Exception e,
final HttpServletRequest req
) {
final Map<String, String> result = new HashMap<String, String>();
result.put("code", "500");
result.put("status", "Internal server error");
result.put("message", e.getMessage());
return result;
public ControllerExceptionHandler(final ControllerExceptionHelper helper) {
this.helper = helper;
}
@ExceptionHandler(NoContentException.class)
@ResponseBody
@ResponseStatus(HttpStatus.NO_CONTENT)
public Map<String, Object> handleNoContentException(final Exception e, final HttpServletRequest request) {
return helper.handleException(e, Level.TRACE);
}
@ResponseStatus(HttpStatus.NOT_FOUND)
@ExceptionHandler(NotFoundException.class)
public void handleNotFoundException(final Exception e, final HttpServletRequest request) {
@ResponseBody
@ResponseStatus(HttpStatus.NOT_FOUND)
public Map<String, Object> handleNotFoundException(final Exception e, final HttpServletRequest request) {
return helper.handleException(e, Level.TRACE);
}
@ResponseStatus(HttpStatus.UNAUTHORIZED)
@ExceptionHandler(UnauthorizedException.class)
public void handleUnauthorizedException(final Exception e, final HttpServletRequest request) {
@ResponseBody
@ResponseStatus(HttpStatus.UNAUTHORIZED)
public Map<String, Object> handleUnauthorizedException(final Exception e, final HttpServletRequest request) {
return helper.handleException(e, Level.TRACE);
}
@ExceptionHandler(AuthenticationException.class)
@ResponseStatus(HttpStatus.UNAUTHORIZED)
@ExceptionHandler(AuthenticationCredentialsNotFoundException.class)
public void handleAuthenticationCredentialsNotFoundException(final Exception e, final HttpServletRequest request) {
@ResponseBody
public Map<String, Object> handleAuthenticationExceptionException(
final Exception e, final HttpServletRequest request) {
return helper.handleException(e, Level.DEBUG);
}
@ExceptionHandler(AccessDeniedException.class)
public void handleAccessDeniedException(
@ResponseBody
public Map<String, Object> handleAccessDeniedException(
final Exception e,
final HttpServletRequest request,
final HttpServletResponse response
) {
final HttpServletResponse response) {
final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (
authentication == null
if (authentication == null
|| authentication.getPrincipal() == null
|| authentication instanceof AnonymousAuthenticationToken
) {
|| authentication instanceof AnonymousAuthenticationToken) {
response.setStatus(HttpStatus.UNAUTHORIZED.value());
return;
} else {
response.setStatus(HttpStatus.FORBIDDEN.value());
}
response.setStatus(HttpStatus.FORBIDDEN.value());
return helper.handleException(e, Level.DEBUG);
}
@ResponseStatus(HttpStatus.FORBIDDEN)
@ExceptionHandler(ForbiddenException.class)
public void handleForbiddenException(final Exception e, final HttpServletRequest request) {
@ResponseBody
@ResponseStatus(HttpStatus.FORBIDDEN)
public Map<String, Object> handleForbiddenException(final Exception e, final HttpServletRequest request) {
return helper.handleException(e, Level.DEBUG);
}
@ResponseStatus(HttpStatus.NO_CONTENT)
@ExceptionHandler(NoContentException.class)
public void handleNoContentException(final Exception e, final HttpServletRequest request) {
@ExceptionHandler(BadRequestException.class)
@ResponseBody
@ResponseStatus(HttpStatus.BAD_REQUEST)
public Map<String, Object> handleBadRequestException(final Exception e, final HttpServletRequest request) {
return helper.handleException(e, Level.DEBUG);
}
@ExceptionHandler(EntityValidationException.class)
@ResponseBody
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(BadRequestException.class)
public void handleBadRequestException(final Exception e, final HttpServletRequest request) {
public Map<String, Object> handleEntityValidationException(
final EntityValidationException e, final HttpServletRequest request) {
return helper.handleException(e, Level.DEBUG);
}
@ResponseStatus(HttpStatus.PRECONDITION_FAILED)
@ExceptionHandler(PreconditionFailedException.class)
public void handlePreconditionFailedException(final Exception e, final HttpServletRequest request) {
@ResponseBody
@ResponseStatus(HttpStatus.PRECONDITION_FAILED)
public Map<String, Object> handlePreconditionFailedException(final Exception e, final HttpServletRequest request) {
return helper.handleException(e, Level.DEBUG);
}
@ExceptionHandler({NotImplementedException.class, OperationNotSupportedException.class})
@ResponseBody
@ResponseStatus(HttpStatus.NOT_IMPLEMENTED)
@ExceptionHandler(NotImplementedException.class)
public void handleNotImplementedException(final Exception e, final HttpServletRequest request) {
public Map<String, Object> handleNotImplementedException(final Exception e, final HttpServletRequest request) {
return helper.handleException(e, Level.DEBUG);
}
@ResponseStatus(HttpStatus.PAYLOAD_TOO_LARGE)
@ExceptionHandler(PayloadTooLargeException.class)
public void handlePayloadTooLargeException(final Exception e, final HttpServletRequest request) {
@ResponseBody
@ResponseStatus(HttpStatus.PAYLOAD_TOO_LARGE)
public Map<String, Object> handlePayloadTooLargeException(final Exception e, final HttpServletRequest request) {
return helper.handleException(e, Level.DEBUG);
}
/* FIXME: Wrap persistance Exceptions - do not handle persistance Exceptions at the controller layer */
@ExceptionHandler(DocumentNotFoundException.class)
@ResponseBody
@ResponseStatus(HttpStatus.NOT_FOUND)
public Map<String, Object> handleDocumentNotFoundException(final Exception e, final HttpServletRequest request) {
return helper.handleException(e, Level.TRACE);
}
@Override
protected ResponseEntity<Object> handleExceptionInternal(final Exception ex, final Object body,
final HttpHeaders headers, final HttpStatus status, final WebRequest request) {
return new ResponseEntity<>(helper.handleException(ex, Level.TRACE), headers, status);
}
}
/*
* This file is part of ARSnova Backend.
* Copyright (C) 2012-2019 The ARSnova Team and Contributors
*
* ARSnova Backend is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* ARSnova Backend is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.thm.arsnova.controller;
import java.util.HashMap;
import java.util.Map;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.event.Level;
import org.springframework.stereotype.Component;
import de.thm.arsnova.config.properties.SystemProperties;
@Component
public class ControllerExceptionHelper {
private static final Logger logger = LoggerFactory.getLogger(ControllerExceptionHelper.class);
/* Since exception messages might contain sensitive data, they are not exposed by default. */
private boolean exposeMessages;
public ControllerExceptionHelper(final SystemProperties systemProperties) {
this.exposeMessages = systemProperties.getApi().isExposeErrorMessages();
}
public Map<String, Object> handleException(@NonNull final Throwable e, @NonNull final Level level) {
final String message = e.getMessage() != null ? e.getMessage() : "";
log(level, message, e);
final Map<String, Object> result = new HashMap<>();
result.put("errorType", e.getClass().getSimpleName());
if (exposeMessages) {
result.put("errorMessage", e.getMessage());
}
return result;
}
private void log(final Level level, final String message, final Throwable e) {
switch (level) {
case ERROR:
logger.error(message, e);
break;
case WARN:
logger.warn(message, e);
break;
case INFO:
logger.info(message, e);
break;
case DEBUG:
logger.debug(message, e);
break;
case TRACE:
logger.trace(message, e);
break;
default:
break;
}
}
}