Commit dbdee32e by Tuukka Kivilahti

Merge branch 'drd-apis' into 'master'

Add drd required apis

See merge request !381
2 parents 288fff6b 950a912f
Showing with 660 additions and 285 deletions
...@@ -18,7 +18,9 @@ ...@@ -18,7 +18,9 @@
*/ */
package fi.codecrew.moya; package fi.codecrew.moya;
public class AuthenticationResult { import java.io.Serializable;
public class AuthenticationResult implements Serializable {
private String username = null; private String username = null;
private String usertype = null; private String usertype = null;
......
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<artifactId>moya-authmodule</artifactId> <artifactId>moya-authmodule</artifactId>
<build>
<plugins>
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<configuration>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
</configuration>
</plugin>
</plugins>
</build>
<dependencies> <dependencies>
<dependency> <dependency>
<groupId>org.glassfish.main.security</groupId> <groupId>org.glassfish.main.security</groupId>
......
...@@ -33,4 +33,8 @@ public interface ApiApplicationBeanLocal { ...@@ -33,4 +33,8 @@ public interface ApiApplicationBeanLocal {
List<ApiApplication> findAllApplications(); List<ApiApplication> findAllApplications();
ApiApplicationInstance createApplicationInstance(ApiApplication application); ApiApplicationInstance createApplicationInstance(ApiApplication application);
ApiApplication findApplication(String appKey);
String findUsernameForApikey(String appkey, String userkey, String domain);
} }
/* /*
* Copyright Codecrew Ry * Copyright Codecrew Ry
* *
* All rights reserved. * All rights reserved.
* *
* This license applies to any software containing a notice placed by the * This license applies to any software containing a notice placed by the
* copyright holder. Such software is herein referred to as the Software. * copyright holder. Such software is herein referred to as the Software.
* This license covers modification, distribution and use of the Software. * This license covers modification, distribution and use of the Software.
* *
* Any distribution and use in source and binary forms, with or without * Any distribution and use in source and binary forms, with or without
* modification is not permitted without explicit written permission from the * modification is not permitted without explicit written permission from the
* copyright owner. * copyright owner.
* *
* A non-exclusive royalty-free right is granted to the copyright owner of the * A non-exclusive royalty-free right is granted to the copyright owner of the
* Software to use, modify and distribute all modifications to the Software in * Software to use, modify and distribute all modifications to the Software in
* future versions of the Software. * future versions of the Software.
* *
*/ */
package fi.codecrew.moya.beans; package fi.codecrew.moya.beans;
import java.util.Calendar; import java.util.Calendar;
import java.util.Date;
import java.util.List; import java.util.List;
import javax.annotation.security.DeclareRoles; import javax.annotation.security.DeclareRoles;
import javax.annotation.security.RolesAllowed; import javax.annotation.security.RolesAllowed;
import javax.ejb.EJB; import javax.ejb.EJB;
import javax.ejb.EJBException;
import javax.ejb.LocalBean; import javax.ejb.LocalBean;
import javax.ejb.Singleton; import javax.ejb.Singleton;
...@@ -34,6 +36,7 @@ import fi.codecrew.moya.facade.EventUserFacade; ...@@ -34,6 +36,7 @@ import fi.codecrew.moya.facade.EventUserFacade;
import fi.codecrew.moya.model.ApiApplication; import fi.codecrew.moya.model.ApiApplication;
import fi.codecrew.moya.model.ApiApplicationInstance; import fi.codecrew.moya.model.ApiApplicationInstance;
import fi.codecrew.moya.model.EventUser; import fi.codecrew.moya.model.EventUser;
import fi.codecrew.moya.model.LanEvent;
import fi.codecrew.moya.utilities.PasswordFunctions; import fi.codecrew.moya.utilities.PasswordFunctions;
import fi.codecrew.moya.utilities.moyamessage.MoyaEventType; import fi.codecrew.moya.utilities.moyamessage.MoyaEventType;
...@@ -76,14 +79,18 @@ public class ApiApplicationBean implements ApiApplicationBeanLocal { ...@@ -76,14 +79,18 @@ public class ApiApplicationBean implements ApiApplicationBeanLocal {
@RolesAllowed(SpecialPermission.S_USER) @RolesAllowed(SpecialPermission.S_USER)
public ApiApplicationInstance createApplicationInstance(ApiApplication application) { public ApiApplicationInstance createApplicationInstance(ApiApplication application) {
application = applicationFacade.reload(application);
// ugly as shit sanitation for eventName, sorry // ugly as shit sanitation for eventName, sorry
String eventName = eventBean.getCurrentEvent().getName().replace(" ", "_").replace("ä", "a").replace("ö", "o") LanEvent currevent = eventBean.getCurrentEvent();
.replace("Ä", "A").replace("Ö", "O").replace("å", "a").replace("Å", "A");
String authname = permissionBean.getCurrentUser().getLogin() + "_" + application.getName() + "_" + eventName; String authname = permissionBean.getCurrentUser().getLogin() + "_" + application.getName() + "_" + currevent.getId() + "_" + currevent.getName();
// Replace all non-valid characters with '_'
authname.replaceAll("[^a-zA-Z0-9._]", "_");
while (instanceFacade.findInstance(application, authname, eventBean.getCurrentEvent()) != null) { // Ensure authname is unique;
authname += "_"; final String origAuthname = authname;
for (int i = 2; instanceFacade.findInstance(application, authname, eventBean.getCurrentEvent()) != null; ++i) {
authname = origAuthname + "_" + i;
} }
ApiApplicationInstance instance = new ApiApplicationInstance(); ApiApplicationInstance instance = new ApiApplicationInstance();
...@@ -91,19 +98,45 @@ public class ApiApplicationBean implements ApiApplicationBeanLocal { ...@@ -91,19 +98,45 @@ public class ApiApplicationBean implements ApiApplicationBeanLocal {
instance.setApplication(application); instance.setApplication(application);
instance.setAuthname(authname); instance.setAuthname(authname);
instance.setName(application.getName() + " for user: " + permissionBean.getCurrentUser().getLogin()); instance.setName(application.getName() + " for user: " + permissionBean.getCurrentUser().getLogin());
instance.setCreated(Calendar.getInstance().getTime()); instance.setCreated(new Date());
instance.setEnabled(true); instance.setEnabled(true);
instance.setEventuser(permissionBean.getCurrentUser()); instance.setEventuser(permissionBean.getCurrentUser());
instance.setSecretKey(PasswordFunctions.generateRandomString(30)); instance.setSecretKey(PasswordFunctions.generateRandomString(30));
instanceFacade.create(instance); instanceFacade.create(instance);
loggingBean.sendMessage(MoyaEventType.APPLICATION_INSTANCE_CREATED, loggingBean.sendMessage(MoyaEventType.APPLICATION_INSTANCE_CREATED,
"New applicationinstance created for software: ", application); "New applicationinstance created for software: ", application);
return instance; return instance;
} }
@Override @Override
public ApiApplication findApplication(String appKey) {
return applicationFacade.findByAppid(appKey);
}
/**
* Note that this function can sould be allowed to be called without principal, ie without domain information.
*
* @param appkey
* @param userkey
* @param domain
* @return
*/
@Override
public String findUsernameForApikey(String appkey, String userkey, String domain) {
LanEvent event = eventBean.getEventForHostname(domain);
if (event == null) {
throw new EJBException("Event not found for domain: " + domain);
}
ApiApplicationInstance instance = instanceFacade.findInstance(appkey, userkey, event);
if (instance == null) {
throw new EJBException("ApiApplicationInstance not found");
}
return instance.getEventuser().getUser().getLogin();
}
@Override
@RolesAllowed(SpecialPermission.S_USER) @RolesAllowed(SpecialPermission.S_USER)
public List<ApiApplication> findMyApplications() { public List<ApiApplication> findMyApplications() {
EventUser curruser = permissionBean.getCurrentUser(); EventUser curruser = permissionBean.getCurrentUser();
......
/* /*
* Copyright Codecrew Ry * Copyright Codecrew Ry
* *
* All rights reserved. * All rights reserved.
* *
* This license applies to any software containing a notice placed by the * This license applies to any software containing a notice placed by the
* copyright holder. Such software is herein referred to as the Software. * copyright holder. Such software is herein referred to as the Software.
* This license covers modification, distribution and use of the Software. * This license covers modification, distribution and use of the Software.
* *
* Any distribution and use in source and binary forms, with or without * Any distribution and use in source and binary forms, with or without
* modification is not permitted without explicit written permission from the * modification is not permitted without explicit written permission from the
* copyright owner. * copyright owner.
* *
* A non-exclusive royalty-free right is granted to the copyright owner of the * A non-exclusive royalty-free right is granted to the copyright owner of the
* Software to use, modify and distribute all modifications to the Software in * Software to use, modify and distribute all modifications to the Software in
* future versions of the Software. * future versions of the Software.
* *
*/ */
package fi.codecrew.moya.beans; package fi.codecrew.moya.beans;
...@@ -65,13 +65,10 @@ import fi.codecrew.moya.util.MailMessage; ...@@ -65,13 +65,10 @@ import fi.codecrew.moya.util.MailMessage;
*/ */
@Stateless @Stateless
@LocalBean @LocalBean
@DeclareRoles({ UserPermission.S_WRITE_ROLES }) @DeclareRoles({UserPermission.S_WRITE_ROLES})
public class CardTemplateBean implements CardTemplateBeanLocal { public class CardTemplateBean implements CardTemplateBeanLocal {
private static final Logger logger = LoggerFactory.getLogger(CardTemplateBean.class); private static final Logger logger = LoggerFactory.getLogger(CardTemplateBean.class);
/** /**
...@@ -114,7 +111,6 @@ public class CardTemplateBean implements CardTemplateBeanLocal { ...@@ -114,7 +111,6 @@ public class CardTemplateBean implements CardTemplateBeanLocal {
private CardCodeFacade cardCodeFacade; private CardCodeFacade cardCodeFacade;
// @Override // @Override
// @RolesAllowed("USER_MANAGEMENT/WRITE") // @RolesAllowed("USER_MANAGEMENT/WRITE")
// public List<CardTemplate> findAll() { // public List<CardTemplate> findAll() {
...@@ -126,8 +122,7 @@ public class CardTemplateBean implements CardTemplateBeanLocal { ...@@ -126,8 +122,7 @@ public class CardTemplateBean implements CardTemplateBeanLocal {
public void create(CardTemplate card) { public void create(CardTemplate card) {
LanEvent currEv = eventBean.getCurrentEvent(); LanEvent currEv = eventBean.getCurrentEvent();
if (currEv.getCardTemplates() == null) if (currEv.getCardTemplates() == null) {
{
currEv.setCardTemplates(new ArrayList<CardTemplate>()); currEv.setCardTemplates(new ArrayList<CardTemplate>());
} }
card.setEvent(currEv); card.setEvent(currEv);
...@@ -161,28 +156,28 @@ public class CardTemplateBean implements CardTemplateBeanLocal { ...@@ -161,28 +156,28 @@ public class CardTemplateBean implements CardTemplateBeanLocal {
/** /**
* Checks users printed card roles and return the biggestCard * Checks users printed card roles and return the biggestCard
* *
* @throws PermissionDeniedException * @throws PermissionDeniedException
*/ */
@Override @Override
public PrintedCard checkPrintedCard(EventUser user) { public PrintedCard checkPrintedCard(EventUser user) {
logger.info("Checking printed card"); logger.info("Checking printed card");
user = eventUserFacade.find(user.getId()); user = eventUserFacade.reload(user);
if (user == null)
return null;
LanEvent currEvent = eventBean.getCurrentEvent(); LanEvent currEvent = eventBean.getCurrentEvent();
List<PrintedCard> myCards = printedcardfacade.getCards(user); List<PrintedCard> myCards = printedcardfacade.getCards(user);
PrintedCard biggestCard = null; PrintedCard biggestCard = null;
for (PrintedCard card : myCards) { for (PrintedCard card : myCards) {
if (card.getEnabled()) { if (card.getEnabled() && biggestCard == null || biggestCard.getTemplate().getPower() < card.getTemplate().getPower()) {
if (biggestCard == null || biggestCard.getTemplate().getPower() < card.getTemplate().getPower()) { // The biggest card should be the only one enabled.
// The biggest card should be the only one enabled. if (biggestCard != null) {
if (biggestCard != null) { biggestCard.setEnabled(false);
biggestCard.setEnabled(false);
}
biggestCard = card;
} }
biggestCard = card;
} }
} }
...@@ -211,12 +206,11 @@ public class CardTemplateBean implements CardTemplateBeanLocal { ...@@ -211,12 +206,11 @@ public class CardTemplateBean implements CardTemplateBeanLocal {
user.getPrintedCards().add(pc); user.getPrintedCards().add(pc);
// printedcardfacade.create(pc); // printedcardfacade.create(pc);
biggestCard = pc; biggestCard = pc;
logger.info("User {} has too little power old role {} New role {}", new Object[] { user.getUser().getLogin(), existingPower, newPower }); logger.info("User {} has too little power old role {} New role {}", new Object[]{user.getUser().getLogin(), existingPower, newPower});
} else if (existingPower > newPower) { } else if (existingPower > newPower) {
MailMessage msg = new MailMessage(); MailMessage msg = new MailMessage();
LanEventProperty value = eventPropertyFacade.find(eventBean.getCurrentEvent(), LanEventPropertyKey.ADMIN_MAIL); LanEventProperty value = eventPropertyFacade.find(eventBean.getCurrentEvent(), LanEventPropertyKey.ADMIN_MAIL);
if (value != null && value.getTextvalue() != null && !value.getTextvalue().isEmpty()) if (value != null && value.getTextvalue() != null && !value.getTextvalue().isEmpty()) {
{
msg.setFromAddress(value.getTextvalue()); msg.setFromAddress(value.getTextvalue());
msg.setFromName("Lippukauppa"); msg.setFromName("Lippukauppa");
...@@ -226,12 +220,12 @@ public class CardTemplateBean implements CardTemplateBeanLocal { ...@@ -226,12 +220,12 @@ public class CardTemplateBean implements CardTemplateBeanLocal {
mailbean.sendMail(msg); mailbean.sendMail(msg);
} }
logger.info("User {} has too much power old role {} New role {}, old card revoked.", new Object[] { user.getUser().getLogin(), existingPower, newPower }); logger.info("User {} has too much power old role {} New role {}, old card revoked.", new Object[]{user.getUser().getLogin(), existingPower, newPower});
biggestCard.setEnabled(false); biggestCard.setEnabled(false);
return this.checkPrintedCard(user); return this.checkPrintedCard(user);
} else { } else {
logger.info("User {} has power {} and roles has power {}", new Object[] { user.getUser().getLogin(), existingPower, newPower }); logger.info("User {} has power {} and roles has power {}", new Object[]{user.getUser().getLogin(), existingPower, newPower});
} }
return biggestCard; return biggestCard;
...@@ -361,40 +355,35 @@ public class CardTemplateBean implements CardTemplateBeanLocal { ...@@ -361,40 +355,35 @@ public class CardTemplateBean implements CardTemplateBeanLocal {
@Override @Override
public PrintedCard setCardState(Integer cardId, CardState state) throws Exception { public PrintedCard setCardState(Integer cardId, CardState state) throws Exception {
PrintedCard card = printedcardfacade.find(cardId); PrintedCard card = printedcardfacade.find(cardId);
switch (state) switch (state) {
{ case PRINTED:
case PRINTED: card.setPrintCount(card.getPrintCount() + 1);
card.setPrintCount(card.getPrintCount() + 1); card.setPrintTime(Calendar.getInstance());
card.setPrintTime(Calendar.getInstance()); break;
break; case PRINTING_IN_PROGRESS:
case PRINTING_IN_PROGRESS: if (card.getCardState().equals(CardState.PRINTING_IN_PROGRESS)
if (card.getCardState().equals(CardState.PRINTING_IN_PROGRESS)
|| card.getCardState().equals(CardState.PRINTED)) { || card.getCardState().equals(CardState.PRINTED)) {
String response = "Unable to change type to PRINTING_IN_PROGRESS value is already {}" + card.getCardState(); String response = "Unable to change type to PRINTING_IN_PROGRESS value is already {}" + card.getCardState();
logger.warn(response); logger.warn(response);
throw new Exception(response); throw new Exception(response);
} }
break; break;
default: default:
break; break;
} }
card.setCardState(state); card.setCardState(state);
return card; return card;
} }
@Override @Override
public EventUser giveCard(EventUser user, boolean markUserPlacesDelivered) { public EventUser giveCard(EventUser user, boolean markUserPlacesDelivered) {
user = eventUserFacade.reload(user); user = eventUserFacade.reload(user);
PrintedCard card = checkPrintedCard(user); PrintedCard card = checkPrintedCard(user);
if (card.getCardState() != CardState.DELIVERED) { if (card.getCardState() != CardState.DELIVERED) {
card.setCardState(CardState.DELIVERED); card.setCardState(CardState.DELIVERED);
} else { } else {
...@@ -413,24 +402,24 @@ public class CardTemplateBean implements CardTemplateBeanLocal { ...@@ -413,24 +402,24 @@ public class CardTemplateBean implements CardTemplateBeanLocal {
@Override @Override
public void removeCardCode(CardCode code) { public void removeCardCode(CardCode code) {
code = cardCodeFacade.reload(code); code = cardCodeFacade.reload(code);
if(code.getPrintedCard().getCardCodes().contains(code)) { if (code.getPrintedCard().getCardCodes().contains(code)) {
code.getPrintedCard().getCardCodes().remove(code); code.getPrintedCard().getCardCodes().remove(code);
} }
cardCodeFacade.remove(code); cardCodeFacade.remove(code);
} }
@Override @Override
public CardTemplate removeCardTextData(CardTextData data) { public CardTemplate removeCardTextData(CardTextData data) {
data = ctdFacade.reload(data); data = ctdFacade.reload(data);
CardTemplate template = data.getCardTemplate(); CardTemplate template = data.getCardTemplate();
ctdFacade.remove(data); ctdFacade.remove(data);
return template; return template;
} }
@Override @Override
public CardTemplate removeCardObjectData(CardObjectData data) { public CardTemplate removeCardObjectData(CardObjectData data) {
data = codFacade.reload(data); data = codFacade.reload(data);
...@@ -454,6 +443,4 @@ public class CardTemplateBean implements CardTemplateBeanLocal { ...@@ -454,6 +443,4 @@ public class CardTemplateBean implements CardTemplateBeanLocal {
} }
} }
...@@ -37,6 +37,7 @@ import org.slf4j.LoggerFactory; ...@@ -37,6 +37,7 @@ import org.slf4j.LoggerFactory;
import fi.codecrew.moya.enums.apps.EventPermission; import fi.codecrew.moya.enums.apps.EventPermission;
import fi.codecrew.moya.enums.apps.SpecialPermission; import fi.codecrew.moya.enums.apps.SpecialPermission;
import fi.codecrew.moya.enums.apps.UserPermission;
import fi.codecrew.moya.facade.EventFacade; import fi.codecrew.moya.facade.EventFacade;
import fi.codecrew.moya.facade.EventOrganiserFacade; import fi.codecrew.moya.facade.EventOrganiserFacade;
import fi.codecrew.moya.facade.LanEventDomainFacade; import fi.codecrew.moya.facade.LanEventDomainFacade;
...@@ -55,10 +56,12 @@ import fi.codecrew.moya.model.LanEventPropertyKey; ...@@ -55,10 +56,12 @@ import fi.codecrew.moya.model.LanEventPropertyKey;
*/ */
@Stateless @Stateless
@LocalBean @LocalBean
@DeclareRoles({ EventPermission.S_MANAGE_PRIVATE_PROPERTIES, @DeclareRoles({
EventPermission.S_MANAGE_PROPERTIES, EventPermission.S_MANAGE_PRIVATE_PROPERTIES,
EventPermission.S_MANAGE_EVENT, EventPermission.S_MANAGE_PROPERTIES,
SpecialPermission.S_SUPERADMIN, EventPermission.S_MANAGE_EVENT,
SpecialPermission.S_SUPERADMIN,
SpecialPermission.S_USER
}) })
public class EventBean implements EventBeanLocal { public class EventBean implements EventBeanLocal {
...@@ -158,7 +161,7 @@ public class EventBean implements EventBeanLocal { ...@@ -158,7 +161,7 @@ public class EventBean implements EventBeanLocal {
} }
@Override @Override
@RolesAllowed({ SpecialPermission.S_SUPERADMIN, EventPermission.S_MANAGE_EVENT }) @RolesAllowed({SpecialPermission.S_SUPERADMIN, EventPermission.S_MANAGE_EVENT})
public LanEvent mergeChanges(LanEvent event) { public LanEvent mergeChanges(LanEvent event) {
if (!permbean.hasPermission(SpecialPermission.SUPERADMIN) && !getCurrentEvent().equals(event)) { if (!permbean.hasPermission(SpecialPermission.SUPERADMIN) && !getCurrentEvent().equals(event)) {
throw new EJBAccessException("Trying to save another event."); throw new EJBAccessException("Trying to save another event.");
...@@ -167,7 +170,7 @@ public class EventBean implements EventBeanLocal { ...@@ -167,7 +170,7 @@ public class EventBean implements EventBeanLocal {
} }
@Override @Override
@RolesAllowed({ SpecialPermission.S_SUPERADMIN, EventPermission.S_MANAGE_EVENT }) @RolesAllowed({SpecialPermission.S_SUPERADMIN, EventPermission.S_MANAGE_EVENT})
public void create(LanEvent event) { public void create(LanEvent event) {
eventFacade.create(event); eventFacade.create(event);
...@@ -181,7 +184,7 @@ public class EventBean implements EventBeanLocal { ...@@ -181,7 +184,7 @@ public class EventBean implements EventBeanLocal {
} }
@Override @Override
@RolesAllowed({ EventPermission.S_MANAGE_PRIVATE_PROPERTIES, EventPermission.S_MANAGE_EVENT }) @RolesAllowed({EventPermission.S_MANAGE_PRIVATE_PROPERTIES, EventPermission.S_MANAGE_EVENT})
public List<LanEventPrivateProperty> getPrivateProperties() { public List<LanEventPrivateProperty> getPrivateProperties() {
return eventPrivatePropertyFacade.findAllForEvent(); return eventPrivatePropertyFacade.findAllForEvent();
} }
...@@ -211,8 +214,7 @@ public class EventBean implements EventBeanLocal { ...@@ -211,8 +214,7 @@ public class EventBean implements EventBeanLocal {
} }
@Override @Override
public long getPropertyLong(LanEventPropertyKey property) public long getPropertyLong(LanEventPropertyKey property) {
{
LanEventProperty retProp = eventPropertyFacade.find(getCurrentEvent(), property); LanEventProperty retProp = eventPropertyFacade.find(getCurrentEvent(), property);
long ret = 0; long ret = 0;
if (retProp == null) { if (retProp == null) {
...@@ -224,8 +226,7 @@ public class EventBean implements EventBeanLocal { ...@@ -224,8 +226,7 @@ public class EventBean implements EventBeanLocal {
} }
@Override @Override
public String getPropertyString(LanEventPropertyKey property) public String getPropertyString(LanEventPropertyKey property) {
{
LanEventProperty retProp = eventPropertyFacade.find(getCurrentEvent(), property); LanEventProperty retProp = eventPropertyFacade.find(getCurrentEvent(), property);
String ret = null; String ret = null;
if (retProp == null) { if (retProp == null) {
...@@ -255,10 +256,11 @@ public class EventBean implements EventBeanLocal { ...@@ -255,10 +256,11 @@ public class EventBean implements EventBeanLocal {
} }
@Override @Override
@RolesAllowed({ SpecialPermission.S_SUPERADMIN, EventPermission.S_MANAGE_EVENT }) @RolesAllowed({SpecialPermission.S_SUPERADMIN, EventPermission.S_MANAGE_EVENT})
public LanEventProperty saveOrCreateProperty(LanEventProperty property) { public LanEventProperty saveOrCreateProperty(LanEventProperty property) {
LanEventProperty ret = null; LanEventProperty ret = null;
logger.info("Saving property {}, eventorg {}, key {}", new Object[] { property.getEvent(), property.getEventorg(), property.getKey() }); logger.info("Saving property {}, eventorg {}, key {}",
new Object[]{property.getEvent(), property.getEventorg(), property.getKey()});
if (property.getId() == null) { if (property.getId() == null) {
ret = property; ret = property;
...@@ -270,8 +272,7 @@ public class EventBean implements EventBeanLocal { ...@@ -270,8 +272,7 @@ public class EventBean implements EventBeanLocal {
} }
event.getProperties().add(property); event.getProperties().add(property);
} } else {
else {
ret = eventPropertyFacade.merge(property); ret = eventPropertyFacade.merge(property);
} }
return ret; return ret;
...@@ -279,16 +280,17 @@ public class EventBean implements EventBeanLocal { ...@@ -279,16 +280,17 @@ public class EventBean implements EventBeanLocal {
} }
@Override @Override
@RolesAllowed({ SpecialPermission.S_SUPERADMIN, EventPermission.S_MANAGE_EVENT }) @RolesAllowed({SpecialPermission.S_SUPERADMIN, EventPermission.S_MANAGE_EVENT})
public EventOrganiser mergeChanges(EventOrganiser eventorg) { public EventOrganiser mergeChanges(EventOrganiser eventorg) {
return eventOrganiserFacade.merge(eventorg); return eventOrganiserFacade.merge(eventorg);
} }
@Override @Override
@RolesAllowed({ EventPermission.S_MANAGE_PRIVATE_PROPERTIES, EventPermission.S_MANAGE_EVENT }) @RolesAllowed({EventPermission.S_MANAGE_PRIVATE_PROPERTIES, EventPermission.S_MANAGE_EVENT})
public LanEventPrivateProperty saveOrCreatePrivateProperty(LanEventPrivateProperty privateProperty) { public LanEventPrivateProperty saveOrCreatePrivateProperty(LanEventPrivateProperty privateProperty) {
LanEventPrivateProperty ret = null; LanEventPrivateProperty ret = null;
logger.info("Saving property {}, eventorg {}, key {}", new Object[] { privateProperty.getEvent(), privateProperty.getEventorg(), privateProperty.getKey() }); logger.info("Saving property {}, eventorg {}, key {}",
new Object[]{privateProperty.getEvent(), privateProperty.getEventorg(), privateProperty.getKey()});
if (privateProperty.getId() == null) { if (privateProperty.getId() == null) {
ret = privateProperty; ret = privateProperty;
...@@ -320,7 +322,7 @@ public class EventBean implements EventBeanLocal { ...@@ -320,7 +322,7 @@ public class EventBean implements EventBeanLocal {
} }
@Override @Override
@RolesAllowed({ EventPermission.S_MANAGE_PRIVATE_PROPERTIES, EventPermission.S_MANAGE_EVENT }) @RolesAllowed({EventPermission.S_MANAGE_PRIVATE_PROPERTIES, EventPermission.S_MANAGE_EVENT})
public LanEvent deletePrivateProperty(LanEventPrivateProperty property) { public LanEvent deletePrivateProperty(LanEventPrivateProperty property) {
property = eventPrivatePropertyFacade.reload(property); property = eventPrivatePropertyFacade.reload(property);
LanEvent event = property.getEvent(); LanEvent event = property.getEvent();
...@@ -335,14 +337,15 @@ public class EventBean implements EventBeanLocal { ...@@ -335,14 +337,15 @@ public class EventBean implements EventBeanLocal {
} }
@Override @Override
@RolesAllowed({SpecialPermission.S_USER})
public List<LanEvent> findAllEventsForCurrentUser() { public List<LanEvent> findAllEventsForCurrentUser() {
return eventFacade.findAll(permbean.getCurrentUser().getUser()); return eventFacade.findAll(permbean.getCurrentUser().getUser());
} }
@Override @Override
@RolesAllowed({SpecialPermission.S_USER})
public List<LanEvent> findFutureAndRunningEventsForCurrentUser() { public List<LanEvent> findFutureAndRunningEventsForCurrentUser() {
List<LanEvent> events = findAllEventsForCurrentUser(); List<LanEvent> events = findAllEventsForCurrentUser();
List<LanEvent> retlist = new ArrayList<>(); List<LanEvent> retlist = new ArrayList<>();
...@@ -351,19 +354,18 @@ public class EventBean implements EventBeanLocal { ...@@ -351,19 +354,18 @@ public class EventBean implements EventBeanLocal {
tmp.add(Calendar.DAY_OF_MONTH, -5); tmp.add(Calendar.DAY_OF_MONTH, -5);
Date compareDate = tmp.getTime(); Date compareDate = tmp.getTime();
for(LanEvent event : events) { for (LanEvent event : events) {
if(event.getEndTime() == null) { if (event.getEndTime() == null) {
retlist.add(event); retlist.add(event);
continue; continue;
} }
if(event.getEndTime().compareTo(compareDate) > 0) { if (event.getEndTime().compareTo(compareDate) > 0) {
retlist.add(event); retlist.add(event);
} }
} }
return retlist; return retlist;
} }
......
...@@ -174,6 +174,9 @@ public class PermissionBean implements PermissionBeanLocal { ...@@ -174,6 +174,9 @@ public class PermissionBean implements PermissionBeanLocal {
@Override @Override
public EventUser getCurrentUser() { public EventUser getCurrentUser() {
LanEvent event = eventbean.getEventForHostname(getPrincipalDomain()); LanEvent event = eventbean.getEventForHostname(getPrincipalDomain());
if (event == null) {
throw new EJBException("Could not find event for current user");
}
EventUser ret = eventUserFacade.findByLogin(getPrincipalName(), event); EventUser ret = eventUserFacade.findByLogin(getPrincipalName(), event);
if (ret == null) { if (ret == null) {
ret = getAnonEventUser(); ret = getAnonEventUser();
......
...@@ -413,7 +413,7 @@ public class PlaceBean implements PlaceBeanLocal { ...@@ -413,7 +413,7 @@ public class PlaceBean implements PlaceBeanLocal {
} }
} }
if (freePlace == null) { if (freePlace == null) {
throw new EJBException("Could find a place to be reserved...."); throw new EJBException("Could not find a place to be reserved....");
} }
GroupMembership gm = buy(freePlace, pg); GroupMembership gm = buy(freePlace, pg);
......
...@@ -107,7 +107,7 @@ public class ReaderBean implements ReaderBeanLocal { ...@@ -107,7 +107,7 @@ public class ReaderBean implements ReaderBeanLocal {
/** /**
* Some of rfid-readers adds zeros to start, some to end * Some of rfid-readers adds zeros to start, some to end
* *
* Also, under 16 char -rdid (the smaller one) should be 16 character * Also, under 16 char -rdid (the smaller one) should be 16 character
* long, with zeros on beginning. * long, with zeros on beginning.
*/ */
if (ReaderType.RFID.equals(reader.getType())) { if (ReaderType.RFID.equals(reader.getType())) {
...@@ -138,8 +138,8 @@ public class ReaderBean implements ReaderBeanLocal { ...@@ -138,8 +138,8 @@ public class ReaderBean implements ReaderBeanLocal {
if (lastevent.getValue().equals(event.getValue()) && (lastevent.getUpdatetime().getTime() + 60000l) > event.getTime().getTime()) { if (lastevent.getValue().equals(event.getValue()) && (lastevent.getUpdatetime().getTime() + 60000l) > event.getTime().getTime()) {
lastevent = readerEventFacade.reload(lastevent); //lastevent = readerEventFacade.reload(lastevent);
lastevent = readerEventFacade.merge(lastevent); //lastevent = readerEventFacade.merge(lastevent);
return lastevent; // todo: update lastevent bfore return return lastevent; // todo: update lastevent bfore return
} }
...@@ -210,8 +210,9 @@ public class ReaderBean implements ReaderBeanLocal { ...@@ -210,8 +210,9 @@ public class ReaderBean implements ReaderBeanLocal {
cardCodeFacade.create(code); cardCodeFacade.create(code);
card.getCardCodes().add(code); card.getCardCodes().add(code);
cardCodeFacade.flush();
return readerEvent; return checkCode(readerEvent.getReader(), readerEvent.getValue());
} }
@Override @Override
......
...@@ -36,25 +36,39 @@ public class BasicAuthPBean extends ApiAuth implements AuthenticationFormat { ...@@ -36,25 +36,39 @@ public class BasicAuthPBean extends ApiAuth implements AuthenticationFormat {
@EJB @EJB
private EventBean eventbean; private EventBean eventbean;
/**
* Authenticate application with username being `null` and password containing basic auth credentials:
* username should be constant 'appauth' and password should contain the following fields delimited by: `:`
* 1) application Id
* 2) application instance authname
* 3) application instance secret
*/
@Override @Override
public AuthenticationResult authenticate(String jaasUsername, String password) { public AuthenticationResult authenticate(final String username, final String password) {
AuthenticationResult ret = null; AuthenticationResult ret = null;
String username = UserLoginUtils.getUsernameFromJaasString(jaasUsername); //String username = UserLoginUtils.getUsernameFromJaasString(jaasUsername);
String domain = UserLoginUtils.getDomainFromJaasString(jaasUsername);
LanEvent event = eventbean.getEventForHostname(domain);
if ((username == null || username.isEmpty()) && password.startsWith(HEADER_PREFIX)) { if (password.startsWith(HEADER_PREFIX)) {
ret = new AuthenticationResult(); ret = new AuthenticationResult();
ret.setUsertype(UserType.REST.name()); ret.setUsertype(UserType.REST.name());
try { try {
String domain = UserLoginUtils.getDomainFromJaasString(username);
LanEvent event = eventbean.getEventForHostname(domain);
String[] pwdsplit = password.split(" "); String[] pwdsplit = password.split(" ");
if (pwdsplit.length != 2) { if (pwdsplit.length != 2) {
logger.warn("Rest auth with Basic failed because pwdsplit != 2: user '{}', password '{}'", username, logger.warn("Rest auth with Basic failed because pwdsplit != 2: user '{}''", username );
password); return null;
}
// There is a possibility that user has a password that starts with "Basic ". To combat this,
// we chech that the authdata is really a base64 string. If not, we continue trying with other methods
String authStr = null;
try {
authStr = new String(Base64.getDecoder().decode(pwdsplit[1]), UTF8);
} catch (IllegalArgumentException ie) {
return null; return null;
} }
String authStr = new String(Base64.getDecoder().decode(pwdsplit[1]), UTF8);
String[] splitStr = authStr.split(PASSWORD_DELIMITER); String[] splitStr = authStr.split(PASSWORD_DELIMITER);
if (splitStr.length != 4 || !PASSWORD_PREFIX.equals(splitStr[0])) { if (splitStr.length != 4 || !PASSWORD_PREFIX.equals(splitStr[0])) {
logger.warn( logger.warn(
...@@ -68,11 +82,11 @@ public class BasicAuthPBean extends ApiAuth implements AuthenticationFormat { ...@@ -68,11 +82,11 @@ public class BasicAuthPBean extends ApiAuth implements AuthenticationFormat {
ApiApplicationInstance appInstance = verifyAppInstance(appId, userId, event); ApiApplicationInstance appInstance = verifyAppInstance(appId, userId, event);
if (appInstance != null && appKey != null && !appKey.isEmpty() && appKey.equals(appInstance.getSecretKey())) { if (appInstance != null && appKey != null && !appKey.isEmpty() && appKey.equals(appInstance.getSecretKey())) {
ret.setUsername(getUsername(appInstance) + '@' + domain); ret.setUsername(username);
} }
} catch (Exception e) { } catch (Exception e) {
ret = null;
logger.warn("Invalid base64 string on Rest Basic auth: " + password, e); logger.warn("Invalid base64 string on Rest Basic auth: " + password, e);
} }
} }
return ret; return ret;
......
...@@ -35,7 +35,10 @@ public class RestMacAuthPBean extends ApiAuth implements AuthenticationFormat { ...@@ -35,7 +35,10 @@ public class RestMacAuthPBean extends ApiAuth implements AuthenticationFormat {
if ((username == null || username.isEmpty()) && password.startsWith(JaasBeanLocal.REST_PREFIX)) { if ((username == null || username.isEmpty()) && password.startsWith(JaasBeanLocal.REST_PREFIX)) {
ret = new AuthenticationResult(); ret = new AuthenticationResult();
ret.setUsertype(UserType.REST.name()); ret.setUsertype(UserType.REST.name());
ret.setUsername(restAuth(password, event) + '@'+domain); if(restAuth(password, event) != null) {
ret.setUsername(jaasUsername);
}
//ret.setUsername(restAuth(password, event) + '@'+domain);
} }
return ret; return ret;
} }
......
/* /*
* Copyright Codecrew Ry * Copyright Codecrew Ry
* *
* All rights reserved. * All rights reserved.
* *
* This license applies to any software containing a notice placed by the * This license applies to any software containing a notice placed by the
* copyright holder. Such software is herein referred to as the Software. * copyright holder. Such software is herein referred to as the Software.
* This license covers modification, distribution and use of the Software. * This license covers modification, distribution and use of the Software.
* *
* Any distribution and use in source and binary forms, with or without * Any distribution and use in source and binary forms, with or without
* modification is not permitted without explicit written permission from the * modification is not permitted without explicit written permission from the
* copyright owner. * copyright owner.
* *
* A non-exclusive royalty-free right is granted to the copyright owner of the * A non-exclusive royalty-free right is granted to the copyright owner of the
* Software to use, modify and distribute all modifications to the Software in * Software to use, modify and distribute all modifications to the Software in
* future versions of the Software. * future versions of the Software.
* *
*/ */
package fi.codecrew.moya.facade; package fi.codecrew.moya.facade;
...@@ -45,4 +45,16 @@ public class ApiApplicationInstanceFacade extends IntegerPkGenericFacade<ApiAppl ...@@ -45,4 +45,16 @@ public class ApiApplicationInstanceFacade extends IntegerPkGenericFacade<ApiAppl
return super.getSingleNullableResult(getEm().createQuery(q)); return super.getSingleNullableResult(getEm().createQuery(q));
} }
public ApiApplicationInstance findInstance(String appkey, String userId, LanEvent event) {
CriteriaBuilder cb = getEm().getCriteriaBuilder();
CriteriaQuery<ApiApplicationInstance> q = cb.createQuery(ApiApplicationInstance.class);
Root<ApiApplicationInstance> root = q.from(ApiApplicationInstance.class);
q.where(cb.equal(root.get(ApiApplicationInstance_.application).get(ApiApplication_.applicationKey), appkey),
cb.equal(root.get(ApiApplicationInstance_.authname), userId),
cb.equal(root.get(ApiApplicationInstance_.eventuser).get(EventUser_.event), event));
return super.getSingleNullableResult(getEm().createQuery(q));
}
} }
...@@ -4,7 +4,7 @@ ...@@ -4,7 +4,7 @@
<artifactId>moya-restpojo</artifactId> <artifactId>moya-restpojo</artifactId>
<!-- This is set here on purpose, so that remote dependencies do not break <!-- This is set here on purpose, so that remote dependencies do not break
If this is updated. remember to update also version in moya-web --> If this is updated. remember to update also version in moya-web -->
<version>1.2.1</version> <version>1.2.4</version>
<distributionManagement> <distributionManagement>
<downloadUrl>http://codecrew.fi/mvn</downloadUrl> <downloadUrl>http://codecrew.fi/mvn</downloadUrl>
<repository> <repository>
......
...@@ -23,7 +23,6 @@ public class ApplicationInstancePojo { ...@@ -23,7 +23,6 @@ public class ApplicationInstancePojo {
} }
@XmlElement() @XmlElement()
public String getSecretKey() { public String getSecretKey() {
return secretKey; return secretKey;
...@@ -34,11 +33,6 @@ public class ApplicationInstancePojo { ...@@ -34,11 +33,6 @@ public class ApplicationInstancePojo {
} }
@XmlElement() @XmlElement()
public String getName() { public String getName() {
return name; return name;
......
...@@ -4,6 +4,8 @@ package fi.codecrew.moya.rest.pojo.appconfig.v1; ...@@ -4,6 +4,8 @@ package fi.codecrew.moya.rest.pojo.appconfig.v1;
import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModel;
import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlElement;
import java.util.Date;
import java.util.List; import java.util.List;
/** /**
...@@ -15,6 +17,7 @@ public class EventPojo { ...@@ -15,6 +17,7 @@ public class EventPojo {
private Integer lanEventId; private Integer lanEventId;
private String name; private String name;
private List<String> urls; private List<String> urls;
private Date startTime;
@XmlElement @XmlElement
public Integer getLanEventId() { public Integer getLanEventId() {
...@@ -42,4 +45,12 @@ public class EventPojo { ...@@ -42,4 +45,12 @@ public class EventPojo {
public void setUrls(List<String> urls) { public void setUrls(List<String> urls) {
this.urls = urls; this.urls = urls;
} }
public Date getStartTime() {
return startTime;
}
public void setStartTime(Date startTime) {
this.startTime = startTime;
}
} }
...@@ -28,6 +28,7 @@ import io.swagger.annotations.ApiModel; ...@@ -28,6 +28,7 @@ import io.swagger.annotations.ApiModel;
@ApiModel @ApiModel
public class ReaderEventRestPojo { public class ReaderEventRestPojo {
private EventUserRestPojo eventUser; private EventUserRestPojo eventUser;
private PrintedCardRestPojo printedCard; private PrintedCardRestPojo printedCard;
...@@ -40,32 +41,32 @@ public class ReaderEventRestPojo { ...@@ -40,32 +41,32 @@ public class ReaderEventRestPojo {
public ReaderEventRestPojo() { public ReaderEventRestPojo() {
} }
@XmlElement(name = "eventuser") @XmlElement(name = "eventuser", nillable = true)
public EventUserRestPojo getEventuser() { public EventUserRestPojo getEventuser() {
return eventUser; return eventUser;
} }
@XmlElement(name = "readerEventId") @XmlElement(name = "readerEventId", nillable = false)
public Integer getEventId() { public Integer getEventId() {
return readerEventId; return readerEventId;
} }
@XmlElement(name = "readerEventTime") @XmlElement(name = "readerEventTime", nillable = true)
public Date getReaderEventTime() { public Date getReaderEventTime() {
return readerEventTime; return readerEventTime;
} }
@XmlElement(name = "readerId") @XmlElement(name = "readerId", nillable = false)
public Integer getReaderId() { public Integer getReaderId() {
return readerId; return readerId;
} }
@XmlElement(name = "printedCardId") @XmlElement(name = "printedCardId", nillable = true)
public Integer getPrintedCardId() { public Integer getPrintedCardId() {
return printedCardId; return printedCardId;
} }
@XmlElement(name = "printedCardState") @XmlElement(name = "printedCardState", nillable = true)
public String getPrintedCardState() { public String getPrintedCardState() {
return printedCardState; return printedCardState;
} }
......
package fi.codecrew.moya.rest.pojo.userinfo.v1;
import java.io.Serializable;
import java.util.Date;
import io.swagger.annotations.ApiModel;
@ApiModel
public class ApiApplicationInstancePojo implements Serializable {
private static final long serialVersionUID = 1L;
private boolean enabled;
private Date created;
private String authname;
private String secret;
public boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public Date getCreated() {
return created;
}
public void setCreated(Date created) {
this.created = created;
}
public String getAuthname() {
return authname;
}
public void setAuthname(String authname) {
this.authname = authname;
}
public String getSecret() {
return secret;
}
public void setSecret(String secret) {
this.secret = secret;
}
}
package fi.codecrew.moya.rest.pojo.userinfo.v1;
public class PrintedCardUpdateCodePojo {
private String readerName;
private String code;
public PrintedCardUpdateCodePojo(String readerName, String code) {
this.readerName = readerName;
this.code = code;
}
public PrintedCardUpdateCodePojo() {
super();
}
public String getReaderName() {
return readerName;
}
public void setReaderName(String readerName) {
this.readerName = readerName;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
}
package fi.codecrew.moya.rest.pojo.userinfo.v1;
import java.io.Serializable;
import java.util.Date;
public class UserPwdPojo implements Serializable {
private static final long serialVersionUID = 1L;
public UserPwdPojo() {
super();
}
public UserPwdPojo(String username, String password, Date submitTime) {
this();
this.username = username;
this.password = password;
this.submitTime = submitTime;
}
private String username;
private String password;
private Date submitTime;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Date getSubmitTime() {
return submitTime;
}
public void setSubmitTime(Date submitTime) {
this.submitTime = submitTime;
}
}
/* /*
* Copyright Codecrew Ry * Copyright Codecrew Ry
* *
* All rights reserved. * All rights reserved.
* *
* This license applies to any software containing a notice placed by the * This license applies to any software containing a notice placed by the
* copyright holder. Such software is herein referred to as the Software. * copyright holder. Such software is herein referred to as the Software.
* This license covers modification, distribution and use of the Software. * This license covers modification, distribution and use of the Software.
* *
* Any distribution and use in source and binary forms, with or without * Any distribution and use in source and binary forms, with or without
* modification is not permitted without explicit written permission from the * modification is not permitted without explicit written permission from the
* copyright owner. * copyright owner.
* *
* A non-exclusive royalty-free right is granted to the copyright owner of the * A non-exclusive royalty-free right is granted to the copyright owner of the
* Software to use, modify and distribute all modifications to the Software in * Software to use, modify and distribute all modifications to the Software in
* future versions of the Software. * future versions of the Software.
* *
*/ */
package fi.codecrew.moya.utilities; package fi.codecrew.moya.utilities;
...@@ -32,23 +32,23 @@ public class JsonUtils { ...@@ -32,23 +32,23 @@ public class JsonUtils {
/** /**
* Gets a sub object from a JsonObject. Returns an empty object if not * Gets a sub object from a JsonObject. Returns an empty object if not
* found. * found.
* *
* @param jsonObject * @param jsonObject
* @param path * @param path
* @return * @return
*/ */
public static JsonValue getSubObject(JsonObject jsonObject, public static JsonValue getSubObject(JsonObject jsonObject, List<String> path) {
List<String> path) {
JsonValue sub = jsonObject; JsonValue sub = jsonObject;
// Burrow into object hierarchy // Burrow into object hierarchy
for (String s : path) { for (String s : path) {
if (sub.getValueType() == ValueType.OBJECT) { if (sub != null && sub.getValueType() == ValueType.OBJECT) {
JsonObject subObject = (JsonObject) sub; JsonObject subObject = (JsonObject) sub;
sub = subObject.get(s); sub = subObject.get(s);
} else { } else {
// Trying to get sub-object of something not an object. Bad. // Trying to get sub-object of something not an object. Bad.
return null; sub = null;
break;
} }
} }
...@@ -62,16 +62,13 @@ public class JsonUtils { ...@@ -62,16 +62,13 @@ public class JsonUtils {
/** /**
* Adds or alters one key in JsonObject * Adds or alters one key in JsonObject
* *
* @param jsonObject * @param jsonObject
* @param key * @param key which key to add/alter
* which key to add/alter * @param value The value associate to the key
* @param value
* The value associate to the key
* @return JsonObject with the key:value pair added * @return JsonObject with the key:value pair added
*/ */
public static JsonObject assocJsonObject(JsonObject jsonObject, String key, public static JsonObject assocJsonObject(JsonObject jsonObject, String key, JsonValue value) {
JsonValue value) {
JsonObjectBuilder builder = Json.createObjectBuilder(); JsonObjectBuilder builder = Json.createObjectBuilder();
// Copy all non conflicting json entries // Copy all non conflicting json entries
...@@ -90,15 +87,13 @@ public class JsonUtils { ...@@ -90,15 +87,13 @@ public class JsonUtils {
/** /**
* Goes into a json object and sets subobject assocInJsonObject("{}", * Goes into a json object and sets subobject assocInJsonObject("{}",
* ["foo", "bar"], "{\"a\":\"b\"}") => {\"foo\":{\"bar\":{\"a\":\"b\"}}} * ["foo", "bar"], "{\"a\":\"b\"}") => {\"foo\":{\"bar\":{\"a\":\"b\"}}}
* *
* @param jsonObject * @param jsonObject
* @param keys * @param keys path inside key hierarchy
* path inside key hierarchy
* @param value * @param value
* @return JsonObject with the value added * @return JsonObject with the value added
*/ */
public static JsonObject assocInJsonObject(JsonObject jsonObject, public static JsonObject assocInJsonObject(JsonObject jsonObject, List<String> keys, JsonValue value) {
List<String> keys, JsonValue value) {
// Recurse? // Recurse?
if (keys.size() > 1) { if (keys.size() > 1) {
...@@ -106,7 +101,7 @@ public class JsonUtils { ...@@ -106,7 +101,7 @@ public class JsonUtils {
List<String> restKeys = keys.subList(1, keys.size()); List<String> restKeys = keys.subList(1, keys.size());
JsonObject subObj = jsonObject.getJsonObject(firstKey); JsonObject subObj = jsonObject.getJsonObject(firstKey);
return assocJsonObject(jsonObject, firstKey, return assocJsonObject(jsonObject, firstKey,
assocInJsonObject(subObj, restKeys, value)); assocInJsonObject(subObj, restKeys, value));
} }
// End? // End?
...@@ -114,9 +109,7 @@ public class JsonUtils { ...@@ -114,9 +109,7 @@ public class JsonUtils {
return assocJsonObject(jsonObject, firstKey, value); return assocJsonObject(jsonObject, firstKey, value);
} }
public static JsonObject alterSubObject(JsonObject jsonObject, public static JsonObject alterSubObject(JsonObject jsonObject, List<String> path, JsonObject subObject) {
List<String> path, JsonObject subObject) {
return assocInJsonObject(jsonObject, path, subObject); return assocInJsonObject(jsonObject, path, subObject);
} }
} }
...@@ -32,6 +32,12 @@ public class UserLoginUtils { ...@@ -32,6 +32,12 @@ public class UserLoginUtils {
} }
public static String getUsernameFromJaasString(String username) { public static String getUsernameFromJaasString(String username) {
return username.split("@[^@]+$")[0]; String[] splitted = username.split("@[^@]+$");
String ret = null;
if (splitted.length > 0) {
ret = splitted[0];
}
return ret;
} }
} }
...@@ -44,7 +44,7 @@ ...@@ -44,7 +44,7 @@
<dependency> <dependency>
<groupId>fi.codecrew.moya</groupId> <groupId>fi.codecrew.moya</groupId>
<artifactId>moya-restpojo</artifactId> <artifactId>moya-restpojo</artifactId>
<version>1.2.1</version> <version>1.2.4</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.glassfish.jersey.media</groupId> <groupId>org.glassfish.jersey.media</groupId>
......
...@@ -21,6 +21,7 @@ package fi.codecrew.moya; ...@@ -21,6 +21,7 @@ package fi.codecrew.moya;
import java.io.IOException; import java.io.IOException;
import java.nio.charset.Charset; import java.nio.charset.Charset;
import java.security.Principal; import java.security.Principal;
import java.util.Base64;
import javax.ejb.EJB; import javax.ejb.EJB;
import javax.faces.application.ProjectStage; import javax.faces.application.ProjectStage;
...@@ -36,15 +37,12 @@ import javax.servlet.http.HttpServletRequest; ...@@ -36,15 +37,12 @@ import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession; import javax.servlet.http.HttpSession;
import fi.codecrew.moya.beans.*;
import fi.codecrew.moya.utilities.UserLoginUtils; import fi.codecrew.moya.utilities.UserLoginUtils;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.slf4j.MDC; import org.slf4j.MDC;
import fi.codecrew.moya.beans.JaasBeanLocal;
import fi.codecrew.moya.beans.LoggingBeanLocal;
import fi.codecrew.moya.beans.RestBeanLocal;
import fi.codecrew.moya.beans.SessionMgmtBeanLocal;
import fi.codecrew.moya.clientutils.BortalLocalContextHolder; import fi.codecrew.moya.clientutils.BortalLocalContextHolder;
import fi.codecrew.moya.model.User; import fi.codecrew.moya.model.User;
import fi.codecrew.moya.rest.RestApplicationEntrypoint; import fi.codecrew.moya.rest.RestApplicationEntrypoint;
...@@ -67,6 +65,9 @@ public class HostnameFilter implements Filter { ...@@ -67,6 +65,9 @@ public class HostnameFilter implements Filter {
@EJB @EJB
private LoggingBeanLocal logbean; private LoggingBeanLocal logbean;
@EJB
private ApiApplicationBeanLocal apibean;
@Override @Override
public void init(FilterConfig config) throws ServletException { public void init(FilterConfig config) throws ServletException {
// check if software is in development -mode // check if software is in development -mode
...@@ -145,7 +146,12 @@ public class HostnameFilter implements Filter { ...@@ -145,7 +146,12 @@ public class HostnameFilter implements Filter {
MDC.remove("req.eventhost"); MDC.remove("req.eventhost");
} }
private static final String[] NOAUTH_RESTPATHS = new String[]{"/reader/EventRole/", "/user/auth"}; private static final String[] NOAUTH_RESTPATHS = new String[]{
"/reader/EventRole/",
"/user/auth",
"/appconfig/v1/eventinfo/allevents",
"/apiapp/v1/createInstance/"
};
/** /**
* @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain) * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
...@@ -165,11 +171,14 @@ public class HostnameFilter implements Filter { ...@@ -165,11 +171,14 @@ public class HostnameFilter implements Filter {
try { try {
httpRequest = (HttpServletRequest) request; httpRequest = (HttpServletRequest) request;
insertServerLoggingContext(httpRequest, authtype); insertServerLoggingContext(httpRequest, authtype);
logger.info("Logging in with username {} and password {}, remote {}, authtype: {}", httpRequest.getUserPrincipal(), httpRequest.getRemoteUser(), httpRequest.getAuthType());
String hostname = parseHostname(httpRequest); String hostname = parseHostname(httpRequest);
if (httpRequest.getUserPrincipal() == null) { if (httpRequest.getUserPrincipal() == null) {
// Check if we are logging in with rest // Check if we are can login in with rest alternative methods ( appkey, basic auth, etc.. )
if (RestApplicationEntrypoint.REST_PATH.equals(httpRequest.getServletPath())) { if (RestApplicationEntrypoint.REST_PATH.equals(httpRequest.getServletPath())
|| "/dydata".equals(httpRequest.getServletPath())) {
authtype = AuthType.REST; authtype = AuthType.REST;
if (!restAuth(httpRequest, response)) { if (!restAuth(httpRequest, response)) {
...@@ -240,20 +249,45 @@ public class HostnameFilter implements Filter { ...@@ -240,20 +249,45 @@ public class HostnameFilter implements Filter {
restAuthStr = httpRequest.getHeader("Authorization"); restAuthStr = httpRequest.getHeader("Authorization");
// } // }
if (restAuthStr == null) { String userkey = null;
String appkey = null;
// Payara got updated, and does not allow changing of username anymore, so we must send
// username and domain to initial jaas-login query...
if (restAuthStr != null) {
String decodedStr = new String(Base64.getDecoder().decode(restAuthStr.split(" ")[1]), UTF8);
String[] splitStr = decodedStr.split(":");
appkey = splitStr[1];
userkey = splitStr[2];
// final String appKey = splitStr[3];
} else if (httpRequest.getParameter("appkey") != null) {
appkey = httpRequest.getParameter("appkey");
userkey = httpRequest.getParameter("appuser");
StringBuilder hashBuilder = new StringBuilder(); StringBuilder hashBuilder = new StringBuilder();
hashBuilder.append(JaasBeanLocal.REST_PREFIX); hashBuilder.append(JaasBeanLocal.REST_PREFIX);
hashBuilder.append(httpRequest.getParameter("appkey")).append(":"); hashBuilder.append(appkey).append(":");
hashBuilder.append(httpRequest.getParameter("appuser")).append(":"); hashBuilder.append(userkey).append(":");
hashBuilder.append(httpRequest.getParameter("appstamp")).append(":"); hashBuilder.append(httpRequest.getParameter("appstamp")).append(":");
hashBuilder.append(httpRequest.getParameter("appmac")).append(":"); hashBuilder.append(httpRequest.getParameter("appmac")).append(":");
hashBuilder.append(httpRequest.getPathInfo()); hashBuilder.append(httpRequest.getPathInfo());
restAuthStr = hashBuilder.toString(); restAuthStr = hashBuilder.toString();
} }
boolean ret = true; boolean ret = true;
String domain = parseHostname(httpRequest);
try { try {
httpRequest.login('@' + parseHostname(httpRequest), restAuthStr); if (restAuthStr == null) {
throw new ServletException("No auth data");
}
//final String username = "@" + parseHostname(httpRequest);
String userLogin = apibean.findUsernameForApikey(appkey, userkey, domain);
if (userLogin != null) {
httpRequest.login(userLogin + '@' + domain, restAuthStr);
}
Principal p = httpRequest.getUserPrincipal();
logger.warn("Logged in with rest:{}, ", (p == null) ? null : p.getName());
} catch (ServletException loginEx) { } catch (ServletException loginEx) {
ret = false; ret = false;
logger.info("Rest api authentication failed for path " + httpRequest.getPathInfo() + " " logger.info("Rest api authentication failed for path " + httpRequest.getPathInfo() + " "
...@@ -281,18 +315,20 @@ public class HostnameFilter implements Filter { ...@@ -281,18 +315,20 @@ public class HostnameFilter implements Filter {
scheme = url.substring(0, 5).toLowerCase(); scheme = url.substring(0, 5).toLowerCase();
} }
String userDomain = UserLoginUtils.getDomainFromJaas(httpRequest.getUserPrincipal()); Principal principal = httpRequest.getUserPrincipal();
if (!hostname.equals(userDomain)) { if (principal != null) {
String userDomain = UserLoginUtils.getDomainFromJaas(principal);
// If there is no logged-in user, we can and should not check userDomain against hostname
if (principal != null && !hostname.equals(userDomain)) {
logbean.sendMessage(MoyaEventType.USER_PERMISSION_VIOLATION, logbean.sendMessage(MoyaEventType.USER_PERMISSION_VIOLATION,
"Hostname mismatch privilege escalation! User '", httpRequest.getUserPrincipal(), "' tried to change hostname from '", "Hostname mismatch privilege escalation! User '", httpRequest.getUserPrincipal(), "' tried to change hostname from '",
userDomain, "' to '", hostname, ","); userDomain, "' to '", hostname, ",");
throw new RuntimeException("Hostname mismatch!"); throw new RuntimeException("Hostname mismatch! Expected: " + hostname + " but logged in as " + userDomain);
}
} }
BortalLocalContextHolder.setHostname(hostname);
BortalLocalContextHolder.setInDevelopmentMode(developmentMode); BortalLocalContextHolder.setInDevelopmentMode(developmentMode);
return hostname; return hostname;
......
...@@ -27,8 +27,7 @@ import fi.codecrew.moya.rest.pojo.userinfo.v1.UserReservationPlacePojo; ...@@ -27,8 +27,7 @@ import fi.codecrew.moya.rest.pojo.userinfo.v1.UserReservationPlacePojo;
import fi.codecrew.moya.rest.pojo.util.v1.ErrorRoot; import fi.codecrew.moya.rest.pojo.util.v1.ErrorRoot;
public class PojoUtils { public class PojoUtils {
public static EventUserRestPojo initEventUserRestPojo(EventUser user) public static EventUserRestPojo initEventUserRestPojo(EventUser user) {
{
EventUserRestPojo ret = new EventUserRestPojo(); EventUserRestPojo ret = new EventUserRestPojo();
ret.setNick(user.getUser().getNick()); ret.setNick(user.getUser().getNick());
ret.setLogin(user.getUser().getLogin()); ret.setLogin(user.getUser().getLogin());
...@@ -49,8 +48,7 @@ public class PojoUtils { ...@@ -49,8 +48,7 @@ public class PojoUtils {
} }
public static PrintedCardRestPojo initPrintedCardRestPojo(PrintedCard card) public static PrintedCardRestPojo initPrintedCardRestPojo(PrintedCard card) {
{
PrintedCardRestPojo ret = new PrintedCardRestPojo(); PrintedCardRestPojo ret = new PrintedCardRestPojo();
ret.setEventuserId(card.getUser().getId()); ret.setEventuserId(card.getUser().getId());
ret.setId(card.getId()); ret.setId(card.getId());
...@@ -66,8 +64,7 @@ public class PojoUtils { ...@@ -66,8 +64,7 @@ public class PojoUtils {
return ret; return ret;
} }
public static CardRoot parsePrintedCards(List<PrintedCard> cards) public static CardRoot parsePrintedCards(List<PrintedCard> cards) {
{
ArrayList<PrintedCardRestPojo> ret = new ArrayList<PrintedCardRestPojo>(); ArrayList<PrintedCardRestPojo> ret = new ArrayList<PrintedCardRestPojo>();
for (PrintedCard c : cards) { for (PrintedCard c : cards) {
ret.add(initPrintedCardRestPojo(c)); ret.add(initPrintedCardRestPojo(c));
...@@ -98,17 +95,15 @@ public class PojoUtils { ...@@ -98,17 +95,15 @@ public class PojoUtils {
ret.setDisabled(place.isDisabled()); ret.setDisabled(place.isDisabled());
// I cannot change REST -api without making new version, so let's simulate this ReleaseTime -feature from reserveTime
Calendar relTime = Calendar.getInstance();
// I cannot change REST -api without making new version, so let's simulate this ReleaseTime -feature from reserveTime relTime.add(relTime.HOUR, 4);
Calendar relTime = Calendar.getInstance();
relTime.add(relTime.HOUR, 4);
if(place.getReserveTime() != null)
ret.setReleaseTime(relTime);
else
ret.setReleaseTime(null);
if (place.getReserveTime() != null)
ret.setReleaseTime(relTime);
else
ret.setReleaseTime(null);
if (place.getMap() != null) { if (place.getMap() != null) {
...@@ -156,7 +151,7 @@ public class PojoUtils { ...@@ -156,7 +151,7 @@ public class PojoUtils {
public static ReaderEventRestPojo initReaderEventRestPojo(ReaderEvent event) { public static ReaderEventRestPojo initReaderEventRestPojo(ReaderEvent event) {
ReaderEventRestPojo ret = new ReaderEventRestPojo(); ReaderEventRestPojo ret = new ReaderEventRestPojo();
if ( event.getPrintedCard() != null) { if (event.getPrintedCard() != null) {
if (event.getPrintedCard().getUser() != null) { if (event.getPrintedCard().getUser() != null) {
ret.setEventUser(PojoUtils.initEventUserRestPojo(event.getPrintedCard().getUser())); ret.setEventUser(PojoUtils.initEventUserRestPojo(event.getPrintedCard().getUser()));
} }
...@@ -186,8 +181,7 @@ public class PojoUtils { ...@@ -186,8 +181,7 @@ public class PojoUtils {
return ret; return ret;
} }
public static ReaderRestPojo initReaderRestPojo(Reader reader) public static ReaderRestPojo initReaderRestPojo(Reader reader) {
{
ReaderRestPojo ret = new ReaderRestPojo(); ReaderRestPojo ret = new ReaderRestPojo();
ret.setReaderId(reader.getId()); ret.setReaderId(reader.getId());
ret.setIdentification(reader.getIdentification()); ret.setIdentification(reader.getIdentification());
...@@ -217,8 +211,7 @@ public class PojoUtils { ...@@ -217,8 +211,7 @@ public class PojoUtils {
return ret; return ret;
} }
public static ProductRestPojo initProductRestPojo(Product product) public static ProductRestPojo initProductRestPojo(Product product) {
{
ProductRestPojo ret = new ProductRestPojo(); ProductRestPojo ret = new ProductRestPojo();
ret.setId(product.getId()); ret.setId(product.getId());
ret.setName(product.getName()); ret.setName(product.getName());
...@@ -233,8 +226,7 @@ public class PojoUtils { ...@@ -233,8 +226,7 @@ public class PojoUtils {
return parseSimplePlaces(places, user, hasPermissionViewAllusers, false); return parseSimplePlaces(places, user, hasPermissionViewAllusers, false);
} }
public static SimplePlacelistRoot parseSimplePlaces(List<Place> places, EventUser user, boolean hasPermissionViewAllusers, boolean onlyHilightPlaces) public static SimplePlacelistRoot parseSimplePlaces(List<Place> places, EventUser user, boolean hasPermissionViewAllusers, boolean onlyHilightPlaces) {
{
SimplePlacelistRoot ret = new SimplePlacelistRoot(); SimplePlacelistRoot ret = new SimplePlacelistRoot();
ArrayList<SimplePlacePojo> placeList = new ArrayList<>(); ArrayList<SimplePlacePojo> placeList = new ArrayList<>();
ret.setPlaces(placeList); ret.setPlaces(placeList);
...@@ -251,41 +243,40 @@ public class PojoUtils { ...@@ -251,41 +243,40 @@ public class PojoUtils {
ret.setName(p.getName()); ret.setName(p.getName());
String state = null; String state = null;
if(hasPermissionViewAllusers) { if (hasPermissionViewAllusers) {
if(p.getPlaceReserver() != null) { if (p.getPlaceReserver() != null) {
if(p.getPlaceReserver().getUser() != null) { if (p.getPlaceReserver().getUser() != null) {
ret.setUserDescription(p.getPlaceReserver().getUser().getUser().getShortUserDescriptor()); ret.setUserDescription(p.getPlaceReserver().getUser().getUser().getShortUserDescriptor());
} else if(p.getPlaceReserver().getPlaceGroup() != null && p.getPlaceReserver().getPlaceGroup().getCreator() != null) { } else if (p.getPlaceReserver().getPlaceGroup() != null && p.getPlaceReserver().getPlaceGroup().getCreator() != null) {
ret.setUserDescription(p.getPlaceReserver().getPlaceGroup().getCreator().getUser().getShortUserDescriptor()); ret.setUserDescription(p.getPlaceReserver().getPlaceGroup().getCreator().getUser().getShortUserDescriptor());
} }
} }
} }
switch (p.getState(user)) switch (p.getState(user)) {
{
case DISABLED: case DISABLED:
state = (onlyHilightPlaces)?"F":"D"; state = (onlyHilightPlaces) ? "F" : "D";
break; break;
case FREE: case FREE:
state = "F"; state = "F";
break; break;
case LOCKED: case LOCKED:
state = (onlyHilightPlaces)?"F":"L"; state = (onlyHilightPlaces) ? "F" : "L";
break; break;
case MY_PLACE: case MY_PLACE:
state = "P"; state = "P";
break; break;
case RESERVED: case RESERVED:
state = (onlyHilightPlaces)?"F":"R"; state = (onlyHilightPlaces) ? "F" : "R";
break; break;
case TEMP_RESERVED_FORME: case TEMP_RESERVED_FORME:
state = (onlyHilightPlaces)?"F":"T"; state = (onlyHilightPlaces) ? "F" : "T";
break; break;
default: default:
break; break;
} }
if(onlyHilightPlaces) { if (onlyHilightPlaces) {
} }
...@@ -321,23 +312,28 @@ public class PojoUtils { ...@@ -321,23 +312,28 @@ public class PojoUtils {
return ur; return ur;
} }
public static EventPojo parseEvent(LanEvent event) {
ArrayList<String> urls = new ArrayList<>();
for (LanEventDomain domain : event.getDomains()) {
urls.add(domain.getDomain());
}
EventPojo pojo = new EventPojo();
pojo.setName(event.getName());
pojo.setLanEventId(event.getId());
pojo.setUrls(urls);
pojo.setStartTime(event.getStartTime());
return pojo;
}
public static EventRoot parseEvents(List<LanEvent> events) { public static EventRoot parseEvents(List<LanEvent> events) {
EventRoot root = new EventRoot(); EventRoot root = new EventRoot();
ArrayList<EventPojo> eventPojos = new ArrayList<>(); ArrayList<EventPojo> eventPojos = new ArrayList<>();
for(LanEvent event : events) { for (LanEvent event : events) {
ArrayList<String> urls = new ArrayList<>(); eventPojos.add(parseEvent(event));
for(LanEventDomain domain : event.getDomains()) {
urls.add(domain.getDomain());
}
EventPojo pojo = new EventPojo();
pojo.setName(event.getName());
pojo.setLanEventId(event.getId());
pojo.setUrls(urls);
eventPojos.add(pojo);
} }
root.setEvents(eventPojos); root.setEvents(eventPojos);
...@@ -356,11 +352,11 @@ public class PojoUtils { ...@@ -356,11 +352,11 @@ public class PojoUtils {
return pojo; return pojo;
} }
public static ErrorRoot initErrorPojo(String errorMessage) { public static ErrorRoot initErrorPojo(String errorMessage) {
ErrorRoot errorRoot = new ErrorRoot(); ErrorRoot errorRoot = new ErrorRoot();
errorRoot.setError(errorMessage); errorRoot.setError(errorMessage);
return errorRoot; return errorRoot;
} }
} }
...@@ -22,11 +22,7 @@ import java.util.List; ...@@ -22,11 +22,7 @@ import java.util.List;
import javax.ejb.EJB; import javax.ejb.EJB;
import javax.enterprise.context.RequestScoped; import javax.enterprise.context.RequestScoped;
import javax.ws.rs.Consumes; import javax.ws.rs.*;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response; import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.ResponseBuilder; import javax.ws.rs.core.Response.ResponseBuilder;
...@@ -86,6 +82,15 @@ public class ReaderRestView { ...@@ -86,6 +82,15 @@ public class ReaderRestView {
return Response.ok().build(); return Response.ok().build();
} }
@POST
@Path("/createevent/{reader}/{code}")
public Response createReaderEvent(@PathParam("reader") String readerName, @PathParam("code") String readerCode) {
ReaderEvent readerEvent = readerbean.checkCode(readerName, readerCode);
return Response.ok(PojoUtils.initReaderEventRestPojo(readerEvent)).build();
}
@GET @GET
@Path("/LastEventusers") @Path("/LastEventusers")
public ReaderEventRestRoot getLastEventusers() public ReaderEventRestRoot getLastEventusers()
......
package fi.codecrew.moya.rest.apiapp.v1;
import java.nio.charset.Charset;
import java.security.Principal;
import java.util.Base64;
import javax.ejb.EJB;
import javax.enterprise.context.RequestScoped;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.*;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import fi.codecrew.moya.beans.ApiApplicationBeanLocal;
import fi.codecrew.moya.model.ApiApplication;
import fi.codecrew.moya.model.ApiApplicationInstance;
import fi.codecrew.moya.rest.pojo.userinfo.v1.ApiApplicationInstancePojo;
import fi.codecrew.moya.rest.pojo.userinfo.v1.UserPwdPojo;
import io.swagger.annotations.Api;
@RequestScoped
@Path("/apiapp/v1")
@Consumes({MediaType.APPLICATION_JSON})
@Produces({MediaType.APPLICATION_JSON + "; charset=UTF-8"})
@Api(value = "/apiapp/v1/", description = "Manage api application and keys")
public class ApiAppRestViewV1 {
private static final Logger logger = LoggerFactory.getLogger(ApiAppRestViewV1.class);
@Context
private HttpServletRequest servletRequest;
@EJB
private ApiApplicationBeanLocal apibean;
private static final String AUTH_HEADER = "authorization";
private static final String AUTH_PREFIX = "Basic ";
@POST
@Path("/createInstance/{appKey}")
//public Response createApiInstance(@PathParam("appKey") String appKey, @QueryParam("username") String username, @QueryParam("password") String password, @QueryParam("nonce") Long timestamp) {
public Response createApiInstance(@PathParam("appKey") String appKey) {
try {
Principal principal = servletRequest.getUserPrincipal();
// ensure logged out user
if (principal != null && principal.getName() != null) {
servletRequest.logout();
principal = null;
}
servletRequest.getSession(true);
String domain = servletRequest.getHeader("host");
String authHeader = servletRequest.getHeader(AUTH_HEADER);
logger.info("Got auth header {}", authHeader);
if (!authHeader.startsWith(AUTH_PREFIX)) {
return Response.status(Response.Status.FORBIDDEN).entity("No basic auth provided").build();
}
String[] splitAuth = new String(Base64.getDecoder().decode(authHeader.substring(AUTH_PREFIX.length()))).split(":", 2);
servletRequest.login(splitAuth[0] + "@" + domain, splitAuth[1]);
ApiApplication app = apibean.findApplication(appKey);
ApiApplicationInstance apiInstance = apibean.createApplicationInstance(app);
ApiApplicationInstancePojo ret = new ApiApplicationInstancePojo();
ret.setAuthname(apiInstance.getAuthname());
ret.setCreated(apiInstance.getCreated());
ret.setEnabled(apiInstance.isEnabled());
ret.setSecret(apiInstance.getSecretKey());
return Response.ok(ret).build();
} catch (ServletException e) {
logger.warn("Error logging in while creating ApiApplication instance");
return Response.serverError().entity(e.getCause()).build();
}
}
}
package fi.codecrew.moya.rest.appconfig.v1; package fi.codecrew.moya.rest.appconfig.v1;
import java.security.Principal;
import java.util.Base64;
import java.util.Date;
import javax.ejb.EJB; import javax.ejb.EJB;
import javax.enterprise.context.RequestScoped; import javax.enterprise.context.RequestScoped;
import javax.ws.rs.Consumes; import javax.servlet.ServletException;
import javax.ws.rs.GET; import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.Path; import javax.ws.rs.*;
import javax.ws.rs.Produces; import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response; import javax.ws.rs.core.Response;
import jdk.nashorn.internal.objects.annotations.Getter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import io.swagger.annotations.Api; import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse; import io.swagger.annotations.ApiResponse;
...@@ -16,7 +24,9 @@ import io.swagger.annotations.ApiResponse; ...@@ -16,7 +24,9 @@ import io.swagger.annotations.ApiResponse;
import fi.codecrew.moya.beans.EventBeanLocal; import fi.codecrew.moya.beans.EventBeanLocal;
import fi.codecrew.moya.beans.PermissionBeanLocal; import fi.codecrew.moya.beans.PermissionBeanLocal;
import fi.codecrew.moya.rest.PojoUtils; import fi.codecrew.moya.rest.PojoUtils;
import fi.codecrew.moya.rest.apiapp.v1.ApiAppRestViewV1;
import fi.codecrew.moya.rest.pojo.appconfig.v1.EventRoot; import fi.codecrew.moya.rest.pojo.appconfig.v1.EventRoot;
import fi.codecrew.moya.rest.pojo.userinfo.v1.UserPwdPojo;
/** /**
* Created by tuukka on 28.3.2015. * Created by tuukka on 28.3.2015.
...@@ -24,17 +34,59 @@ import fi.codecrew.moya.rest.pojo.appconfig.v1.EventRoot; ...@@ -24,17 +34,59 @@ import fi.codecrew.moya.rest.pojo.appconfig.v1.EventRoot;
@RequestScoped @RequestScoped
@Path("/appconfig/v1/eventinfo") @Path("/appconfig/v1/eventinfo")
@Consumes({ MediaType.APPLICATION_JSON }) @Consumes({MediaType.APPLICATION_JSON})
@Produces({ MediaType.APPLICATION_JSON + "; charset=UTF-8" }) @Produces({MediaType.APPLICATION_JSON + "; charset=UTF-8"})
@Api(value="/appconfig/v1/eventinfo", description = "Event information for application") @Api(value = "/appconfig/v1/eventinfo", description = "Event information for application")
public class EventInfoV1 { public class EventInfoV1 {
private static final Logger logger = LoggerFactory.getLogger(EventInfoV1.class);
@EJB private static final String AUTH_HEADER = "authorization";
PermissionBeanLocal permissionBean; private static final String AUTH_PREFIX = "Basic ";
@Context
private HttpServletRequest servletRequest;
@EJB
private PermissionBeanLocal permissionBean;
@EJB @EJB
EventBeanLocal eventBean; private EventBeanLocal eventBean;
@GET
@Path("/current")
public Response getCurrentEventInfo() {
return Response.ok(PojoUtils.parseEvent(eventBean.getCurrentEvent())).build();
}
@GET
@Path("/allevents")
public Response getEventsForUser() {
try {
String authHeader = servletRequest.getHeader(AUTH_HEADER);
if (authHeader == null || !authHeader.startsWith(AUTH_PREFIX)) {
return Response.status(Response.Status.FORBIDDEN).entity("No basic auth provided").build();
}
String authStr = new String(Base64.getDecoder().decode(authHeader.substring(AUTH_PREFIX.length())));
String[] splitAuth = authStr.split(":", 2);
Principal principal = servletRequest.getUserPrincipal();
// ensure logged out user
if (principal != null && principal.getName() != null) {
servletRequest.logout();
}
String domain = servletRequest.getHeader("host");
servletRequest.getSession(true);
servletRequest.login(splitAuth[0] + "@" + domain, splitAuth[1]);
return Response.ok(PojoUtils.parseEvents(eventBean.findAllEventsForCurrentUser())).build();
} catch (ServletException e) {
logger.warn("Error logging in while creating ApiApplication instance");
return Response.serverError().entity(e.getCause()).build();
}
}
@GET @GET
@Path("/listevents/") @Path("/listevents/")
...@@ -42,10 +94,11 @@ public class EventInfoV1 { ...@@ -42,10 +94,11 @@ public class EventInfoV1 {
@ApiResponse(code = 200, message = "Return events for current user") @ApiResponse(code = 200, message = "Return events for current user")
public Response getEventsForCurrentUser() { public Response getEventsForCurrentUser() {
if(permissionBean.getCurrentUser().isAnonymous()) { if (permissionBean.getCurrentUser().isAnonymous()) {
return Response.status(Response.Status.FORBIDDEN).build(); return Response.status(Response.Status.FORBIDDEN).build();
} }
return Response.ok(PojoUtils.parseEvents(eventBean.findFutureAndRunningEventsForCurrentUser())).build(); return Response.ok(PojoUtils.parseEvents(eventBean.findFutureAndRunningEventsForCurrentUser())).build();
} }
} }
...@@ -91,8 +91,7 @@ public class BortalCommand implements Command, Runnable { ...@@ -91,8 +91,7 @@ public class BortalCommand implements Command, Runnable {
@Override @Override
public void run() { public void run() {
BortalLocalContextHolder.copy(contextHolder); BortalLocalContextHolder.copy(contextHolder);
BortalLocalContextHolder.getInstance().executeLogin();
try { try {
logger.info("Created new bortalCommane"); logger.info("Created new bortalCommane");
outstream.write("Hello you..."); outstream.write("Hello you...");
...@@ -113,7 +112,7 @@ public class BortalCommand implements Command, Runnable { ...@@ -113,7 +112,7 @@ public class BortalCommand implements Command, Runnable {
outstream.flush(); outstream.flush();
returnValue = parseCommand(cmdBuilder.toString()); returnValue = parseCommand(cmdBuilder.toString());
outstream.write("[" + returnValue + "] " + BortalLocalContextHolder.getInstance().getLoginContext().getSubject().getPrincipals().iterator().next().getName() + " # "); //outstream.write("[" + returnValue + "] " + BortalLocalContextHolder.getInstance().getLoginContext().getSubject().getPrincipals().iterator().next().getName() + " # ");
outstream.flush(); outstream.flush();
cmdBuilder = new StringBuilder(); cmdBuilder = new StringBuilder();
...@@ -134,7 +133,6 @@ public class BortalCommand implements Command, Runnable { ...@@ -134,7 +133,6 @@ public class BortalCommand implements Command, Runnable {
e.printStackTrace(); e.printStackTrace();
} }
BortalLocalContextHolder.getInstance().executeLogout();
exitCallback.onExit(3); exitCallback.onExit(3);
} }
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!