use of fi.otavanopisto.pyramus.plugin.auth.InternalAuthenticationProvider in project pyramus by otavanopisto.
the class PersonRESTService method updateCredentials.
@Path("/persons/{ID:[0-9]*}/credentials")
@PUT
@RESTPermit(handling = Handling.INLINE)
public Response updateCredentials(@PathParam("ID") Long id, UserCredentials userCredentialChange) {
Person person = personController.findPersonById(id);
if (person == null) {
return Response.status(Status.NOT_FOUND).build();
}
// Check that logged in user is the same we're modifying
User user = sessionController.getUser();
// User needs to be logged in for password change
if (user == null) {
return Response.status(Status.BAD_REQUEST).build();
}
// Persons must match
if (!user.getPerson().getId().equals(person.getId())) {
return Response.status(Status.BAD_REQUEST).build();
}
if (!restSecurity.hasPermission(new String[] { PersonPermissions.PERSON_OWNER }, person, Style.OR)) {
return Response.status(Status.FORBIDDEN).build();
}
String newUserName = userCredentialChange.getUsername();
String newPassword = userCredentialChange.getNewPassword();
String oldPassword = userCredentialChange.getOldPassword();
boolean usernameBlank = StringUtils.isBlank(newUserName);
boolean passwordBlank = StringUtils.isBlank(newPassword);
if (!usernameBlank || !passwordBlank) {
// TODO: Support for multiple internal authentication providers
List<InternalAuthenticationProvider> internalAuthenticationProviders = AuthenticationProviderVault.getInstance().getInternalAuthenticationProviders();
if (internalAuthenticationProviders.size() == 1) {
InternalAuthenticationProvider internalAuthenticationProvider = internalAuthenticationProviders.get(0);
if (internalAuthenticationProvider != null) {
UserIdentification userIdentification = userIdentificationDAO.findByAuthSourceAndPerson(internalAuthenticationProvider.getName(), person);
if (internalAuthenticationProvider.canUpdateCredentials()) {
if (userIdentification == null) {
String externalId = internalAuthenticationProvider.createCredentials(newUserName, newPassword);
userIdentificationDAO.create(person, internalAuthenticationProvider.getName(), externalId);
} else {
if ("-1".equals(userIdentification.getExternalId())) {
String externalId = internalAuthenticationProvider.createCredentials(newUserName, newPassword);
userIdentificationDAO.updateExternalId(userIdentification, externalId);
} else {
// Check that old password matches
User userByName = internalAuthenticationProvider.getUserByName(newUserName);
boolean usernameAvailable = userByName == null || userByName.getId().equals(user.getId());
if (!usernameAvailable) {
return Response.status(Status.CONFLICT).entity("Duplicate username").build();
}
if (internalAuthenticationProvider.validatePassword(userIdentification.getExternalId(), oldPassword)) {
if (!StringUtils.isBlank(newUserName))
internalAuthenticationProvider.updateUsername(userIdentification.getExternalId(), newUserName);
if (!StringUtils.isBlank(newPassword))
internalAuthenticationProvider.updatePassword(userIdentification.getExternalId(), newPassword);
} else {
return Response.status(Status.FORBIDDEN).build();
}
}
}
}
}
}
}
return Response.noContent().build();
}
use of fi.otavanopisto.pyramus.plugin.auth.InternalAuthenticationProvider in project pyramus by otavanopisto.
the class EditStudentJSONRequestController method process.
public void process(JSONRequestContext requestContext) {
StudentDAO studentDAO = DAOFactory.getInstance().getStudentDAO();
PersonDAO personDAO = DAOFactory.getInstance().getPersonDAO();
StudentActivityTypeDAO activityTypeDAO = DAOFactory.getInstance().getStudentActivityTypeDAO();
StudentExaminationTypeDAO examinationTypeDAO = DAOFactory.getInstance().getStudentExaminationTypeDAO();
StudentEducationalLevelDAO educationalLevelDAO = DAOFactory.getInstance().getStudentEducationalLevelDAO();
StudentStudyEndReasonDAO studyEndReasonDAO = DAOFactory.getInstance().getStudentStudyEndReasonDAO();
UserVariableDAO userVariableDAO = DAOFactory.getInstance().getUserVariableDAO();
LanguageDAO languageDAO = DAOFactory.getInstance().getLanguageDAO();
MunicipalityDAO municipalityDAO = DAOFactory.getInstance().getMunicipalityDAO();
NationalityDAO nationalityDAO = DAOFactory.getInstance().getNationalityDAO();
SchoolDAO schoolDAO = DAOFactory.getInstance().getSchoolDAO();
AddressDAO addressDAO = DAOFactory.getInstance().getAddressDAO();
ContactInfoDAO contactInfoDAO = DAOFactory.getInstance().getContactInfoDAO();
EmailDAO emailDAO = DAOFactory.getInstance().getEmailDAO();
PhoneNumberDAO phoneNumberDAO = DAOFactory.getInstance().getPhoneNumberDAO();
TagDAO tagDAO = DAOFactory.getInstance().getTagDAO();
ContactTypeDAO contactTypeDAO = DAOFactory.getInstance().getContactTypeDAO();
UserIdentificationDAO userIdentificationDAO = DAOFactory.getInstance().getUserIdentificationDAO();
UserDAO userDAO = DAOFactory.getInstance().getUserDAO();
CurriculumDAO curriculumDAO = DAOFactory.getInstance().getCurriculumDAO();
StudentLodgingPeriodDAO lodgingPeriodDAO = DAOFactory.getInstance().getStudentLodgingPeriodDAO();
PersonVariableDAO personVariableDAO = DAOFactory.getInstance().getPersonVariableDAO();
StudentStudyPeriodDAO studentStudyPeriodDAO = DAOFactory.getInstance().getStudentStudyPeriodDAO();
StaffMemberDAO staffMemberDAO = DAOFactory.getInstance().getStaffMemberDAO();
User loggedUser = userDAO.findById(requestContext.getLoggedUserId());
Long personId = NumberUtils.createLong(requestContext.getRequest().getParameter("personId"));
Person person = personDAO.findById(personId);
Date birthday = requestContext.getDate("birthday");
String ssecId = requestContext.getString("ssecId");
Sex sex = (Sex) requestContext.getEnum("gender", Sex.class);
String basicInfo = requestContext.getString("basicInfo");
Long version = requestContext.getLong("version");
Boolean secureInfo = requestContext.getBoolean("secureInfo");
String username = requestContext.getString("username");
String password = requestContext.getString("password1");
String password2 = requestContext.getString("password2");
if (UserUtils.allowEditCredentials(loggedUser, person)) {
if (!person.getVersion().equals(version)) {
throw new StaleObjectStateException(Person.class.getName(), person.getId());
}
boolean usernameBlank = StringUtils.isBlank(username);
boolean passwordBlank = StringUtils.isBlank(password);
UserIdentification userIdentification = userIdentificationDAO.findByAuthSourceAndPerson("internal", person);
if (usernameBlank && passwordBlank) {
// #1108: Existing credential deletion
if (userIdentification != null && NumberUtils.isNumber(userIdentification.getExternalId())) {
InternalAuthDAO internalAuthDAO = DAOFactory.getInstance().getInternalAuthDAO();
InternalAuth internalAuth = internalAuthDAO.findById(new Long(userIdentification.getExternalId()));
if (internalAuth != null) {
internalAuthDAO.delete(internalAuth);
}
userIdentificationDAO.delete(userIdentification);
}
} else if (!usernameBlank || !passwordBlank) {
if (!passwordBlank && !password.equals(password2)) {
throw new SmvcRuntimeException(PyramusStatusCode.PASSWORD_MISMATCH, "Passwords don't match");
}
// #921: Check username
InternalAuthDAO internalAuthDAO = DAOFactory.getInstance().getInternalAuthDAO();
InternalAuth internalAuth = internalAuthDAO.findByUsername(username);
if (internalAuth != null) {
userIdentification = userIdentificationDAO.findByAuthSourceAndExternalId("internal", internalAuth.getId().toString());
if (userIdentification != null && !person.getId().equals(userIdentification.getPerson().getId())) {
throw new RuntimeException(Messages.getInstance().getText(requestContext.getRequest().getLocale(), "generic.errors.usernameInUse"));
}
} else if (!usernameBlank && passwordBlank) {
throw new RuntimeException(Messages.getInstance().getText(requestContext.getRequest().getLocale(), "generic.errors.nopassword"));
}
// TODO: Support for multiple internal authentication providers
List<InternalAuthenticationProvider> internalAuthenticationProviders = AuthenticationProviderVault.getInstance().getInternalAuthenticationProviders();
if (internalAuthenticationProviders.size() == 1) {
InternalAuthenticationProvider internalAuthenticationProvider = internalAuthenticationProviders.get(0);
if (internalAuthenticationProvider != null) {
userIdentification = userIdentificationDAO.findByAuthSourceAndPerson(internalAuthenticationProvider.getName(), person);
if (internalAuthenticationProvider.canUpdateCredentials()) {
if (userIdentification == null) {
String externalId = internalAuthenticationProvider.createCredentials(username, password);
userIdentificationDAO.create(person, internalAuthenticationProvider.getName(), externalId);
} else {
if ("-1".equals(userIdentification.getExternalId())) {
String externalId = internalAuthenticationProvider.createCredentials(username, password);
userIdentificationDAO.updateExternalId(userIdentification, externalId);
} else {
if (!StringUtils.isBlank(username))
internalAuthenticationProvider.updateUsername(userIdentification.getExternalId(), username);
if (!StringUtils.isBlank(password))
internalAuthenticationProvider.updatePassword(userIdentification.getExternalId(), password);
}
}
}
}
}
}
}
// Abstract student
personDAO.update(person, birthday, ssecId, sex, basicInfo, secureInfo);
// Person Variables
Integer personVariableCount = requestContext.getInteger("personVariablesTable.rowCount");
if (personVariableCount != null) {
for (int i = 0; i < personVariableCount; i++) {
String colPrefix = "personVariablesTable." + i;
Long edited = requestContext.getLong(colPrefix + ".edited");
if (Objects.equals(new Long(1), edited)) {
String variableKey = requestContext.getString(colPrefix + ".key");
String variableValue = requestContext.getString(colPrefix + ".value");
personVariableDAO.setPersonVariable(person, variableKey, variableValue);
}
}
}
List<Student> students = UserUtils.canAccessAllOrganizations(loggedUser) ? studentDAO.listByPerson(person) : studentDAO.listByPersonAndOrganization(person, loggedUser.getOrganization());
for (Student student : students) {
int rowCount = requestContext.getInteger("emailTable." + student.getId() + ".rowCount");
for (int i = 0; i < rowCount; i++) {
String colPrefix = "emailTable." + student.getId() + "." + i;
String email = StringUtils.trim(requestContext.getString(colPrefix + ".email"));
if (StringUtils.isNotBlank(email)) {
ContactType contactType = contactTypeDAO.findById(requestContext.getLong(colPrefix + ".contactTypeId"));
if (!UserUtils.isAllowedEmail(email, contactType, person.getId()))
throw new RuntimeException(Messages.getInstance().getText(requestContext.getRequest().getLocale(), "generic.errors.emailInUse"));
}
}
}
for (Student student : students) {
Long studentVersion = requestContext.getLong("studentVersion." + student.getId());
if (!student.getVersion().equals(studentVersion))
throw new StaleObjectStateException(Student.class.getName(), student.getId());
String firstName = StringUtils.trim(requestContext.getString("firstName." + student.getId()));
String lastName = StringUtils.trim(requestContext.getString("lastName." + student.getId()));
String nickname = StringUtils.trim(requestContext.getString("nickname." + student.getId()));
String additionalInfo = requestContext.getString("additionalInfo." + student.getId());
String additionalContactInfo = requestContext.getString("otherContactInfo." + student.getId());
String education = requestContext.getString("education." + student.getId());
Double previousStudies = requestContext.getDouble("previousStudies." + student.getId());
Date studyTimeEnd = requestContext.getDate("studyTimeEnd." + student.getId());
Date studyStartDate = requestContext.getDate("studyStartDate." + student.getId());
Date studyEndDate = requestContext.getDate("studyEndDate." + student.getId());
String studyEndText = requestContext.getString("studyEndText." + student.getId());
String tagsText = requestContext.getString("tags." + student.getId());
StudentFunding funding = (StudentFunding) requestContext.getEnum("funding." + student.getId(), StudentFunding.class);
Set<Tag> tagEntities = new HashSet<>();
if (!StringUtils.isBlank(tagsText)) {
List<String> tags = Arrays.asList(tagsText.split("[\\ ,]"));
for (String tag : tags) {
if (!StringUtils.isBlank(tag)) {
Tag tagEntity = tagDAO.findByText(tag.trim());
if (tagEntity == null)
tagEntity = tagDAO.create(tag);
tagEntities.add(tagEntity);
}
}
}
Long entityId = requestContext.getLong("language." + student.getId());
Language language = entityId == null ? null : languageDAO.findById(entityId);
entityId = requestContext.getLong("activityType." + student.getId());
StudentActivityType activityType = entityId == null ? null : activityTypeDAO.findById(entityId);
entityId = requestContext.getLong("examinationType." + student.getId());
StudentExaminationType examinationType = entityId == null ? null : examinationTypeDAO.findById(entityId);
entityId = requestContext.getLong("educationalLevel." + student.getId());
StudentEducationalLevel educationalLevel = entityId == null ? null : educationalLevelDAO.findById(entityId);
entityId = requestContext.getLong("nationality." + student.getId());
Nationality nationality = entityId == null ? null : nationalityDAO.findById(entityId);
entityId = requestContext.getLong("municipality." + student.getId());
Municipality municipality = entityId == null ? null : municipalityDAO.findById(entityId);
entityId = requestContext.getLong("school." + student.getId());
School school = entityId != null && entityId > 0 ? schoolDAO.findById(entityId) : null;
entityId = requestContext.getLong("studyEndReason." + student.getId());
StudentStudyEndReason studyEndReason = entityId == null ? null : studyEndReasonDAO.findById(entityId);
entityId = requestContext.getLong("curriculum." + student.getId());
Curriculum curriculum = entityId == null ? null : curriculumDAO.findById(entityId);
entityId = requestContext.getLong("studyApprover." + student.getId());
StaffMember approver = entityId == null ? null : staffMemberDAO.findById(entityId);
Integer variableCount = requestContext.getInteger("variablesTable." + student.getId() + ".rowCount");
if (variableCount != null) {
for (int i = 0; i < variableCount; i++) {
String colPrefix = "variablesTable." + student.getId() + "." + i;
Long edited = requestContext.getLong(colPrefix + ".edited");
if (Objects.equals(new Long(1), edited)) {
String variableKey = requestContext.getString(colPrefix + ".key");
String variableValue = requestContext.getString(colPrefix + ".value");
userVariableDAO.setUserVariable(student, variableKey, variableValue);
}
}
}
Integer lodgingPeriodsCount = requestContext.getInteger("lodgingPeriodsTable." + student.getId() + ".rowCount");
if (lodgingPeriodsCount != null) {
Set<Long> remainingIds = new HashSet<>();
for (int i = 0; i < lodgingPeriodsCount; i++) {
String colPrefix = "lodgingPeriodsTable." + student.getId() + "." + i;
Long id = requestContext.getLong(colPrefix + ".id");
Date begin = requestContext.getDate(colPrefix + ".begin");
Date end = requestContext.getDate(colPrefix + ".end");
if (id == -1 && begin != null) {
StudentLodgingPeriod lodgingPeriod = lodgingPeriodDAO.create(student, begin, end);
remainingIds.add(lodgingPeriod.getId());
} else if (id > 0) {
StudentLodgingPeriod lodgingPeriod = lodgingPeriodDAO.findById(id);
remainingIds.add(id);
if (begin != null) {
if (lodgingPeriod != null) {
lodgingPeriodDAO.update(lodgingPeriod, begin, end);
}
}
}
}
List<StudentLodgingPeriod> periods = lodgingPeriodDAO.listByStudent(student);
periods.removeIf(period -> remainingIds.contains(period.getId()));
periods.forEach(period -> lodgingPeriodDAO.delete(period));
}
Integer studyPeriodsCount = requestContext.getInteger("studentStudyPeriodsTable." + student.getId() + ".rowCount");
if (studyPeriodsCount != null) {
Set<Long> remainingIds = new HashSet<>();
for (int i = 0; i < studyPeriodsCount; i++) {
String colPrefix = "studentStudyPeriodsTable." + student.getId() + "." + i;
Long id = requestContext.getLong(colPrefix + ".id");
StudentStudyPeriodType periodType = (StudentStudyPeriodType) requestContext.getEnum(colPrefix + ".type", StudentStudyPeriodType.class);
Date begin = requestContext.getDate(colPrefix + ".begin");
// Null out the end date when period type allows only begin dates
Date end = !StudentStudyPeriodType.BEGINDATE_ONLY.contains(periodType) ? requestContext.getDate(colPrefix + ".end") : null;
if (id == -1 && begin != null) {
StudentStudyPeriod studyPeriod = studentStudyPeriodDAO.create(student, begin, end, periodType);
remainingIds.add(studyPeriod.getId());
} else if (id > 0) {
StudentStudyPeriod studyPeriod = studentStudyPeriodDAO.findById(id);
remainingIds.add(id);
if (begin != null) {
if (studyPeriod != null) {
studentStudyPeriodDAO.update(studyPeriod, begin, end, periodType);
}
}
}
}
List<StudentStudyPeriod> periods = studentStudyPeriodDAO.listByStudent(student);
periods.removeIf(period -> remainingIds.contains(period.getId()));
periods.forEach(period -> studentStudyPeriodDAO.delete(period));
}
boolean studiesEnded = student.getStudyEndDate() == null && studyEndDate != null;
// Student
studentDAO.update(student, firstName, lastName, nickname, additionalInfo, studyTimeEnd, activityType, examinationType, educationalLevel, education, nationality, municipality, language, school, curriculum, previousStudies, studyStartDate, studyEndDate, studyEndReason, studyEndText);
studentDAO.updateApprover(student, approver);
studentDAO.updateFunding(student, funding);
// Tags
studentDAO.setStudentTags(student, tagEntities);
// Contact info
contactInfoDAO.update(student.getContactInfo(), additionalContactInfo);
// Student addresses
Set<Long> existingAddresses = new HashSet<>();
int rowCount = requestContext.getInteger("addressTable." + student.getId() + ".rowCount");
for (int i = 0; i < rowCount; i++) {
String colPrefix = "addressTable." + student.getId() + "." + i;
Long addressId = requestContext.getLong(colPrefix + ".addressId");
Boolean defaultAddress = requestContext.getBoolean(colPrefix + ".defaultAddress");
ContactType contactType = contactTypeDAO.findById(requestContext.getLong(colPrefix + ".contactTypeId"));
String name = requestContext.getString(colPrefix + ".name");
String street = requestContext.getString(colPrefix + ".street");
String postal = requestContext.getString(colPrefix + ".postal");
String city = requestContext.getString(colPrefix + ".city");
String country = requestContext.getString(colPrefix + ".country");
boolean hasAddress = name != null || street != null || postal != null || city != null || country != null;
if (addressId == -1 && hasAddress) {
Address address = addressDAO.create(student.getContactInfo(), contactType, name, street, postal, city, country, defaultAddress);
existingAddresses.add(address.getId());
} else if (addressId > 0) {
Address address = addressDAO.findById(addressId);
if (hasAddress) {
existingAddresses.add(addressId);
addressDAO.update(address, defaultAddress, contactType, name, street, postal, city, country);
}
}
}
List<Address> addresses = student.getContactInfo().getAddresses();
for (int i = addresses.size() - 1; i >= 0; i--) {
Address address = addresses.get(i);
if (!existingAddresses.contains(address.getId())) {
addressDAO.delete(address);
}
}
// Email addresses
Set<Long> existingEmails = new HashSet<>();
rowCount = requestContext.getInteger("emailTable." + student.getId() + ".rowCount");
for (int i = 0; i < rowCount; i++) {
String colPrefix = "emailTable." + student.getId() + "." + i;
Boolean defaultAddress = requestContext.getBoolean(colPrefix + ".defaultAddress");
ContactType contactType = contactTypeDAO.findById(requestContext.getLong(colPrefix + ".contactTypeId"));
String email = StringUtils.trim(requestContext.getString(colPrefix + ".email"));
if (StringUtils.isNotBlank(email)) {
Long emailId = requestContext.getLong(colPrefix + ".emailId");
if (emailId == -1) {
emailId = emailDAO.create(student.getContactInfo(), contactType, defaultAddress, email).getId();
} else {
emailDAO.update(emailDAO.findById(emailId), contactType, defaultAddress, email);
}
existingEmails.add(emailId);
}
}
List<Email> emails = student.getContactInfo().getEmails();
for (int i = emails.size() - 1; i >= 0; i--) {
Email email = emails.get(i);
if (!existingEmails.contains(email.getId())) {
emailDAO.delete(email);
}
}
// Phone numbers
Set<Long> existingPhoneNumbers = new HashSet<>();
rowCount = requestContext.getInteger("phoneTable." + student.getId() + ".rowCount");
for (int i = 0; i < rowCount; i++) {
String colPrefix = "phoneTable." + student.getId() + "." + i;
Boolean defaultNumber = requestContext.getBoolean(colPrefix + ".defaultNumber");
ContactType contactType = contactTypeDAO.findById(requestContext.getLong(colPrefix + ".contactTypeId"));
String number = requestContext.getString(colPrefix + ".phone");
Long phoneId = requestContext.getLong(colPrefix + ".phoneId");
if (phoneId == -1 && number != null) {
phoneId = phoneNumberDAO.create(student.getContactInfo(), contactType, defaultNumber, number).getId();
existingPhoneNumbers.add(phoneId);
} else if (phoneId > 0 && number != null) {
phoneNumberDAO.update(phoneNumberDAO.findById(phoneId), contactType, defaultNumber, number);
existingPhoneNumbers.add(phoneId);
}
}
List<PhoneNumber> phoneNumbers = student.getContactInfo().getPhoneNumbers();
for (int i = phoneNumbers.size() - 1; i >= 0; i--) {
PhoneNumber phoneNumber = phoneNumbers.get(i);
if (!existingPhoneNumbers.contains(phoneNumber.getId())) {
phoneNumberDAO.delete(phoneNumber);
}
}
Long studyProgrammeId = student.getStudyProgramme() != null ? student.getStudyProgramme().getId() : null;
// #4226: Remove applications of nettipk/nettilukio students when their studies end
if (studiesEnded && studyProgrammeId != null && (studyProgrammeId == 6L || studyProgrammeId == 7L)) {
ApplicationDAO applicationDAO = DAOFactory.getInstance().getApplicationDAO();
Application application = applicationDAO.findByStudent(student);
if (application != null) {
ApplicationUtils.deleteApplication(application);
}
}
}
// Contact information of a student won't be reflected to Person
// used when searching students, so a manual re-index is needed
person = personDAO.findById(person.getId());
personDAO.forceReindex(person);
requestContext.setRedirectURL(requestContext.getReferer(true));
}
use of fi.otavanopisto.pyramus.plugin.auth.InternalAuthenticationProvider in project pyramus by otavanopisto.
the class CreateUserJSONRequestController method process.
/**
* Processes the request to create a new user. Simply gathers the fields submitted from the
* web page and adds the user to the database.
*
* @param requestContext The JSON request context
*/
public void process(JSONRequestContext requestContext) {
StaffMemberDAO userDAO = DAOFactory.getInstance().getStaffMemberDAO();
AddressDAO addressDAO = DAOFactory.getInstance().getAddressDAO();
EmailDAO emailDAO = DAOFactory.getInstance().getEmailDAO();
PhoneNumberDAO phoneNumberDAO = DAOFactory.getInstance().getPhoneNumberDAO();
TagDAO tagDAO = DAOFactory.getInstance().getTagDAO();
ContactTypeDAO contactTypeDAO = DAOFactory.getInstance().getContactTypeDAO();
PersonDAO personDAO = DAOFactory.getInstance().getPersonDAO();
UserIdentificationDAO userIdentificationDAO = DAOFactory.getInstance().getUserIdentificationDAO();
OrganizationDAO organizationDAO = DAOFactory.getInstance().getOrganizationDAO();
Long personId = requestContext.getLong("personId");
int emailCount2 = requestContext.getInteger("emailTable.rowCount");
for (int i = 0; i < emailCount2; i++) {
String colPrefix = "emailTable." + i;
String email = StringUtils.trim(requestContext.getString(colPrefix + ".email"));
if (StringUtils.isNotBlank(email)) {
ContactType contactType = contactTypeDAO.findById(requestContext.getLong(colPrefix + ".contactTypeId"));
if (!UserUtils.isAllowedEmail(email, contactType, personId)) {
throw new RuntimeException(Messages.getInstance().getText(requestContext.getRequest().getLocale(), "generic.errors.emailInUse"));
}
}
}
// Fields from the web page
String firstName = requestContext.getString("firstName");
String lastName = requestContext.getString("lastName");
String title = requestContext.getString("title");
Role role = Role.getRole(requestContext.getInteger("role"));
String tagsText = requestContext.getString("tags");
String username = requestContext.getString("username");
String password = requestContext.getString("password1");
String password2 = requestContext.getString("password2");
Long organizationId = requestContext.getLong("organizationId");
User loggedUser = userDAO.findById(requestContext.getLoggedUserId());
Organization organization = organizationId != null ? organizationDAO.findById(organizationId) : null;
if (!UserUtils.canAccessOrganization(loggedUser, organization)) {
throw new SmvcRuntimeException(PyramusStatusCode.UNAUTHORIZED, "Invalid organization.");
}
Set<Tag> tagEntities = new HashSet<>();
if (!StringUtils.isBlank(tagsText)) {
List<String> tags = Arrays.asList(tagsText.split("[\\ ,]"));
for (String tag : tags) {
if (!StringUtils.isBlank(tag)) {
Tag tagEntity = tagDAO.findByText(tag.trim());
if (tagEntity == null)
tagEntity = tagDAO.create(tag);
tagEntities.add(tagEntity);
}
}
}
// User
Person person = personId != null ? personDAO.findById(personId) : personDAO.create(null, null, null, null, Boolean.FALSE);
StaffMember user = userDAO.create(organization, firstName, lastName, role, person, false);
if (title != null)
userDAO.updateTitle(user, title);
if (person.getDefaultUser() == null) {
personDAO.updateDefaultUser(person, user);
}
if (AuthenticationProviderVault.getInstance().hasInternalStrategies()) {
boolean usernameBlank = StringUtils.isBlank(username);
boolean passwordBlank = StringUtils.isBlank(password);
// TODO: Support multiple internal authentication sources
if (!usernameBlank) {
// #921: Check username
InternalAuthDAO internalAuthDAO = DAOFactory.getInstance().getInternalAuthDAO();
InternalAuth internalAuth = internalAuthDAO.findByUsername(username);
if (internalAuth != null) {
throw new RuntimeException(Messages.getInstance().getText(requestContext.getRequest().getLocale(), "generic.errors.usernameInUse"));
}
InternalAuthenticationProvider internalAuthenticationProvider = AuthenticationProviderVault.getInstance().getInternalAuthenticationProviders().get(0);
if (!passwordBlank) {
if (!password.equals(password2))
throw new SmvcRuntimeException(PyramusStatusCode.PASSWORD_MISMATCH, "Passwords don't match");
}
String externalId = internalAuthenticationProvider.createCredentials(username, password);
userIdentificationDAO.create(person, internalAuthenticationProvider.getName(), externalId);
}
}
// Tags
userDAO.updateTags(user, tagEntities);
// Addresses
int addressCount = requestContext.getInteger("addressTable.rowCount");
for (int i = 0; i < addressCount; i++) {
String colPrefix = "addressTable." + i;
Boolean defaultAddress = requestContext.getBoolean(colPrefix + ".defaultAddress");
ContactType contactType = contactTypeDAO.findById(requestContext.getLong(colPrefix + ".contactTypeId"));
String name = requestContext.getString(colPrefix + ".name");
String street = requestContext.getString(colPrefix + ".street");
String postal = requestContext.getString(colPrefix + ".postal");
String city = requestContext.getString(colPrefix + ".city");
String country = requestContext.getString(colPrefix + ".country");
boolean hasAddress = name != null || street != null || postal != null || city != null || country != null;
if (hasAddress) {
addressDAO.create(user.getContactInfo(), contactType, name, street, postal, city, country, defaultAddress);
}
}
// Email addresses
int emailCount = requestContext.getInteger("emailTable.rowCount");
for (int i = 0; i < emailCount; i++) {
String colPrefix = "emailTable." + i;
Boolean defaultAddress = requestContext.getBoolean(colPrefix + ".defaultAddress");
ContactType contactType = contactTypeDAO.findById(requestContext.getLong(colPrefix + ".contactTypeId"));
String email = StringUtils.trim(requestContext.getString(colPrefix + ".email"));
if (StringUtils.isNotBlank(email)) {
emailDAO.create(user.getContactInfo(), contactType, defaultAddress, email);
}
}
// Phone numbers
int phoneCount = requestContext.getInteger("phoneTable.rowCount");
for (int i = 0; i < phoneCount; i++) {
String colPrefix = "phoneTable." + i;
Boolean defaultNumber = requestContext.getBoolean(colPrefix + ".defaultNumber");
ContactType contactType = contactTypeDAO.findById(requestContext.getLong(colPrefix + ".contactTypeId"));
String number = requestContext.getString(colPrefix + ".phone");
if (number != null) {
phoneNumberDAO.create(user.getContactInfo(), contactType, defaultNumber, number);
}
}
// Redirect to the Edit User view
requestContext.setRedirectURL(requestContext.getRequest().getContextPath() + "/users/edituser.page?userId=" + user.getId());
}
use of fi.otavanopisto.pyramus.plugin.auth.InternalAuthenticationProvider in project pyramus by otavanopisto.
the class EditUserJSONRequestController method process.
/**
* Processes the request to edit an user. Simply gathers the fields submitted from the
* web page and updates the database.
*
* @param jsonRequestContext The JSON request context
*/
public void process(JSONRequestContext requestContext) {
StaffMemberDAO staffDAO = DAOFactory.getInstance().getStaffMemberDAO();
UserVariableDAO userVariableDAO = DAOFactory.getInstance().getUserVariableDAO();
AddressDAO addressDAO = DAOFactory.getInstance().getAddressDAO();
EmailDAO emailDAO = DAOFactory.getInstance().getEmailDAO();
PhoneNumberDAO phoneNumberDAO = DAOFactory.getInstance().getPhoneNumberDAO();
TagDAO tagDAO = DAOFactory.getInstance().getTagDAO();
ContactTypeDAO contactTypeDAO = DAOFactory.getInstance().getContactTypeDAO();
UserIdentificationDAO userIdentificationDAO = DAOFactory.getInstance().getUserIdentificationDAO();
OrganizationDAO organizationDAO = DAOFactory.getInstance().getOrganizationDAO();
Long loggedUserId = requestContext.getLoggedUserId();
StaffMember loggedUser = staffDAO.findById(loggedUserId);
Role loggedUserRole = loggedUser.getRole();
Long userId = requestContext.getLong("userId");
StaffMember user = staffDAO.findById(userId);
if (user.getOrganization() != null) {
// Check that the editing user has access to the organization
if (!UserUtils.canAccessOrganization(loggedUser, user.getOrganization())) {
throw new RuntimeException("Cannot access users' organization");
}
} else {
// Check that the editing user has generic access when users' organization is null
if (!UserUtils.canAccessAllOrganizations(loggedUser)) {
throw new RuntimeException("Cannot access users' organization");
}
}
String firstName = requestContext.getString("firstName");
String lastName = requestContext.getString("lastName");
String title = requestContext.getString("title");
Role role = Role.getRole(requestContext.getInteger("role").intValue());
String username = requestContext.getString("username");
String password = requestContext.getString("password1");
String password2 = requestContext.getString("password2");
String tagsText = requestContext.getString("tags");
Long organizationId = requestContext.getLong("organizationId");
Organization organization = null;
if (organizationId != null) {
organization = organizationDAO.findById(organizationId);
}
if (organization != null) {
// Check that the editing user has access to the organization
if (!UserUtils.canAccessOrganization(loggedUser, organization)) {
throw new RuntimeException("Cannot access organization");
}
} else {
// Check that the editing user can set the organization as null
if (!UserUtils.canAccessAllOrganizations(loggedUser)) {
throw new RuntimeException("Cannot access organization");
}
}
// #921: Check username
if (!StringUtils.isBlank(username)) {
InternalAuthDAO internalAuthDAO = DAOFactory.getInstance().getInternalAuthDAO();
InternalAuth internalAuth = internalAuthDAO.findByUsername(username);
if (internalAuth != null) {
UserIdentification userIdentification = userIdentificationDAO.findByAuthSourceAndExternalId("internal", internalAuth.getId().toString());
if (userIdentification != null && !user.getPerson().getId().equals(userIdentification.getPerson().getId())) {
throw new RuntimeException(Messages.getInstance().getText(requestContext.getRequest().getLocale(), "generic.errors.usernameInUse"));
}
}
}
int emailCount2 = requestContext.getInteger("emailTable.rowCount");
for (int i = 0; i < emailCount2; i++) {
String colPrefix = "emailTable." + i;
String email = StringUtils.trim(requestContext.getString(colPrefix + ".email"));
if (StringUtils.isNotBlank(email)) {
ContactType contactType = contactTypeDAO.findById(requestContext.getLong(colPrefix + ".contactTypeId"));
if (!UserUtils.isAllowedEmail(email, contactType, user.getPerson().getId())) {
throw new RuntimeException(Messages.getInstance().getText(requestContext.getRequest().getLocale(), "generic.errors.emailInUse"));
}
}
}
Set<Tag> tagEntities = new HashSet<>();
if (!StringUtils.isBlank(tagsText)) {
List<String> tags = Arrays.asList(tagsText.split("[\\ ,]"));
for (String tag : tags) {
if (!StringUtils.isBlank(tag)) {
Tag tagEntity = tagDAO.findByText(tag.trim());
if (tagEntity == null)
tagEntity = tagDAO.create(tag);
tagEntities.add(tagEntity);
}
}
}
staffDAO.update(user, organization, firstName, lastName, role);
if (Role.ADMINISTRATOR.equals(loggedUserRole)) {
Integer propertyCount = requestContext.getInteger("propertiesTable.rowCount");
for (int i = 0; i < (propertyCount != null ? propertyCount : 0); i++) {
String colPrefix = "propertiesTable." + i;
String propertyKey = requestContext.getString(colPrefix + ".key");
String propertyValue = requestContext.getString(colPrefix + ".value");
if (StaffMemberProperties.isProperty(propertyKey)) {
user.getProperties().put(propertyKey, propertyValue);
}
}
}
staffDAO.updateTitle(user, title);
// SSN
String ssn = requestContext.getString("ssn");
String existingSsn = user.getPerson().getSocialSecurityNumber();
if (!StringUtils.equals(ssn, existingSsn)) {
PersonDAO personDAO = DAOFactory.getInstance().getPersonDAO();
personDAO.updateSocialSecurityNumber(user.getPerson(), ssn);
}
// Tags
staffDAO.updateTags(user, tagEntities);
// Addresses
Set<Long> existingAddresses = new HashSet<>();
int addressCount = requestContext.getInteger("addressTable.rowCount");
for (int i = 0; i < addressCount; i++) {
String colPrefix = "addressTable." + i;
Long addressId = requestContext.getLong(colPrefix + ".addressId");
Boolean defaultAddress = requestContext.getBoolean(colPrefix + ".defaultAddress");
ContactType contactType = contactTypeDAO.findById(requestContext.getLong(colPrefix + ".contactTypeId"));
String name = requestContext.getString(colPrefix + ".name");
String street = requestContext.getString(colPrefix + ".street");
String postal = requestContext.getString(colPrefix + ".postal");
String city = requestContext.getString(colPrefix + ".city");
String country = requestContext.getString(colPrefix + ".country");
boolean hasAddress = name != null || street != null || postal != null || city != null || country != null;
if (addressId == -1 && hasAddress) {
Address address = addressDAO.create(user.getContactInfo(), contactType, name, street, postal, city, country, defaultAddress);
existingAddresses.add(address.getId());
} else if (addressId > 0) {
Address address = addressDAO.findById(addressId);
if (hasAddress) {
existingAddresses.add(addressId);
addressDAO.update(address, defaultAddress, contactType, name, street, postal, city, country);
}
}
}
List<Address> addresses = user.getContactInfo().getAddresses();
for (int i = addresses.size() - 1; i >= 0; i--) {
Address address = addresses.get(i);
if (!existingAddresses.contains(address.getId())) {
addressDAO.delete(address);
}
}
// E-mail addresses
Set<Long> existingEmails = new HashSet<>();
int emailCount = requestContext.getInteger("emailTable.rowCount");
for (int i = 0; i < emailCount; i++) {
String colPrefix = "emailTable." + i;
Boolean defaultAddress = requestContext.getBoolean(colPrefix + ".defaultAddress");
ContactType contactType = contactTypeDAO.findById(requestContext.getLong(colPrefix + ".contactTypeId"));
String email = StringUtils.trim(requestContext.getString(colPrefix + ".email"));
Long emailId = requestContext.getLong(colPrefix + ".emailId");
if (emailId == -1 && email != null) {
emailId = emailDAO.create(user.getContactInfo(), contactType, defaultAddress, email).getId();
existingEmails.add(emailId);
} else if (emailId > 0 && email != null) {
existingEmails.add(emailId);
emailDAO.update(emailDAO.findById(emailId), contactType, defaultAddress, email);
}
}
List<Email> emails = user.getContactInfo().getEmails();
for (int i = emails.size() - 1; i >= 0; i--) {
Email email = emails.get(i);
if (!existingEmails.contains(email.getId())) {
emailDAO.delete(email);
}
}
// Phone numbers
Set<Long> existingPhoneNumbers = new HashSet<>();
int phoneCount = requestContext.getInteger("phoneTable.rowCount");
for (int i = 0; i < phoneCount; i++) {
String colPrefix = "phoneTable." + i;
Boolean defaultNumber = requestContext.getBoolean(colPrefix + ".defaultNumber");
ContactType contactType = contactTypeDAO.findById(requestContext.getLong(colPrefix + ".contactTypeId"));
String number = requestContext.getString(colPrefix + ".phone");
Long phoneId = requestContext.getLong(colPrefix + ".phoneId");
if (phoneId == -1 && number != null) {
phoneId = phoneNumberDAO.create(user.getContactInfo(), contactType, defaultNumber, number).getId();
existingPhoneNumbers.add(phoneId);
} else if (phoneId > 0 && number != null) {
phoneNumberDAO.update(phoneNumberDAO.findById(phoneId), contactType, defaultNumber, number);
existingPhoneNumbers.add(phoneId);
}
}
List<PhoneNumber> phoneNumbers = user.getContactInfo().getPhoneNumbers();
for (int i = phoneNumbers.size() - 1; i >= 0; i--) {
PhoneNumber phoneNumber = phoneNumbers.get(i);
if (!existingPhoneNumbers.contains(phoneNumber.getId())) {
phoneNumberDAO.delete(phoneNumber);
}
}
if (Role.ADMINISTRATOR.equals(loggedUserRole)) {
Integer variableCount = requestContext.getInteger("variablesTable.rowCount");
for (int i = 0; i < (variableCount != null ? variableCount : 0); i++) {
String colPrefix = "variablesTable." + i;
String variableKey = requestContext.getString(colPrefix + ".key");
String variableValue = requestContext.getString(colPrefix + ".value");
userVariableDAO.setUserVariable(user, variableKey, variableValue);
}
}
boolean usernameBlank = StringUtils.isBlank(username);
boolean passwordBlank = StringUtils.isBlank(password);
if (!usernameBlank || !passwordBlank) {
if (!passwordBlank) {
if (!password.equals(password2))
throw new SmvcRuntimeException(PyramusStatusCode.PASSWORD_MISMATCH, "Passwords don't match");
}
// TODO: Support for multiple internal authentication providers
List<InternalAuthenticationProvider> internalAuthenticationProviders = AuthenticationProviderVault.getInstance().getInternalAuthenticationProviders();
if (internalAuthenticationProviders.size() == 1) {
InternalAuthenticationProvider internalAuthenticationProvider = internalAuthenticationProviders.get(0);
if (internalAuthenticationProvider != null) {
UserIdentification userIdentification = userIdentificationDAO.findByAuthSourceAndPerson(internalAuthenticationProvider.getName(), user.getPerson());
if (internalAuthenticationProvider.canUpdateCredentials()) {
if (userIdentification == null) {
String externalId = internalAuthenticationProvider.createCredentials(username, password);
userIdentificationDAO.create(user.getPerson(), internalAuthenticationProvider.getName(), externalId);
} else {
if ("-1".equals(userIdentification.getExternalId())) {
String externalId = internalAuthenticationProvider.createCredentials(username, password);
userIdentificationDAO.updateExternalId(userIdentification, externalId);
} else {
if (!StringUtils.isBlank(username))
internalAuthenticationProvider.updateUsername(userIdentification.getExternalId(), username);
if (!StringUtils.isBlank(password))
internalAuthenticationProvider.updatePassword(userIdentification.getExternalId(), password);
}
}
}
}
}
}
if (requestContext.getLoggedUserId().equals(user.getId())) {
user = staffDAO.findById(user.getId());
HttpSession session = requestContext.getRequest().getSession(true);
session.setAttribute("loggedUserName", user.getFullName());
session.setAttribute("loggedUserRole", Role.valueOf(user.getRole().name()));
}
requestContext.setRedirectURL(requestContext.getReferer(true));
}
use of fi.otavanopisto.pyramus.plugin.auth.InternalAuthenticationProvider in project pyramus by otavanopisto.
the class LoginJSONRequestController method process.
/**
* Processes the request to log in. Authorizes the given credentials and if they match a user,
* stores the user into the session (keys <code>loggedUserId</code>, <code>loggedUserName</code>,
* and <code>loggedUserRole</code>).
* <p/>
* If the session contains a <code>loginRedirectUrl</code> key, redirects the user to that URL.
* Otherwise, redirects back to the index page of the application.
* <p/>
* If the user is already logged in or the authentication fails, a <code>PyramusRuntimeException</code>
* is thrown with a localized message stating so.
*
* @param jsonRequestContext The JSON request context
*/
public void process(JSONRequestContext jsonRequestContext) {
// Fields submitted from the web page
String username = jsonRequestContext.getRequest().getParameter("username");
String password = jsonRequestContext.getRequest().getParameter("password");
Locale locale = jsonRequestContext.getRequest().getLocale();
// Ensure that the user trying to login isn't already logged in
HttpSession session = jsonRequestContext.getRequest().getSession(true);
if (!session.isNew() && session.getAttribute("loggedUserId") != null) {
String msg = Messages.getInstance().getText(locale, "users.login.alreadyLoggedIn");
throw new AlreadyLoggedInException(PyramusStatusCode.ALREADY_LOGGED_IN, msg);
}
for (InternalAuthenticationProvider provider : AuthenticationProviderVault.getInstance().getInternalAuthenticationProviders()) {
try {
User user = provider.getUser(username, password);
if (user != null && !user.getArchived() && !Role.CLOSED.equals(user.getRole())) {
// User has been authorized, so store him in the session
session.setAttribute("loggedUserId", user.getId());
session.setAttribute("loggedUserName", user.getFullName());
session.setAttribute("authenticationProvider", provider.getName());
if (user instanceof StaffMember) {
session.setAttribute("loggedUserRole", UserRole.valueOf(((StaffMember) user).getRole().name()));
}
try {
DAOFactory.getInstance().getLoginLogDAO().create(user, new Date());
} catch (Exception ex) {
ex.printStackTrace();
}
if (session.getAttribute("loginRedirectUrl") != null) {
String url = (String) session.getAttribute("loginRedirectUrl");
session.removeAttribute("loginRedirectUrl");
jsonRequestContext.setRedirectURL(url);
} else {
jsonRequestContext.setRedirectURL(jsonRequestContext.getRequest().getContextPath() + "/index.page");
}
return;
}
} catch (LocalUserMissingException lume) {
throw new SmvcRuntimeException(PyramusStatusCode.LOCAL_USER_MISSING, Messages.getInstance().getText(locale, "users.login.localUserMissing", new String[] { lume.getExternalUser() }));
} catch (AuthenticationException ae) {
throw new SmvcRuntimeException(ae);
}
}
// Reaching this point means no authentication provider authorized the user, so throw a login exception
String msg = Messages.getInstance().getText(jsonRequestContext.getRequest().getLocale(), "users.login.loginFailed");
throw new InvalidLoginException(msg);
}
Aggregations