45 Commits
Author SHA1 Message Date
Tobias Stottrop 84ce2ebbdf added maxWindSpeed to private method copyCondition.
LocationBasedServices/mowesta/pipeline/head This commit looks good
2021-02-15 20:11:50 +01:00
Tobias Stottrop 67b6344b2e Added maxWindSpeed to createCondition.
LocationBasedServices/mowesta/pipeline/head There was a failure building this commit
2021-02-11 23:03:05 +01:00
Tobias Stottrop 36a888474c Added maxWindSpeed to writeCondition and readCondition. 2021-02-11 23:02:22 +01:00
Tobias Stottrop 17fcbd3cd8 Added maxWindSpeed field to WeatherCondition 2021-02-11 23:00:39 +01:00
Tobias Stottrop d5617a3a0d Added VMAX_10M to Variable-type. 2021-02-11 23:00:10 +01:00
Tobias Stottrop 4bc4b05991 Logging ID and Login for User in AccessCodeServlet
LocationBasedServices/mowesta/pipeline/head This commit looks good
2021-02-11 22:58:30 +01:00
Tobias Stottrop 59eec77e07 Logging UserEntity.
LocationBasedServices/mowesta/pipeline/head This commit looks good
2021-02-11 22:31:12 +01:00
Tobias Stottrop cffe16e153 Added error response.
LocationBasedServices/mowesta/pipeline/head This commit looks good
2021-02-11 22:13:00 +01:00
Tobias Stottrop dc40ec2e5b More logging.
LocationBasedServices/mowesta/pipeline/head This commit looks good
2021-02-11 21:26:12 +01:00
Tobias Stottrop a11656b7b7 Added logging to WeatherstationIntentHandler
LocationBasedServices/mowesta/pipeline/head This commit looks good
2021-02-11 21:13:52 +01:00
Tobias Stottrop 1ab99c816d Fix pipeline.
LocationBasedServices/mowesta/pipeline/head This commit looks good
2021-02-11 20:57:31 +01:00
Tobias Stottrop 01d60700ec Merge branch 'feature/auth' of https://project.nes.uni-due.de/gitea/lbs/mowesta into feature/auth
LocationBasedServices/mowesta/pipeline/head There was a failure building this commit
2021-02-11 20:49:04 +01:00
Tobias Stottrop 5100a320c4 Added fields to AuthorizationResponse. 2021-02-11 20:47:12 +01:00
boese 1c7d7e48e0 fix user back
LocationBasedServices/mowesta/pipeline/head This commit looks good
2021-02-11 19:03:23 +01:00
boese 348b46681f fix user
LocationBasedServices/mowesta/pipeline/head This commit looks good
2021-02-11 18:48:36 +01:00
boese 792a67e6dd Merge remote-tracking branch 'remotes/origin/master' into feature/auth
LocationBasedServices/mowesta/pipeline/head This commit looks good
2021-02-11 18:31:57 +01:00
boese 782c759fb8 create WeatherstationIntentHandler
LocationBasedServices/mowesta/pipeline/head This commit looks good
2021-02-11 18:23:23 +01:00
Tobias Stottrop c69fb5dfdc Corrected false if statement.
LocationBasedServices/mowesta/pipeline/head This commit looks good
2021-02-11 15:32:19 +01:00
Tobias Stottrop f5b49e2ca3 Added URLSafe encoding of accesscode.
LocationBasedServices/mowesta/pipeline/head This commit looks good
2021-02-11 15:18:47 +01:00
Tobias Stottrop 29fcc0fe8f Corrected Param Name to grant_type in OAuthTokenServlet.
LocationBasedServices/mowesta/pipeline/head This commit looks good
2021-02-09 12:17:21 +01:00
handte f0231235f8 Add role for services, add user for alexa.
LocationBasedServices/mowesta/pipeline/head This commit looks good
2021-02-09 11:53:28 +01:00
handte 46cc9f83ac Add more debug output.
LocationBasedServices/mowesta/pipeline/head This commit looks good
2021-02-09 11:20:00 +01:00
Tobias Stottrop c10871016e Test if amazon does not allow dots in accesscode
LocationBasedServices/mowesta/pipeline/head This commit looks good
2021-02-08 21:58:46 +01:00
Tobias Stottrop ecd2119da9 Close PrintWriter.
LocationBasedServices/mowesta/pipeline/head This commit looks good
2021-02-08 21:09:13 +01:00
Tobias Stottrop 9588da3454 Setting no-cache and application/json header
LocationBasedServices/mowesta/pipeline/head This commit looks good
2021-02-08 20:18:03 +01:00
Tobias Stottrop c0106a720d Fixed wrong param name.
LocationBasedServices/mowesta/pipeline/head This commit looks good
2021-02-08 19:52:17 +01:00
Tobias Stottrop 12168e5dc4 Fixed wrong method call.
LocationBasedServices/mowesta/pipeline/head This commit looks good
2021-02-08 19:04:30 +01:00
Tobias Stottrop ed050db16a Logging to debug Login,
LocationBasedServices/mowesta/pipeline/head This commit looks good
2021-02-08 18:41:45 +01:00
Tobias Stottrop 9d0989afb1 Added logging to TokenServlet.
LocationBasedServices/mowesta/pipeline/head This commit looks good
2021-02-08 18:08:26 +01:00
Tobias Stottrop eb593c8aed Added logging.
LocationBasedServices/mowesta/pipeline/head This commit looks good
2021-02-08 17:40:50 +01:00
Tobias Stottrop 10aa8a25e6 Fixed misspelling
LocationBasedServices/mowesta/pipeline/head This commit looks good
2021-02-08 17:05:43 +01:00
Tobias Stottrop 7b81e8a3ec Merge remote-tracking branch 'origin/master' into feature/auth
LocationBasedServices/mowesta/pipeline/head This commit looks good
2021-02-04 23:25:08 +01:00
Tobias Stottrop 99456ddbf6 Added WeatherstationIntentHandler to AlexaServlet
LocationBasedServices/mowesta/pipeline/head This commit looks good
2021-02-04 23:11:42 +01:00
Tobias Stottrop 6de6599924 Merge remote-tracking branch 'origin/master' into feature/auth
LocationBasedServices/mowesta/pipeline/head This commit looks good
2021-02-04 22:44:31 +01:00
Tobias Stottrop 53938dbde8 Added redirect after accesscode generation to OAuthService
LocationBasedServices/mowesta/pipeline/head This commit looks good
2021-02-04 22:16:33 +01:00
Tobias Stottrop 7cd403bc4c Added io.jsonwebtoken to ejb jar.
LocationBasedServices/mowesta/pipeline/head This commit looks good
2021-02-04 21:59:33 +01:00
Tobias Stottrop a2233f477a Added response type for an Authorization response
LocationBasedServices/mowesta/pipeline/head There was a failure building this commit
2021-02-04 19:36:31 +01:00
Tobias Stottrop 327a6eb9e4 Added constraint, that refreshtokens must be unique
LocationBasedServices/mowesta/pipeline/head There was a failure building this commit
2021-02-04 19:23:48 +01:00
Tobias Stottrop 92eb61828f added jjwt dependency as compile 2021-02-04 19:22:37 +01:00
Tobias Stottrop 393f2a6304 Added servlets which handle oauth requests 2021-02-04 19:21:29 +01:00
Tobias Stottrop c14c243043 SecretKey is now dynamically generated. 2021-02-04 19:19:20 +01:00
Tobias Stottrop a9863fa495 Added redirect after access code generation in access-grant.component 2021-02-04 19:17:25 +01:00
Tobias Stottrop 532a7cf35e Corrected common-api description for oauth 2021-02-04 19:15:23 +01:00
Tobias Stottrop 751544c0df added addRefreshTokenToUser in UserSessionBean. User is initialized with an empty Set of RefreshTokenEntities. 2021-02-04 19:13:58 +01:00
Tobias Stottrop 6749700b34 initial
LocationBasedServices/mowesta/pipeline/head This commit looks good
2021-01-27 17:12:54 +01:00
43 changed files with 3447 additions and 1461 deletions
Vendored
+1 -1
View File
@@ -51,7 +51,7 @@ node {
sh 'scp -i $KEYFILE site-ear/build/libs/site-ear-' + version + '.ear wildfly@apps-pro.nes.uni-due.de:/opt/wildfly-21-mowesta/standalone/deployments/mowesta.ear'
sh 'scp -i $KEYFILE android-app/build/outputs/apk/release/*.apk wildfly@apps-pro.nes.uni-due.de:/opt/android/mowesta/'
}
} else if (env.BRANCH_NAME == "master" || env.BRANCH_NAME == "feat/auth") {
} else if (env.BRANCH_NAME == "master" || env.BRANCH_NAME == "feature/auth") {
echo "Deploying to beta server ..."
withCredentials([sshUserPrivateKey(credentialsId: "mowesta-server-key", keyFileVariable: "KEYFILE")]) {
sh 'scp -i $KEYFILE site-ear/build/libs/site-ear-' + version + '.ear wildfly@apps-dev.nes.uni-due.de:/opt/wildfly-21-beta/standalone/deployments/mowesta.ear'
+2 -1
View File
@@ -55,7 +55,8 @@ allprojects {
versionAndroidXRoom = '2.2.6'
versionAndroidXPreference = '1.1.1'
versionRobolectric = '4.5'
//oauth dependencies
versionJWT = '0.11.2'
}
+1
View File
@@ -32,6 +32,7 @@ swagger {
'com.mowesta.api.measurement.IMeasurementService',
'com.mowesta.api.settings.ISettingsService',
'com.mowesta.api.user.IUserService',
'com.mowesta.api.oauth2.IOAuth2Service',
'com.mowesta.api.version.IVersionService',
'com.mowesta.api.weather.IWeatherService',
]
@@ -43,6 +43,11 @@ public class Tags {
*/
public static final String SETTINGS = "Settings";
/**
* Tag for OAuth.
*/
public static final String OAUTH = "OAuth";
/**
* Prevent instantiation.
@@ -2,61 +2,66 @@ package com.mowesta.api.access;
/**
* The user roles used by the application.
*
*
* @author Marcus
*/
public class Roles {
/**
* The string value of the admin role.
*/
public static final String ADMIN = "admin";
/**
* The string value of the user role.
*/
public static final String USER = "user";
/**
* The string value of the device role.
*/
public static final String DEVICE = "device";
/**
* The role granted to valid services that may
* use oauth to authenticate for a user.
*/
public static final String SERVICE = "service";
/**
* Prevents accidential instantiation.
*/
private Roles() { }
/**
* Returns the names of roles used for human
* subjects.
*
*
* @return The roles used for humans.
*/
public static String[] getHumanRoles() {
return new String[] { ADMIN, USER };
}
/**
* Returns the names of roles used for machines.
*
*
* @return The roles used for machines.
*/
public static String[] getMachineRoles() {
return new String[] { DEVICE };
return new String[] { DEVICE, SERVICE };
}
/**
* Returns the names of all roles.
*
*
* @return The names of all roles.
*/
public static String[] getAllRoles() {
return new String[] { ADMIN, USER, DEVICE };
return new String[] { ADMIN, USER, DEVICE, SERVICE };
}
}
@@ -0,0 +1,25 @@
package com.mowesta.api.oauth2;
import javax.validation.constraints.NotNull;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
@XmlRootElement
@ApiModel(description="Represents an authorization grant. The AccessCode is only used once to get an AuthorizationToken/RequestToken pair.")
public class AuthorizationResponse {
@NotNull
@XmlAttribute(required=true)
@ApiModelProperty(value="The Access Code.", required=true)
private String accessCode;
public String getAccessCode() {
return accessCode;
}
public void setAccessCode(String accessCode) {
this.accessCode = accessCode;
}
}
@@ -0,0 +1,73 @@
package com.mowesta.api.oauth2;
import java.net.URI;
import javax.annotation.security.RolesAllowed;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import com.mowesta.api.Tags;
import com.mowesta.api.access.Authorizations;
import com.mowesta.api.access.Roles;
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 io.swagger.annotations.Authorization;
/**
* A service to authenticate with the oauth2 protocol.
*
* @author Tobias Stottrop
*/
@Api
@Produces({ MediaType.APPLICATION_JSON })
@Consumes({ MediaType.APPLICATION_FORM_URLENCODED, MediaType.APPLICATION_JSON })
@Path("/")
public interface IOAuth2Service {
@GET
@Path("oauth2/authorize")
@ApiOperation(value = "Use this endpoint to authenticate a user with a social provider. Will return an Access- and Refreshtoken.", authorizations = { @Authorization(Authorizations.USER)}, tags = {Tags.DEFAULT, Tags.OAUTH})
@ApiResponses({
@ApiResponse(code = HttpServletResponse.SC_OK, message = "Access token created successfully.", response = AuthorizationResponse.class),
@ApiResponse(code = HttpServletResponse.SC_BAD_REQUEST, message = "Invalid request."),
@ApiResponse(code = HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message = "Error creating AccessCode."),
@ApiResponse(code = HttpServletResponse.SC_UNAUTHORIZED, message = "User was not authorized.")
})
@RolesAllowed({Roles.USER})
Response getAccessCode(
@ApiParam(value = "Client identifier.", required = true) @QueryParam(value = "client_id") String client_id,
@ApiParam(value = "Endpoint to which should be redirected.", required = true) @QueryParam(value = "redirect_uri") URI redirect_uri,
@ApiParam(value = "Indicates the type of response that should be returned.", required = true) @QueryParam(value="response_type") String response_type,
@ApiParam(value = "Internal state of service which wants to authenticate.", required = true) @QueryParam(value="state") String state,
@ApiParam(value = "Scope of access.", required = true) @QueryParam(value="scope") String scope
);
@POST
@Path("oauth2/token")
@ApiOperation(value = "Use this endpoint to get an Access Token.", tags = {Tags.DEFAULT, Tags.OAUTH})
@ApiResponses({
@ApiResponse(code = HttpServletResponse.SC_FOUND, message = "Access token created successfully.", response = TokenResponse.class),
@ApiResponse(code = HttpServletResponse.SC_BAD_REQUEST, message = "Invalid request.")
})
@RolesAllowed({Roles.SERVICE})
Response getAccessRefreshTokenPair(
@ApiParam(value = "Grant Type.", required = true) @QueryParam(value = "grant_type") String grant_type,
@ApiParam(value = "Client identifier.", required = true) @QueryParam(value = "client_id") String client_id,
@ApiParam(value = "Client secret.", required = true) @QueryParam(value = "client_secret") String client_secret,
@ApiParam(value = "Access Code.", required = false) @QueryParam(value="code") String code,
@ApiParam(value = "Refresh Token.", required = false) @QueryParam(value = "refresh_token") String refresh_token
);
}
@@ -0,0 +1,79 @@
package com.mowesta.api.oauth2;
import javax.validation.constraints.NotNull;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
@XmlRootElement
@ApiModel(description="Represents a token response.")
public class TokenResponse {
@NotNull
@XmlAttribute(required=true)
@ApiModelProperty(value="type of token", required=true)
private String token_type;
@NotNull
@XmlAttribute(required=false)
@ApiModelProperty(value="expiration in seconds", required=false)
private long expires_in;
@NotNull
@XmlAttribute(required=true)
@ApiModelProperty(value="The access token", required=true)
private String access_token;
@NotNull
@XmlAttribute(required=false)
@ApiModelProperty(value="The refresh token.", required=false)
private String refresh_token;
@XmlAttribute(required=false)
@ApiModelProperty(value="The granted scope.", required=false)
private String scope;
public long getExpires_in() {
return expires_in;
}
public void setExpires_in(long expires_in) {
this.expires_in = expires_in;
}
public String getAccess_token() {
return access_token;
}
public void setAccess_token(String access_token) {
this.access_token = access_token;
}
public String getRefresh_token() {
return refresh_token;
}
public void setRefresh_token(String refresh_token) {
this.refresh_token = refresh_token;
}
public String getScope() {
return scope;
}
public void setScope(String scope) {
this.scope = scope;
}
public String getToken_type() {
return token_type;
}
public void setToken_type(String token_type) {
this.token_type = token_type;
}
}
@@ -1,12 +1,12 @@
package com.mowesta.api.weather;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
@@ -80,6 +80,13 @@ public class WeatherCondition {
@XmlAttribute(required = true)
@ApiModelProperty(value="The wind speed at ten meters above the ground in meters per second.", required=true)
private double windSpeed;
/**
* The maximal wind speed 10 meter above the ground.
*/
@XmlAttribute(required = true)
@ApiModelProperty(value="The maximal wind speed at ten meters above the ground in meters per second.", required=true)
private double maxWindSpeed;
/**
* The cloud cover in percent from 0 (no clouds) to 1 (just clouds).
@@ -403,5 +410,19 @@ public class WeatherCondition {
public void setSnowDepth(double snowDepth) {
this.snowDepth = snowDepth;
}
/**
* Returns the maxWindSpeed.
*
* @return The maxWindSpeed.
*/
public double getMaxWindSpeed() { return maxWindSpeed; }
/**
* Sets the maxWindSpeed.
*
* @param maxWindSpeed The maxWindSpeed to set.
*/
public void setMaxWindSpeed(double maxWindSpeed) { this.maxWindSpeed = maxWindSpeed; }
}
+6
View File
@@ -6,6 +6,7 @@ description = 'Mowesta Alexa Service'
dependencies {
implementation project(path: ':service-war')
providedCompile project(':service-ejb')
compile "com.amazon.alexa:ask-sdk:2.37.1"
@@ -14,6 +15,11 @@ dependencies {
testCompile "org.jboss.arquillian.junit:arquillian-junit-container:${versionArquillianJunit}"
testCompile "org.wildfly.arquillian:wildfly-arquillian-container-managed:${versionArquillianContainer}"
compile "io.jsonwebtoken:jjwt-api:0.11.2"
compile "io.jsonwebtoken:jjwt-impl:0.11.2"
compile "org.bouncycastle:bcprov-jdk15on:1.60"
compile "io.jsonwebtoken:jjwt-jackson:0.11.2" // or 'io.jsonwebtoken:jjwt-gson:0.11.2' for gson
providedCompile "jakarta.platform:jakarta.jakartaee-api:${versionJavaee}"
providedCompile "com.fasterxml.jackson.core:jackson-databind:${versionJackson}"
}
@@ -2,6 +2,7 @@ package com.mowesta.service.alexa;
import com.amazon.ask.Skills;
import com.amazon.ask.servlet.SkillServlet;
import com.mowesta.api.measurement.Measurement;
import com.mowesta.service.alexa.impl.CancelandStopIntentHandler;
import com.mowesta.service.alexa.impl.ClothingRecommendationIntentHandler;
import com.mowesta.service.alexa.impl.CurrentWeatherIntentHandler;
@@ -9,7 +10,11 @@ import com.mowesta.service.alexa.impl.HelpIntentHandler;
import com.mowesta.service.alexa.impl.LaunchRequestHandler;
import com.mowesta.service.alexa.impl.SessionEndedRequestHandler;
import com.mowesta.service.alexa.impl.WeatherForecastIntentHandler;
import com.mowesta.service.alexa.impl.WeatherstationIntentHandler;
import com.mowesta.service.session.DeviceSessionBean;
import com.mowesta.service.session.LocationSessionBean;
import com.mowesta.service.session.MeasurementSessionBean;
import com.mowesta.service.session.UserSessionBean;
import com.mowesta.service.session.WeatherSessionBean;
import java.io.IOException;
@@ -18,6 +23,7 @@ import java.util.logging.Logger;
import javax.enterprise.context.RequestScoped;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
@@ -35,6 +41,18 @@ public class AlexaServlet extends HttpServlet {
@Inject
WeatherSessionBean weatherSessionBean;
@Inject
UserSessionBean userSessionBean;
@Inject
DeviceSessionBean deviceSessionBean;
@Inject
MeasurementSessionBean measurementSessionBean;
@Inject
protected EntityManager entityManager;
Logger log = Logger.getLogger(getClass().getName());
@Override
@@ -64,9 +82,9 @@ public class AlexaServlet extends HttpServlet {
new SessionEndedRequestHandler(),
new CurrentWeatherIntentHandler(locationSessionBean, weatherSessionBean),
new WeatherForecastIntentHandler(locationSessionBean, weatherSessionBean),
new WeatherstationIntentHandler(userSessionBean, deviceSessionBean, measurementSessionBean, entityManager),
new ClothingRecommendationIntentHandler(locationSessionBean, weatherSessionBean))
.withSkillId("amzn1.ask.skill.208278db-dd0c-477e-9946-5ebe634831aa")
.build());
}
}
@@ -4,14 +4,51 @@ import com.amazon.ask.dispatcher.request.handler.HandlerInput;
import com.amazon.ask.dispatcher.request.handler.impl.IntentRequestHandler;
import com.amazon.ask.model.IntentRequest;
import com.amazon.ask.model.Response;
import com.mowesta.api.PageConfig;
import com.mowesta.api.TimeRange;
import com.mowesta.api.device.Device;
import com.mowesta.api.device.DevicePage;
import com.mowesta.api.measurement.Measurement;
import com.mowesta.service.entity.EntityForbiddenException;
import com.mowesta.service.entity.EntityNotFoundException;
import com.mowesta.service.entity.OAuthSecretEntity;
import com.mowesta.service.entity.UserEntity;
import com.mowesta.service.session.DeviceSessionBean;
import com.mowesta.service.session.MeasurementSessionBean;
import com.mowesta.service.session.UserSessionBean;
import java.util.List;
import java.util.Optional;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.persistence.EntityManager;
import javax.persistence.TypedQuery;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import static com.amazon.ask.request.Predicates.intentName;
public class WeatherstationIntentHandler implements IntentRequestHandler {
UserSessionBean userSessionBean;
DeviceSessionBean deviceSessionBean;
MeasurementSessionBean measurementSessionBean;
EntityManager entityManager;
Logger logger = Logger.getLogger(getClass().getName());
public WeatherstationIntentHandler(UserSessionBean userSessionBean,
DeviceSessionBean deviceSessionBean,
MeasurementSessionBean measurementSessionBean,
EntityManager entityManager) {
this.userSessionBean = userSessionBean;
this.deviceSessionBean = deviceSessionBean;
this.measurementSessionBean = measurementSessionBean;
this.entityManager = entityManager;
}
@Override
public boolean canHandle(HandlerInput input, IntentRequest intentRequest) {
return input.matches(intentName("WeatherstationIntent"));
@@ -19,10 +56,14 @@ public class WeatherstationIntentHandler implements IntentRequestHandler {
@Override
public Optional<Response> handle(HandlerInput input, IntentRequest intentRequest) {
logger.log(Level.INFO, "WeatherStationIntent started");
String accessToken = input.getRequestEnvelope().getContext().getSystem().getUser().getAccessToken();
logger.log(Level.INFO, "AccessToken: " + accessToken);
if (accessToken!=null) {
if (accessToken == null) {
String errorText = "Du musst mit angemeldet sein, um diesen Service nutzen zu können. " +
"Bitte gehe in die Alexa App und melde dich an.";
return input.getResponseBuilder()
@@ -30,12 +71,88 @@ public class WeatherstationIntentHandler implements IntentRequestHandler {
.withLinkAccountCard()
.build();
} else {
String errorText = "Herzlichen Glückwunsch";
return input.getResponseBuilder()
.withSpeech(errorText)
.withSimpleCard("Glückwunsch", errorText)
.build();
Optional<OAuthSecretEntity> secretKey = findCurrentValidSecret();
if (secretKey.isPresent()) {
OAuthSecretEntity secretEntity = secretKey.get();
Claims claims = Jwts
.parserBuilder()
.setSigningKey(secretEntity.getSecret().getBytes())
.build()
.parseClaimsJws(accessToken)
.getBody();
String userId = claims.getId();
logger.log(Level.INFO, "UserID: " + userId);
UserEntity userEntity = userSessionBean.findUser(userId);
if (userEntity != null) {
logger.log(Level.INFO, "UserEntity: " + userEntity.getName());
DevicePage devicePage = null;
try {
devicePage = deviceSessionBean.getAllDevicesForCurrentUser(new PageConfig(0, 60), true);
} catch (EntityNotFoundException e) {
e.printStackTrace();
}
logger.log(Level.INFO, "device at 0: " + devicePage.getElements().get(0));
if (devicePage == null) {
String errorText = "Es konnten keine Geräte gefunden werden.";
return input.getResponseBuilder()
.withSpeech(errorText)
.withSimpleCard("Error", errorText)
.build();
}
Device device = devicePage.getElements().get(0);
Measurement measurement = null;
try {
measurement = measurementSessionBean.getDeviceMeasurements(device.getId(), new TimeRange(System.currentTimeMillis(), System.currentTimeMillis() + 10),
new PageConfig(0, 1), false).getElements().get(0);
logger.log(Level.INFO, "measurement: " + measurement.getTemperature());
} catch (EntityNotFoundException e) {
e.printStackTrace();
} catch (EntityForbiddenException e) {
e.printStackTrace();
}
String measurementString = "";
if (measurement != null) {
measurementString += "Die Temperatur beträgt " + measurement.getTemperature() + " Grad.";
} else measurementString += "Es wurde keine Messung gefunden.";
return input.getResponseBuilder()
.withSpeech(measurementString)
.withSimpleCard("Measurement", measurementString)
.build();
} else {
String errorText = "Der Nutzer konnte nicht gefunden werden.";
return input.getResponseBuilder()
.withSpeech(errorText)
.withSimpleCard("Error", errorText)
.build();
}
} else {
String errorText = "Es ist ein Fehler aufgetreten. Bitte versuche es später nochmal.";
return input.getResponseBuilder()
.withSpeech(errorText)
.withSimpleCard("Error", errorText)
.build();
}
}
}
private Optional<OAuthSecretEntity> findCurrentValidSecret() {
TypedQuery<OAuthSecretEntity> query = entityManager.createNamedQuery("OAuth.findAllSecrets", OAuthSecretEntity.class);
List<OAuthSecretEntity> oAuthSecretEntityList = query.getResultList();
return oAuthSecretEntityList.stream()
.filter(oAuthSecretEntity -> oAuthSecretEntity.getCreationTime() + oAuthSecretEntity.getTimeValid() < System.currentTimeMillis())
.findAny();
}
}
@@ -1,5 +1,19 @@
package com.mowesta.data.dwd;
import com.mowesta.data.ftp.FileStatus;
import com.mowesta.data.ftp.FileStatusListener;
import com.mowesta.data.ftp.FtpFolderSync;
import com.mowesta.data.grib2.Grib2Data;
import com.mowesta.data.grib2.Grib2File;
import com.mowesta.data.grib2.decoder.RegularGridDecoder;
import com.mowesta.data.grib2.decoder.RotatedGridDecoder;
import com.mowesta.data.grib2.decoder.SimpleDataDecoder;
import com.mowesta.data.grib2.template.product.ForecastProduct;
import com.mowesta.data.process.util.DoubleArray;
import com.mowesta.data.process.util.FileNameComparator;
import org.apache.commons.compress.compressors.bzip2.BZip2CompressorInputStream;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
@@ -13,20 +27,6 @@ import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.compress.compressors.bzip2.BZip2CompressorInputStream;
import com.mowesta.data.ftp.FileStatus;
import com.mowesta.data.ftp.FileStatusListener;
import com.mowesta.data.ftp.FtpFolderSync;
import com.mowesta.data.grib2.Grib2Data;
import com.mowesta.data.grib2.Grib2File;
import com.mowesta.data.grib2.decoder.RegularGridDecoder;
import com.mowesta.data.grib2.decoder.RotatedGridDecoder;
import com.mowesta.data.grib2.decoder.SimpleDataDecoder;
import com.mowesta.data.grib2.template.product.ForecastProduct;
import com.mowesta.data.process.util.DoubleArray;
import com.mowesta.data.process.util.FileNameComparator;
/**
* Represents a numeric weather prediction from DWD.
*/
@@ -284,6 +284,11 @@ public class NumericPrediction {
* The meridional wind at 10m height.
*/
V10M("v_10m", false),
/**
* The maximum wind speed at 10m height.
*/
VMAX_10M("vmax_10m", false),
/**
* The weather interpretation type.
@@ -443,7 +448,7 @@ public class NumericPrediction {
type.getSystem().isComputed()?Variable.RLAT:Variable.CLAT,
type.getSystem().isComputed()?Variable.RLON:Variable.CLON,
Variable.HSURF, Variable.PLCOV, Variable.SOILTYP, Variable.PREC, Variable.T2M, Variable.CLCT, Variable.CLDEPTH,
Variable.PMSL, Variable.WW, Variable.U10M, Variable.V10M, Variable.RELHUM2M, Variable.HSNOW, Variable.PS
Variable.PMSL, Variable.WW, Variable.U10M, Variable.V10M, Variable.VMAX_10M, Variable.RELHUM2M, Variable.HSNOW, Variable.PS
};
}
+7
View File
@@ -12,6 +12,12 @@ dependencies {
compile "org.mapstruct:mapstruct-jdk8:${mapstructVersion}"
compile "org.infinispan:infinispan-query:${versionInfinispan}"
compile "io.jsonwebtoken:jjwt-api:0.11.2"
compile "io.jsonwebtoken:jjwt-impl:0.11.2"
// Uncomment the next line if you want to use RSASSA-PSS (PS256, PS384, PS512) algorithms:
compile "org.bouncycastle:bcprov-jdk15on:1.60"
compile "io.jsonwebtoken:jjwt-jackson:0.11.2" // or 'io.jsonwebtoken:jjwt-gson:0.11.2' for gson
compileOnly "org.hibernate:hibernate-search-orm:${versionHibernateSearch}"
compileOnly "jakarta.platform:jakarta.jakartaee-api:${versionJavaee}"
compileOnly "com.fasterxml.jackson.core:jackson-annotations:${versionJackson}"
@@ -74,3 +80,4 @@ compileJava {
options.annotationProcessorPath = configurations.annotationProcessor
}
@@ -0,0 +1,62 @@
package com.mowesta.service.entity;
import java.security.Key;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;
import javax.validation.constraints.NotNull;
/**
* The entity that represents an OAuthSecret.
*
* @author Tobias S.
*/
@Entity
@Table(name="oauthsecret", uniqueConstraints=@UniqueConstraint(columnNames= {"secret"}))
@NamedQueries({
@NamedQuery(name = "OAuth.findAllSecrets", query = "select o from OAuthSecretEntity o")
})
public class OAuthSecretEntity extends AbstractEntity {
/**
* The serialization version.
*/
private static final long serialVersionUID = 287153745987186120L;
@NotNull
private String secret;
@NotNull
private long timeValid;
@NotNull
private boolean valid;
public String getSecret() {
return secret;
}
public void setSecret(String secret) {
this.secret = secret;
}
public long getTimeValid() {
return timeValid;
}
public void setTimeValid(long timeValid) {
this.timeValid = timeValid;
}
public boolean isValid() {
return valid;
}
public void setValid(boolean valid) {
this.valid = valid;
}
}
@@ -0,0 +1,104 @@
package com.mowesta.service.entity;
import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;
import javax.validation.constraints.NotNull;
/**
* The entity that represents Refreshtoken.
*
* @author Tobias S.
*/
@Entity
@Table(name="authtoken", uniqueConstraints=@UniqueConstraint(columnNames= {"user_id", "refreshtoken"}))
@NamedQueries({
@NamedQuery(name="findRefreshToken", query="select r from RefreshTokenEntity r where r.refreshToken=:refreshToken"),
})
public class RefreshTokenEntity extends AbstractEntity {
/**
* The serialization version.
*/
private static final long serialVersionUID = 287453795983186000L;
/**
* The user that has this refreshtoken.
*/
@NotNull
@ManyToOne
@JoinColumn(name="user_id")
private UserEntity user;
/**
* The refreshtoken.
*/
@NotNull
@JoinColumn(name="refreshtoken")
private String refreshToken;
/**
* The service name.
*/
private String serviceName;
/**
* Returns the user.
*
* @return The user.
*/
public UserEntity getUser() {
return user;
}
/**
* Sets the user.
*
* @param user The user to set.
*/
public void setUser(UserEntity user) {
this.user = user;
}
/**
* Returns the refreshtoken.
*
* @return The refreshtoken.
*/
public String getRefreshToken() {
return refreshToken;
}
/**
* Sets the refreshtoken.
*
* @param refreshToken The Refreshtoken to set.
*/
public void setRefreshToken(String refreshToken) {
this.refreshToken = refreshToken;
}
/**
* Returns the refreshtoken.
*
* @return The refreshtoken.
*/
public String getServiceName() {
return serviceName;
}
/**
* Sets the name of the service.
*
* @param serviceName The servicename to set.
*/
public void setServiceName(String serviceName) {
this.serviceName = serviceName;
}
}
@@ -1,5 +1,7 @@
package com.mowesta.service.entity;
import com.mowesta.api.PageConfig;
import java.util.List;
import java.util.Set;
@@ -28,8 +30,6 @@ import javax.persistence.criteria.Root;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
import com.mowesta.api.PageConfig;
/**
* The entity to store users.
*
@@ -87,7 +87,14 @@ public class UserEntity extends AbstractEntity {
@CollectionTable(name = "user_location")
@ElementCollection(fetch = FetchType.LAZY)
private List<EmbeddedLocation> locations;
/**
* The refresh tokens of the user.
*/
@OneToMany(fetch = FetchType.EAGER, mappedBy = "user")
private Set<RefreshTokenEntity> refreshTokens;
/**
* The iterations of the password hash.
*/
@@ -104,12 +111,13 @@ public class UserEntity extends AbstractEntity {
*/
@NotNull
private byte[] salt;
/**
* A flag that indicates that the account is deactivated.
*/
private boolean suspended;
/**
* Returns the name.
*
@@ -271,6 +279,24 @@ public class UserEntity extends AbstractEntity {
public void setSuspended(boolean suspended) {
this.suspended = suspended;
}
/**
* Returns the Refreshtokens.
*
* @return The refreshTokens.
*/
public Set<RefreshTokenEntity> getRefreshTokens() {
return refreshTokens;
}
/**
* Sets the refreshtokens.
*
* @param refreshTokens The refreshTokens to set.
*/
public void setRefreshTokens(Set<RefreshTokenEntity> refreshTokens) {
this.refreshTokens = refreshTokens;
}
/**
@@ -1,10 +1,12 @@
package com.mowesta.service.entity;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.ArrayList;
import java.util.List;
import com.mowesta.api.Coordinate;
import com.mowesta.api.weather.SoilType;
import com.mowesta.api.weather.WeatherCondition;
import com.mowesta.api.weather.WeatherForecast;
import com.mowesta.api.weather.WeatherSource;
import com.mowesta.api.weather.WeatherType;
import com.mowesta.api.weather.WindDirection;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.Sort;
@@ -21,13 +23,11 @@ import org.infinispan.commons.marshall.Externalizer;
import org.infinispan.commons.marshall.SerializeWith;
import org.infinispan.query.SearchManager;
import com.mowesta.api.Coordinate;
import com.mowesta.api.weather.SoilType;
import com.mowesta.api.weather.WeatherCondition;
import com.mowesta.api.weather.WeatherForecast;
import com.mowesta.api.weather.WeatherSource;
import com.mowesta.api.weather.WeatherType;
import com.mowesta.api.weather.WindDirection;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.ArrayList;
import java.util.List;
/**
* A container to store weather forecasts in an infinispan cache with
@@ -136,6 +136,7 @@ public class WeatherForecastContainer implements Coordinates {
result.setType(WeatherType.values()[in.readInt()]);
result.setWindDirection(WindDirection.values()[in.readInt()]);
result.setWindSpeed(in.readDouble());
result.setMaxWindSpeed(in.readDouble());
return result;
}
@@ -161,6 +162,7 @@ public class WeatherForecastContainer implements Coordinates {
out.writeInt(c.getType().ordinal());
out.writeInt(c.getWindDirection().ordinal());
out.writeDouble(c.getWindSpeed());
out.writeDouble(c.getMaxWindSpeed());
}
}
@@ -21,24 +21,24 @@ import com.mowesta.service.session.sync.LocationSyncSessionBean;
/**
* A bean that is executed by the startup bean to initialize the database
* with a default set of roles and user accounts, unless they exist already.
*
*
* @author Marcus
*/
@Stateless
public class DataSessionBean {
@Inject
protected Logger log;
@Inject
protected EntityManager em;
@Inject
protected LocationSyncSessionBean syncSession;
@Inject
protected ShutdownSessionBean shutdownSession;
@Inject
protected WeatherSessionBean forecastSession;
@@ -65,11 +65,12 @@ public class DataSessionBean {
addRole(Roles.ADMIN, "Grants admin privileges.");
addRole(Roles.USER, "Grants user privileges.");
addRole(Roles.DEVICE, "Grants device privileges.");
addRole(Roles.SERVICE, "Grants service privileges.");
}
/**
* Adds a role, if it is not present already, and returns it.
*
*
* @param name The name of the role.
* @param description The description of the role.
* @return The role that was present or has been added.
@@ -99,11 +100,12 @@ public class DataSessionBean {
log.log(Level.INFO, "Initializing users.");
initUser("admin", "Administrator", "admin", "nes-admin@uni-due.de", new String[] { Roles.ADMIN, Roles.USER});
initUser("handte", "Marcus Handte", "secure", "marcus.handte@uni-due.de", new String[] { Roles.USER });
initUser("alexa", "Amazon Alexa", "p8exqbInnyYKe5YkLIDVbKftiNnXbtHTVNohEYSqUfFXF66NuVnrF6psufLPg2BuNRdTjqHkSlz", "nes-admin@uni-due.de", new String[] { Roles.SERVICE });
}
/**
* Adds a user, if it does not exist already, and returns it.
*
*
* @param login The login.
* @param name The name.
* @param password The password.
@@ -121,10 +123,10 @@ public class DataSessionBean {
return createUser(login, name, password, email, roles);
}
}
/**
* Creates the specified user.
*
*
* @param login The login name.
* @param name The user name.
* @param password The password.
@@ -153,7 +155,7 @@ public class DataSessionBean {
/**
* Creates a new email entity for the user.
*
*
* @param u The user.
* @param email The email address.
* @param verified The state of the verified flag.
@@ -168,7 +170,7 @@ public class DataSessionBean {
u.getEmails().add(e);
em.persist(e);
}
}
@@ -125,7 +125,7 @@ public class DeviceSessionBean extends AbstractUserSpecificSessionBean {
* @return The page of devices.
* @throws EntityNotFoundException Thrown if the user cannot be found.
*/
@RolesAllowed({ Roles.USER })
@RolesAllowed({ Roles.USER , Roles.SERVICE})
public DevicePage getAllDevicesForCurrentUser(PageConfig pageConfig, boolean filtered)
throws EntityNotFoundException {
UserEntity user = getPrincipalUser();
@@ -1,18 +1,5 @@
package com.mowesta.service.session;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.logging.Level;
import javax.annotation.security.DeclareRoles;
import javax.annotation.security.PermitAll;
import javax.annotation.security.RolesAllowed;
import javax.ejb.Stateless;
import javax.inject.Inject;
import com.mowesta.api.PageConfig;
import com.mowesta.api.access.Roles;
import com.mowesta.api.user.Email;
@@ -33,12 +20,26 @@ import com.mowesta.service.entity.EntityConflictException;
import com.mowesta.service.entity.EntityForbiddenException;
import com.mowesta.service.entity.EntityNotFoundException;
import com.mowesta.service.entity.OrderCriterion;
import com.mowesta.service.entity.RefreshTokenEntity;
import com.mowesta.service.entity.RoleEntity;
import com.mowesta.service.entity.UserEntity;
import com.mowesta.service.principal.LoginManager;
import com.mowesta.service.template.EmailAssignment;
import com.mowesta.service.template.EmailTemplate;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.logging.Level;
import javax.annotation.security.DeclareRoles;
import javax.annotation.security.PermitAll;
import javax.annotation.security.RolesAllowed;
import javax.ejb.Stateless;
import javax.inject.Inject;
/**
* A stateful session bean that provides methods to manipulate
* users.
@@ -116,6 +117,21 @@ public class UserSessionBean extends AbstractPrincipalSessionBean {
if (u.isDeleted() || u.isSuspended()) throw new EntityForbiddenException(UserEntity.class, u.getId(), "Cannot access suspended or deleted user.");
return Convert.with(UserConverter.class).apply(u, true);
}
/**
* Returns the account of the user that is currently logged in as UserEntity.
*
* @return The user that is currently logged in as UserEntity.
* @throws EntityForbiddenException Thrown if the current account is suspended or deleted.
* @throws EntityNotFoundException Thrown if the current account is not found.
*/
@RolesAllowed({ Roles.USER })
public UserEntity getCurrentUserEntity() throws EntityForbiddenException, EntityNotFoundException {
UserEntity u = getPrincipalUser();
if (u == null) throw new EntityNotFoundException(UserEntity.class, null, "Cannot access current user.");
if (u.isDeleted() || u.isSuspended()) throw new EntityForbiddenException(UserEntity.class, u.getId(), "Cannot access suspended or deleted user.");
return u;
}
/**
* Modifies the current user.
@@ -211,6 +227,17 @@ public class UserSessionBean extends AbstractPrincipalSessionBean {
return page;
}
@PermitAll
public void addRefreshTokenToUser(String login, RefreshTokenEntity refreshTokenEntity) throws EntityNotFoundException {
UserEntity u = findUser(login);
if (u == null)
throw new EntityNotFoundException(UserEntity.class, Long.valueOf(login), "User request by admin for non-existing user.");
refreshTokenEntity.setUser(u);
u.getRefreshTokens().add(refreshTokenEntity);
em.persist(refreshTokenEntity);
em.flush();
}
/**
* Registers the user and returns the new account or
@@ -234,6 +261,7 @@ public class UserSessionBean extends AbstractPrincipalSessionBean {
setPassword(u, registration.getPassword());
setRoles(u, roles);
u.setEmails(new HashSet<EmailEntity>());
u.setRefreshTokens(new HashSet<RefreshTokenEntity>());
em.persist(u);
EmailEntity e = addEmail(u, registration.getEmail(), true);
em.persist(e);
@@ -516,6 +544,19 @@ public class UserSessionBean extends AbstractPrincipalSessionBean {
emailSession.sendEmailTemplate(email.getAddress(), EmailTemplate.RESET_USER, assignment);
}
}
/**
* Returns true, if refreshToken matches
*
* @param refreshToken The refreshToken to compare.
*
*/
@PermitAll
public Boolean compareRefreshToken(String refreshToken) throws EntityNotFoundException {
UserEntity u = getPrincipalUser();
if (u == null) throw new EntityNotFoundException(UserEntity.class, null, "Cannot access current user.");
return true;
}
/**
* Gets and updates an exisiting code for the specified action type
@@ -647,4 +688,6 @@ public class UserSessionBean extends AbstractPrincipalSessionBean {
c.setExpirationTime(expirationTime);
return c;
}
}
@@ -0,0 +1,110 @@
package com.mowesta.service.session.sync;
import com.mowesta.api.PageConfig;
import com.mowesta.service.entity.AbstractEntity;
import com.mowesta.service.entity.OAuthSecretEntity;
import com.mowesta.service.entity.OrderCriterion;
import java.security.Key;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import javax.annotation.security.PermitAll;
import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.io.Encoders;
import io.jsonwebtoken.security.Keys;
@Stateless
public class GenerateOAuthSecretSessionBean extends AbstractSyncSessionBean {
private final long offset = 720000;
private final long secretValidTime = 360000;
@PermitAll
@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
public void syncToken(boolean first) {
deleteOldToken();
if (first) {
invalidateAllToken();
} else {
invalidateOldToken();
}
createSecretKey();
}
/**
* Creates a new Secret Key.
*/
private void createSecretKey() {
log.log(Level.INFO, "Creating new Secret Key.");
Key secretKey = Keys.secretKeyFor(SignatureAlgorithm.HS256);
OAuthSecretEntity oAuthSecretEntity = new OAuthSecretEntity();
oAuthSecretEntity.setValid(true);
oAuthSecretEntity.setTimeValid(secretValidTime);
oAuthSecretEntity.setSecret(Encoders.BASE64.encode(secretKey.getEncoded()));
em.persist(oAuthSecretEntity);
log.log(Level.INFO, "New Secret Key: " + oAuthSecretEntity.getSecret().toString());
}
/**
* Invalidates all OAuthSecretEntities without validation check.
*/
private void invalidateAllToken() {
log.log(Level.INFO, "First Startup - invalidating all OAuthSecretEntities.");
List<OAuthSecretEntity> oAuthSecretEntities = AbstractEntity.findAll(em, OAuthSecretEntity.class, new PageConfig(0, 40), new OrderCriterion("timeValid"), false);
oAuthSecretEntities.forEach((oAuthSecretEntity -> {
oAuthSecretEntity.setValid(false);
em.persist(oAuthSecretEntity);
}));
}
/**
* Invalidates all OAuthSecretEntities, which are no longer valid.
*/
private void invalidateOldToken() {
log.log(Level.INFO, "Checking all OAuthSecretEntities for validation.");
List<OAuthSecretEntity> oAuthSecretEntities = AbstractEntity.findAll(em, OAuthSecretEntity.class, new PageConfig(0, 40), new OrderCriterion("timeValid"), false);
List<OAuthSecretEntity> invalidateoAuthSecretEntities = new ArrayList<>();
oAuthSecretEntities.forEach((oAuthSecretEntity -> {
if (oAuthSecretEntity.getCreationTime() + oAuthSecretEntity.getTimeValid() + offset < System.currentTimeMillis()) {
invalidateoAuthSecretEntities.add(oAuthSecretEntity);
}
}));
log.log(Level.INFO,"Found " + invalidateoAuthSecretEntities.size() + " Entities to invalidate");
invalidateoAuthSecretEntities.forEach((invalidOAuthSecretEntity) -> {
invalidOAuthSecretEntity.setValid(false);
em.persist(invalidOAuthSecretEntity);
});
log.log(Level.INFO, "Invalidated all old OAuthSecretEntities");
}
/**
* Deletes all OAuthSecretEntities, which are longer invalid than a defined offset.
*/
private void deleteOldToken() {
log.log(Level.INFO, "Checking for old OAuthSecretEntities.");
List<OAuthSecretEntity> allOAuthSecretEntities = AbstractEntity.findAll(em, OAuthSecretEntity.class, new PageConfig(0, 40), new OrderCriterion("timeValid"), false);
List<OAuthSecretEntity> allOldOAuthSecretEntites = new ArrayList<>();
allOAuthSecretEntities.forEach((oAuthSecretEntity -> {
if (oAuthSecretEntity.getCreationTime() + oAuthSecretEntity.getTimeValid() + offset < System.currentTimeMillis()) {
allOldOAuthSecretEntites.add(oAuthSecretEntity);
}
}));
log.log(Level.INFO, "Found " + allOldOAuthSecretEntites.size() + "Entities to remove.");
allOldOAuthSecretEntites.forEach((oldOAuthSecretEntity) -> {
oldOAuthSecretEntity.setDeleted(true);
em.remove(oldOAuthSecretEntity);
em.persist(oldOAuthSecretEntity);
});
log.log(Level.INFO, "Removed all old OAuthSecretEntities");
}
}
@@ -52,7 +52,11 @@ public class PeriodicSyncSessionBean {
/**
* The task that generates weather videos.
*/
VIDEO;
VIDEO,
/**
* The task that generates oauth-tokens.
*/
OAUTHTOKEN;
};
@@ -73,6 +77,9 @@ public class PeriodicSyncSessionBean {
@Inject
protected WeatherVideoSyncSessionBean videoSyncSession;
@Inject
protected GenerateOAuthSecretSessionBean generateOAuthSecretSessionBean;
@Resource
protected SessionContext context;
@@ -94,6 +101,9 @@ public class PeriodicSyncSessionBean {
jobs[JobType.VIDEO.ordinal()] = new Job("VideoSync", (first)-> {
videoSyncSession.syncVideos(first);
});
jobs[JobType.OAUTHTOKEN.ordinal()] = new Job("OAuthTokenSync", (first)-> {
generateOAuthSecretSessionBean.syncToken(first);
});
}
@@ -111,6 +121,8 @@ public class PeriodicSyncSessionBean {
timerService.createIntervalTimer(TimeUnit.MINUTES.toMillis(3), TimeUnit.HOURS.toMillis(1), forecastConfig);
final TimerConfig locationConfig = new TimerConfig(JobType.LOCATION, false);
timerService.createIntervalTimer(0, TimeUnit.MINUTES.toMillis(5), locationConfig);
final TimerConfig oAuthConfig = new TimerConfig(JobType.OAUTHTOKEN, false);
timerService.createIntervalTimer(0, TimeUnit.MINUTES.toMillis(12), oAuthConfig);
}
/**
@@ -1,5 +1,27 @@
package com.mowesta.service.session.sync;
import com.mowesta.api.Coordinate;
import com.mowesta.api.weather.SoilType;
import com.mowesta.api.weather.WeatherCondition;
import com.mowesta.api.weather.WeatherForecast;
import com.mowesta.api.weather.WeatherSource;
import com.mowesta.api.weather.WeatherType;
import com.mowesta.api.weather.WindDirection;
import com.mowesta.data.dwd.NumericPrediction;
import com.mowesta.data.dwd.NumericPrediction.Time;
import com.mowesta.data.dwd.NumericPrediction.Variable;
import com.mowesta.data.grib2.Grib2Data;
import com.mowesta.data.grib2.Grib2File;
import com.mowesta.data.grib2.decoder.SimpleDataDecoder;
import com.mowesta.data.process.conversion.KelvinCelsiusConversion;
import com.mowesta.data.process.source.Grib2MixedSource;
import com.mowesta.data.process.source.IDataSource;
import com.mowesta.data.process.util.DoubleArray;
import com.mowesta.service.entity.WeatherForecastContainer;
import com.mowesta.service.session.InfinispanSessionBean.MetadataType;
import org.infinispan.Cache;
import java.io.File;
import java.io.IOException;
import java.io.ObjectInputStream;
@@ -22,28 +44,6 @@ import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.inject.Inject;
import org.infinispan.Cache;
import com.mowesta.api.Coordinate;
import com.mowesta.api.weather.WeatherSource;
import com.mowesta.api.weather.SoilType;
import com.mowesta.api.weather.WeatherCondition;
import com.mowesta.api.weather.WeatherForecast;
import com.mowesta.api.weather.WeatherType;
import com.mowesta.api.weather.WindDirection;
import com.mowesta.data.dwd.NumericPrediction;
import com.mowesta.data.dwd.NumericPrediction.Time;
import com.mowesta.data.dwd.NumericPrediction.Variable;
import com.mowesta.data.grib2.Grib2Data;
import com.mowesta.data.grib2.Grib2File;
import com.mowesta.data.grib2.decoder.SimpleDataDecoder;
import com.mowesta.data.process.conversion.KelvinCelsiusConversion;
import com.mowesta.data.process.source.Grib2MixedSource;
import com.mowesta.data.process.source.IDataSource;
import com.mowesta.data.process.util.DoubleArray;
import com.mowesta.service.entity.WeatherForecastContainer;
import com.mowesta.service.session.InfinispanSessionBean.MetadataType;
/**
* A bean to synchronize the weather forecasts.
*
@@ -408,6 +408,7 @@ public class WeatherForecastSyncSessionBean extends AbstractSyncSessionBean {
double u = getValue(Variable.U10M, hour, chunk, index, cache);
double v = getValue(Variable.V10M, hour, chunk, index, cache);
result.setWindSpeed(getWindSpeed(u, v));
result.setMaxWindSpeed(getValue(Variable.VMAX_10M, hour, chunk, index, cache));
result.setWindDirection(getWindDirection(u, v));
return result;
}
@@ -23,6 +23,8 @@
<class>com.mowesta.service.entity.RoleEntity</class>
<class>com.mowesta.service.entity.StateEntity</class>
<class>com.mowesta.service.entity.UserEntity</class>
<class>com.mowesta.service.entity.RefreshTokenEntity</class>
<class>com.mowesta.service.entity.OAuthSecretEntity</class>
<class>com.mowesta.service.entity.WeatherReportEntity</class>
<class>com.mowesta.service.entity.WeatherStationEntity</class>
<exclude-unlisted-classes>true</exclude-unlisted-classes>
+8
View File
@@ -12,11 +12,19 @@ dependencies {
testCompile "org.jboss.arquillian.junit:arquillian-junit-container:${versionArquillianJunit}"
testCompile "org.wildfly.arquillian:wildfly-arquillian-container-managed:${versionArquillianContainer}"
compile "io.jsonwebtoken:jjwt-api:0.11.2"
compile "io.jsonwebtoken:jjwt-impl:0.11.2"
// Uncomment the next line if you want to use RSASSA-PSS (PS256, PS384, PS512) algorithms:
compile "org.bouncycastle:bcprov-jdk15on:1.60"
compile "io.jsonwebtoken:jjwt-jackson:0.11.2" // or 'io.jsonwebtoken:jjwt-gson:0.11.2' for gson
compile 'com.google.code.gson:gson:2.8.6'
providedCompile "jakarta.platform:jakarta.jakartaee-api:${versionJavaee}"
providedCompile "com.fasterxml.jackson.core:jackson-databind:${versionJackson}"
providedCompile("org.jboss.resteasy:resteasy-client:${versionResteasy}") {
exclude group: 'org.reactivestreams', module: 'reactive-streams'
}
}
jar {
@@ -1,17 +1,29 @@
package com.mowesta.service.app;
import com.mowesta.service.access.AccessControlFilter;
import com.mowesta.service.rest.*;
import org.jboss.resteasy.plugins.interceptors.CorsFilter;
import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;
import java.util.HashSet;
import java.util.Set;
import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;
import org.jboss.resteasy.plugins.interceptors.CorsFilter;
import com.mowesta.service.access.AccessControlFilter;
import com.mowesta.service.rest.CorsResponseFilter;
import com.mowesta.service.rest.DeviceResource;
import com.mowesta.service.rest.LocationResource;
import com.mowesta.service.rest.LogResource;
import com.mowesta.service.rest.MeasurementResource;
import com.mowesta.service.rest.ProcessingTimeFilter;
import com.mowesta.service.rest.ServerDebugFilter;
import com.mowesta.service.rest.SettingsResource;
import com.mowesta.service.rest.UserResource;
import com.mowesta.service.rest.VersionResource;
import com.mowesta.service.rest.WeatherResource;
/**
* The application is the main entry point of JAX-RS.
*
*
* @author Marcus
*
*/
@@ -22,7 +34,7 @@ public class MowestaApplication extends Application {
* The cors filter implementing the cors policy.
*/
protected CorsFilter corsFilter = new CorsFilter();
/**
* The set of classes.
*/
@@ -32,7 +44,7 @@ public class MowestaApplication extends Application {
* The singleton objects.
*/
protected Set<Object> singletons = new HashSet<>();
/**
* Initializes the application and explicitly
* sets the cors policy and the exposed resources.
@@ -57,17 +69,17 @@ public class MowestaApplication extends Application {
classes.add(SettingsResource.class);
classes.add(CorsResponseFilter.class);
// uncomment to enable heavy debugging
// classes.add(ServerDebugFilter.class);
classes.add(ServerDebugFilter.class);
}
@Override
public Set<Object> getSingletons() {
return singletons;
}
@Override
public Set<Class<?>> getClasses() {
return classes;
}
}
@@ -33,22 +33,22 @@ import com.mowesta.service.principal.LoginManager;
import com.mowesta.service.principal.MowestaPrincipal;
/**
* The server authentication module that
*
* The server authentication module that
*
*/
public class MowestaAuthModule extends AbstractHttpServletAuthModule {
/**
* The realm transmitted as part of a challenge.
*/
public static final String REALM_CHALLENGE = "Basic realm=\"mowesta-api\"";
/**
* The "magic" parameter that enables challenges.
*/
public static final String PARAMETER_CHALLENGE = "testAuth";
/**
* The logger to write debug data to the console.
*/
@@ -56,7 +56,6 @@ public class MowestaAuthModule extends AbstractHttpServletAuthModule {
@Override
protected AuthStatus validateRequest(HttpServletMessageInfo messageInfo, Subject clientSubject, Subject serviceSubject) throws AuthException {
// extract credentials from (possibly multiple headers)
HttpServletRequest request = messageInfo.getRequest();
BearerAuthCredential deviceCredential = null;
@@ -68,8 +67,10 @@ public class MowestaAuthModule extends AbstractHttpServletAuthModule {
String[] subHeaders = header.split(",");
for (String subHeader: subHeaders) {
subHeader = subHeader.trim();
if (deviceCredential == null) deviceCredential = BearerAuthCredential.valueOf(subHeader);
if (userCredential == null) userCredential = BasicAuthCredential.valueOf(subHeader);
if (deviceCredential == null)
deviceCredential = BearerAuthCredential.valueOf(subHeader);
if (userCredential == null)
userCredential = BasicAuthCredential.valueOf(subHeader);
}
}
}
@@ -83,7 +84,7 @@ public class MowestaAuthModule extends AbstractHttpServletAuthModule {
return sendForbidden(messageInfo, "Access not allowed.");
}
}
// perform user and device authentication
Device device = null;
User user = null;
@@ -99,15 +100,16 @@ public class MowestaAuthModule extends AbstractHttpServletAuthModule {
try {
LoginManager manager = new LoginManager(em);
ta.begin();
if (deviceCredential != null) device = manager.login(deviceCredential.getToken());
if (userCredential != null) user = manager.login(userCredential.getUsername(), userCredential.getPassword());
if (deviceCredential != null)
device = manager.login(deviceCredential.getToken());
if (userCredential != null)
user = manager.login(userCredential.getUsername(), userCredential.getPassword());
} finally {
ta.commit();
}
} catch (Exception e) {
return sendServerError(messageInfo, "Transactional error.");
}
// create principal or issue error
if (user != null || device != null) {
// create principal
@@ -143,11 +145,11 @@ public class MowestaAuthModule extends AbstractHttpServletAuthModule {
return sendForbidden(messageInfo, "Access not allowed.");
}
}
/**
* Tests whether the request requires an auth challenge to be sent out.
* This is done, if the caller has set the
*
*
* @param request The request.
* @return
*/
@@ -163,37 +165,37 @@ public class MowestaAuthModule extends AbstractHttpServletAuthModule {
/**
* Returns the entity manager for the mowesta datastore.
*
*
* @return The entity manager or null, if the entity manager cannot be found.
*/
private EntityManager getEntityManager() {
try {
Context context = new InitialContext();
return (EntityManager)context.lookup("java:app/mowesta/datastore");
return (EntityManager)context.lookup("java:app/mowesta/datastore");
} catch (NamingException e) {
log.log(Level.SEVERE, "Failed to resolve entity manager.", e);
return null;
}
}
/**
* Returns a user transaction for the datastore.
*
*
* @return The user transaction or null, if the transaction cannot be found.
*/
private UserTransaction getUserTransaction() {
try {
Context context = new InitialContext();
return (UserTransaction)context.lookup("java:comp/UserTransaction");
return (UserTransaction)context.lookup("java:comp/UserTransaction");
} catch (NamingException e) {
log.log(Level.SEVERE, "Failed to resolve user transaction.", e);
return null;
}
}
/**
* Sends a forbidden message and returns failed.
*
*
* @param messageInfo The message info.
* @param message The error message.
* @return AuthStatus.FAILED
@@ -202,11 +204,11 @@ public class MowestaAuthModule extends AbstractHttpServletAuthModule {
HttpServletResponse response = messageInfo.getResponse();
return sendError(response, HttpServletResponse.SC_FORBIDDEN, message);
}
/**
* Sends an unauthorized message and returns failed. A browser will create a
* credentials dialog in response to receiving this message.
*
*
* @param messageInfo The message info.
* @param message The error message.
* @return AuthStatus.FAILED
@@ -216,10 +218,10 @@ public class MowestaAuthModule extends AbstractHttpServletAuthModule {
response.addHeader(HttpHeaders.WWW_AUTHENTICATE, REALM_CHALLENGE);
return sendError(response, HttpServletResponse.SC_UNAUTHORIZED, message);
}
/**
* Sends a server error and returns a auth status failure.
*
*
* @param messageInfo The message info.
* @param message The error message.
* @return AuthStatus.FAILED
@@ -227,11 +229,11 @@ public class MowestaAuthModule extends AbstractHttpServletAuthModule {
private AuthStatus sendServerError(HttpServletMessageInfo messageInfo, String message) {
return sendError(messageInfo.getResponse(), HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
}
/**
* Sends an http error with the specified code and message and returns failure.
*
*
* @param response The servlet response.
* @param code The message code.
* @param message The error message.
@@ -239,11 +241,11 @@ public class MowestaAuthModule extends AbstractHttpServletAuthModule {
*/
private AuthStatus sendError(HttpServletResponse response, int code, String message) {
try {
response.sendError(code, message);
response.sendError(code, message);
} catch (IOException e) {
log.log(Level.WARNING, "Failed to send error " + code + " " + message + ".", e);
}
return AuthStatus.FAILURE;
}
}
@@ -7,6 +7,8 @@ import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.logging.Level;
import java.util.logging.Logger;
@@ -15,42 +17,39 @@ import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerRequestFilter;
import javax.ws.rs.container.ContainerResponseContext;
import javax.ws.rs.container.ContainerResponseFilter;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.ext.Provider;
/**
* A filter that provides heavy (i.e. expensive) debug output after the
* completion of each request.
*
*
* @author Marcus
*/
@Provider
public class ServerDebugFilter implements ContainerResponseFilter, ContainerRequestFilter {
@Inject
Logger log;
@Override
public void filter(ContainerRequestContext requestContext) throws IOException {
log.log(Level.INFO, "Request: " + requestContext.getMethod() + " " + requestContext.getUriInfo().getAbsolutePath().toString());
printParameters("Path", requestContext.getUriInfo().getPathParameters());
printParameters("Query", requestContext.getUriInfo().getQueryParameters());
List<String> authHeaders = requestContext.getHeaders().get(HttpHeaders.AUTHORIZATION);
if (authHeaders != null) {
for (String authHeader: authHeaders) {
log.log(Level.INFO, " Authorization: " + authHeader);
}
Map<String, List<String>> allHeaders = requestContext.getHeaders();
for (Entry<String, List<String>> e: allHeaders.entrySet()) {
for (String s: e.getValue()) {
log.log(Level.INFO, " " + e.getKey() + ": " + s);
}
}
log.log(Level.INFO, " Accept: " + requestContext.getHeaderString(HttpHeaders.ACCEPT));
log.log(Level.INFO, " Encoding: " + requestContext.getHeaderString(HttpHeaders.ACCEPT_ENCODING));
byte[] data = readBytes(requestContext.getEntityStream());
if (data != null) {
if (data.length > 0) {
log.log(Level.INFO, "Begin request entity (" + data.length + " bytes):");
log.log(Level.INFO, new String(data, "UTF-8"));
log.log(Level.INFO, "End request entity.");
log.log(Level.INFO, "End request entity.");
} else {
log.log(Level.INFO, "Request entity has 0 bytes.");
}
@@ -59,10 +58,10 @@ public class ServerDebugFilter implements ContainerResponseFilter, ContainerRequ
log.log(Level.INFO, "Request entity stream is null.");
}
}
/**
* Prints a parameter map.
*
*
* @param type The parameter type.
* @param params The parameter map.
*/
@@ -77,10 +76,10 @@ public class ServerDebugFilter implements ContainerResponseFilter, ContainerRequ
log.log(Level.INFO, " " + paramName + " = " + b.toString());
}
}
/**
* Logs most parts of the request and the resulting response.
*
*
* @param requestContext The request context.
* @param responseContext The response context.
*/
@@ -98,13 +97,13 @@ public class ServerDebugFilter implements ContainerResponseFilter, ContainerRequ
log.log(Level.INFO, "Result header: " + key + ": " + o);
}
}
}
/**
* Copies the response entity from the input stream and returns it.
*
*
* @param is The input stream which may be null.
* @return The bytes that have been read or null (if the input stream
* is null).
@@ -0,0 +1,178 @@
package com.mowesta.service.servlet;
import com.google.gson.Gson;
import com.mowesta.api.oauth2.AuthorizationResponse;
import com.mowesta.api.user.User;
import com.mowesta.service.entity.EntityForbiddenException;
import com.mowesta.service.entity.EntityNotFoundException;
import com.mowesta.service.session.UserSessionBean;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.file.attribute.UserPrincipalNotFoundException;
import java.security.Key;
import java.util.Arrays;
import java.util.Base64;
import java.util.Date;
import java.util.Enumeration;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.UnsupportedJwtException;
import io.jsonwebtoken.security.Keys;
@WebServlet(urlPatterns = "/oauth2/authorize")
public class OAuthAccessCodeServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final long timeAccessCodeIsValidInMilliSeconds = 240000;
protected static final String secretKey = "SecretForGeneratingAccessCode730474";
//only authorization code is supported
private final List<String> supportedGrantTypes = Arrays.asList("code");
@Inject
protected EntityManager em;
@Inject
UserSessionBean userSessionBean;
Logger logger = Logger.getLogger(getClass().getName());
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
String client_id = "";
String redirect_uri = "";
String response_type = "";
String state = "";
String scope = "";
logger.log(Level.INFO, "Received Authorize Request - HEADER:");
Enumeration<String> headerNames = request.getHeaderNames();
while(headerNames.hasMoreElements()) {
String headerName = headerNames.nextElement();
logger.log(Level.INFO,"Header Name - " + headerName + ", Value - " + request.getHeader(headerName));
}
logger.log(Level.INFO, "Received Authorize Request - PARAMETERS:");
Enumeration<String> parameterNames = request.getParameterNames();
while(parameterNames.hasMoreElements()) {
String paramName = parameterNames.nextElement();
logger.log(Level.INFO,"Param Name - " + paramName + ", Value - " + request.getParameter(paramName));
}
logger.log(Level.INFO, "End Authorize request.");
Enumeration<String> params = request.getParameterNames();
while(params.hasMoreElements()){
String paramName = params.nextElement();
if (paramName.equals("client_id")) client_id = request.getParameter(paramName);
if (paramName.equals("redirect_uri")) redirect_uri = request.getParameter(paramName);
if (paramName.equals("response_type")) response_type = request.getParameter(paramName);
if (paramName.equals("state")) state = request.getParameter(paramName);
if (paramName.equals("scope")) scope = request.getParameter(paramName);
}
//logger.log(Level.INFO, "Authorize Request with: clientid " + client_id + "; redirect_uri: " + redirect_uri + "; response_type " + response_type + "; state:" + state + "; scope: " + scope);
if (!supportedGrantTypes.contains(response_type)) {
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
response.setContentType("text/plain");
BufferedWriter w = new BufferedWriter(response.getWriter());
w.write("Grant Type currently not supported.");
w.close();
throw new UnsupportedJwtException("Grant Type currently not supported.");
}
// state and scope are optional, checking if client_id, redirect_uri and response type is set
if (Arrays.asList(client_id, redirect_uri, response_type).contains("")) {
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
response.setContentType("text/plain");
BufferedWriter w = new BufferedWriter(response.getWriter());
w.write("Please provide a client_id, redirect_uri and response_type.");
w.close();
throw new UnsupportedJwtException("Request needs to include client_id, redirect_uri and response_type.");
}
//an authorization code can only be generated if user is logged in
if (request.getUserPrincipal() != null || request.authenticate(response)) {
logger.log(Level.INFO, "UserPrincipal: " + request.getUserPrincipal().getName());
//Principal is set, we can use the UserSessionBean to get the current user
try {
User user = userSessionBean.getCurrentUser();
logger.log(Level.INFO, "User: " + user.getName() + " with ID:" + user.getId() + "and login: " + user.getLogin());
//generate AccessCode
String accessCode = createAccessCode(user.getLogin());
String base64Accesscode = Base64.getUrlEncoder().encodeToString(accessCode.getBytes());
AuthorizationResponse authorizationResponse = new AuthorizationResponse();
authorizationResponse.setAccessCode(base64Accesscode);
Gson gson = new Gson();
String jsonAuthorizationResponse = gson.toJson(authorizationResponse);
//generate Response
response.setStatus(HttpServletResponse.SC_OK);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
PrintWriter out = response.getWriter();
out.print(jsonAuthorizationResponse);
out.flush();
out.close();
} catch (EntityForbiddenException e) {
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
response.setContentType("text/plain");
BufferedWriter w = new BufferedWriter(response.getWriter());
w.write("Could not identify user.");
w.close();
throw new UserPrincipalNotFoundException("Could not identify user");
} catch (EntityNotFoundException e) {
response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
response.setContentType("text/plain");
BufferedWriter w = new BufferedWriter(response.getWriter());
w.write("An error occurred. Please try again.");
w.close();
throw new UserPrincipalNotFoundException("Could not identify user");
}
} else {
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
response.setContentType("text/plain");
BufferedWriter w = new BufferedWriter(response.getWriter());
w.write("Could not identify user.");
w.close();
throw new UserPrincipalNotFoundException("Could not identify user");
}
}
public String createAccessCode(String id) {
Key key = Keys.hmacShaKeyFor(secretKey.getBytes());
return Jwts.builder()
.setSubject("mowesta:access")
.setId(id)
.setIssuedAt(new Date())
.setNotBefore(new Date())
.setExpiration(new Date(System.currentTimeMillis() + timeAccessCodeIsValidInMilliSeconds))
.signWith(key).compact();
}
public String getAccessToken(String refreshToken, String secret) {
Jwts.parserBuilder().setSigningKey(Keys.hmacShaKeyFor(secret.getBytes())).build().parseClaimsJws(refreshToken).getBody().getSubject().equals("access");
return null;
}
}
@@ -0,0 +1,311 @@
package com.mowesta.service.servlet;
import com.google.gson.Gson;
import com.mowesta.api.oauth2.TokenResponse;
import com.mowesta.service.entity.EntityNotFoundException;
import com.mowesta.service.entity.OAuthSecretEntity;
import com.mowesta.service.entity.RefreshTokenEntity;
import com.mowesta.service.entity.UserEntity;
import com.mowesta.service.session.UserSessionBean;
import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.security.Key;
import java.util.Arrays;
import java.util.Base64;
import java.util.Date;
import java.util.Enumeration;
import java.util.List;
import java.util.Optional;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.TypedQuery;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.UnsupportedJwtException;
import io.jsonwebtoken.security.Keys;
@WebServlet(urlPatterns = "/oauth2/token")
public class OAuthTokenServlet extends HttpServlet {
//only authorization code is supported
enum SupportedGrantTypes {
authorization_code ("authorization_code"),
refresh_token ("refresh_token");
private final String identifier;
private SupportedGrantTypes(String s) {
identifier = s;
}
public boolean equals(String other) {
// (otherName == null) check is not needed because name.equals(null) returns false
return identifier.equals(other);
}
public String toString() {
return this.identifier;
}
}
private final List<String> supportedGrantTypes = Arrays.asList("authorization_code, refresh_token");
private static final long timeAccessTokenIsValidInMilliSeconds = 360000;
@Inject
protected EntityManager em;
@Inject
protected UserSessionBean userSessionBean;
Logger logger = Logger.getLogger(getClass().getName());
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws IOException {
String code = "";
logger.log(Level.INFO, "Received Token Request - HEADER:");
Enumeration<String> headerNames = request.getHeaderNames();
while(headerNames.hasMoreElements()) {
String headerName = headerNames.nextElement();
logger.log(Level.INFO,"Header Name - " + headerName + ", Value - " + request.getHeader(headerName));
}
logger.log(Level.INFO, "Received Authorize Request - PARAMETERS:");
Enumeration<String> parameterNames = request.getParameterNames();
while(parameterNames.hasMoreElements()) {
String paramName = parameterNames.nextElement();
logger.log(Level.INFO,"Param Name - " + paramName + ", Value - " + request.getParameter(paramName));
}
logger.log(Level.INFO, "End Token request.");
response.setHeader("Cache-Control", "no-cache, no-store");
response.setHeader("Pragma", "no-cache");
Enumeration<String> params = request.getParameterNames();
while (params.hasMoreElements()) {
String paramName = params.nextElement();
if (paramName.equals("grant_type")) code = request.getParameter(paramName);
}
//if code is present in request, verify and return refresh/accesstoken pair
if (code.equals("authorization_code")) {
handleAccessCodeRequest(request, response);
} else if (code.equals("refresh_token")) {
handleRefreshTokenRequest(request, response);
}
}
private void handleRefreshTokenRequest(HttpServletRequest request, HttpServletResponse response) throws IOException {
String grant_type = "";
String client_id = "";
String refresh_token = "";
String code = "";
Enumeration<String> params = request.getParameterNames();
while (params.hasMoreElements()) {
String paramName = params.nextElement();
if (paramName.equals("grant_type")) grant_type = request.getParameter(paramName);
if (paramName.equals("client_id")) client_id = request.getParameter(paramName);
if (paramName.equals("refresh_token")) refresh_token = request.getParameter(paramName);
}
if (Arrays.asList(grant_type, refresh_token).contains("")) {
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
response.setContentType("text/plain");
BufferedWriter w = new BufferedWriter(response.getWriter());
w.write("Please provide a refresh token.");
w.close();
throw new UnsupportedJwtException("Request needs to include grant type and refresh_token.");
}
Optional<OAuthSecretEntity> secretKey = findCurrentValidSecret();
//find the current secret to generate an AccessToken
if (!secretKey.isPresent()) {
response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
response.setContentType("text/plain");
BufferedWriter w = new BufferedWriter(response.getWriter());
w.write("An error occurred. Please try again.");
w.close();
}
try {
Claims claims = Jwts.parserBuilder().setSigningKey(OAuthAccessCodeServlet.secretKey.getBytes()).build().parseClaimsJws(code).getBody();
String userId = claims.getId();
UserEntity u = userSessionBean.findUser(userId);
if (u == null)
throw new EntityNotFoundException(UserEntity.class, Long.valueOf(userId), "User request for non-existing user.");
String accessToken = createAccessTokenForUser(u, secretKey.get());
long accessTokenExpirationTime = (timeAccessTokenIsValidInMilliSeconds / 1000);
TokenResponse tokenResponse = new TokenResponse();
tokenResponse.setAccess_token(accessToken);
tokenResponse.setToken_type("bearer");
tokenResponse.setExpires_in(accessTokenExpirationTime);
Gson gson = new Gson();
String jsonAuthorizationResponse = gson.toJson(tokenResponse);
logger.log(Level.INFO, "Token response: " + tokenResponse.getAccess_token() + " " + tokenResponse.getToken_type() + " " + tokenResponse.getExpires_in());
BufferedWriter w = new BufferedWriter(response.getWriter());
w.write(jsonAuthorizationResponse);
w.close();
} catch (Exception e) {
}
}
private void handleAccessCodeRequest(HttpServletRequest request, HttpServletResponse response) throws IOException {
String grant_type = "";
String client_id = "";
String client_secret = "";
String code = "";
Enumeration<String> params = request.getParameterNames();
while (params.hasMoreElements()) {
String paramName = params.nextElement();
if (paramName.equals("grant_type")) grant_type = request.getParameter(paramName);
if (paramName.equals("client_id")) client_id = request.getParameter(paramName);
if (paramName.equals("code")) code = request.getParameter(paramName);
}
if (Arrays.asList(grant_type, client_id, code).contains("")) {
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
response.setContentType("text/plain");
BufferedWriter w = new BufferedWriter(response.getWriter());
w.write("Please provide a client_id and accesscode.");
w.close();
throw new UnsupportedJwtException("Request needs to include client_id, redirect_uri and response_type.");
}
try {
byte[] accessClaimBytes = Base64.getUrlDecoder().decode(code);
String accessClaimString = new String(accessClaimBytes, StandardCharsets.UTF_8);
Claims claims = Jwts.parserBuilder().setSigningKey(OAuthAccessCodeServlet.secretKey.getBytes()).build().parseClaimsJws(accessClaimString).getBody();
if (new Date().after(claims.getExpiration())) {
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
response.setContentType("text/plain");
BufferedWriter w = new BufferedWriter(response.getWriter());
w.write("AccessCode was invalid");
w.close();
throw new UnsupportedJwtException("AccessCode expired.");
}
String userId = claims.getId();
logger.log(Level.INFO, "Claims had userID: " + userId);
UserEntity u = userSessionBean.findUser(userId);
if (u == null)
throw new EntityNotFoundException(UserEntity.class, Long.valueOf(userId), "User request for non-existing user.");
//here we could use client secret to identify service type (for example alexa as service type)
String refreshToken = createRefreshTokenForUser(u);
RefreshTokenEntity refreshTokenEntity = new RefreshTokenEntity();
refreshTokenEntity.setRefreshToken(refreshToken);
refreshTokenEntity.setServiceName("dummy");
userSessionBean.addRefreshTokenToUser(userId, refreshTokenEntity);
Optional<OAuthSecretEntity> secretKey = findCurrentValidSecret();
//find the current secret to generate an AccessToken
if (!secretKey.isPresent()) {
response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
response.setContentType("text/plain");
BufferedWriter w = new BufferedWriter(response.getWriter());
w.write("An error occurred. Please try again.");
w.close();
}
String accessToken = createAccessTokenForUser(u, secretKey.get());
long accessTokenExpirationTime = (timeAccessTokenIsValidInMilliSeconds / 1000);
TokenResponse tokenResponse = new TokenResponse();
tokenResponse.setAccess_token(accessToken);
tokenResponse.setExpires_in(accessTokenExpirationTime);
tokenResponse.setRefresh_token(refreshToken);
tokenResponse.setToken_type("bearer");
Gson gson = new Gson();
String jsonAuthorizationResponse = gson.toJson(tokenResponse);
BufferedWriter w = new BufferedWriter(response.getWriter());
w.write(jsonAuthorizationResponse);
w.close();
} catch (JwtException | EntityNotFoundException e) {
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
response.setContentType("text/plain");
BufferedWriter w = new BufferedWriter(response.getWriter());
w.write("Something went wrong.");
w.close();
throw new UnsupportedJwtException("AccessCode could not be verified.");
}
}
/**
* @return returns an refresh token. The refresh token is signed with a static secret and is mapped to a user
*/
private String createRefreshTokenForUser(UserEntity userEntity) {
Key key = Keys.hmacShaKeyFor(OAuthAccessCodeServlet.secretKey.getBytes());
return Jwts.builder()
.setSubject("mowesta:refresh:token")
.setId(String.valueOf(userEntity.getLogin()))
.setIssuedAt(new Date())
.setNotBefore(new Date())
.signWith(key).compact();
}
/**
* @param userEntity
* @param oAuthSecretEntity
* @return returns an access token. An access token includes a user id and expiration date in his body and is signed with a dynamically changing key.
*/
private String createAccessTokenForUser(UserEntity userEntity, OAuthSecretEntity oAuthSecretEntity) {
Key key = Keys.hmacShaKeyFor(oAuthSecretEntity.getSecret().getBytes());
return Jwts.builder()
.setSubject("mowesta:acess:token")
.setId(String.valueOf(userEntity.getId()))
.setIssuedAt(new Date())
.setNotBefore(new Date())
.setExpiration(new Date(System.currentTimeMillis() + timeAccessTokenIsValidInMilliSeconds))
.signWith(key).compact();
}
private Optional<OAuthSecretEntity> findCurrentValidSecret() {
TypedQuery<OAuthSecretEntity> query = em.createNamedQuery("OAuth.findAllSecrets", OAuthSecretEntity.class);
List<OAuthSecretEntity> oAuthSecretEntityList = query.getResultList();
return oAuthSecretEntityList.stream()
.filter(oAuthSecretEntity -> oAuthSecretEntity.getCreationTime() + oAuthSecretEntity.getTimeValid() < System.currentTimeMillis())
.findAny();
}
}
@@ -22,6 +22,7 @@
<filter-name>Resteasy</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
@@ -26,6 +26,7 @@ public class WarDeployment {
public static JavaArchive createEjb() {
return mergeLibraries(ShrinkWrap.create(JavaArchive.class, "ejb.jar")) // name used in ear (see application.xml)
.addPackages(true, "org.geojson")
.addPackages(true, "io.jsonwebtoken")
.addPackages(true, "org.apache.commons.compress")
.addPackages(true, "com.mowesta.api")
.addPackages(true, "com.mowesta.data")
+34 -2
View File
@@ -2630,6 +2630,16 @@
"integrity": "sha512-1Yj8h9Q+QDF5FzhMs/c9+6UntbD5MkRfRwac8DoEm9ZfUBZ7tZ55YcGVAzEe4bXsdQHEk+s9S5wsOKVdZrw0tQ==",
"dev": true
},
"bindings": {
"version": "1.5.0",
"resolved": "https://registry.npmjs.org/bindings/-/bindings-1.5.0.tgz",
"integrity": "sha512-p2q/t/mhvuOj/UeLlV6566GD/guowlr0hHxClI0W9m7MWYkL1F0hLo+0Aexs9HSPCtR1SXQ0TD3MMKrXZajbiQ==",
"dev": true,
"optional": true,
"requires": {
"file-uri-to-path": "1.0.0"
}
},
"blob": {
"version": "0.0.5",
"resolved": "https://registry.npmjs.org/blob/-/blob-0.0.5.tgz",
@@ -5205,6 +5215,13 @@
}
}
},
"file-uri-to-path": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/file-uri-to-path/-/file-uri-to-path-1.0.0.tgz",
"integrity": "sha512-0Zt+s3L7Vf1biwWZ29aARiVYLx7iMGnEUl9x33fbB/j3jR81u/O2LbqK+Bm1CDSNDKVtJ/YjwY7TUd5SkeLQLw==",
"dev": true,
"optional": true
},
"fill-range": {
"version": "7.0.1",
"resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.0.1.tgz",
@@ -7894,6 +7911,13 @@
"integrity": "sha512-1t2payD3Y8izfZRq7tfUQlhL2fKzjeLr9v1/2qNCTkEQnd9Abtn1JgzsBgGZubEXh6lM5L8B0iLGoWQiukjtbQ==",
"dev": true
},
"nan": {
"version": "2.14.2",
"resolved": "https://registry.npmjs.org/nan/-/nan-2.14.2.tgz",
"integrity": "sha512-M2ufzIiINKCuDfBSAUr1vWQ+vuVcA9kqx8JJUsbQi6yf1uGRyb7HfpdfUr5qLXf3B/t8dPvcjhKMmlfnP47EzQ==",
"dev": true,
"optional": true
},
"nanomatch": {
"version": "1.2.13",
"resolved": "https://registry.npmjs.org/nanomatch/-/nanomatch-1.2.13.tgz",
@@ -12956,7 +12980,11 @@
"resolved": "https://registry.npmjs.org/fsevents/-/fsevents-1.2.13.tgz",
"integrity": "sha512-oWb1Z6mkHIskLzEJ/XWX0srkpkTQ7vaopMQkyaEIoq0fmtFVxOthb8cCxeT+p3ynTdkk/RZwbgG4brR5BeWECw==",
"dev": true,
"optional": true
"optional": true,
"requires": {
"bindings": "^1.5.0",
"nan": "^2.12.1"
}
},
"glob-parent": {
"version": "3.1.0",
@@ -13633,7 +13661,11 @@
"resolved": "https://registry.npmjs.org/fsevents/-/fsevents-1.2.13.tgz",
"integrity": "sha512-oWb1Z6mkHIskLzEJ/XWX0srkpkTQ7vaopMQkyaEIoq0fmtFVxOthb8cCxeT+p3ynTdkk/RZwbgG4brR5BeWECw==",
"dev": true,
"optional": true
"optional": true,
"requires": {
"bindings": "^1.5.0",
"nan": "^2.12.1"
}
},
"glob-parent": {
"version": "3.1.0",
+346 -127
View File
@@ -1,93 +1,197 @@
import { BrowserModule } from '@angular/platform-browser';
import { NgModule, LOCALE_ID } from '@angular/core';
import { FlexLayoutModule } from '@angular/flex-layout';
import { NgxGaugeModule } from 'ngx-gauge';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { MatAutocompleteModule } from '@angular/material/autocomplete';
import { MatButtonModule } from '@angular/material/button';
import { MatCardModule } from '@angular/material/card';
import { MatCheckboxModule } from '@angular/material/checkbox';
import { MatNativeDateModule } from '@angular/material/core';
import { MatDatepickerModule } from '@angular/material/datepicker';
import { MatDialogModule } from '@angular/material/dialog';
import { MatExpansionModule } from '@angular/material/expansion';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatGridListModule } from '@angular/material/grid-list';
import { MatIconModule } from '@angular/material/icon';
import { MatInputModule } from '@angular/material/input';
import { MatListModule } from '@angular/material/list';
import { MatPaginatorModule, MatPaginatorIntl } from '@angular/material/paginator';
import { MatProgressBarModule } from '@angular/material/progress-bar';
import { MatProgressSpinnerModule } from '@angular/material/progress-spinner';
import { MatSelectModule } from '@angular/material/select';
import { MatSidenavModule } from '@angular/material/sidenav';
import { MatSnackBarModule } from '@angular/material/snack-bar';
import { MatTableModule } from '@angular/material/table';
import { MatTabsModule } from '@angular/material/tabs';
import { MatToolbarModule } from '@angular/material/toolbar';
import { MatTooltipModule } from '@angular/material/tooltip';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { LocationStrategy, PathLocationStrategy, registerLocaleData, DatePipe } from '@angular/common';
import LocaleDE from '@angular/common/locales/de';
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
import { AppRoutingModule } from './app.routing';
import { AppComponent } from './app.component';
import { LayoutDrawerComponent, LayoutPlainComponent, DrawerComponent, FooterComponent,
LayoutSingleComponent, LayoutDoubleComponent } from './layouts';
import { ToolbarButtonComponent, DecisionPanelComponent, EmailFieldComponent, LanguageSelectComponent,
LoginFieldComponent, MapComponent, NameFieldComponent, PasswordFieldComponent, ProfileButtonComponent,
SearchFieldComponent, FavoriteButtonComponent, LogoPanelComponent, ClickButtonComponent,
LocationAutocompleteComponent } from './widgets-common';
import { CitiesListComponent, WeatherConditionComponent, WeatherVideoComponent,
WeatherVideoBarComponent, WeatherVideoListComponent, WeatherStationsListComponent, WeatherReportsListComponent,
WeatherReportComponent, WeatherSummaryComponent, WeatherDiagramComponent } from './widgets-weather';
import { LoginComponent, ActivateComponent, ChangeComponent, RegisterComponent, ResetComponent,
LoadingComponent } from './views-common';
import { CitiesComponent, CityComponent, CountryComponent, StateComponent, VideosComponent,
StationsComponent, StationComponent, ConditionMapComponent } from './views-weather';
import { UserAccountComponent, UserDevicesComponent, UserFavoritesComponent, UserDeviceComponent } from './views-user';
import { ManageLogComponent, ManageSystemComponent, ManageUsersComponent } from './views-manage';
import { DelayInterceptor, AuthInterceptor } from './interceptors';
import { DefaultService, Configuration } from './api';
import { MessageDialogComponent, ConfirmationDialogComponent, LogDialogComponent,
ConditionsDialogComponent, CodeDialogComponent } from './dialogs';
import { ConsoleService, UserService, CredentialService, DeviceService, ManageLogService, ManageUserService,
ResourceService, VersionService, CitiesService, VideosService, StationsService, ReportsService,
SettingsService, MeasurementsService } from './services';
import { UseParentFormDirective } from './directives';
import { GermanPaginatorProvider } from './providers/paginator.provider';
import { CityResolver, UserResolver, StateResolver, CountryResolver, StationResolver,
DeviceResolver, LanguageResolver, BootstrapResolver } from './resolvers';
import { HumidityPipe, CloudPipe, PressurePipe, TemperaturePipe, SpeedPipe, SnowPipe, PrecipitationPipe,
WeatherPipe, DirectionPipe, SourcePipe, LocalTimePipe, LocalDatePipe, LocalNamePipe, BingMapsPipe,
GoogleMapsPipe, WikipediaPipe, CityTypePipe, VideoSourcePipe, VideoTypePipe, LocationIconPipe, WeatherIconPipe,
DirectionIconPipe, MeasurementTypePipe, MeasurementTypeIconPipe, OsIconPipe } from './pipes';
import { ManageMeasurementsMapComponent } from './views-manage/manage-measurements-map.component';
import {
ActivateComponent,
ChangeComponent,
LoadingComponent,
LoginComponent,
RegisterComponent,
ResetComponent,
} from "./views-common";
import { AuthInterceptor, DelayInterceptor } from "./interceptors";
import {
BingMapsPipe,
CityTypePipe,
CloudPipe,
DirectionIconPipe,
DirectionPipe,
GoogleMapsPipe,
HumidityPipe,
LocalDatePipe,
LocalNamePipe,
LocalTimePipe,
LocationIconPipe,
MeasurementTypeIconPipe,
MeasurementTypePipe,
OsIconPipe,
PrecipitationPipe,
PressurePipe,
SnowPipe,
SourcePipe,
SpeedPipe,
TemperaturePipe,
VideoSourcePipe,
VideoTypePipe,
WeatherIconPipe,
WeatherPipe,
WikipediaPipe,
} from "./pipes";
import {
BootstrapResolver,
CityResolver,
CountryResolver,
DeviceResolver,
LanguageResolver,
StateResolver,
StationResolver,
UserResolver,
} from "./resolvers";
import {
CitiesComponent,
CityComponent,
ConditionMapComponent,
CountryComponent,
StateComponent,
StationComponent,
StationsComponent,
VideosComponent,
} from "./views-weather";
import {
CitiesListComponent,
WeatherConditionComponent,
WeatherDiagramComponent,
WeatherReportComponent,
WeatherReportsListComponent,
WeatherStationsListComponent,
WeatherSummaryComponent,
WeatherVideoBarComponent,
WeatherVideoComponent,
WeatherVideoListComponent,
} from "./widgets-weather";
import {
CitiesService,
ConsoleService,
CredentialService,
DeviceService,
ManageLogService,
ManageUserService,
MeasurementsService,
ReportsService,
ResourceService,
SettingsService,
StationsService,
UserService,
VersionService,
VideosService,
} from "./services";
import {
ClickButtonComponent,
DecisionPanelComponent,
EmailFieldComponent,
FavoriteButtonComponent,
LanguageSelectComponent,
LocationAutocompleteComponent,
LoginFieldComponent,
LogoPanelComponent,
MapComponent,
NameFieldComponent,
PasswordFieldComponent,
ProfileButtonComponent,
SearchFieldComponent,
ToolbarButtonComponent,
} from "./widgets-common";
import {
CodeDialogComponent,
ConditionsDialogComponent,
ConfirmationDialogComponent,
LogDialogComponent,
MessageDialogComponent,
} from "./dialogs";
import { Configuration, DefaultService } from "./api";
import {
DatePipe,
LocationStrategy,
PathLocationStrategy,
registerLocaleData,
} from "@angular/common";
import {
DrawerComponent,
FooterComponent,
LayoutDoubleComponent,
LayoutDrawerComponent,
LayoutPlainComponent,
LayoutSingleComponent,
} from "./layouts";
import { FormsModule, ReactiveFormsModule } from "@angular/forms";
import { HTTP_INTERCEPTORS, HttpClientModule } from "@angular/common/http";
import { LOCALE_ID, NgModule } from "@angular/core";
import {
ManageLogComponent,
ManageSystemComponent,
ManageUsersComponent,
} from "./views-manage";
import {
MatPaginatorIntl,
MatPaginatorModule,
} from "@angular/material/paginator";
import {
UserAccountComponent,
UserDeviceComponent,
UserDevicesComponent,
UserFavoritesComponent,
} from "./views-user";
import { AccessGrantComponent } from "./views-oauth/access-grant/access-grant.component";
import { AppComponent } from "./app.component";
import { AppRoutingModule } from "./app.routing";
import { BrowserAnimationsModule } from "@angular/platform-browser/animations";
import { BrowserModule } from "@angular/platform-browser";
import { FlexLayoutModule } from "@angular/flex-layout";
import { GermanPaginatorProvider } from "./providers/paginator.provider";
import LocaleDE from "@angular/common/locales/de";
import { ManageMeasurementsMapComponent } from "./views-manage/manage-measurements-map.component";
import { MatAutocompleteModule } from "@angular/material/autocomplete";
import { MatButtonModule } from "@angular/material/button";
import { MatCardModule } from "@angular/material/card";
import { MatCheckboxModule } from "@angular/material/checkbox";
import { MatDatepickerModule } from "@angular/material/datepicker";
import { MatDialogModule } from "@angular/material/dialog";
import { MatExpansionModule } from "@angular/material/expansion";
import { MatFormFieldModule } from "@angular/material/form-field";
import { MatGridListModule } from "@angular/material/grid-list";
import { MatIconModule } from "@angular/material/icon";
import { MatInputModule } from "@angular/material/input";
import { MatListModule } from "@angular/material/list";
import { MatNativeDateModule } from "@angular/material/core";
import { MatProgressBarModule } from "@angular/material/progress-bar";
import { MatProgressSpinnerModule } from "@angular/material/progress-spinner";
import { MatSelectModule } from "@angular/material/select";
import { MatSidenavModule } from "@angular/material/sidenav";
import { MatSnackBarModule } from "@angular/material/snack-bar";
import { MatTableModule } from "@angular/material/table";
import { MatTabsModule } from "@angular/material/tabs";
import { MatToolbarModule } from "@angular/material/toolbar";
import { MatTooltipModule } from "@angular/material/tooltip";
import { NgxGaugeModule } from "ngx-gauge";
import { OAuthLoginComponentComponent } from "./views-oauth/oauth-login-component/oauth-login-component.component";
import { UseParentFormDirective } from "./directives";
/**
* Computes the api domain from the browser location.
*/
const apidomain = (): { http: string, ws: string } => {
const apidomain = (): { http: string; ws: string } => {
const host = document.location.hostname;
const port = document.location.port;
const protocol = document.location.protocol;
let hostportpath = '';
let hostportpath = "";
if (port.length > 0) {
hostportpath = '://' + host + ':' + port + '/api';
hostportpath = "://" + host + ":" + port + "/api";
} else {
hostportpath = '://' + host + '/api';
hostportpath = "://" + host + "/api";
}
const secure = (protocol !== 'http:') ? 's' : '';
return { http: 'http' + secure + hostportpath, ws: 'ws' + secure + hostportpath };
const secure = protocol !== "http:" ? "s" : "";
return {
http: "http" + secure + hostportpath,
ws: "ws" + secure + hostportpath,
};
};
/**
@@ -97,65 +201,180 @@ registerLocaleData(LocaleDE);
@NgModule({
declarations: [
AppComponent, FooterComponent, LayoutDrawerComponent, LayoutPlainComponent, LayoutSingleComponent,
AppComponent,
FooterComponent,
LayoutDrawerComponent,
LayoutPlainComponent,
LayoutSingleComponent,
LayoutDoubleComponent,
ToolbarButtonComponent, ProfileButtonComponent, LanguageSelectComponent,
DrawerComponent, LoginFieldComponent, PasswordFieldComponent, EmailFieldComponent,
NameFieldComponent, DecisionPanelComponent, MessageDialogComponent, ConfirmationDialogComponent,
ConditionsDialogComponent, LogoPanelComponent,
LoginComponent, RegisterComponent, ActivateComponent, ResetComponent, ChangeComponent,
UserDevicesComponent, UserAccountComponent, ManageLogComponent, LogDialogComponent, ManageSystemComponent,
ManageUsersComponent, SearchFieldComponent, CityComponent, CountryComponent, StateComponent,
MapComponent, WeatherConditionComponent, CitiesListComponent, CitiesComponent, WeatherVideoListComponent,
WeatherVideoComponent, WeatherVideoBarComponent, VideosComponent,
WeatherStationsListComponent, StationsComponent, StationComponent, WeatherReportsListComponent,
WeatherReportComponent, WeatherSummaryComponent, UserFavoritesComponent, FavoriteButtonComponent,
LoadingComponent, UserDeviceComponent, WeatherDiagramComponent,
HumidityPipe, CloudPipe, PressurePipe, TemperaturePipe, SpeedPipe, SnowPipe, PrecipitationPipe,
WeatherPipe, DirectionPipe, SourcePipe, BingMapsPipe, GoogleMapsPipe, WikipediaPipe, LocalTimePipe,
LocalDatePipe, LocalNamePipe, LocationIconPipe, CityTypePipe, VideoSourcePipe, VideoTypePipe,
WeatherIconPipe, DirectionIconPipe, OsIconPipe, MeasurementTypePipe, MeasurementTypeIconPipe,
UseParentFormDirective, ClickButtonComponent, CodeDialogComponent, ConditionMapComponent, LocationAutocompleteComponent, ManageMeasurementsMapComponent,
ToolbarButtonComponent,
ProfileButtonComponent,
LanguageSelectComponent,
DrawerComponent,
LoginFieldComponent,
PasswordFieldComponent,
EmailFieldComponent,
NameFieldComponent,
DecisionPanelComponent,
MessageDialogComponent,
ConfirmationDialogComponent,
ConditionsDialogComponent,
LogoPanelComponent,
LoginComponent,
RegisterComponent,
ActivateComponent,
ResetComponent,
ChangeComponent,
UserDevicesComponent,
UserAccountComponent,
ManageLogComponent,
LogDialogComponent,
ManageSystemComponent,
ManageUsersComponent,
SearchFieldComponent,
CityComponent,
CountryComponent,
StateComponent,
MapComponent,
WeatherConditionComponent,
CitiesListComponent,
CitiesComponent,
WeatherVideoListComponent,
WeatherVideoComponent,
WeatherVideoBarComponent,
VideosComponent,
WeatherStationsListComponent,
StationsComponent,
StationComponent,
WeatherReportsListComponent,
WeatherReportComponent,
WeatherSummaryComponent,
UserFavoritesComponent,
FavoriteButtonComponent,
LoadingComponent,
UserDeviceComponent,
WeatherDiagramComponent,
HumidityPipe,
CloudPipe,
PressurePipe,
TemperaturePipe,
SpeedPipe,
SnowPipe,
PrecipitationPipe,
WeatherPipe,
DirectionPipe,
SourcePipe,
BingMapsPipe,
GoogleMapsPipe,
WikipediaPipe,
LocalTimePipe,
LocalDatePipe,
LocalNamePipe,
LocationIconPipe,
CityTypePipe,
VideoSourcePipe,
VideoTypePipe,
WeatherIconPipe,
DirectionIconPipe,
OsIconPipe,
MeasurementTypePipe,
MeasurementTypeIconPipe,
UseParentFormDirective,
ClickButtonComponent,
CodeDialogComponent,
ConditionMapComponent,
LocationAutocompleteComponent,
ManageMeasurementsMapComponent,
OAuthLoginComponentComponent,
AccessGrantComponent,
],
imports: [
BrowserModule, BrowserAnimationsModule,
FormsModule, ReactiveFormsModule,
FlexLayoutModule, NgxGaugeModule,
HttpClientModule, MatProgressBarModule,
MatProgressSpinnerModule, MatPaginatorModule,
MatExpansionModule, MatTableModule,
MatButtonModule, MatInputModule,
MatFormFieldModule, MatListModule,
MatIconModule, MatCardModule,
MatSelectModule, MatSnackBarModule,
MatTooltipModule, MatToolbarModule,
MatSidenavModule, MatProgressBarModule,
MatDialogModule, MatCheckboxModule,
MatDatepickerModule, MatNativeDateModule,
MatTabsModule, MatGridListModule,
AppRoutingModule, MatAutocompleteModule
BrowserModule,
BrowserAnimationsModule,
FormsModule,
ReactiveFormsModule,
FlexLayoutModule,
NgxGaugeModule,
HttpClientModule,
MatProgressBarModule,
MatProgressSpinnerModule,
MatPaginatorModule,
MatExpansionModule,
MatTableModule,
MatButtonModule,
MatInputModule,
MatFormFieldModule,
MatListModule,
MatIconModule,
MatCardModule,
MatSelectModule,
MatSnackBarModule,
MatTooltipModule,
MatToolbarModule,
MatSidenavModule,
MatProgressBarModule,
MatDialogModule,
MatCheckboxModule,
MatDatepickerModule,
MatNativeDateModule,
MatTabsModule,
MatGridListModule,
AppRoutingModule,
MatAutocompleteModule,
],
providers: [
// injection token for http client
{ provide: Configuration, useValue: new Configuration({ basePath: apidomain().http }) },
{ provide: 'wsdomain', useValue: apidomain().ws },
{
provide: Configuration,
useValue: new Configuration({ basePath: apidomain().http }),
},
{ provide: "wsdomain", useValue: apidomain().ws },
// location stategy for passing that with the router
{ provide: LocationStrategy, useClass: PathLocationStrategy },
// add two global interceptors (one two slow down the server and one for authentication)
// {provide: HTTP_INTERCEPTORS, useClass: DelayInterceptor, multi: true},
{provide: HTTP_INTERCEPTORS, useClass: AuthInterceptor, multi: true},
{ provide: HTTP_INTERCEPTORS, useClass: AuthInterceptor, multi: true },
// change the locale to DE and add custom paginator provider for tables
{ provide: LOCALE_ID, useValue: 'de' },
{ provide: LOCALE_ID, useValue: "de" },
{ provide: MatPaginatorIntl, useClass: GermanPaginatorProvider },
DatePipe, LocalNamePipe, LocalDatePipe, LocalTimePipe, HumidityPipe, PressurePipe, TemperaturePipe,
DatePipe,
LocalNamePipe,
LocalDatePipe,
LocalTimePipe,
HumidityPipe,
PressurePipe,
TemperaturePipe,
// add our application services (api access, logging, authentication)
DefaultService, ConsoleService, UserResolver, CityResolver, StateResolver, CountryResolver, StationResolver,
DeviceResolver, LanguageResolver, BootstrapResolver,
ResourceService, CredentialService, UserService, VersionService, DeviceService, MeasurementsService,
ManageLogService, ManageUserService, CitiesService, VideosService, StationsService, ReportsService,
SettingsService
],
entryComponents: [MessageDialogComponent, ConfirmationDialogComponent, LogDialogComponent, ConditionsDialogComponent],
bootstrap: [AppComponent]
DefaultService,
ConsoleService,
UserResolver,
CityResolver,
StateResolver,
CountryResolver,
StationResolver,
DeviceResolver,
LanguageResolver,
BootstrapResolver,
ResourceService,
CredentialService,
UserService,
VersionService,
DeviceService,
MeasurementsService,
ManageLogService,
ManageUserService,
CitiesService,
VideosService,
StationsService,
ReportsService,
SettingsService,
],
entryComponents: [
MessageDialogComponent,
ConfirmationDialogComponent,
LogDialogComponent,
ConditionsDialogComponent,
],
bootstrap: [AppComponent],
})
export class AppModule { }
export class AppModule {}
+175 -67
View File
@@ -1,82 +1,190 @@
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import {
ActivateComponent,
ChangeComponent,
LoadingComponent,
LoginComponent,
RegisterComponent,
ResetComponent,
} from "./views-common";
import {
BootstrapResolver,
CityResolver,
CountryResolver,
DeviceResolver,
LanguageResolver,
StateResolver,
StationResolver,
UserResolver,
} from "./resolvers";
import {
CitiesComponent,
CityComponent,
ConditionMapComponent,
CountryComponent,
StateComponent,
StationComponent,
StationsComponent,
VideosComponent,
} from "./views-weather";
import {
ManageLogComponent,
ManageSystemComponent,
ManageUsersComponent,
} from "./views-manage";
import { RouterModule, Routes } from "@angular/router";
import {
UserAccountComponent,
UserDeviceComponent,
UserDevicesComponent,
UserFavoritesComponent,
} from "./views-user";
// Import custom pages
import { LayoutDrawerComponent } from './layouts';
import { LoginComponent, RegisterComponent, ActivateComponent, ChangeComponent, ResetComponent, LoadingComponent } from './views-common';
import { CityComponent, StateComponent, CountryComponent, CitiesComponent, VideosComponent,
StationsComponent, StationComponent, ConditionMapComponent } from './views-weather';
import { UserDevicesComponent, UserAccountComponent, UserFavoritesComponent, UserDeviceComponent } from './views-user';
import { ManageLogComponent, ManageSystemComponent, ManageUsersComponent } from './views-manage';
import { CityResolver, StateResolver, CountryResolver, UserResolver, StationResolver, LanguageResolver,
BootstrapResolver, DeviceResolver } from './resolvers';
import { AccessGrantComponent } from "./views-oauth/access-grant/access-grant.component";
import { CanDeactivateGuard } from "./guards/can-deactivate.guard";
// Import custom pages
import { LayoutDrawerComponent } from "./layouts";
import { ManageMeasurementsMapComponent } from "./views-manage/manage-measurements-map.component";
import { NgModule } from "@angular/core";
import { OAuthLoginComponentComponent } from "./views-oauth/oauth-login-component/oauth-login-component.component";
export const routes: Routes = [
// backwards compatibility
{ path: 'activate/:token', resolve: { bs: BootstrapResolver}, component: LoadingComponent },
{ path: 'reset/:token', resolve: { bs: BootstrapResolver}, component: LoadingComponent },
{ path: 'loading', component: LoadingComponent },
// main app routing
{ path: ':lang', component: LayoutDrawerComponent, resolve: { user: UserResolver, lang: LanguageResolver }, children: [
// backwards compatibility
{
path: "activate/:token",
resolve: { bs: BootstrapResolver },
component: LoadingComponent,
},
{
path: "reset/:token",
resolve: { bs: BootstrapResolver },
component: LoadingComponent,
},
{ path: "loading", component: LoadingComponent },
{ path: "oauth/login", component: OAuthLoginComponentComponent },
{ path: "oauth/grant", component: AccessGrantComponent },
// main app routing
{
path: ":lang",
component: LayoutDrawerComponent,
resolve: { user: UserResolver, lang: LanguageResolver },
children: [
/// administrative functions
{ path: 'manage', children: [
{ path: 'logs', component: ManageLogComponent },
{ path: 'system', component: ManageSystemComponent },
{ path: 'users', component: ManageUsersComponent },
{ path: 'measurements', component: ManageMeasurementsMapComponent, canDeactivate: [CanDeactivateGuard] },
{ path: '**', redirectTo: '/manage/system' }
]},
{
path: "manage",
children: [
{ path: "logs", component: ManageLogComponent },
{ path: "system", component: ManageSystemComponent },
{ path: "users", component: ManageUsersComponent },
{
path: "measurements",
component: ManageMeasurementsMapComponent,
canDeactivate: [CanDeactivateGuard],
},
{ path: "**", redirectTo: "/manage/system" },
],
},
// user functions
{ path: 'user', children: [
{ path: 'devices', children: [
{ path: ':id', component: UserDeviceComponent, resolve: { device: DeviceResolver } },
{ path: '**', component: UserDevicesComponent },
] },
{ path: 'account', component: UserAccountComponent, canDeactivate: [CanDeactivateGuard] },
{ path: 'favorites', component: UserFavoritesComponent },
{ path: '**', redirectTo: '/user/account' }
]},
{
path: "user",
children: [
{
path: "devices",
children: [
{
path: ":id",
component: UserDeviceComponent,
resolve: { device: DeviceResolver },
},
{ path: "**", component: UserDevicesComponent },
],
},
{
path: "account",
component: UserAccountComponent,
canDeactivate: [CanDeactivateGuard],
},
{ path: "favorites", component: UserFavoritesComponent },
{ path: "**", redirectTo: "/user/account" },
],
},
// weather functions
{ path: 'weather', children: [
{ path: 'map', component: ConditionMapComponent },
{ path: 'cities', children: [
{ path: ':id', component: CityComponent, resolve: { city: CityResolver } },
{ path: '**', component: CitiesComponent },
]},
{ path: 'states', children: [
{ path: ':id', component: StateComponent, resolve: { state: StateResolver } }
]},
{ path: 'countries', children: [
{ path: ':id', component: CountryComponent, resolve: { country: CountryResolver } }
]},
{ path: 'stations', children: [
{ path: ':id', component: StationComponent, resolve: { station: StationResolver } },
{ path: '**', component: StationsComponent },
]},
{ path: 'videos', component: VideosComponent },
]},
{
path: "weather",
children: [
{ path: "map", component: ConditionMapComponent },
{
path: "cities",
children: [
{
path: ":id",
component: CityComponent,
resolve: { city: CityResolver },
},
{ path: "**", component: CitiesComponent },
],
},
{
path: "states",
children: [
{
path: ":id",
component: StateComponent,
resolve: { state: StateResolver },
},
],
},
{
path: "countries",
children: [
{
path: ":id",
component: CountryComponent,
resolve: { country: CountryResolver },
},
],
},
{
path: "stations",
children: [
{
path: ":id",
component: StationComponent,
resolve: { station: StationResolver },
},
{ path: "**", component: StationsComponent },
],
},
{ path: "videos", component: VideosComponent },
],
},
// common functions
{ path: 'login', component: LoginComponent },
{ path: 'register', component: RegisterComponent },
{ path: 'reset', children: [
{ path: '', component: ResetComponent },
{ path: ':token', component: ChangeComponent }
]},
{ path: 'activate', children: [
{ path: ':token', component: ActivateComponent }
] },
{ path: "login", component: LoginComponent },
{ path: "register", component: RegisterComponent },
{
path: "reset",
children: [
{ path: "", component: ResetComponent },
{ path: ":token", component: ChangeComponent },
],
},
{
path: "activate",
children: [{ path: ":token", component: ActivateComponent }],
},
// catch all
{ path: '**', redirectTo: 'weather/map' }
]},
// catch all, redirect to browser language
{ path: '**', resolve: { bs: BootstrapResolver}, component: LoadingComponent }
{ path: "**", redirectTo: "weather/map" },
],
},
// catch all, redirect to browser language
{
path: "**",
resolve: { bs: BootstrapResolver },
component: LoadingComponent,
},
];
@NgModule({
imports: [ RouterModule.forRoot(routes, { relativeLinkResolution: 'legacy' }) ],
exports: [ RouterModule ]
imports: [RouterModule.forRoot(routes, { relativeLinkResolution: "legacy" })],
exports: [RouterModule],
})
export class AppRoutingModule {}
@@ -0,0 +1,55 @@
import { Inject, Injectable } from "@angular/core";
import { DOCUMENT } from '@angular/common';
import { DefaultService } from "../../api/api/default.service";
import { HttpResponse } from "@angular/common/http";
import { Observable } from "rxjs";
@Injectable({
providedIn: "root",
})
export class OAuthService {
public client_id: string = "";
public redirect_uri: string = "";
public response_type: string = "";
public scope: string = "";
public state: string = "";
private accessCode: string;
constructor(private apiClientService: DefaultService) {}
public getAccessCode(): void {
this.apiClientService
.getAccessCode(
this.client_id,
this.redirect_uri,
this.response_type,
this.state,
this.scope,
)
.subscribe((val) => {
this.accessCode = val.accessCode;
this.redirect();
/**
this.apiClientService
.getAccessRefreshTokenPairFromAccessCode(
"code",
"1222",
"312525",
val.accessCode
)
.subscribe((val) => {
console.log(val);
});
*/
});
}
private redirect(): void {
const url: string = this.redirect_uri + "?state=" + this.state + "&code=" + this.accessCode;
console.log("Redirecting to: ", url)
window.location.href = url;
}
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,33 @@
<div class="fx-fill fx-column fx-stretch fx-mh100">
<app-layout-single class="fx-fill fx-row fx-stretch">
<div id="main" class="fx-column">
<div class="mat-typography">
<h2>
{{ res.strings("oauth_grant_title") }}
</h2>
<p>
{{ res.strings("oauth_grant_body") }}
</p>
</div>
<div
class="fx-row"
style="justify-content: space-around; align-items: center"
>
<button
#grantAcessButton
mat-raised-button
color="accent"
(click)="onGrantAcess()"
>
<mat-icon class="icon-button">lock_open</mat-icon>
<span>{{ res.strings("oauth_grant_button_grant") }}</span>
</button>
<button #dismissAcessButton mat-raised-button color="primary">
<mat-icon class="icon-button">clear</mat-icon>
<span>{{ res.strings("oauth_grant_button_dismiss") }}</span>
</button>
</div>
</div>
</app-layout-single>
<app-footer></app-footer>
</div>
@@ -0,0 +1,24 @@
import { Component, OnInit } from "@angular/core";
import { DefaultService } from "../../../api/api/default.service";
import { HttpClient } from "@angular/common/http";
import { OAuthService } from "../../services/oauth.service";
import { ResourceService } from "../../services";
@Component({
selector: "app-access-grant",
templateUrl: "./access-grant.component.html",
})
export class AccessGrantComponent implements OnInit {
constructor(
public res: ResourceService,
private oAuthService: OAuthService,
private apiClientService: DefaultService
) {}
ngOnInit(): void {}
onGrantAcess(): void {
this.oAuthService.getAccessCode();
}
}
@@ -0,0 +1,39 @@
<div class="fx-fill fx-column fx-stretch fx-mh100">
<app-layout-single class="fx-fill fx-row fx-stretch">
<div id="main" class="fx-column">
<div class="m-lg mat-typography">
<h2>{{ res.strings("login_login_title") }}</h2>
<h4>{{ res.strings("oauth_login_subtitle") }}</h4>
<form #loginForm="ngForm">
<app-login-field class="mb-sm" [login]="login"></app-login-field>
<app-password-field
class="mb-lg"
[password]="password"
(keyup.enter)="loginForm.valid && onLogin()"
></app-password-field>
</form>
<div
class="fx-row"
style="justify-content: space-around; align-items: center"
>
<ng-container *ngIf="idle | async as submittable; else progressBar">
<button
#loginButton
mat-raised-button
color="accent"
[disabled]="!submittable || loginForm.invalid"
(click)="onLogin()"
>
<mat-icon class="icon-button">open_in_browser</mat-icon>
<span>{{ res.strings("button_login") }}</span>
</button>
</ng-container>
<ng-template #progressBar>
<mat-spinner [diameter]="36"></mat-spinner>
</ng-template>
</div>
</div>
</div>
</app-layout-single>
<app-footer></app-footer>
</div>
@@ -0,0 +1,89 @@
import { ActivatedRoute, Router } from "@angular/router";
import { BehaviorSubject, Subscription } from "rxjs";
import { Component, HostListener, OnInit, ViewChild } from "@angular/core";
import { HttpStatusCode, Snackbars } from "../../utils";
import {
LoginFieldComponent,
PasswordFieldComponent,
} from "../../widgets-common";
import { ResourceService, UserService, UserState } from "../../services";
import { MatSnackBar } from "@angular/material/snack-bar";
import { NgForm } from "@angular/forms";
import { OAuthService } from "../../services/oauth.service";
@Component({
selector: "app-oauth-login-component",
templateUrl: "./oauth-login-component.component.html",
})
export class OAuthLoginComponentComponent implements OnInit {
login: string;
password: string;
readonly idle = new BehaviorSubject<boolean>(false);
@ViewChild(LoginFieldComponent, { static: true })
loginField: LoginFieldComponent;
@ViewChild(PasswordFieldComponent, { static: true })
passwordField: PasswordFieldComponent;
@ViewChild("loginForm", { static: true }) loginForm: NgForm;
private errorSubscription: Subscription;
private stateSubscription: Subscription;
constructor(
public res: ResourceService,
private snackbar: MatSnackBar,
private oAuthService: OAuthService,
private userService: UserService,
private router: Router,
private route: ActivatedRoute
) {}
ngOnInit(): void {
this.route.queryParams.subscribe((params) => {
this.oAuthService.client_id = params["client_id"];
this.oAuthService.redirect_uri = params["redirect_uri"];
this.oAuthService.response_type = params["response_type"];
this.oAuthService.scope = params["scope"];
this.oAuthService.state = params["state"];
});
this.stateSubscription = this.userService.state.subscribe((state) => {
if (state === UserState.Available) {
this.idle.next(false);
const url = "/oauth/grant";
this.router.navigateByUrl(url);
} else {
this.idle.next(state !== UserState.Changing);
this.loginField.disabled = !this.idle.getValue();
this.loginField.disabled = !this.idle.getValue();
}
});
this.errorSubscription = this.userService.error.subscribe((error) => {
this.password = "";
if (error.status === HttpStatusCode.FORBIDDEN) {
Snackbars.showError(
this.snackbar,
"Zugriff verweigert. Prüf Deine Eingaben und versuchs nochmal."
);
} else {
Snackbars.showError(
this.snackbar,
"Fehler bei der Anmeldung (" +
error.status +
"). Hast Du gerade kein Netz?"
);
}
});
}
onLogin(): void {
this.snackbar.dismiss();
if (!this.idle || !this.loginForm.valid) {
return;
}
this.login = this.loginField.login;
this.password = this.passwordField.password;
this.userService.setUser(this.login, this.password);
this.userService.login();
}
}
@@ -1,233 +1,278 @@
import { Component, Input, OnChanges, SimpleChanges, OnInit } from '@angular/core';
import { MatDialog } from '@angular/material/dialog';
import { ResourceService } from '../services/resource.service';
import { WeatherCondition } from '../api';
import { LocalTimePipe, LocalDatePipe } from '../pipes/location.pipes';
import { ConditionsDialogComponent } from '../dialogs/conditions-dialog.component';
import {
Component,
Input,
OnChanges,
OnInit,
SimpleChanges,
} from "@angular/core";
import { LocalDatePipe, LocalTimePipe } from "../pipes/location.pipes";
import { ConditionsDialogComponent } from "../dialogs/conditions-dialog.component";
import { MatDialog } from "@angular/material/dialog";
import { ResourceService } from "../services/resource.service";
import { WeatherCondition } from "../api";
/**
* Implements a component to display a single
* weather condition.
*/
@Component({
selector: 'app-weather-summary',
templateUrl: './weather-summary.component.html'
selector: "app-weather-summary",
templateUrl: "./weather-summary.component.html",
})
export class WeatherSummaryComponent implements OnInit, OnChanges {
@Input() conditions: WeatherCondition[];
@Input() timezone: string;
@Input() title: string;
@Input() subtitle: string;
@Input() clickHandler: () => void;
@Input() noMargin: boolean;
@Input() concise: boolean;
@Input() conditions: WeatherCondition[];
@Input() timezone: string;
@Input() title: string;
@Input() subtitle: string;
@Input() clickHandler: () => void;
@Input() noMargin: boolean;
@Input() concise: boolean;
min: WeatherCondition = null;
max: WeatherCondition = null;
displayTitle = "";
displaySubtitle = "";
min: WeatherCondition = null;
max: WeatherCondition = null;
displayTitle = '';
displaySubtitle = '';
constructor(
public res: ResourceService,
private localTime: LocalTimePipe,
private localDate: LocalDatePipe,
private dialog: MatDialog
) {}
constructor(
public res: ResourceService,
private localTime: LocalTimePipe,
private localDate: LocalDatePipe,
private dialog: MatDialog
) { }
hasCondition() {
return this.min != null && this.max != null;
}
hasCondition() {
return this.min != null && this.max != null;
ngOnInit(): void {
if (!this.clickHandler) {
this.clickHandler = () => {
ConditionsDialogComponent.open(
this.dialog,
this.conditions,
this.timezone
);
};
}
}
ngOnInit(): void {
if (!this.clickHandler) {
this.clickHandler = () => {
ConditionsDialogComponent.open(this.dialog, this.conditions, this.timezone);
};
ngOnChanges(c: SimpleChanges) {
if (
c.conditions &&
c.conditions.currentValue != null &&
c.conditions.currentValue.length > 0
) {
this.min = this.copyCondition(c.conditions.currentValue[0]);
this.max = this.copyCondition(c.conditions.currentValue[0]);
for (let i = 1; i < c.conditions.currentValue.length; i++) {
const next = c.conditions.currentValue[i];
// compute maximum
this.max.cloudCoverage = Math.max(
this.max.cloudCoverage,
next.cloudCoverage
);
this.max.cloudDepth = Math.max(this.max.cloudDepth, next.cloudDepth);
this.max.duration = Math.max(this.max.duration, next.duration);
this.max.hour = Math.max(this.max.duration, next.duration);
this.max.humidity = Math.max(this.max.humidity, next.humidity);
this.max.precipitation = Math.max(
this.max.precipitation,
next.precipitation
);
this.max.pressure = Math.max(this.max.pressure, next.pressure);
this.max.snowDepth = Math.max(this.max.snowDepth, next.snowDepth);
this.max.temperature = Math.max(this.max.temperature, next.temperature);
this.max.time = Math.max(this.max.time, next.time);
this.max.source = this.maximum(
this.max.source,
next.source,
this.sourceValue
);
this.max.type = this.maximum(this.max.type, next.type, this.typeValue);
if (next.windSpeed > this.max.windSpeed) {
this.max.windSpeed = next.windSpeed;
this.max.windDirection = next.windDirection;
}
}
ngOnChanges(c: SimpleChanges) {
if (c.conditions && c.conditions.currentValue != null && c.conditions.currentValue.length > 0) {
this.min = this.copyCondition(c.conditions.currentValue[0]);
this.max = this.copyCondition(c.conditions.currentValue[0]);
for (let i = 1; i < c.conditions.currentValue.length; i++) {
const next = c.conditions.currentValue[i];
// compute maximum
this.max.cloudCoverage = Math.max(this.max.cloudCoverage, next.cloudCoverage);
this.max.cloudDepth = Math.max(this.max.cloudDepth, next.cloudDepth);
this.max.duration = Math.max(this.max.duration, next.duration);
this.max.hour = Math.max(this.max.duration, next.duration);
this.max.humidity = Math.max(this.max.humidity, next.humidity);
this.max.precipitation = Math.max(this.max.precipitation, next.precipitation);
this.max.pressure = Math.max(this.max.pressure, next.pressure);
this.max.snowDepth = Math.max(this.max.snowDepth, next.snowDepth);
this.max.temperature = Math.max(this.max.temperature, next.temperature);
this.max.time = Math.max(this.max.time, next.time);
this.max.source = this.maximum(this.max.source, next.source, this.sourceValue);
this.max.type = this.maximum(this.max.type, next.type, this.typeValue);
if (next.windSpeed > this.max.windSpeed) {
this.max.windSpeed = next.windSpeed;
this.max.windDirection = next.windDirection;
}
// compute minimum
this.min.cloudCoverage = Math.min(this.min.cloudCoverage, next.cloudCoverage);
this.min.cloudDepth = Math.min(this.min.cloudDepth, next.cloudDepth);
this.min.duration = Math.min(this.min.duration, next.duration);
this.min.hour = Math.min(this.min.duration, next.duration);
this.min.humidity = Math.min(this.min.humidity, next.humidity);
this.min.precipitation = Math.min(this.min.precipitation, next.precipitation);
this.min.pressure = Math.min(this.min.pressure, next.pressure);
this.min.snowDepth = Math.min(this.min.snowDepth, next.snowDepth);
this.min.temperature = Math.min(this.min.temperature, next.temperature);
this.min.time = Math.min(this.min.time, next.time);
this.min.source = this.minimum(this.min.source, next.source, this.sourceValue);
this.min.type = this.minimum(this.min.type, next.type, this.typeValue);
if (next.windSpeed < this.min.windSpeed) {
this.min.windSpeed = next.windSpeed;
this.min.windDirection = next.windDirection;
}
}
} else {
this.min = null;
this.max = null;
// compute minimum
this.min.cloudCoverage = Math.min(
this.min.cloudCoverage,
next.cloudCoverage
);
this.min.cloudDepth = Math.min(this.min.cloudDepth, next.cloudDepth);
this.min.duration = Math.min(this.min.duration, next.duration);
this.min.hour = Math.min(this.min.duration, next.duration);
this.min.humidity = Math.min(this.min.humidity, next.humidity);
this.min.precipitation = Math.min(
this.min.precipitation,
next.precipitation
);
this.min.pressure = Math.min(this.min.pressure, next.pressure);
this.min.snowDepth = Math.min(this.min.snowDepth, next.snowDepth);
this.min.temperature = Math.min(this.min.temperature, next.temperature);
this.min.time = Math.min(this.min.time, next.time);
this.min.source = this.minimum(
this.min.source,
next.source,
this.sourceValue
);
this.min.type = this.minimum(this.min.type, next.type, this.typeValue);
if (next.windSpeed < this.min.windSpeed) {
this.min.windSpeed = next.windSpeed;
this.min.windDirection = next.windDirection;
}
this.updateTitle();
}
} else {
this.min = null;
this.max = null;
}
this.updateTitle();
}
private updateTitle() {
if (this.title && this.title != null) {
this.displayTitle = this.title;
} else if (this.hasCondition()) {
const minDate = this.localDate.transform(this.min.time, this.timezone);
const maxDate = this.localDate.transform(this.max.time, this.timezone);
if (minDate === maxDate) {
this.displayTitle = minDate;
} else {
this.displayTitle = minDate + ' - ' + maxDate;
}
} else {
this.displayTitle = '';
}
if (this.subtitle && this.subtitle != null) {
this.displaySubtitle = this.subtitle;
} else if (this.hasCondition()) {
const minTime = this.localTime.transform(this.min.time, this.timezone);
const maxTime = this.localTime.transform(this.max.time, this.timezone);
if (minTime === maxTime) {
this.displaySubtitle = minTime;
} else {
this.displaySubtitle = minTime + ' - ' + maxTime;
}
} else {
this.displaySubtitle = '';
}
private updateTitle() {
if (this.title && this.title != null) {
this.displayTitle = this.title;
} else if (this.hasCondition()) {
const minDate = this.localDate.transform(this.min.time, this.timezone);
const maxDate = this.localDate.transform(this.max.time, this.timezone);
if (minDate === maxDate) {
this.displayTitle = minDate;
} else {
this.displayTitle = minDate + " - " + maxDate;
}
} else {
this.displayTitle = "";
}
private copyCondition(c: WeatherCondition): WeatherCondition {
return { cloudCoverage: c.cloudCoverage, cloudDepth: c.cloudDepth, duration: c.duration, hour: c.hour,
humidity: c.humidity, precipitation: c.precipitation, pressure: c.pressure, snowDepth: c.snowDepth,
source: c.source, temperature: c.temperature, time: c.time, type: c.type, windDirection: c.windDirection,
windSpeed: c.windSpeed };
if (this.subtitle && this.subtitle != null) {
this.displaySubtitle = this.subtitle;
} else if (this.hasCondition()) {
const minTime = this.localTime.transform(this.min.time, this.timezone);
const maxTime = this.localTime.transform(this.max.time, this.timezone);
if (minTime === maxTime) {
this.displaySubtitle = minTime;
} else {
this.displaySubtitle = minTime + " - " + maxTime;
}
} else {
this.displaySubtitle = "";
}
}
private maximum<T>(a: T, b: T, v: (T) => number): T {
const va = v(a);
const vb = v(b);
if (va >= vb && va >= 0) {
return a;
} else {
return b;
}
private copyCondition(c: WeatherCondition): WeatherCondition {
return {
cloudCoverage: c.cloudCoverage,
cloudDepth: c.cloudDepth,
duration: c.duration,
hour: c.hour,
humidity: c.humidity,
precipitation: c.precipitation,
pressure: c.pressure,
snowDepth: c.snowDepth,
source: c.source,
temperature: c.temperature,
time: c.time,
type: c.type,
windDirection: c.windDirection,
windSpeed: c.windSpeed,
maxWindSpeed: c.maxWindSpeed,
};
}
private maximum<T>(a: T, b: T, v: (T) => number): T {
const va = v(a);
const vb = v(b);
if (va >= vb && va >= 0) {
return a;
} else {
return b;
}
}
private minimum<T>(a: T, b: T, v: (T) => number): T {
const va = v(a);
const vb = v(b);
if (va <= vb && va >= 0) {
return a;
} else {
return b;
}
private minimum<T>(a: T, b: T, v: (T) => number): T {
const va = v(a);
const vb = v(b);
if (va <= vb && va >= 0) {
return a;
} else {
return b;
}
}
private sourceValue(s: WeatherCondition.SourceEnum): number {
switch (s) {
case WeatherCondition.SourceEnum.ICONGLOBAL:
return 2;
case WeatherCondition.SourceEnum.ICONEUROPE:
return 1;
case WeatherCondition.SourceEnum.COSMOEUROPE:
return 0;
default:
return -1;
}
private sourceValue(s: WeatherCondition.SourceEnum): number {
switch (s) {
case WeatherCondition.SourceEnum.ICONGLOBAL:
return 2;
case WeatherCondition.SourceEnum.ICONEUROPE:
return 1;
case WeatherCondition.SourceEnum.COSMOEUROPE:
return 0;
default:
return -1;
}
}
private typeValue(t: WeatherCondition.TypeEnum): number {
switch (t) {
case WeatherCondition.TypeEnum.CLEARSKY:
return 0;
case WeatherCondition.TypeEnum.MAINLYCLEAR:
return 1;
case WeatherCondition.TypeEnum.PARTLYCLOUDY:
return 2;
case WeatherCondition.TypeEnum.CLOUDY:
return 3;
case WeatherCondition.TypeEnum.FOG:
return 4;
case WeatherCondition.TypeEnum.FOGDEPOSITINGRIME:
return 5;
case WeatherCondition.TypeEnum.SLIGHTDRIZZLE:
return 6;
case WeatherCondition.TypeEnum.SLIGHTRAINNOTFREEZING:
return 7;
case WeatherCondition.TypeEnum.RAINSHOWERSLIGHT:
return 8;
case WeatherCondition.TypeEnum.DRIZZLEFREEZINGSLIGHT:
return 9;
case WeatherCondition.TypeEnum.RAINFREEZINGSLIGHT:
return 10;
case WeatherCondition.TypeEnum.SLIGHTFALLOFSNOWFLAKES:
return 11;
case WeatherCondition.TypeEnum.SNOWSHOWERSLIGHT:
return 12;
case WeatherCondition.TypeEnum.MODERATEDRIZZLE:
return 13;
case WeatherCondition.TypeEnum.HEAVYDRIZZLE:
return 14;
case WeatherCondition.TypeEnum.MODERATERAINNOTFREEZING:
return 15;
case WeatherCondition.TypeEnum.SNOWGRAINS:
return 16;
case WeatherCondition.TypeEnum.MODERATEFALLOFSNOWFLAKES:
return 17;
case WeatherCondition.TypeEnum.HEAVYRAINNOTFREEZING:
return 18;
case WeatherCondition.TypeEnum.DRIZZLEFREEZINGMODERATEHEAVY:
return 19;
case WeatherCondition.TypeEnum.HEAVYFALLOFSNOWFLAKES:
return 20;
case WeatherCondition.TypeEnum.RAINSHOWERMODERATEHEAVY:
return 21;
case WeatherCondition.TypeEnum.RAINFREEZINGMODERATEHEAVY:
return 22;
case WeatherCondition.TypeEnum.SNOWSHOWERMODERATEHEAVY:
return 23;
case WeatherCondition.TypeEnum.RAINSHOWERVIOLENT:
return 24;
case WeatherCondition.TypeEnum.THUNDERSTORMSLIGHTMODERATE:
return 25;
case WeatherCondition.TypeEnum.THUNDERSTORMHAILHEAVY:
return 26;
default:
return -1;
}
}
onClick() {
this.clickHandler();
private typeValue(t: WeatherCondition.TypeEnum): number {
switch (t) {
case WeatherCondition.TypeEnum.CLEARSKY:
return 0;
case WeatherCondition.TypeEnum.MAINLYCLEAR:
return 1;
case WeatherCondition.TypeEnum.PARTLYCLOUDY:
return 2;
case WeatherCondition.TypeEnum.CLOUDY:
return 3;
case WeatherCondition.TypeEnum.FOG:
return 4;
case WeatherCondition.TypeEnum.FOGDEPOSITINGRIME:
return 5;
case WeatherCondition.TypeEnum.SLIGHTDRIZZLE:
return 6;
case WeatherCondition.TypeEnum.SLIGHTRAINNOTFREEZING:
return 7;
case WeatherCondition.TypeEnum.RAINSHOWERSLIGHT:
return 8;
case WeatherCondition.TypeEnum.DRIZZLEFREEZINGSLIGHT:
return 9;
case WeatherCondition.TypeEnum.RAINFREEZINGSLIGHT:
return 10;
case WeatherCondition.TypeEnum.SLIGHTFALLOFSNOWFLAKES:
return 11;
case WeatherCondition.TypeEnum.SNOWSHOWERSLIGHT:
return 12;
case WeatherCondition.TypeEnum.MODERATEDRIZZLE:
return 13;
case WeatherCondition.TypeEnum.HEAVYDRIZZLE:
return 14;
case WeatherCondition.TypeEnum.MODERATERAINNOTFREEZING:
return 15;
case WeatherCondition.TypeEnum.SNOWGRAINS:
return 16;
case WeatherCondition.TypeEnum.MODERATEFALLOFSNOWFLAKES:
return 17;
case WeatherCondition.TypeEnum.HEAVYRAINNOTFREEZING:
return 18;
case WeatherCondition.TypeEnum.DRIZZLEFREEZINGMODERATEHEAVY:
return 19;
case WeatherCondition.TypeEnum.HEAVYFALLOFSNOWFLAKES:
return 20;
case WeatherCondition.TypeEnum.RAINSHOWERMODERATEHEAVY:
return 21;
case WeatherCondition.TypeEnum.RAINFREEZINGMODERATEHEAVY:
return 22;
case WeatherCondition.TypeEnum.SNOWSHOWERMODERATEHEAVY:
return 23;
case WeatherCondition.TypeEnum.RAINSHOWERVIOLENT:
return 24;
case WeatherCondition.TypeEnum.THUNDERSTORMSLIGHTMODERATE:
return 25;
case WeatherCondition.TypeEnum.THUNDERSTORMHAILHEAVY:
return 26;
default:
return -1;
}
}
onClick() {
this.clickHandler();
}
}