Commit 4e431207 by Anton Sudak

Merge branch 'PLAY-157' into 'master'

Resolve PLAY-157 Closes PLAY-157 See merge request !91
parents 23869e57 00ee52ab
Pipeline #11204 failed with stages
in 12 minutes 44 seconds
......@@ -89,6 +89,7 @@ object Settings {
"org.mapstruct" % "mapstruct-jdk8" % versions.mapStruct,
"org.mapstruct" % "mapstruct-processor" % versions.mapStruct,
"com.adrianhurt" %% "play-bootstrap" % "1.2-P26-B3",
"org.springframework.data" % "spring-data-commons" % "2.0.10.RELEASE",
"org.mockito" % "mockito-all" % "1.9.5" % Test
))
......
......@@ -9,7 +9,6 @@ import ch.insign.commons.i18n.Language;
import ch.insign.playauth.PlayAuthApi;
import ch.insign.playauth.controllers.actions.RequiresUser;
import ch.insign.playauth.party.Party;
import ch.insign.playauth.party.PartyManager;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.google.inject.Provider;
import data.form.EditPasswordForm;
......@@ -20,7 +19,7 @@ import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import party.User;
import play.*;
import party.UserRepository;
import play.Application;
import play.data.Form;
import play.data.FormFactory;
......@@ -35,7 +34,9 @@ import play.mvc.With;
import javax.inject.Inject;
import java.io.File;
import java.util.*;
import java.util.Date;
import java.util.HashMap;
import java.util.Optional;
import static util.DemoProjectBootstrapper.EMAIL_KEY_CHANGE_EMAIL;
......@@ -48,7 +49,7 @@ public class AccountController extends Controller {
private final PlayAuthApi playAuthApi;
private final CMSApi cmsApi;
private final MessagesApi messagesApi;
private final PartyManager partyManager;
private final UserRepository userRepository;
private final FormFactory formFactory;
private final UserProfileMapper userProfileMapper;
private final UserEmailValidator userEmailValidator;
......@@ -60,7 +61,7 @@ public class AccountController extends Controller {
PlayAuthApi playAuthApi,
CMSApi cmsApi,
UserProfileMapper userProfileMapper,
PartyManager partyManager,
UserRepository userRepository,
UserEmailValidator userEmailValidator,
MessagesApi messagesApi,
FormFactory formFactory,
......@@ -69,7 +70,7 @@ public class AccountController extends Controller {
) {
this.playAuthApi = playAuthApi;
this.cmsApi = cmsApi;
this.partyManager = partyManager;
this.userRepository = userRepository;
this.messagesApi = messagesApi;
this.userProfileMapper = userProfileMapper;
this.formFactory = formFactory;
......@@ -122,7 +123,7 @@ public class AccountController extends Controller {
user = userProfileMapper.update(userForm, user);
user.setName((user.getFirstName() + " " + user.getLastName()).trim());
partyManager.save(user);
userRepository.save(user);
if (!user.getEmail().equals(oldEmail)){
sendChangeEmailEmails(user, oldEmail);
......
......@@ -11,7 +11,6 @@ import ch.insign.cms.utils.Error;
import ch.insign.commons.i18n.Language;
import ch.insign.playauth.PlayAuthApi;
import ch.insign.playauth.authz.AccessControlManager;
import ch.insign.playauth.party.PartyManager;
import ch.insign.playauth.party.PartyRoleManager;
import ch.insign.playauth.party.support.DefaultPartyRole;
import ch.insign.playauth.permissions.PartyPermission;
......@@ -24,6 +23,7 @@ import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import party.User;
import party.UserRepository;
import play.data.Form;
import play.data.FormFactory;
import play.db.jpa.JPAApi;
......@@ -48,7 +48,7 @@ public class UserController extends Controller {
private final CMSApi cmsApi;
private final PlayAuthApi playAuthApi;
private final PartyRoleManager partyRoleManager;
private final PartyManager partyManager;
private final UserRepository userRepository;
private final PartyEvents partyEvents;
private final MessagesApi messagesApi;
private final FormFactory formFactory;
......@@ -63,7 +63,7 @@ public class UserController extends Controller {
CMSApi cmsApi,
PlayAuthApi playAuthApi,
PartyRoleManager partyRoleManager,
PartyManager partyManager,
UserRepository userRepository,
MessagesApi messagesApi,
FormFactory formFactory,
UserEmailValidator userEmailValidator,
......@@ -76,7 +76,7 @@ public class UserController extends Controller {
this.cmsApi = cmsApi;
this.playAuthApi = playAuthApi;
this.partyRoleManager = partyRoleManager;
this.partyManager = partyManager;
this.userRepository = userRepository;
this.messagesApi = messagesApi;
this.formFactory = formFactory;
this.partyEvents = partyEvents;
......@@ -116,10 +116,10 @@ public class UserController extends Controller {
RegisterUserForm userForm = form.get();
User user = userMapper.fromForm(userForm);
user.setName((user.getFirstName() + " " + user.getLastName()).trim());
user = userRepository.save(user);
user.addRole(partyRoleManager.findOneByName(DefaultPartyRole.ROLE_USER));
user.setCredentials(playAuthApi.getPasswordService().encryptPassword(form.get().getPassword()));
partyManager.save(user);
playAuthApi.authenticate(user);
// Add permissions for the created user
......@@ -140,11 +140,8 @@ public class UserController extends Controller {
return AjaxResult.error(form);
}
User user = (User) partyManager.findOneByPrincipal(form.get().getEmail());
if (null != user) {
sendEmailRestorePassword(user);
}
userRepository.findOneByEmail(form.get().getEmail())
.ifPresent(this::sendEmailRestorePassword);
flash("success-disappear", messagesApi.get(lang(), "reset.password.msg.reset_email_sent"));
return redirect(controller.routes.UserController.showResetPasswordPage());
......
......@@ -53,7 +53,7 @@ public class RegisterUserForm implements UserEmailForm {
@Required
private String passwordRepeat;
@Constraints.MaxLength(11)
@Constraints.Pattern(PHONE_PATTERN)
private String phone;
private String language;
......
......@@ -16,8 +16,7 @@ import java.util.Date;
)
})
@Entity
@Table(name = "rasch_token_action")
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@Table(name = "demo_token_action")
public class TokenAction {
/**
......@@ -73,6 +72,7 @@ public class TokenAction {
final Date created = new Date();
tokenAction.created = created;
tokenAction.expires = new Date(created.getTime() + EXPIRATION_TIME * 1000);
user.getTokenActions().add(tokenAction);
return tokenAction;
}
......
......@@ -3,8 +3,9 @@ package data.validator;
import ch.insign.cms.validator.FormValidator;
import ch.insign.playauth.PlayAuthApi;
import ch.insign.playauth.party.Party;
import ch.insign.playauth.party.PartyManager;
import ch.insign.playauth.party.PartyRepository;
import data.form.UserEmailForm;
import party.User;
import play.data.validation.ValidationError;
import javax.inject.Inject;
......@@ -14,12 +15,12 @@ import java.util.Optional;
public class UserEmailValidator<T extends UserEmailForm> extends FormValidator<T> {
private final PartyManager partyManager;
private final PartyRepository<User> partyRepository;
private final PlayAuthApi playAuthApi;
@Inject
public UserEmailValidator(PartyManager partyManager, PlayAuthApi playAuthApi) {
this.partyManager = partyManager;
public UserEmailValidator(PartyRepository partyRepository, PlayAuthApi playAuthApi) {
this.partyRepository = partyRepository;
this.playAuthApi = playAuthApi;
}
......@@ -27,7 +28,7 @@ public class UserEmailValidator<T extends UserEmailForm> extends FormValidator<T
protected List<ValidationError> validate(T form) {
List<ValidationError> errors = new ArrayList<>();
Optional.ofNullable(partyManager.findOneByPrincipal(form.getEmail()))
partyRepository.findOneByEmail(form.getEmail())
.ifPresent(p -> {
Optional<Party> maybeCurrentParty = playAuthApi.getCurrentParty()
.filter(c -> c.getId().equals(p.getId()));
......
package inject;
import auth.LoggingAuthenticationListener;
import ch.insign.playauth.party.PartyRepository;
import ch.insign.playauth.party.PartyService;
import com.google.inject.AbstractModule;
import party.UserRepository;
import party.UserService;
public class DemoProjectAuthModule extends AbstractModule {
@Override
protected void configure() {
bind(PartyRepository.class).to(UserRepository.class);
bind(PartyService.class).to(UserService.class);
bind(LoggingAuthenticationListener.class).asEagerSingleton();
}
}
package inject;
import auth.LoggingAuthenticationListener;
import ch.insign.playauth.party.PartyManager;
import party.DemoPartyManager;
import play.api.Configuration;
import play.api.Environment;
import play.api.inject.Binding;
import play.api.inject.Module;
import scala.collection.Seq;
public class DemoProjectPartyManagerModule extends Module {
public Seq<Binding<?>> bindings(Environment environment, Configuration configuration) {
return seq(
bind(PartyManager.class).to(DemoPartyManager.class),
bind(LoggingAuthenticationListener.class).toSelf());
}
}
package party;
import ch.insign.cms.email.EmailService;
import ch.insign.cms.models.CMS;
import ch.insign.cms.models.party.DefaultPartyHandler;
import ch.insign.playauth.PlayAuthApi;
import ch.insign.playauth.party.support.DefaultParty;
import ch.insign.playauth.party.Party;
import ch.insign.playauth.party.support.DefaultPartyRole;
import com.google.inject.Inject;
import com.google.inject.Provider;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import play.Application;
import play.data.Form;
import play.mvc.Http;
import java.io.File;
import java.util.Date;
import javax.inject.Inject;
import java.util.HashMap;
import java.util.regex.Pattern;
import static data.form.RegisterUserForm.PHONE_PATTERN;
public class DemoPartyHandler extends DefaultPartyHandler {
private final PlayAuthApi playAuthApi;
private final EmailService emailService;
private Provider<Application> application;
@Inject
public DemoPartyHandler(
PlayAuthApi playAuthApi,
EmailService emailService,
Provider<Application> application
) {
public DemoPartyHandler(PlayAuthApi playAuthApi, EmailService emailService) {
this.playAuthApi = playAuthApi;
this.emailService = emailService;
this.application = application;
}
@Override
public void onCreate(Form form, DefaultParty party) {
User user = (User) party;
User userForm = (User) form.get();
user.setGender(userForm.getGender());
if (!StringUtils.isBlank(userForm.getPhone()) && Pattern.compile(PHONE_PATTERN).matcher(userForm.getPhone()).find()) {
user.setPhone(userForm.getPhone());
}
if (CMS.getConfig().frontendLanguages().stream().anyMatch(l -> l.equals(userForm.getLanguage()))) {
user.setLanguage(userForm.getLanguage());
}
user.setFirstName(userForm.getFirstName());
user.setLastName(userForm.getLastName());
user.setName((user.getFirstName() + " " + user.getLastName()).trim());
if (!StringUtils.isBlank(userForm.getImage())) setFileName(user, userForm);
user.addRole(playAuthApi.getPartyRoleManager().findOneByName(DefaultPartyRole.ROLE_USER));
public void onCreate(Form form, Party party) {
party.addRole(playAuthApi.getPartyRoleManager().findOneByName(DefaultPartyRole.ROLE_USER));
}
@Override
public void onUpdate(Form form, DefaultParty party) {
User user = (User) party;
User userForm = (User) form.get();
user.setName((user.getFirstName() + " " + user.getLastName()).trim());
if (!StringUtils.isBlank(userForm.getPhone()) && Pattern.compile(PHONE_PATTERN).matcher(userForm.getPhone()).find()) {
user.setPhone(userForm.getPhone());
}
if (CMS.getConfig().frontendLanguages().stream().anyMatch(l -> l.equals(userForm.getLanguage()))) {
user.setLanguage(userForm.getLanguage());
}
if (!StringUtils.isBlank(userForm.getImage())) setFileName(user, userForm);
else {
user.setImage(null);
deletePreviouseFile(user);
}
public void onUpdate(Form form, Party party) {
}
@Override
public void onPasswordUpdate(Form form, DefaultParty party) {
public void onPasswordUpdate(Form form, Party party) {
User user = (User) party;
HashMap<String, String> emailData = new HashMap<>();
emailData.put("name", user.getName());
emailService.send("password.recovery.success", user.getEmail(), emailData, Http.Context.current().lang().language());
}
private void setFileName(User user, User userForm) {
String appPath = application.get().path().getPath();
try {
File tmpFile = FileUtils.getFile(appPath + File.separator + userForm.getImage());
File userAvatar = new File(appPath + CMS.getConfig().imageUploadRootPath() + File.separator +
(new Date()).getTime() + user.getId());
FileUtils.copyFile(tmpFile, userAvatar);
user.setImage(userAvatar.getName());
tmpFile.delete();
} catch (Exception e) {
e.printStackTrace();
}
}
private void deletePreviouseFile(User user) {
String appPath = application.get().path().getPath();
try {
File folder = new File(appPath + CMS.getConfig().imageUploadRootPath());
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile() && listOfFiles[i].getName().endsWith(user.getId())) {
listOfFiles[i].delete();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
package party;
import ch.insign.playauth.party.Party;
import ch.insign.playauth.party.support.DefaultPartyManager;
import com.google.inject.Inject;
import play.db.jpa.JPAApi;
public class DemoPartyManager extends DefaultPartyManager {
@Inject
public DemoPartyManager(JPAApi jpaApi) {
super(jpaApi);
}
@Override
public Class<? extends Party> getPartyClass() {
return User.class;
}
}
......@@ -2,31 +2,37 @@ package party;
import ch.insign.playauth.party.ISOGender;
import ch.insign.playauth.party.support.DefaultParty;
import org.apache.commons.lang3.StringUtils;
import play.data.validation.ValidationError;
import data.model.TokenAction;
import play.data.validation.Constraints;
import javax.persistence.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.regex.Pattern;
import static data.form.RegisterUserForm.PASSWORD_PATTERN;
import static data.form.RegisterUserForm.PHONE_PATTERN;
/**
* Demo user class extends DefaultParty with custom fields
*/
@Entity
public class User extends DefaultParty {
@Constraints.Required
@Constraints.MaxLength(25)
private String firstName;
@Constraints.Required
@Constraints.MaxLength(30)
private String lastName;
private String image;
@Constraints.Required
@Enumerated(EnumType.STRING)
public ISOGender gender;
@Constraints.Pattern(PHONE_PATTERN)
public String phone;
public String language;
......@@ -34,6 +40,9 @@ public class User extends DefaultParty {
@Temporal(TemporalType.TIMESTAMP)
private Date lastLogin;
@OneToMany(cascade = CascadeType.ALL)
private List<TokenAction> tokenActions = new ArrayList<>();
private int loginCount = 0;
public String getPhone() {
......@@ -89,23 +98,6 @@ public class User extends DefaultParty {
this.language = language;
}
public List<ValidationError> validate() {
List<ValidationError> errors = new ArrayList<>();
if (StringUtils.isBlank(firstName)) {
errors.add(new ValidationError("firstName", "error.required"));
}
if (StringUtils.isBlank(lastName)) {
errors.add(new ValidationError("lastName", "error.required"));
}
if (!StringUtils.isEmpty(this.getPassword()) && !Pattern.compile(PASSWORD_PATTERN).matcher(this.getPassword()).find()) {
errors.add(new ValidationError("password", "auth.login.password.pattern.not.match"));
}
return errors.isEmpty() ? null : errors;
}
public Date getLastLogin() {
return lastLogin;
}
......@@ -121,4 +113,12 @@ public class User extends DefaultParty {
public void setLoginCount(int logins) {
this.loginCount = logins;
}
public List<TokenAction> getTokenActions() {
return tokenActions;
}
public void setTokenActions(List<TokenAction> tokenActions) {
this.tokenActions = tokenActions;
}
}
package party;
import ch.insign.playauth.party.support.AbstractPartyRepository;
import play.db.jpa.JPAApi;
import javax.inject.Inject;
public class UserRepository extends AbstractPartyRepository<User> {
@Inject
public UserRepository(JPAApi jpaApi) {
super(jpaApi, User.class);
}
}
package party;
import ch.insign.commons.db.SmartFormFactory;
import ch.insign.playauth.PlayAuthApi;
import ch.insign.playauth.party.PartyRepository;
import ch.insign.playauth.party.PartyService;
import javax.inject.Inject;
public class UserService extends PartyService<User> {
@Inject
public UserService(PlayAuthApi playAuthApi,
PartyRepository partyRepository,
SmartFormFactory formFactory) {
super(playAuthApi, partyRepository, formFactory);
}
public Class<User> getPartyClass() {
return User.class;
}
}
package service
import java.util.function.Supplier
import javax.inject._
import ch.insign.playauth.PlayAuthApi
import javax.inject._
import ch.insign.playauth.party.{Party, PartyRepository}
import party.{User, UserService}
import play.db.jpa.JPAApi
import shared.{Api, UserItem}
import scala.collection.JavaConversions._
class ApiService @Inject() (jPAApi: JPAApi, playAuth: PlayAuthApi) extends Api {
class ApiService @Inject() (jPAApi: JPAApi, userService: UserService) extends Api {
// message of the day
override def simpleAjaxCall(name: String): String = "this is a plain string originating from server"
......@@ -18,7 +19,7 @@ class ApiService @Inject() (jPAApi: JPAApi, playAuth: PlayAuthApi) extends Api {
override def getUsers: Seq[UserItem] = {
jPAApi.withTransaction(new Supplier[Seq[UserItem]]{
override def get(): Seq[UserItem] = {
val users = playAuth.getPartyManager.findAll
val users = userService.findAll()
users.map(u => UserItem(u.getId, u.getName, u.getEmail)).toSeq
}
})
......
......@@ -13,9 +13,7 @@ import ch.insign.cms.permissions.BlockPermission;
import ch.insign.commons.i18n.Language;
import ch.insign.playauth.authz.AccessControlManager;
import ch.insign.playauth.party.*;
import ch.insign.playauth.party.address.EmailAddress;
import ch.insign.playauth.party.support.DefaultPartyRole;
import com.google.inject.Provider;
import crud.page.CarInventoryPage;
import crud.data.entity.Brand;
import crud.data.entity.Car;
......@@ -24,7 +22,7 @@ import crud.data.repository.CarRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import party.User;
import play.Application;
import party.UserService;
import play.db.jpa.JPAApi;
import javax.inject.Inject;
......@@ -44,32 +42,28 @@ public class DemoProjectBootstrapper extends DefaultBootstrapper {
// Predefined Demo Role
private static final String ROLE_DEMO_ROLE = "DemoRole";
private final PartyManager pm;
private final PartyRoleManager prm;
private final AccessControlManager acm;
private final UserService userService;
private final CarRepository carRepository;
private final BrandRepository brandRepository;
private Provider<Application> application;
@Inject
public DemoProjectBootstrapper(
AccessControlManager accessControlManager,
CMSApi cmsApi,
PartyManager partyManager,
PartyRoleManager partyRoleManager,
JPAApi jpaApi,
UserService userService,
CarRepository carRepository,
BrandRepository brandRepository,
Provider<Application> application
BrandRepository brandRepository
) {
super(accessControlManager, cmsApi, partyRoleManager, jpaApi);
this.pm = partyManager;
this.prm = partyRoleManager;
this.acm = accessControlManager;
this.userService = userService;
this.carRepository = carRepository;
this.brandRepository = brandRepository;
this.application = application;
}
@Override
......@@ -175,28 +169,26 @@ public class DemoProjectBootstrapper extends DefaultBootstrapper {
PartyRole demoRole = prm.findOneByName(ROLE_DEMO_ROLE);
PartyRole userRole = prm.findOneByName(ROLE_USER);
Party superuser = pm.create(
"admin",
"temp123",
new EmailAddress("admin@insign.ch"),
PartyType.PERSON);
((User) superuser).setFirstName("admin");
((User) superuser).setLastName("insign");
((User) superuser).setGender(ISOGender.MALE);
User superuser = new User();
superuser.setName("admin");
superuser.setCredentials("temp123");
superuser.setEmail("admin@insign.ch");
superuser.setFirstName("admin");
superuser.setLastName("insign");
superuser.setGender(ISOGender.MALE);
superuser = userService.save(superuser);
superuser.addRole(superuserRole);
pm.save(superuser);
Party demouser = pm.create(
"demouser",
"temp123",
new EmailAddress("demouser@insign.ch"),
PartyType.PERSON);
((User) demouser).setFirstName("demouser");
((User) demouser).setLastName("insign");
((User) demouser).setGender(ISOGender.MALE);
User demouser = new User();
demouser.setName("demouser");
demouser.setCredentials("temp123");
demouser.setEmail("demouser@insign.ch");
demouser.setFirstName("demouser");
demouser.setLastName("insign");
demouser.setGender(ISOGender.MALE);
demouser = userService.save(demouser);
demouser.addRole(demoRole);
demouser.addRole(userRole);
pm.save(demouser);
}
private void createWidgetExampleBlock() {
......
......@@ -12,15 +12,16 @@ import ch.insign.cms.blocks.errorblock.ErrorPage;
import ch.insign.cms.blocks.groupingblock.GroupingBlock;
import ch.insign.cms.blocks.horizontalcollection.HorizontalCollectionBlock;
import ch.insign.cms.blocks.jotformpageblock.JotFormPageBlock;
import ch.insign.cms.blocks.jotformpageblock.service.JotFormService;
import ch.insign.cms.blocks.linkblock.LinkBlock;
import ch.insign.cms.blocks.searchresultblock.SearchResultBlock;
import ch.insign.cms.blocks.sliderblock.SliderCollectionBlock;
import ch.insign.cms.models.CollectionBlock;
import ch.insign.cms.models.ContentBlock;
import ch.insign.playauth.PlayAuthApi;
import ch.insign.playauth.party.PartyRepository;
import crud.page.CarInventoryPage;
import play.db.jpa.JPAApi;
import play.i18n.MessagesApi;
import widgets.registeredusers.RegisteredUsersWidget;
import javax.inject.Inject;
......@@ -30,18 +31,21 @@ import javax.inject.Singleton;
public class DemoProjectCmsApiLifecycle extends CMSApiLifecycleImpl {
private final PlayAuthApi playAuthApi;
private final PartyRepository partyRepository;
private final LoggingAuthenticationListener loggingAuthenticationListener;
@Inject
public DemoProjectCmsApiLifecycle(
JPAApi jpaApi,
ActorSystem actorSystem,
MessagesApi messagesApi,
PlayAuthApi playAuthApi,
JotFormService jotFormService,
PartyRepository partyRepository,
LoggingAuthenticationListener loggingAuthenticationListener
) {
super(jpaApi, actorSystem, messagesApi);
super(jpaApi, actorSystem, jotFormService);
this.playAuthApi = playAuthApi;
this.partyRepository = partyRepository;
this.loggingAuthenticationListener = loggingAuthenticationListener;
}
......@@ -77,7 +81,7 @@ public class DemoProjectCmsApiLifecycle extends CMSApiLifecycleImpl {
@Override
protected void registerContentFilters(CMSApi cmsApi) {
super.registerContentFilters(cmsApi);
cmsApi.getFilterManager().register(new RegisteredUsersWidget());
cmsApi.getFilterManager().register(new RegisteredUsersWidget(partyRepository));
}
@Override
......
......@@ -10,25 +10,21 @@
@partyNameExtension={
<div class="form-group">
@inputText(
userForm("firstName"),
'class -> "form-control",
'placeholder -> Messages("backend.u