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 1103 additions and 667 deletions
......@@ -18,7 +18,9 @@
*/
package fi.codecrew.moya;
public class AuthenticationResult {
import java.io.Serializable;
public class AuthenticationResult implements Serializable {
private String username = null;
private String usertype = null;
......
<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>
<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>
<dependency>
<groupId>org.glassfish.main.security</groupId>
......
......@@ -33,4 +33,8 @@ public interface ApiApplicationBeanLocal {
List<ApiApplication> findAllApplications();
ApiApplicationInstance createApplicationInstance(ApiApplication application);
ApiApplication findApplication(String appKey);
String findUsernameForApikey(String appkey, String userkey, String domain);
}
/*
* Copyright Codecrew Ry
*
*
* All rights reserved.
*
* This license applies to any software containing a notice placed by the
* copyright holder. Such software is herein referred to as the Software.
* This license covers modification, distribution and use of the Software.
*
* Any distribution and use in source and binary forms, with or without
* modification is not permitted without explicit written permission from the
* copyright owner.
*
* 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
* future versions of the Software.
*
*
* This license applies to any software containing a notice placed by the
* copyright holder. Such software is herein referred to as the Software.
* This license covers modification, distribution and use of the Software.
*
* Any distribution and use in source and binary forms, with or without
* modification is not permitted without explicit written permission from the
* copyright owner.
*
* 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
* future versions of the Software.
*
*/
package fi.codecrew.moya.beans;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import javax.annotation.security.DeclareRoles;
import javax.annotation.security.RolesAllowed;
import javax.ejb.EJB;
import javax.ejb.EJBException;
import javax.ejb.LocalBean;
import javax.ejb.Singleton;
......@@ -34,6 +36,7 @@ import fi.codecrew.moya.facade.EventUserFacade;
import fi.codecrew.moya.model.ApiApplication;
import fi.codecrew.moya.model.ApiApplicationInstance;
import fi.codecrew.moya.model.EventUser;
import fi.codecrew.moya.model.LanEvent;
import fi.codecrew.moya.utilities.PasswordFunctions;
import fi.codecrew.moya.utilities.moyamessage.MoyaEventType;
......@@ -76,14 +79,18 @@ public class ApiApplicationBean implements ApiApplicationBeanLocal {
@RolesAllowed(SpecialPermission.S_USER)
public ApiApplicationInstance createApplicationInstance(ApiApplication application) {
application = applicationFacade.reload(application);
// ugly as shit sanitation for eventName, sorry
String eventName = eventBean.getCurrentEvent().getName().replace(" ", "_").replace("ä", "a").replace("ö", "o")
.replace("Ä", "A").replace("Ö", "O").replace("å", "a").replace("Å", "A");
LanEvent currevent = eventBean.getCurrentEvent();
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) {
authname += "_";
// Ensure authname is unique;
final String origAuthname = authname;
for (int i = 2; instanceFacade.findInstance(application, authname, eventBean.getCurrentEvent()) != null; ++i) {
authname = origAuthname + "_" + i;
}
ApiApplicationInstance instance = new ApiApplicationInstance();
......@@ -91,19 +98,45 @@ public class ApiApplicationBean implements ApiApplicationBeanLocal {
instance.setApplication(application);
instance.setAuthname(authname);
instance.setName(application.getName() + " for user: " + permissionBean.getCurrentUser().getLogin());
instance.setCreated(Calendar.getInstance().getTime());
instance.setCreated(new Date());
instance.setEnabled(true);
instance.setEventuser(permissionBean.getCurrentUser());
instance.setSecretKey(PasswordFunctions.generateRandomString(30));
instanceFacade.create(instance);
loggingBean.sendMessage(MoyaEventType.APPLICATION_INSTANCE_CREATED,
"New applicationinstance created for software: ", application);
"New applicationinstance created for software: ", application);
return instance;
}
@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)
public List<ApiApplication> findMyApplications() {
EventUser curruser = permissionBean.getCurrentUser();
......
/*
* Copyright Codecrew Ry
*
*
* All rights reserved.
*
* This license applies to any software containing a notice placed by the
* copyright holder. Such software is herein referred to as the Software.
* This license covers modification, distribution and use of the Software.
*
* Any distribution and use in source and binary forms, with or without
* modification is not permitted without explicit written permission from the
* copyright owner.
*
* 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
* future versions of the Software.
*
*
* This license applies to any software containing a notice placed by the
* copyright holder. Such software is herein referred to as the Software.
* This license covers modification, distribution and use of the Software.
*
* Any distribution and use in source and binary forms, with or without
* modification is not permitted without explicit written permission from the
* copyright owner.
*
* 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
* future versions of the Software.
*
*/
package fi.codecrew.moya.beans;
......@@ -65,13 +65,10 @@ import fi.codecrew.moya.util.MailMessage;
*/
@Stateless
@LocalBean
@DeclareRoles({ UserPermission.S_WRITE_ROLES })
@DeclareRoles({UserPermission.S_WRITE_ROLES})
public class CardTemplateBean implements CardTemplateBeanLocal {
private static final Logger logger = LoggerFactory.getLogger(CardTemplateBean.class);
/**
......@@ -114,7 +111,6 @@ public class CardTemplateBean implements CardTemplateBeanLocal {
private CardCodeFacade cardCodeFacade;
// @Override
// @RolesAllowed("USER_MANAGEMENT/WRITE")
// public List<CardTemplate> findAll() {
......@@ -126,8 +122,7 @@ public class CardTemplateBean implements CardTemplateBeanLocal {
public void create(CardTemplate card) {
LanEvent currEv = eventBean.getCurrentEvent();
if (currEv.getCardTemplates() == null)
{
if (currEv.getCardTemplates() == null) {
currEv.setCardTemplates(new ArrayList<CardTemplate>());
}
card.setEvent(currEv);
......@@ -161,28 +156,28 @@ public class CardTemplateBean implements CardTemplateBeanLocal {
/**
* Checks users printed card roles and return the biggestCard
*
*
* @throws PermissionDeniedException
*/
@Override
public PrintedCard checkPrintedCard(EventUser user) {
logger.info("Checking printed card");
user = eventUserFacade.find(user.getId());
user = eventUserFacade.reload(user);
if (user == null)
return null;
LanEvent currEvent = eventBean.getCurrentEvent();
List<PrintedCard> myCards = printedcardfacade.getCards(user);
PrintedCard biggestCard = null;
for (PrintedCard card : myCards) {
if (card.getEnabled()) {
if (biggestCard == null || biggestCard.getTemplate().getPower() < card.getTemplate().getPower()) {
// The biggest card should be the only one enabled.
if (biggestCard != null) {
biggestCard.setEnabled(false);
}
biggestCard = card;
if (card.getEnabled() && biggestCard == null || biggestCard.getTemplate().getPower() < card.getTemplate().getPower()) {
// The biggest card should be the only one enabled.
if (biggestCard != null) {
biggestCard.setEnabled(false);
}
biggestCard = card;
}
}
......@@ -211,12 +206,11 @@ public class CardTemplateBean implements CardTemplateBeanLocal {
user.getPrintedCards().add(pc);
// printedcardfacade.create(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) {
MailMessage msg = new MailMessage();
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.setFromName("Lippukauppa");
......@@ -226,12 +220,12 @@ public class CardTemplateBean implements CardTemplateBeanLocal {
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);
return this.checkPrintedCard(user);
} 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;
......@@ -361,40 +355,35 @@ public class CardTemplateBean implements CardTemplateBeanLocal {
@Override
public PrintedCard setCardState(Integer cardId, CardState state) throws Exception {
PrintedCard card = printedcardfacade.find(cardId);
switch (state)
{
case PRINTED:
card.setPrintCount(card.getPrintCount() + 1);
card.setPrintTime(Calendar.getInstance());
break;
case PRINTING_IN_PROGRESS:
if (card.getCardState().equals(CardState.PRINTING_IN_PROGRESS)
switch (state) {
case PRINTED:
card.setPrintCount(card.getPrintCount() + 1);
card.setPrintTime(Calendar.getInstance());
break;
case PRINTING_IN_PROGRESS:
if (card.getCardState().equals(CardState.PRINTING_IN_PROGRESS)
|| card.getCardState().equals(CardState.PRINTED)) {
String response = "Unable to change type to PRINTING_IN_PROGRESS value is already {}" + card.getCardState();
logger.warn(response);
throw new Exception(response);
}
break;
default:
break;
String response = "Unable to change type to PRINTING_IN_PROGRESS value is already {}" + card.getCardState();
logger.warn(response);
throw new Exception(response);
}
break;
default:
break;
}
card.setCardState(state);
return card;
}
@Override
public EventUser giveCard(EventUser user, boolean markUserPlacesDelivered) {
user = eventUserFacade.reload(user);
PrintedCard card = checkPrintedCard(user);
if (card.getCardState() != CardState.DELIVERED) {
card.setCardState(CardState.DELIVERED);
} else {
......@@ -413,24 +402,24 @@ public class CardTemplateBean implements CardTemplateBeanLocal {
@Override
public void removeCardCode(CardCode code) {
code = cardCodeFacade.reload(code);
if(code.getPrintedCard().getCardCodes().contains(code)) {
if (code.getPrintedCard().getCardCodes().contains(code)) {
code.getPrintedCard().getCardCodes().remove(code);
}
cardCodeFacade.remove(code);
}
}
@Override
public CardTemplate removeCardTextData(CardTextData data) {
data = ctdFacade.reload(data);
CardTemplate template = data.getCardTemplate();
ctdFacade.remove(data);
return template;
}
@Override
public CardTemplate removeCardObjectData(CardObjectData data) {
data = codFacade.reload(data);
......@@ -454,6 +443,4 @@ public class CardTemplateBean implements CardTemplateBeanLocal {
}
}
......@@ -37,6 +37,7 @@ import org.slf4j.LoggerFactory;
import fi.codecrew.moya.enums.apps.EventPermission;
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.EventOrganiserFacade;
import fi.codecrew.moya.facade.LanEventDomainFacade;
......@@ -55,10 +56,12 @@ import fi.codecrew.moya.model.LanEventPropertyKey;
*/
@Stateless
@LocalBean
@DeclareRoles({ EventPermission.S_MANAGE_PRIVATE_PROPERTIES,
EventPermission.S_MANAGE_PROPERTIES,
EventPermission.S_MANAGE_EVENT,
SpecialPermission.S_SUPERADMIN,
@DeclareRoles({
EventPermission.S_MANAGE_PRIVATE_PROPERTIES,
EventPermission.S_MANAGE_PROPERTIES,
EventPermission.S_MANAGE_EVENT,
SpecialPermission.S_SUPERADMIN,
SpecialPermission.S_USER
})
public class EventBean implements EventBeanLocal {
......@@ -158,7 +161,7 @@ public class EventBean implements EventBeanLocal {
}
@Override
@RolesAllowed({ SpecialPermission.S_SUPERADMIN, EventPermission.S_MANAGE_EVENT })
@RolesAllowed({SpecialPermission.S_SUPERADMIN, EventPermission.S_MANAGE_EVENT})
public LanEvent mergeChanges(LanEvent event) {
if (!permbean.hasPermission(SpecialPermission.SUPERADMIN) && !getCurrentEvent().equals(event)) {
throw new EJBAccessException("Trying to save another event.");
......@@ -167,7 +170,7 @@ public class EventBean implements EventBeanLocal {
}
@Override
@RolesAllowed({ SpecialPermission.S_SUPERADMIN, EventPermission.S_MANAGE_EVENT })
@RolesAllowed({SpecialPermission.S_SUPERADMIN, EventPermission.S_MANAGE_EVENT})
public void create(LanEvent event) {
eventFacade.create(event);
......@@ -181,7 +184,7 @@ public class EventBean implements EventBeanLocal {
}
@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() {
return eventPrivatePropertyFacade.findAllForEvent();
}
......@@ -211,8 +214,7 @@ public class EventBean implements EventBeanLocal {
}
@Override
public long getPropertyLong(LanEventPropertyKey property)
{
public long getPropertyLong(LanEventPropertyKey property) {
LanEventProperty retProp = eventPropertyFacade.find(getCurrentEvent(), property);
long ret = 0;
if (retProp == null) {
......@@ -224,8 +226,7 @@ public class EventBean implements EventBeanLocal {
}
@Override
public String getPropertyString(LanEventPropertyKey property)
{
public String getPropertyString(LanEventPropertyKey property) {
LanEventProperty retProp = eventPropertyFacade.find(getCurrentEvent(), property);
String ret = null;
if (retProp == null) {
......@@ -255,10 +256,11 @@ public class EventBean implements EventBeanLocal {
}
@Override
@RolesAllowed({ SpecialPermission.S_SUPERADMIN, EventPermission.S_MANAGE_EVENT })
@RolesAllowed({SpecialPermission.S_SUPERADMIN, EventPermission.S_MANAGE_EVENT})
public LanEventProperty saveOrCreateProperty(LanEventProperty property) {
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) {
ret = property;
......@@ -270,8 +272,7 @@ public class EventBean implements EventBeanLocal {
}
event.getProperties().add(property);
}
else {
} else {
ret = eventPropertyFacade.merge(property);
}
return ret;
......@@ -279,16 +280,17 @@ public class EventBean implements EventBeanLocal {
}
@Override
@RolesAllowed({ SpecialPermission.S_SUPERADMIN, EventPermission.S_MANAGE_EVENT })
@RolesAllowed({SpecialPermission.S_SUPERADMIN, EventPermission.S_MANAGE_EVENT})
public EventOrganiser mergeChanges(EventOrganiser eventorg) {
return eventOrganiserFacade.merge(eventorg);
}
@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) {
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) {
ret = privateProperty;
......@@ -320,7 +322,7 @@ public class EventBean implements EventBeanLocal {
}
@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) {
property = eventPrivatePropertyFacade.reload(property);
LanEvent event = property.getEvent();
......@@ -335,14 +337,15 @@ public class EventBean implements EventBeanLocal {
}
@Override
@RolesAllowed({SpecialPermission.S_USER})
public List<LanEvent> findAllEventsForCurrentUser() {
return eventFacade.findAll(permbean.getCurrentUser().getUser());
}
@Override
@RolesAllowed({SpecialPermission.S_USER})
public List<LanEvent> findFutureAndRunningEventsForCurrentUser() {
List<LanEvent> events = findAllEventsForCurrentUser();
List<LanEvent> retlist = new ArrayList<>();
......@@ -351,19 +354,18 @@ public class EventBean implements EventBeanLocal {
tmp.add(Calendar.DAY_OF_MONTH, -5);
Date compareDate = tmp.getTime();
for(LanEvent event : events) {
for (LanEvent event : events) {
if(event.getEndTime() == null) {
if (event.getEndTime() == null) {
retlist.add(event);
continue;
}
if(event.getEndTime().compareTo(compareDate) > 0) {
if (event.getEndTime().compareTo(compareDate) > 0) {
retlist.add(event);
}
}
return retlist;
}
......
......@@ -174,6 +174,9 @@ public class PermissionBean implements PermissionBeanLocal {
@Override
public EventUser getCurrentUser() {
LanEvent event = eventbean.getEventForHostname(getPrincipalDomain());
if (event == null) {
throw new EJBException("Could not find event for current user");
}
EventUser ret = eventUserFacade.findByLogin(getPrincipalName(), event);
if (ret == null) {
ret = getAnonEventUser();
......
......@@ -413,7 +413,7 @@ public class PlaceBean implements PlaceBeanLocal {
}
}
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);
......
......@@ -107,7 +107,7 @@ public class ReaderBean implements ReaderBeanLocal {
/**
* 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.
*/
if (ReaderType.RFID.equals(reader.getType())) {
......@@ -138,8 +138,8 @@ public class ReaderBean implements ReaderBeanLocal {
if (lastevent.getValue().equals(event.getValue()) && (lastevent.getUpdatetime().getTime() + 60000l) > event.getTime().getTime()) {
lastevent = readerEventFacade.reload(lastevent);
lastevent = readerEventFacade.merge(lastevent);
//lastevent = readerEventFacade.reload(lastevent);
//lastevent = readerEventFacade.merge(lastevent);
return lastevent; // todo: update lastevent bfore return
}
......@@ -210,8 +210,9 @@ public class ReaderBean implements ReaderBeanLocal {
cardCodeFacade.create(code);
card.getCardCodes().add(code);
cardCodeFacade.flush();
return readerEvent;
return checkCode(readerEvent.getReader(), readerEvent.getValue());
}
@Override
......
......@@ -36,25 +36,39 @@ public class BasicAuthPBean extends ApiAuth implements AuthenticationFormat {
@EJB
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
public AuthenticationResult authenticate(String jaasUsername, String password) {
public AuthenticationResult authenticate(final String username, final String password) {
AuthenticationResult ret = null;
String username = UserLoginUtils.getUsernameFromJaasString(jaasUsername);
String domain = UserLoginUtils.getDomainFromJaasString(jaasUsername);
LanEvent event = eventbean.getEventForHostname(domain);
//String username = UserLoginUtils.getUsernameFromJaasString(jaasUsername);
if ((username == null || username.isEmpty()) && password.startsWith(HEADER_PREFIX)) {
if (password.startsWith(HEADER_PREFIX)) {
ret = new AuthenticationResult();
ret.setUsertype(UserType.REST.name());
try {
String domain = UserLoginUtils.getDomainFromJaasString(username);
LanEvent event = eventbean.getEventForHostname(domain);
String[] pwdsplit = password.split(" ");
if (pwdsplit.length != 2) {
logger.warn("Rest auth with Basic failed because pwdsplit != 2: user '{}', password '{}'", username,
password);
logger.warn("Rest auth with Basic failed because pwdsplit != 2: user '{}''", username );
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;
}
String authStr = new String(Base64.getDecoder().decode(pwdsplit[1]), UTF8);
String[] splitStr = authStr.split(PASSWORD_DELIMITER);
if (splitStr.length != 4 || !PASSWORD_PREFIX.equals(splitStr[0])) {
logger.warn(
......@@ -68,11 +82,11 @@ public class BasicAuthPBean extends ApiAuth implements AuthenticationFormat {
ApiApplicationInstance appInstance = verifyAppInstance(appId, userId, event);
if (appInstance != null && appKey != null && !appKey.isEmpty() && appKey.equals(appInstance.getSecretKey())) {
ret.setUsername(getUsername(appInstance) + '@' + domain);
ret.setUsername(username);
}
} catch (Exception e) {
ret = null;
logger.warn("Invalid base64 string on Rest Basic auth: " + password, e);
}
}
return ret;
......
......@@ -35,7 +35,10 @@ public class RestMacAuthPBean extends ApiAuth implements AuthenticationFormat {
if ((username == null || username.isEmpty()) && password.startsWith(JaasBeanLocal.REST_PREFIX)) {
ret = new AuthenticationResult();
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;
}
......
/*
* Copyright Codecrew Ry
*
*
* All rights reserved.
*
* This license applies to any software containing a notice placed by the
* copyright holder. Such software is herein referred to as the Software.
* This license covers modification, distribution and use of the Software.
*
* Any distribution and use in source and binary forms, with or without
* modification is not permitted without explicit written permission from the
* copyright owner.
*
* 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
* future versions of the Software.
*
*
* This license applies to any software containing a notice placed by the
* copyright holder. Such software is herein referred to as the Software.
* This license covers modification, distribution and use of the Software.
*
* Any distribution and use in source and binary forms, with or without
* modification is not permitted without explicit written permission from the
* copyright owner.
*
* 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
* future versions of the Software.
*
*/
package fi.codecrew.moya.facade;
......@@ -45,4 +45,16 @@ public class ApiApplicationInstanceFacade extends IntegerPkGenericFacade<ApiAppl
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 @@
<artifactId>moya-restpojo</artifactId>
<!-- 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 -->
<version>1.2.1</version>
<version>1.2.4</version>
<distributionManagement>
<downloadUrl>http://codecrew.fi/mvn</downloadUrl>
<repository>
......
......@@ -23,7 +23,6 @@ public class ApplicationInstancePojo {
}
@XmlElement()
public String getSecretKey() {
return secretKey;
......@@ -34,11 +33,6 @@ public class ApplicationInstancePojo {
}
@XmlElement()
public String getName() {
return name;
......
......@@ -4,6 +4,8 @@ package fi.codecrew.moya.rest.pojo.appconfig.v1;
import io.swagger.annotations.ApiModel;
import javax.xml.bind.annotation.XmlElement;
import java.util.Date;
import java.util.List;
/**
......@@ -15,6 +17,7 @@ public class EventPojo {
private Integer lanEventId;
private String name;
private List<String> urls;
private Date startTime;
@XmlElement
public Integer getLanEventId() {
......@@ -42,4 +45,12 @@ public class EventPojo {
public void setUrls(List<String> 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;
@ApiModel
public class ReaderEventRestPojo {
private EventUserRestPojo eventUser;
private PrintedCardRestPojo printedCard;
......@@ -40,32 +41,32 @@ public class ReaderEventRestPojo {
public ReaderEventRestPojo() {
}
@XmlElement(name = "eventuser")
@XmlElement(name = "eventuser", nillable = true)
public EventUserRestPojo getEventuser() {
return eventUser;
}
@XmlElement(name = "readerEventId")
@XmlElement(name = "readerEventId", nillable = false)
public Integer getEventId() {
return readerEventId;
}
@XmlElement(name = "readerEventTime")
@XmlElement(name = "readerEventTime", nillable = true)
public Date getReaderEventTime() {
return readerEventTime;
}
@XmlElement(name = "readerId")
@XmlElement(name = "readerId", nillable = false)
public Integer getReaderId() {
return readerId;
}
@XmlElement(name = "printedCardId")
@XmlElement(name = "printedCardId", nillable = true)
public Integer getPrintedCardId() {
return printedCardId;
}
@XmlElement(name = "printedCardState")
@XmlElement(name = "printedCardState", nillable = true)
public String getPrintedCardState() {
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
*
*
* All rights reserved.
*
* This license applies to any software containing a notice placed by the
* copyright holder. Such software is herein referred to as the Software.
* This license covers modification, distribution and use of the Software.
*
* Any distribution and use in source and binary forms, with or without
* modification is not permitted without explicit written permission from the
* copyright owner.
*
* 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
* future versions of the Software.
*
*
* This license applies to any software containing a notice placed by the
* copyright holder. Such software is herein referred to as the Software.
* This license covers modification, distribution and use of the Software.
*
* Any distribution and use in source and binary forms, with or without
* modification is not permitted without explicit written permission from the
* copyright owner.
*
* 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
* future versions of the Software.
*
*/
package fi.codecrew.moya.utilities;
......@@ -32,23 +32,23 @@ public class JsonUtils {
/**
* Gets a sub object from a JsonObject. Returns an empty object if not
* found.
*
*
* @param jsonObject
* @param path
* @return
*/
public static JsonValue getSubObject(JsonObject jsonObject,
List<String> path) {
public static JsonValue getSubObject(JsonObject jsonObject, List<String> path) {
JsonValue sub = jsonObject;
// Burrow into object hierarchy
for (String s : path) {
if (sub.getValueType() == ValueType.OBJECT) {
if (sub != null && sub.getValueType() == ValueType.OBJECT) {
JsonObject subObject = (JsonObject) sub;
sub = subObject.get(s);
} else {
// Trying to get sub-object of something not an object. Bad.
return null;
sub = null;
break;
}
}
......@@ -62,16 +62,13 @@ public class JsonUtils {
/**
* Adds or alters one key in JsonObject
*
*
* @param jsonObject
* @param key
* which key to add/alter
* @param value
* The value associate to the key
* @param key which key to add/alter
* @param value The value associate to the key
* @return JsonObject with the key:value pair added
*/
public static JsonObject assocJsonObject(JsonObject jsonObject, String key,
JsonValue value) {
public static JsonObject assocJsonObject(JsonObject jsonObject, String key, JsonValue value) {
JsonObjectBuilder builder = Json.createObjectBuilder();
// Copy all non conflicting json entries
......@@ -90,15 +87,13 @@ public class JsonUtils {
/**
* Goes into a json object and sets subobject assocInJsonObject("{}",
* ["foo", "bar"], "{\"a\":\"b\"}") => {\"foo\":{\"bar\":{\"a\":\"b\"}}}
*
*
* @param jsonObject
* @param keys
* path inside key hierarchy
* @param keys path inside key hierarchy
* @param value
* @return JsonObject with the value added
*/
public static JsonObject assocInJsonObject(JsonObject jsonObject,
List<String> keys, JsonValue value) {
public static JsonObject assocInJsonObject(JsonObject jsonObject, List<String> keys, JsonValue value) {
// Recurse?
if (keys.size() > 1) {
......@@ -106,7 +101,7 @@ public class JsonUtils {
List<String> restKeys = keys.subList(1, keys.size());
JsonObject subObj = jsonObject.getJsonObject(firstKey);
return assocJsonObject(jsonObject, firstKey,
assocInJsonObject(subObj, restKeys, value));
assocInJsonObject(subObj, restKeys, value));
}
// End?
......@@ -114,9 +109,7 @@ public class JsonUtils {
return assocJsonObject(jsonObject, firstKey, value);
}
public static JsonObject alterSubObject(JsonObject jsonObject,
List<String> path, JsonObject subObject) {
public static JsonObject alterSubObject(JsonObject jsonObject, List<String> path, JsonObject subObject) {
return assocInJsonObject(jsonObject, path, subObject);
}
}
......@@ -32,6 +32,12 @@ public class UserLoginUtils {
}
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 @@
<dependency>
<groupId>fi.codecrew.moya</groupId>
<artifactId>moya-restpojo</artifactId>
<version>1.2.1</version>
<version>1.2.4</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
......
......@@ -21,6 +21,7 @@ package fi.codecrew.moya;
import java.io.IOException;
import java.nio.charset.Charset;
import java.security.Principal;
import java.util.Base64;
import javax.ejb.EJB;
import javax.faces.application.ProjectStage;
......@@ -36,15 +37,12 @@ import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import fi.codecrew.moya.beans.*;
import fi.codecrew.moya.utilities.UserLoginUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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.model.User;
import fi.codecrew.moya.rest.RestApplicationEntrypoint;
......@@ -67,6 +65,9 @@ public class HostnameFilter implements Filter {
@EJB
private LoggingBeanLocal logbean;
@EJB
private ApiApplicationBeanLocal apibean;
@Override
public void init(FilterConfig config) throws ServletException {
// check if software is in development -mode
......@@ -145,7 +146,12 @@ public class HostnameFilter implements Filter {
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)
......@@ -165,11 +171,14 @@ public class HostnameFilter implements Filter {
try {
httpRequest = (HttpServletRequest) request;
insertServerLoggingContext(httpRequest, authtype);
logger.info("Logging in with username {} and password {}, remote {}, authtype: {}", httpRequest.getUserPrincipal(), httpRequest.getRemoteUser(), httpRequest.getAuthType());
String hostname = parseHostname(httpRequest);
if (httpRequest.getUserPrincipal() == null) {
// Check if we are logging in with rest
if (RestApplicationEntrypoint.REST_PATH.equals(httpRequest.getServletPath())) {
// Check if we are can login in with rest alternative methods ( appkey, basic auth, etc.. )
if (RestApplicationEntrypoint.REST_PATH.equals(httpRequest.getServletPath())
|| "/dydata".equals(httpRequest.getServletPath())) {
authtype = AuthType.REST;
if (!restAuth(httpRequest, response)) {
......@@ -240,20 +249,45 @@ public class HostnameFilter implements Filter {
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();
hashBuilder.append(JaasBeanLocal.REST_PREFIX);
hashBuilder.append(httpRequest.getParameter("appkey")).append(":");
hashBuilder.append(httpRequest.getParameter("appuser")).append(":");
hashBuilder.append(appkey).append(":");
hashBuilder.append(userkey).append(":");
hashBuilder.append(httpRequest.getParameter("appstamp")).append(":");
hashBuilder.append(httpRequest.getParameter("appmac")).append(":");
hashBuilder.append(httpRequest.getPathInfo());
restAuthStr = hashBuilder.toString();
}
boolean ret = true;
String domain = parseHostname(httpRequest);
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) {
ret = false;
logger.info("Rest api authentication failed for path " + httpRequest.getPathInfo() + " "
......@@ -281,18 +315,20 @@ public class HostnameFilter implements Filter {
scheme = url.substring(0, 5).toLowerCase();
}
String userDomain = UserLoginUtils.getDomainFromJaas(httpRequest.getUserPrincipal());
if (!hostname.equals(userDomain)) {
Principal principal = httpRequest.getUserPrincipal();
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,
"Hostname mismatch privilege escalation! User '", httpRequest.getUserPrincipal(), "' tried to change hostname from '",
userDomain, "' to '", hostname, ",");
throw new RuntimeException("Hostname mismatch!");
logbean.sendMessage(MoyaEventType.USER_PERMISSION_VIOLATION,
"Hostname mismatch privilege escalation! User '", httpRequest.getUserPrincipal(), "' tried to change hostname from '",
userDomain, "' to '", hostname, ",");
throw new RuntimeException("Hostname mismatch! Expected: " + hostname + " but logged in as " + userDomain);
}
}
BortalLocalContextHolder.setHostname(hostname);
BortalLocalContextHolder.setInDevelopmentMode(developmentMode);
return hostname;
......
......@@ -27,8 +27,7 @@ import fi.codecrew.moya.rest.pojo.userinfo.v1.UserReservationPlacePojo;
import fi.codecrew.moya.rest.pojo.util.v1.ErrorRoot;
public class PojoUtils {
public static EventUserRestPojo initEventUserRestPojo(EventUser user)
{
public static EventUserRestPojo initEventUserRestPojo(EventUser user) {
EventUserRestPojo ret = new EventUserRestPojo();
ret.setNick(user.getUser().getNick());
ret.setLogin(user.getUser().getLogin());
......@@ -49,8 +48,7 @@ public class PojoUtils {
}
public static PrintedCardRestPojo initPrintedCardRestPojo(PrintedCard card)
{
public static PrintedCardRestPojo initPrintedCardRestPojo(PrintedCard card) {
PrintedCardRestPojo ret = new PrintedCardRestPojo();
ret.setEventuserId(card.getUser().getId());
ret.setId(card.getId());
......@@ -66,8 +64,7 @@ public class PojoUtils {
return ret;
}
public static CardRoot parsePrintedCards(List<PrintedCard> cards)
{
public static CardRoot parsePrintedCards(List<PrintedCard> cards) {
ArrayList<PrintedCardRestPojo> ret = new ArrayList<PrintedCardRestPojo>();
for (PrintedCard c : cards) {
ret.add(initPrintedCardRestPojo(c));
......@@ -98,17 +95,15 @@ public class PojoUtils {
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
Calendar relTime = Calendar.getInstance();
relTime.add(relTime.HOUR, 4);
if(place.getReserveTime() != null)
ret.setReleaseTime(relTime);
else
ret.setReleaseTime(null);
relTime.add(relTime.HOUR, 4);
if (place.getReserveTime() != null)
ret.setReleaseTime(relTime);
else
ret.setReleaseTime(null);
if (place.getMap() != null) {
......@@ -156,7 +151,7 @@ public class PojoUtils {
public static ReaderEventRestPojo initReaderEventRestPojo(ReaderEvent event) {
ReaderEventRestPojo ret = new ReaderEventRestPojo();
if ( event.getPrintedCard() != null) {
if (event.getPrintedCard() != null) {
if (event.getPrintedCard().getUser() != null) {
ret.setEventUser(PojoUtils.initEventUserRestPojo(event.getPrintedCard().getUser()));
}
......@@ -186,8 +181,7 @@ public class PojoUtils {
return ret;
}
public static ReaderRestPojo initReaderRestPojo(Reader reader)
{
public static ReaderRestPojo initReaderRestPojo(Reader reader) {
ReaderRestPojo ret = new ReaderRestPojo();
ret.setReaderId(reader.getId());
ret.setIdentification(reader.getIdentification());
......@@ -217,8 +211,7 @@ public class PojoUtils {
return ret;
}
public static ProductRestPojo initProductRestPojo(Product product)
{
public static ProductRestPojo initProductRestPojo(Product product) {
ProductRestPojo ret = new ProductRestPojo();
ret.setId(product.getId());
ret.setName(product.getName());
......@@ -233,8 +226,7 @@ public class PojoUtils {
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();
ArrayList<SimplePlacePojo> placeList = new ArrayList<>();
ret.setPlaces(placeList);
......@@ -251,41 +243,40 @@ public class PojoUtils {
ret.setName(p.getName());
String state = null;
if(hasPermissionViewAllusers) {
if(p.getPlaceReserver() != null) {
if(p.getPlaceReserver().getUser() != null) {
if (hasPermissionViewAllusers) {
if (p.getPlaceReserver() != null) {
if (p.getPlaceReserver().getUser() != null) {
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());
}
}
}
switch (p.getState(user))
{
switch (p.getState(user)) {
case DISABLED:
state = (onlyHilightPlaces)?"F":"D";
state = (onlyHilightPlaces) ? "F" : "D";
break;
case FREE:
state = "F";
break;
case LOCKED:
state = (onlyHilightPlaces)?"F":"L";
state = (onlyHilightPlaces) ? "F" : "L";
break;
case MY_PLACE:
state = "P";
break;
case RESERVED:
state = (onlyHilightPlaces)?"F":"R";
state = (onlyHilightPlaces) ? "F" : "R";
break;
case TEMP_RESERVED_FORME:
state = (onlyHilightPlaces)?"F":"T";
state = (onlyHilightPlaces) ? "F" : "T";
break;
default:
break;
}
if(onlyHilightPlaces) {
if (onlyHilightPlaces) {
}
......@@ -321,23 +312,28 @@ public class PojoUtils {
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) {
EventRoot root = new EventRoot();
ArrayList<EventPojo> eventPojos = new ArrayList<>();
for(LanEvent event : events) {
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);
eventPojos.add(pojo);
for (LanEvent event : events) {
eventPojos.add(parseEvent(event));
}
root.setEvents(eventPojos);
......@@ -356,11 +352,11 @@ public class PojoUtils {
return pojo;
}
public static ErrorRoot initErrorPojo(String errorMessage) {
ErrorRoot errorRoot = new ErrorRoot();
errorRoot.setError(errorMessage);
return errorRoot;
}
public static ErrorRoot initErrorPojo(String errorMessage) {
ErrorRoot errorRoot = new ErrorRoot();
errorRoot.setError(errorMessage);
return errorRoot;
}
}
......@@ -22,11 +22,7 @@ import java.util.List;
import javax.ejb.EJB;
import javax.enterprise.context.RequestScoped;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.ResponseBuilder;
......@@ -86,6 +82,15 @@ public class ReaderRestView {
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
@Path("/LastEventusers")
public ReaderEventRestRoot getLastEventusers()
......
/*
* Copyright Codecrew Ry
*
*
* All rights reserved.
*
* This license applies to any software containing a notice placed by the
* copyright holder. Such software is herein referred to as the Software.
* This license covers modification, distribution and use of the Software.
*
* Any distribution and use in source and binary forms, with or without
* modification is not permitted without explicit written permission from the
* copyright owner.
*
* 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
* future versions of the Software.
*
*
* This license applies to any software containing a notice placed by the
* copyright holder. Such software is herein referred to as the Software.
* This license covers modification, distribution and use of the Software.
*
* Any distribution and use in source and binary forms, with or without
* modification is not permitted without explicit written permission from the
* copyright owner.
*
* 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
* future versions of the Software.
*
*/
package fi.codecrew.moya.rest;
......@@ -43,6 +43,7 @@ import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.ResponseBuilder;
import javax.ws.rs.core.Response.Status;
import fi.codecrew.moya.model.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
......@@ -59,12 +60,6 @@ import fi.codecrew.moya.beans.TicketBeanLocal;
import fi.codecrew.moya.beans.UserBeanLocal;
import fi.codecrew.moya.entitysearch.UserSearchQuery;
import fi.codecrew.moya.enums.apps.UserPermission;
import fi.codecrew.moya.model.EventUser;
import fi.codecrew.moya.model.GroupMembership;
import fi.codecrew.moya.model.Place;
import fi.codecrew.moya.model.ReaderEvent;
import fi.codecrew.moya.model.User;
import fi.codecrew.moya.model.UserImage;
import fi.codecrew.moya.rest.pojo.userinfo.v1.EventUserRestPojo;
import fi.codecrew.moya.rest.pojo.userinfo.v1.PrintedCardRestPojo;
import fi.codecrew.moya.rest.pojo.userinfo.v1.SimpleEventuserRoot;
......@@ -75,8 +70,8 @@ import fi.codecrew.moya.utilities.SearchResult;
@RequestScoped
@Path("/user")
@Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
@Produces({ MediaType.APPLICATION_JSON + "; charset=UTF-8" })
@Consumes({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
@Produces({MediaType.APPLICATION_JSON + "; charset=UTF-8"})
@Api(value = "/user", description = "Administer users")
public class UserRestView {
......@@ -108,10 +103,10 @@ public class UserRestView {
@POST
@Path("/giveplace/{placeId}")
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
@ApiOperation(value = "Set place status to give/ungive", response = UserReservationPlacePojo.class)
@ApiOperation(value = "Set place status to give/ungive", response = UserReservationPlacePojo.class)
public Response setPlacesGivenStatus(
@PathParam("placeId") Integer id,
@FormParam("action") String status) {
@PathParam("placeId") Integer id,
@FormParam("action") String status) {
Place place = placebean.find(id);
if (place == null) {
......@@ -129,17 +124,17 @@ public class UserRestView {
ResponseBuilder resp = Response.ok();
switch (status) {
case "give":
gm = placegroupbean.markGroupMembershipEntered(gm);
break;
case "ungive":
gm = placegroupbean.markGroupMembershipNotEntered(gm);
break;
default:
resp = Response.status(Status.BAD_REQUEST);
resp.status(Status.BAD_REQUEST);
resp.entity("Unknown status" + status + " possible values: 'give' and 'ungive'");
return resp.build();
case "give":
gm = placegroupbean.markGroupMembershipEntered(gm);
break;
case "ungive":
gm = placegroupbean.markGroupMembershipNotEntered(gm);
break;
default:
resp = Response.status(Status.BAD_REQUEST);
resp.status(Status.BAD_REQUEST);
resp.entity("Unknown status" + status + " possible values: 'give' and 'ungive'");
return resp.build();
}
......@@ -150,38 +145,39 @@ public class UserRestView {
@GET
@Path("/reservationswithcode/{code}")
@ApiOperation(value = "Get places with code", response = UserReservationRoot.class)
@ApiOperation(value = "Get places with code", response = UserReservationRoot.class)
public Response getPlacesWithCode(@PathParam("code") String code) {
try {
try {
EventUser curruser = permbean.getCurrentUser();
ReaderEvent revent = readerbean.checkCode("restapi: " + curruser.getLogin(), code);
EventUser curruser = permbean.getCurrentUser();
if (revent != null && revent.getUser() != null) {
EventUser eu = revent.getUser();
List<GroupMembership> gms = ticketbean.findMembershipPrintlistForUser(eu);
ReaderEvent revent = readerbean.checkCode("restapi: " + curruser.getLogin(), code);
UserReservationRoot ret = new UserReservationRoot();
ret.setUser(PojoUtils.initEventUserRestPojo(eu));
if (revent != null && revent.getUser() != null) {
EventUser eu = revent.getUser();
List<GroupMembership> gms = ticketbean.findMembershipPrintlistForUser(eu);
for (GroupMembership g : gms) {
UserReservationRoot ret = new UserReservationRoot();
ret.setUser(PojoUtils.initEventUserRestPojo(eu));
ret.getReservations().add(PojoUtils.initUserReservationPlace(g));
}
return Response.ok(ret).build();
}
return Response.status(Status.NOT_FOUND).build();
for (GroupMembership g : gms) {
} catch (Exception e) {
logger.error("Getting places failed", e);
return Response.serverError().build();
}
ret.getReservations().add(PojoUtils.initUserReservationPlace(g));
}
return Response.ok(ret).build();
}
return Response.status(Status.NOT_FOUND).build();
} catch (Exception e) {
logger.error("Getting places failed", e);
return Response.serverError().build();
}
}
@GET
@Path("/{userid}/reservations")
@ApiOperation(value = "Get user's reservations", response = UserReservationRoot.class)
@ApiOperation(value = "Get user's reservations", response = UserReservationRoot.class)
public Response usersPlaces(@PathParam("userid") Integer userid) {
EventUser eu = userbean.findByUserId(userid, false);
if (eu != null) {
......@@ -200,12 +196,12 @@ public class UserRestView {
@POST
@Path("/auth")
@Produces({ MediaType.APPLICATION_JSON })
@Produces({MediaType.APPLICATION_JSON})
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
@ApiOperation(value = "Authenticate", response = EventUserRestPojo.class)
@ApiOperation(value = "Authenticate", response = EventUserRestPojo.class)
public Response auth(
@FormParam("username") String username,
@FormParam("password") String password) {
@FormParam("username") String username,
@FormParam("password") String password) {
logger.info("Tried to login with rest {} , {}", username, password);
boolean success = true;
try {
......@@ -243,30 +239,36 @@ public class UserRestView {
@Path("/eventusers")
@ApiOperation(value = "Get EventUsers", response = SimpleEventuserRoot.class)
public SimpleEventuserRoot getEventUsers(
@DefaultValue("0") @QueryParam("pagesize") Integer pagesize,
@DefaultValue("0") @QueryParam("page") Integer page,
@QueryParam("search") String search
) {
@DefaultValue("0") @QueryParam("pagesize") Integer pagesize,
@DefaultValue("0") @QueryParam("page") Integer page,
@QueryParam("search") String search
) {
try {
try {
UserSearchQuery q = new UserSearchQuery(page, pagesize, null, search, QuerySortOrder.UNSORTED);
SearchResult<EventUser> users = userbean.getThisEventsUsers(q);
return PojoUtils.parseEventusers(users.getResults());
UserSearchQuery q = new UserSearchQuery(page, pagesize, null, search, QuerySortOrder.UNSORTED);
SearchResult<EventUser> users = userbean.getThisEventsUsers(q);
return PojoUtils.parseEventusers(users.getResults());
} catch (Exception e) {
logger.error("Getting EventUsers failed", e);
throw e;
}
} catch (Exception e) {
logger.error("Getting EventUsers failed", e);
throw e;
}
}
@GET
@Path("/card/{eventuserId}")
@ApiOperation(value = "Get PrintedCard for EventUser", response = PrintedCardRestPojo.class)
public PrintedCardRestPojo getUsersCard(
@ApiParam("EventUser entity ID") @PathParam("eventuserId") Integer eventuserid) {
@ApiParam("EventUser entity ID") @PathParam("eventuserId") Integer eventuserid) {
EventUser user = userbean.findByEventUserId(eventuserid);
return PojoUtils.initPrintedCardRestPojo(cardbean.checkPrintedCard(user));
logger.warn("users card for user: {}", user);
PrintedCard card = cardbean.checkPrintedCard(user);
if (card == null) {
return null;
}
return PojoUtils.initPrintedCardRestPojo(card);
}
......@@ -274,7 +276,7 @@ public class UserRestView {
@Path("/eventuser/{cardauthcode}")
@ApiOperation(value = "Get EventUser by cardAuthCode", response = EventUserRestPojo.class)
public EventUserRestPojo getEventUser(
@ApiParam("Card authentication code") @PathParam("cardauthcode") String code) {
@ApiParam("Card authentication code") @PathParam("cardauthcode") String code) {
EventUser user = userbean.getUserByAuthcode(code);
if (user != null)
......@@ -283,123 +285,139 @@ public class UserRestView {
return new EventUserRestPojo();
}
@GET
@Path("/")
@Produces({ MediaType.APPLICATION_JSON })
@ApiOperation(value = "Find event user", response = EventUserRestPojo.class)
public Response getEventUser(@QueryParam("email") @ApiParam("Email address") String email,
@QueryParam("login") @ApiParam("Username") String userName) {
try {
if (permbean.hasPermission(UserPermission.VIEW_ALL) == false) {
return Response.status(Status.FORBIDDEN).build();
}
EventUser eventUser;
User user = null;
// If username not given, try to find username by email
if (userName == null || userName.isEmpty()) {
user = userbean.findUserByEmailUsername(email);
}
if(user != null) {
eventUser = userbean.getEventUser(user, true);
} else {
// Get the user
eventUser = userbean.findEventuserByLogin(userName);
}
if (eventUser == null) {
return Response.status(Status.NOT_FOUND).build();
}
// Return the EventUser
return Response.ok(PojoUtils.initEventUserRestPojo(eventUser)).build();
} catch (Exception e) {
logger.error("Finding event user failed", e);
return Response.serverError().build();
}
}
@POST
@Path("/{userid}/check-password")
@Produces({ MediaType.APPLICATION_JSON })
@ApiOperation(value = "Check user password", response = EventUserRestPojo.class)
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public Response checkPassword(@PathParam("userid") @ApiParam("User ID") Integer userId,
@FormParam("password") @ApiParam("Password") String password) {
try {
if (permbean.hasPermission(UserPermission.VIEW_ALL) == false) {
return Response.status(Status.FORBIDDEN).build();
}
EventUser user = userbean.findByUserId(userId, true);
if (user == null) {
return Response.status(Status.NOT_FOUND).build();
}
//boolean passwordOk = user.checkPassword(password);
boolean passwordOk = userbean.checkPassword(user, password);
if (passwordOk) {
return Response.ok(PojoUtils.initEventUserRestPojo(user), MediaType.APPLICATION_JSON_TYPE).build();
}
return Response.status(Status.UNAUTHORIZED).entity(PojoUtils.initErrorPojo("Wrong password")).build();
} catch (Exception e) {
logger.error("Checking user authentication failed", e);
return Response.serverError().entity(PojoUtils.initErrorPojo("Checking password failed")).build();
}
}
@POST
@Path("/{userid}/reset-password")
@Produces({ MediaType.APPLICATION_JSON })
@ApiOperation(value = "Reset user password", response = EventUserRestPojo.class)
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public Response resetPassword(@PathParam("userid") @ApiParam("User ID") Integer userId,
@FormParam("password") @ApiParam("New password") String password) {
try {
if (permbean.hasPermission(UserPermission.MODIFY) == false || permbean.hasPermission(UserPermission.VIEW_ALL)) {
return Response.status(Status.FORBIDDEN).build();
}
EventUser eventUser = userbean.findByUserId(userId, true);
User user = eventUser.getUser();
userbean.resetPassword(user, password);
return Response.ok(PojoUtils.initEventUserRestPojo(eventUser)).build();
} catch (Exception e) {
logger.error("Checking user authentication failed", e);
return Response.serverError().entity(PojoUtils.initErrorPojo("Resetting user password failed")).build();
}
}
/**
* Post forma parameter "image" with the image data in it.
* @param request
* @param userId
* @return
* @throws IOException
*/
@PUT
@Path("/{userid}/image")
@ApiOperation(value = "Upload image", response = EventUserRestPojo.class)
@Consumes(MediaType.MULTIPART_FORM_DATA)
public Response updateUserImage(@Context HttpServletRequest request,
@PathParam("userid") @ApiParam("User ID") Integer userId) throws IOException {
try {
if (permbean.hasPermission(UserPermission.MODIFY) == false || permbean.hasPermission(UserPermission.VIEW_ALL)) {
return Response.status(Status.FORBIDDEN).build();
}
Part imagePart = request.getPart("image");
EventUser eventUser = userbean.findByUserId(userId, true);
UserImage userImage = userbean.uploadImage(eventUser, imagePart.getContentType(),
imagePart.getInputStream(), imagePart.getSubmittedFileName(), null);
return Response.ok(PojoUtils.initEventUserRestPojo(eventUser)).build();
} catch (ServletException e) {
logger.error("Updating user image failed", e);
return Response.serverError().entity(PojoUtils.initErrorPojo("Updating user image failed")).build();
}
}
@GET
@Path("/")
@Produces({MediaType.APPLICATION_JSON})
@ApiOperation(value = "Find event user", response = EventUserRestPojo.class)
public Response getEventUser(@QueryParam("email") @ApiParam("Email address") String email,
@QueryParam("login") @ApiParam("Username") String userName) {
try {
if (permbean.hasPermission(UserPermission.VIEW_ALL) == false) {
return Response.status(Status.FORBIDDEN).build();
}
EventUser eventUser;
User user = null;
// If username not given, try to find username by email
if (userName == null || userName.isEmpty()) {
user = userbean.findUserByEmailUsername(email);
}
if (user != null) {
eventUser = userbean.getEventUser(user, true);
} else {
// Get the user
eventUser = userbean.findEventuserByLogin(userName);
}
if (eventUser == null) {
return Response.status(Status.NOT_FOUND).build();
}
// Return the EventUser
return Response.ok(PojoUtils.initEventUserRestPojo(eventUser)).build();
} catch (Exception e) {
logger.error("Finding event user failed", e);
return Response.serverError().build();
}
}
@POST
@Path("/{userid}/check-password")
@Produces({MediaType.APPLICATION_JSON})
@ApiOperation(value = "Check user password", response = EventUserRestPojo.class)
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public Response checkPassword(@PathParam("userid") @ApiParam("User ID") Integer userId,
@FormParam("password") @ApiParam("Password") String password) {
try {
if (permbean.hasPermission(UserPermission.VIEW_ALL) == false) {
return Response.status(Status.FORBIDDEN).build();
}
EventUser user = userbean.findByUserId(userId, true);
if (user == null) {
return Response.status(Status.NOT_FOUND).build();
}
//boolean passwordOk = user.checkPassword(password);
boolean passwordOk = userbean.checkPassword(user, password);
if (passwordOk) {
return Response.ok(PojoUtils.initEventUserRestPojo(user), MediaType.APPLICATION_JSON_TYPE).build();
}
return Response.status(Status.UNAUTHORIZED).entity(PojoUtils.initErrorPojo("Wrong password")).build();
} catch (Exception e) {
logger.error("Checking user authentication failed", e);
return Response.serverError().entity(PojoUtils.initErrorPojo("Checking password failed")).build();
}
}
@POST
@Path("/{userid}/reset-password")
@Produces({MediaType.APPLICATION_JSON})
@ApiOperation(value = "Reset user password", response = EventUserRestPojo.class)
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public Response resetPassword(@PathParam("userid") @ApiParam("User ID") Integer userId,
@FormParam("password") @ApiParam("New password") String password) {
try {
if (permbean.hasPermission(UserPermission.MODIFY) == false || permbean.hasPermission(UserPermission.VIEW_ALL)) {
return Response.status(Status.FORBIDDEN).build();
}
EventUser eventUser = userbean.findByUserId(userId, true);
User user = eventUser.getUser();
userbean.resetPassword(user, password);
return Response.ok(PojoUtils.initEventUserRestPojo(eventUser)).build();
} catch (Exception e) {
logger.error("Checking user authentication failed", e);
return Response.serverError().entity(PojoUtils.initErrorPojo("Resetting user password failed")).build();
}
}
/**
* Post forma parameter "image" with the image data in it.
*
* @param request
* @param userId
* @return
* @throws IOException
*/
@PUT
@Path("/{userid}/image")
@ApiOperation(value = "Upload image", response = EventUserRestPojo.class)
@Consumes(MediaType.MULTIPART_FORM_DATA)
public Response updateUserImage(@Context HttpServletRequest request,
@PathParam("userid") @ApiParam("User ID") Integer userId) throws IOException {
try {
if (permbean.hasPermission(UserPermission.MODIFY) == false || permbean.hasPermission(UserPermission.VIEW_ALL)) {
return Response.status(Status.FORBIDDEN).build();
}
Part imagePart = request.getPart("image");
EventUser eventUser = userbean.findByUserId(userId, true);
UserImage userImage = userbean.uploadImage(eventUser, imagePart.getContentType(),
imagePart.getInputStream(), imagePart.getSubmittedFileName(), null);
return Response.ok(PojoUtils.initEventUserRestPojo(eventUser)).build();
} catch (ServletException e) {
logger.error("Updating user image failed", e);
return Response.serverError().entity(PojoUtils.initErrorPojo("Updating user image failed")).build();
}
}
@GET
@Path("/{userid}/image")
public Response fetchUserImage(@PathParam("userid") Integer userid) {
EventUser eventuser = userbean.findByUserId(userid, false);
if (eventuser == null) {
return Response.status(Status.NOT_FOUND).entity("No user found with id").build();
}
UserImage currimage = eventuser.getUser().getCurrentImage();
if (currimage == null) {
return Response.noContent().build();
}
return Response.ok(currimage.getImageData(), currimage.getMimeType()).build();
}
}
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;
import java.security.Principal;
import java.util.Base64;
import java.util.Date;
import javax.ejb.EJB;
import javax.enterprise.context.RequestScoped;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
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 jdk.nashorn.internal.objects.annotations.Getter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
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.PermissionBeanLocal;
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.userinfo.v1.UserPwdPojo;
/**
* Created by tuukka on 28.3.2015.
......@@ -24,17 +34,59 @@ import fi.codecrew.moya.rest.pojo.appconfig.v1.EventRoot;
@RequestScoped
@Path("/appconfig/v1/eventinfo")
@Consumes({ MediaType.APPLICATION_JSON })
@Produces({ MediaType.APPLICATION_JSON + "; charset=UTF-8" })
@Api(value="/appconfig/v1/eventinfo", description = "Event information for application")
@Consumes({MediaType.APPLICATION_JSON})
@Produces({MediaType.APPLICATION_JSON + "; charset=UTF-8"})
@Api(value = "/appconfig/v1/eventinfo", description = "Event information for application")
public class EventInfoV1 {
private static final Logger logger = LoggerFactory.getLogger(EventInfoV1.class);
@EJB
PermissionBeanLocal permissionBean;
private static final String AUTH_HEADER = "authorization";
private static final String AUTH_PREFIX = "Basic ";
@Context
private HttpServletRequest servletRequest;
@EJB
private PermissionBeanLocal permissionBean;
@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
@Path("/listevents/")
......@@ -42,10 +94,11 @@ public class EventInfoV1 {
@ApiResponse(code = 200, message = "Return events for current user")
public Response getEventsForCurrentUser() {
if(permissionBean.getCurrentUser().isAnonymous()) {
if (permissionBean.getCurrentUser().isAnonymous()) {
return Response.status(Response.Status.FORBIDDEN).build();
}
return Response.ok(PojoUtils.parseEvents(eventBean.findFutureAndRunningEventsForCurrentUser())).build();
}
}
package fi.codecrew.moya.rest.v2;
import fi.codecrew.moya.beans.EventBeanLocal;
import fi.codecrew.moya.beans.PermissionBeanLocal;
import fi.codecrew.moya.beans.UserBeanLocal;
import fi.codecrew.moya.beans.*;
import fi.codecrew.moya.enums.Gender;
import fi.codecrew.moya.enums.apps.UserPermission;
import fi.codecrew.moya.model.EventUser;
import fi.codecrew.moya.model.User;
import fi.codecrew.moya.model.UserImage;
import fi.codecrew.moya.model.*;
import fi.codecrew.moya.rest.PojoUtils;
import fi.codecrew.moya.rest.pojo.userinfo.v1.EventUserRestPojo;
import fi.codecrew.moya.rest.pojo.userinfo.v1.PrintedCardUpdateCodePojo;
import fi.codecrew.moya.rest.v2.pojo.UserPojo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
......@@ -36,188 +33,234 @@ import java.io.InputStream;
@Api(value = "/v2/user", description = "User operations")
public class UserRestViewV2 {
private static final Logger logger = LoggerFactory.getLogger(UserRestViewV2.class);
@EJB
EventBeanLocal eventBean;
@EJB
PermissionBeanLocal permissionBean;
@EJB
UserBeanLocal userBean;
@Inject
PojoFactoryV2 pojoFactory;
@GET
@Path("/get")
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(value = "Find user", response = UserPojo.class)
public Response getEventUser(@QueryParam("email") @ApiParam("Email address") String email,
@QueryParam("login") @ApiParam("Username") String userName) {
try {
if (permissionBean.hasPermission(UserPermission.VIEW_ALL) == false) {
return Response.status(Response.Status.FORBIDDEN).build();
}
// If username not given, try to find username by email
if (userName == null || userName.isEmpty()) {
userName = userBean.findUsernameByEmailUsername(email);
}
// Get the user
EventUser eventUser = userBean.findEventuserByLogin(userName);
if (eventUser == null) {
return Response.status(Response.Status.NOT_FOUND).build();
}
// Return the EventUser
return Response.ok(pojoFactory.createUserPojo(eventUser)).build();
} catch (Exception e) {
logger.error("Finding event user failed", e);
return Response.serverError().build();
}
}
@POST
@Path("/create")
@Produces({ MediaType.APPLICATION_JSON })
@Consumes(MediaType.APPLICATION_JSON)
@ApiOperation(value = "Create user", response = UserPojo.class)
public Response createUser(UserPojo userPojo) {
if (permissionBean.hasPermission(UserPermission.CREATE_NEW) == false) {
return Response.status(Response.Status.FORBIDDEN).build();
}
try {
EventUser eventUser = new EventUser(new User(), eventBean.getCurrentEvent(), permissionBean.getCurrentUser());
eventUser.setNick(userPojo.nick);
eventUser.setLogin(userPojo.login);
eventUser.setFirstnames(userPojo.firstname);
eventUser.setLastname(userPojo.lastname);
eventUser.setBirthday(userPojo.birthday);
if (userPojo.gender == UserPojo.UserGender.MALE) {
eventUser.setGender(Gender.MALE);
} else if (userPojo.gender == UserPojo.UserGender.FEMALE) {
eventUser.setGender(Gender.FEMALE);
} else {
eventUser.setGender(Gender.UNDEFINED);
}
eventUser.setPhone(userPojo.phoneNumber);
eventUser.setEmail(userPojo.email);
eventUser.setAddress(userPojo.streetAddress);
eventUser.setZip(userPojo.zipCode);
eventUser.setTown(userPojo.postOffice);
userBean.createNewUser(eventUser, userPojo.password);
return Response.ok(pojoFactory.createUserPojo(eventUser)).build();
} catch(Exception e) {
logger.error("Creating user failed", e);
return Response.serverError().entity(PojoUtils.initErrorPojo(e.getMessage())).build();
}
}
/**
* Post forma parameter "image" with the image data in it.
* @param request
* @param userId
* @return
* @throws IOException
*/
@PUT
@Path("/{userid}/image")
@ApiOperation(value = "Upload image", response = EventUserRestPojo.class)
@Consumes(MediaType.MULTIPART_FORM_DATA)
public Response updateUserImage(@Context HttpServletRequest request,
@PathParam("userid") @ApiParam("User ID") Integer userId,
@FormDataParam("image") FormDataContentDisposition imageInfo,
@FormDataParam("image") InputStream imageStream,
@FormDataParam("image") FormDataBodyPart body) {
logger.info("Starting to upload new user image for user {}", userId);
try {
if (permissionBean.hasPermission(UserPermission.MODIFY) == false || permissionBean.hasPermission(UserPermission.VIEW_ALL) == false) {
return Response.status(Response.Status.FORBIDDEN).build();
}
EventUser eventUser = userBean.findByUserId(userId, true);
logger.info("Mimetype: " + body.getMediaType());
userBean.uploadImage(eventUser, body.getMediaType().getType(), imageStream, imageInfo.getFileName(), null);
logger.info("Image uploaded");
return Response.ok(pojoFactory.createUserPojo(eventUser)).build();
} catch (Exception e) {
logger.error("Image upload failed", e);
return Response.serverError().entity(PojoUtils.initErrorPojo("Image upload failed")).build();
}
}
/**
* Get user image
* @param userId
* @return
*/
@GET
@Path("/{userid}/image")
@ApiOperation(value = "Download user image")
//@Consumes()
//@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
//@Produces({MediaType.APPLICATION_JSON, "image/png", "image/jpeg"})
//@Produces({MediaType.MULTIPART_FORM_DATA, "image/png", "image/jpeg"})
public Response downloadUserImage(@PathParam("userid") @ApiParam("User ID") Integer userId) {
try {
User user = userBean.getUser(userId);
UserImage image = user.getCurrentImage();
//logger.info("Mimetype: " + body.getMediaType());
// XXX: Vectorama2015 - assume image/jpeg if mime type not known
String mimeType = image.getMimeType();
if (mimeType != null) {
if (!mimeType.equals("image/png") && !mimeType.equals("image/gif")) {
// fallback
mimeType = "image/jpeg";
}
} else {
// fallback if null
mimeType = "image/jpeg";
}
return Response.ok(image.getImageData(), mimeType).build();
} catch(Exception e) {
logger.error("Getting image failed", e);
return Response.serverError().entity(PojoUtils.initErrorPojo(e.getMessage())).build();
}
}
@POST
@Path("/{userid}/check-password")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
@ApiOperation(value = "Check user password", response = UserPojo.class)
public Response checkPassword(@PathParam("userid") @ApiParam("User ID") Integer userId,
@FormParam("password") @ApiParam("Password") String password) {
try {
if (permissionBean.hasPermission(UserPermission.VIEW_ALL) == false) {
return Response.status(Response.Status.FORBIDDEN).build();
}
EventUser user = userBean.findByUserId(userId, true);
if (user == null) {
return Response.status(Response.Status.NOT_FOUND).build();
}
//boolean passwordOk = user.checkPassword(password);
boolean passwordOk = userBean.checkPassword(user, password);
if (passwordOk) {
return Response.ok(pojoFactory.createUserPojo(user), MediaType.APPLICATION_JSON_TYPE).build();
}
return Response.status(Response.Status.UNAUTHORIZED).entity(PojoUtils.initErrorPojo("Wrong password")).build();
} catch (Exception e) {
logger.error("Checking user authentication failed", e);
return Response.serverError().entity(PojoUtils.initErrorPojo("Checking password failed")).build();
}
}
private static final Logger logger = LoggerFactory.getLogger(UserRestViewV2.class);
@EJB
private EventBeanLocal eventBean;
@EJB
private PermissionBeanLocal permissionBean;
@EJB
private UserBeanLocal userBean;
@EJB
private ReaderBeanLocal readerbean;
@EJB
private CardTemplateBeanLocal cardBean;
@Inject
PojoFactoryV2 pojoFactory;
@GET
@Path("/get")
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(value = "Find user", response = UserPojo.class)
public Response getEventUser(@QueryParam("email") @ApiParam("Email address") String email,
@QueryParam("login") @ApiParam("Username") String userName) {
try {
if (permissionBean.hasPermission(UserPermission.VIEW_ALL) == false) {
return Response.status(Response.Status.FORBIDDEN).build();
}
// If username not given, try to find username by email
if (userName == null || userName.isEmpty()) {
userName = userBean.findUsernameByEmailUsername(email);
}
// Get the user
EventUser eventUser = userBean.findEventuserByLogin(userName);
if (eventUser == null) {
return Response.status(Response.Status.NOT_FOUND).build();
}
// Return the EventUser
return Response.ok(pojoFactory.createUserPojo(eventUser)).build();
} catch (Exception e) {
logger.error("Finding event user failed", e);
return Response.serverError().build();
}
}
@GET
@Path("/current")
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(value = "Fetch current user", response = EventUserRestPojo.class)
public Response getCurrentUser() {
EventUser usr = permissionBean.getCurrentUser();
logger.info("Got current user {} ", usr);
/*if (usr == null || usr.isAnonymous()) {
return Response.status(Response.Status.NOT_FOUND).entity("User not found, or not logged in").build();
}*/
return Response.ok(pojoFactory.createUserPojo(usr)).build();
}
@POST
@Path("/create")
@Produces({MediaType.APPLICATION_JSON})
@Consumes(MediaType.APPLICATION_JSON)
@ApiOperation(value = "Create user", response = UserPojo.class)
public Response createUser(UserPojo userPojo) {
if (permissionBean.hasPermission(UserPermission.CREATE_NEW) == false) {
return Response.status(Response.Status.FORBIDDEN).build();
}
try {
EventUser eventUser = new EventUser(new User(), eventBean.getCurrentEvent(), permissionBean.getCurrentUser());
eventUser.setNick(userPojo.nick);
eventUser.setLogin(userPojo.login);
eventUser.setFirstnames(userPojo.firstname);
eventUser.setLastname(userPojo.lastname);
eventUser.setBirthday(userPojo.birthday);
if (userPojo.gender == UserPojo.UserGender.MALE) {
eventUser.setGender(Gender.MALE);
} else if (userPojo.gender == UserPojo.UserGender.FEMALE) {
eventUser.setGender(Gender.FEMALE);
} else {
eventUser.setGender(Gender.UNDEFINED);
}
eventUser.setPhone(userPojo.phoneNumber);
eventUser.setEmail(userPojo.email);
eventUser.setAddress(userPojo.streetAddress);
eventUser.setZip(userPojo.zipCode);
eventUser.setTown(userPojo.postOffice);
userBean.createNewUser(eventUser, userPojo.password);
return Response.ok(pojoFactory.createUserPojo(eventUser)).build();
} catch (Exception e) {
logger.error("Creating user failed", e);
return Response.serverError().entity(PojoUtils.initErrorPojo(e.getMessage())).build();
}
}
@PUT
@ApiOperation(value = "Update code ")
@Path("/{userid}/cardcode")
public Response updateUserCard(PrintedCardUpdateCodePojo codepojo, @PathParam("userid") Integer userid) {
ReaderEvent event = readerbean.checkCode(codepojo.getReaderName(), codepojo.getCode());
// If tag is not associated, try to add it to the user.
if (event.getPrintedCard() == null) {
PrintedCard card = cardBean.checkPrintedCard(userBean.findByUserId(userid, false));
logger.info("Updating card {} to event {} ", card, event);
if (card != null) {
event = readerbean.assocCodeToCard(event, card);
return Response.ok(PojoUtils.initReaderEventRestPojo(event)).build();
}
}
Response.Status status = Response.Status.CONFLICT;
if (event.getPrintedCard() != null &&
event.getUser().getEvent().equals(eventBean.getCurrentEvent()) &&
event.getUser().getUser().getId().equals(userid)) {
status = Response.Status.OK;
}
return Response.status(status).entity(PojoUtils.initReaderEventRestPojo(event)).build();
}
/**
* Post forma parameter "image" with the image data in it.
*
* @param request
* @param userId
* @return
* @throws IOException
*/
@PUT
@Path("/{userid}/image")
@ApiOperation(value = "Upload image", response = EventUserRestPojo.class)
@Consumes(MediaType.MULTIPART_FORM_DATA)
public Response updateUserImage(@Context HttpServletRequest request,
@PathParam("userid") @ApiParam("User ID") Integer userId,
@FormDataParam("image") FormDataContentDisposition imageInfo,
@FormDataParam("image") InputStream imageStream,
@FormDataParam("image") FormDataBodyPart body) {
logger.info("Starting to upload new user image for user {}", userId);
try {
if (permissionBean.hasPermission(UserPermission.MODIFY) == false || permissionBean.hasPermission(UserPermission.VIEW_ALL) == false) {
return Response.status(Response.Status.FORBIDDEN).build();
}
EventUser eventUser = userBean.findByUserId(userId, true);
logger.info("Mimetype: " + body.getMediaType());
userBean.uploadImage(eventUser, body.getMediaType().getType(), imageStream, imageInfo.getFileName(), null);
logger.info("Image uploaded");
return Response.ok(pojoFactory.createUserPojo(eventUser)).build();
} catch (Exception e) {
logger.error("Image upload failed", e);
return Response.serverError().entity(PojoUtils.initErrorPojo("Image upload failed")).build();
}
}
/**
* Get user image
*
* @param userId
* @return
*/
@GET
@Path("/{userid}/image")
@ApiOperation(value = "Download user image")
//@Consumes()
//@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
//@Produces({MediaType.APPLICATION_JSON, "image/png", "image/jpeg"})
//@Produces({MediaType.MULTIPART_FORM_DATA, "image/png", "image/jpeg"})
public Response downloadUserImage(@PathParam("userid") @ApiParam("User ID") Integer userId) {
try {
User user = userBean.getUser(userId);
UserImage image = user.getCurrentImage();
//logger.info("Mimetype: " + body.getMediaType());
// XXX: Vectorama2015 - assume image/jpeg if mime type not known
String mimeType = image.getMimeType();
if (mimeType != null) {
if (!mimeType.equals("image/png") && !mimeType.equals("image/gif")) {
// fallback
mimeType = "image/jpeg";
}
} else {
// fallback if null
mimeType = "image/jpeg";
}
return Response.ok(image.getImageData(), mimeType).build();
} catch (Exception e) {
logger.error("Getting image failed", e);
return Response.serverError().entity(PojoUtils.initErrorPojo(e.getMessage())).build();
}
}
@POST
@Path("/{userid}/check-password")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
@ApiOperation(value = "Check user password", response = UserPojo.class)
public Response checkPassword(@PathParam("userid") @ApiParam("User ID") Integer userId,
@FormParam("password") @ApiParam("Password") String password) {
try {
if (permissionBean.hasPermission(UserPermission.VIEW_ALL) == false) {
return Response.status(Response.Status.FORBIDDEN).build();
}
EventUser user = userBean.findByUserId(userId, true);
if (user == null) {
return Response.status(Response.Status.NOT_FOUND).build();
}
//boolean passwordOk = user.checkPassword(password);
boolean passwordOk = userBean.checkPassword(user, password);
if (passwordOk) {
return Response.ok(pojoFactory.createUserPojo(user), MediaType.APPLICATION_JSON_TYPE).build();
}
return Response.status(Response.Status.UNAUTHORIZED).entity(PojoUtils.initErrorPojo("Wrong password")).build();
} catch (Exception e) {
logger.error("Checking user authentication failed", e);
return Response.serverError().entity(PojoUtils.initErrorPojo("Checking password failed")).build();
}
}
}
......@@ -91,8 +91,7 @@ public class BortalCommand implements Command, Runnable {
@Override
public void run() {
BortalLocalContextHolder.copy(contextHolder);
BortalLocalContextHolder.getInstance().executeLogin();
try {
logger.info("Created new bortalCommane");
outstream.write("Hello you...");
......@@ -113,7 +112,7 @@ public class BortalCommand implements Command, Runnable {
outstream.flush();
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();
cmdBuilder = new StringBuilder();
......@@ -134,7 +133,6 @@ public class BortalCommand implements Command, Runnable {
e.printStackTrace();
}
BortalLocalContextHolder.getInstance().executeLogout();
exitCallback.onExit(3);
}
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!