use of cz.metacentrum.perun.registrar.model.Application in project perun by CESNET.
the class MailManagerImpl method sendInvitation.
@Override
public void sendInvitation(PerunSession sess, Vo vo, Group group, User user) throws PerunException {
if (group == null) {
if (!AuthzResolver.isAuthorized(sess, Role.VOADMIN, vo)) {
throw new PrivilegeException(sess, "sendInvitation");
}
} else {
if (!AuthzResolver.isAuthorized(sess, Role.VOADMIN, group) && !AuthzResolver.isAuthorized(sess, Role.GROUPADMIN, group)) {
throw new PrivilegeException(sess, "sendInvitation");
}
}
if (user == null)
throw new RegistrarException("Missing user to send notification to.");
try {
Member m = membersManager.getMemberByUser(registrarSession, vo, user);
// is member, is invite to group ?
if (group != null) {
List<Group> g = groupsManager.getMemberGroups(registrarSession, m);
if (g.contains(group)) {
// user is member of group - can't invite him
throw new RegistrarException("User to invite is already member of your group: " + group.getShortName());
}
} else {
throw new RegistrarException("User to invite is already member of your VO:" + vo.getShortName());
}
} catch (Exception ex) {
log.error("[MAIL MANAGER] Exception {} when getting member by {} from " + vo.toString(), ex, user);
}
// get form
ApplicationForm form;
if (group != null) {
form = registrarManager.getFormForGroup(group);
} else {
form = registrarManager.getFormForVo(vo);
}
// get mail definition
ApplicationMail mail = getMailByParams(form.getId(), AppType.INITIAL, MailType.USER_INVITE);
if (mail == null) {
throw new RegistrarException("You don't have invitation e-mail template defined.");
} else if (mail.getSend() == false) {
throw new RegistrarException("Sending of invitations is disabled.");
}
String language = "en";
try {
Attribute a = attrManager.getAttribute(registrarSession, user, URN_USER_PREFERRED_LANGUAGE);
if (a != null && a.getValue() != null) {
language = BeansUtils.attributeValueToString(a);
}
} catch (Exception ex) {
log.error("[MAIL MANAGER] Exception thrown when getting preferred language for USER={}: {}", user, ex);
}
if (group == null) {
try {
Attribute a = attrManager.getAttribute(registrarSession, vo, URN_VO_LANGUAGE_EMAIL);
if (a != null && a.getValue() != null) {
language = BeansUtils.attributeValueToString(a);
}
} catch (Exception ex) {
log.error("[MAIL MANAGER] Exception thrown when getting preferred language of notification for VO={}: {}", vo, ex);
}
} else {
try {
Attribute a = attrManager.getAttribute(registrarSession, group, URN_GROUP_LANGUAGE_EMAIL);
if (a != null && a.getValue() != null) {
language = BeansUtils.attributeValueToString(a);
}
} catch (Exception ex) {
log.error("[MAIL MANAGER] Exception thrown when getting preferred language of notification for Group={}: {}", group, ex);
}
}
// get language
Locale lang = new Locale(language);
// get localized subject and text
MailText mt = mail.getMessage(lang);
String mailText = "";
String mailSubject = "";
if (mt.getText() != null && !mt.getText().isEmpty()) {
mailText = mt.getText();
}
if (mt.getSubject() != null && !mt.getSubject().isEmpty()) {
mailSubject = mt.getSubject();
}
SimpleMailMessage message = new SimpleMailMessage();
// fake app to get "from" address
Application app = new Application();
app.setVo(vo);
app.setGroup(group);
// get from
setFromMailAddress(message, app);
String email = "";
try {
Attribute a = attrManager.getAttribute(registrarSession, user, URN_USER_PREFERRED_MAIL);
if (a != null && a.getValue() != null) {
email = BeansUtils.attributeValueToString(a);
}
} catch (Exception ex) {
log.error("[MAIL MANAGER] Exception thrown when getting preferred language of notification for Group={}: {}", group, ex);
}
message.setTo(email);
mailText = substituteCommonStringsForInvite(vo, group, user, null, mailText);
mailSubject = substituteCommonStringsForInvite(vo, group, user, null, mailSubject);
message.setSubject(mailSubject);
message.setText(mailText);
try {
mailSender.send(message);
log.info("[MAIL MANAGER] Sending mail: USER_INVITE to: {} / " + app.getVo() + " / " + app.getGroup(), message.getTo());
} catch (MailException ex) {
log.error("[MAIL MANAGER] Sending mail: USER_INVITE failed because of exception: {}", ex);
throw new RegistrarException("Unable to send e-mail.", ex);
}
}
use of cz.metacentrum.perun.registrar.model.Application in project perun by CESNET.
the class RegistrarManagerImpl method validateEmailFromLink.
@Override
public boolean validateEmailFromLink(Map<String, String> urlParameters) throws PerunException {
String idStr = urlParameters.get("i");
if (mailManager.getMessageAuthenticationCode(idStr).equals(urlParameters.get("m"))) {
int appDataId = Integer.parseInt(idStr, Character.MAX_RADIX);
jdbc.update("update application_data set assurance_level=1 where id = ?", appDataId);
Application app = getApplicationById(jdbc.queryForInt("select app_id from application_data where id = ?", appDataId));
tryToVerifyApplication(registrarSession, app);
return true;
}
return false;
}
use of cz.metacentrum.perun.registrar.model.Application in project perun by CESNET.
the class RegistrarManagerImpl method verifyApplication.
@Override
public Application verifyApplication(PerunSession sess, int appId) throws PerunException {
Application app = getApplicationById(appId);
if (app == null)
throw new RegistrarException("Application with ID=" + appId + " doesn't exists.");
if (!AuthzResolver.isAuthorized(sess, Role.VOADMIN, app.getVo())) {
if (app.getGroup() != null) {
if (!AuthzResolver.isAuthorized(sess, Role.GROUPADMIN, app.getGroup())) {
throw new PrivilegeException(sess, "verifyApplication");
}
} else {
throw new PrivilegeException(sess, "verifyApplication");
}
}
// proceed
markApplicationVerified(sess, appId);
perun.getAuditer().log(sess, "Application ID=" + appId + " voID=" + app.getVo().getId() + ((app.getGroup() != null) ? (" groupID=" + app.getGroup().getId()) : "") + " has been verified.");
// return updated application
return getApplicationById(appId);
}
use of cz.metacentrum.perun.registrar.model.Application in project perun by CESNET.
the class RegistrarManagerImpl method approveApplicationInternal.
/**
* Process application approval in 1 transaction
* !! WITHOUT members validation !!
*
* @param sess session for authz
* @param appId application ID to approve
* @return updated application
* @throws PerunException
*/
@Transactional(rollbackFor = Exception.class)
public Application approveApplicationInternal(PerunSession sess, int appId) throws PerunException {
Application app = getApplicationById(appId);
Member member = null;
// authz
if (!AuthzResolver.isAuthorized(sess, Role.VOADMIN, app.getVo())) {
if (app.getGroup() != null) {
if (!AuthzResolver.isAuthorized(sess, Role.GROUPADMIN, app.getGroup())) {
throw new PrivilegeException(sess, "approveApplication");
}
} else {
throw new PrivilegeException(sess, "approveApplication");
}
}
// only VERIFIED applications can be approved
if (!AppState.VERIFIED.equals(app.getState())) {
if (AppState.APPROVED.equals(app.getState()))
throw new RegistrarException("Application is already approved. Try to refresh the view to see changes.");
if (AppState.REJECTED.equals(app.getState()))
throw new RegistrarException("Rejected application cant' be approved. Try to refresh the view to see changes.");
throw new RegistrarException("User didn't verify his email address yet. Please wait until application will be in a 'Submitted' state. You can send mail verification notification to user again if you wish.");
}
// get registrar module
RegistrarModule module;
if (app.getGroup() != null) {
module = getRegistrarModule(getFormForGroup(app.getGroup()));
} else {
module = getRegistrarModule(getFormForVo(app.getVo()));
}
if (module != null) {
// call custom logic before approving
module.beforeApprove(sess, app);
}
// mark as APPROVED
int result = jdbc.update("update application set state=?, modified_by=?, modified_at=? where id=?", AppState.APPROVED.toString(), sess.getPerunPrincipal().getActor(), new Date(), appId);
if (result == 0) {
throw new RegistrarException("Application with ID=" + appId + " not found.");
} else if (result > 1) {
throw new ConsistencyErrorException("More than one application is stored under ID=" + appId + ".");
}
// set back as approved
app.setState(AppState.APPROVED);
log.info("Application {} marked as APPROVED", appId);
// Try to get reservedLogin and reservedNamespace before deletion, it will be used for creating userExtSources
List<Pair<String, String>> logins;
try {
logins = jdbc.query("select namespace,login from application_reserved_logins where app_id=?", new RowMapper<Pair<String, String>>() {
@Override
public Pair<String, String> mapRow(ResultSet rs, int arg1) throws SQLException {
return new Pair<String, String>(rs.getString("namespace"), rs.getString("login"));
}
}, appId);
} catch (EmptyResultDataAccessException e) {
// set empty logins
logins = new ArrayList<Pair<String, String>>();
}
// FOR INITIAL APPLICATION
if (AppType.INITIAL.equals(app.getType())) {
if (app.getGroup() != null) {
// free reserved logins so they can be set as attributes
jdbc.update("delete from application_reserved_logins where app_id=?", appId);
if (app.getUser() == null) {
// application for group doesn't have user set, but it can exists in perun (joined identities after submission)
User u = usersManager.getUserByExtSourceNameAndExtLogin(registrarSession, app.getExtSourceName(), app.getCreatedBy());
// put user back to application
app.setUser(u);
// store user_id in DB
int result2 = jdbc.update("update application set user_id=? where id=?", u.getId(), appId);
if (result2 == 0) {
throw new RegistrarException("Application with ID=" + appId + " not found.");
} else if (result2 > 1) {
throw new ConsistencyErrorException("More than one application is stored under ID=" + appId + ".");
}
}
// add new member of VO as member of group (for group applications)
// !! MUST BE MEMBER OF VO !!
member = membersManager.getMemberByUser(registrarSession, app.getVo(), app.getUser());
// meaning, user should submit membership extension application first !!
if (!Arrays.asList(Status.VALID, Status.INVALID).contains(member.getStatus())) {
throw new CantBeApprovedException("Application of member with membership status: " + member.getStatus() + " can't be approved. Please wait until member extends/re-validate own membership in a VO.");
}
// store all attributes (but not logins)
storeApplicationAttributes(app);
// cancel reservation of new duplicate logins and get purely new logins back
logins = unreserveNewLoginsFromSameNamespace(logins, app.getUser());
// store purely new logins to user
storeApplicationLoginAttributes(app);
for (Pair<String, String> pair : logins) {
// LOGIN IN NAMESPACE IS PURELY NEW => VALIDATE ENTRY IN KDC
// left = namespace, right = login
perun.getUsersManagerBl().validatePasswordAndSetExtSources(registrarSession, app.getUser(), pair.getRight(), pair.getLeft());
}
// update titles before/after users name if part of application !! USER MUST EXISTS !!
updateUserNameTitles(app);
perun.getGroupsManager().addMember(registrarSession, app.getGroup(), member);
log.debug("[REGISTRAR] Member {} added to Group {}.", member, app.getGroup());
} else {
// put application data into Candidate
final Map<String, String> attributes = new HashMap<String, String>();
jdbc.query("select dst_attr,value from application_data d, application_form_items i where d.item_id=i.id " + "and i.dst_attr is not null and d.value is not null and app_id=?", new RowMapper<Object>() {
@Override
public Object mapRow(ResultSet rs, int i) throws SQLException {
attributes.put(rs.getString("dst_attr"), rs.getString("value"));
return null;
}
}, appId);
// DO NOT STORE LOGINS THROUGH CANDIDATE
// we do not set logins by candidate object to prevent accidental overwrite while joining identities in process
Iterator<Map.Entry<String, String>> iter = attributes.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry<String, String> entry = iter.next();
if (entry.getKey().contains("urn:perun:user:attribute-def:def:login-namespace:")) {
iter.remove();
}
}
Candidate candidate = new Candidate();
candidate.setAttributes(attributes);
log.debug("[REGISTRAR] Retrieved candidate from DB {}", candidate);
// first try to parse display_name if not null and not empty
if (attributes.containsKey(URN_USER_DISPLAY_NAME) && attributes.get(URN_USER_DISPLAY_NAME) != null && !attributes.get(URN_USER_DISPLAY_NAME).isEmpty()) {
// parse
Map<String, String> commonName = Utils.parseCommonName(attributes.get(URN_USER_DISPLAY_NAME));
if (commonName.get("titleBefore") != null && !commonName.get("titleBefore").isEmpty()) {
candidate.setTitleBefore(commonName.get("titleBefore"));
}
if (commonName.get("firstName") != null && !commonName.get("firstName").isEmpty()) {
candidate.setFirstName(commonName.get("firstName"));
}
// FIXME - ? there is no middleName in Utils.parseCommonName() implementation
if (commonName.get("middleName") != null && !commonName.get("middleName").isEmpty()) {
candidate.setMiddleName(commonName.get("middleName"));
}
if (commonName.get("lastName") != null && !commonName.get("lastName").isEmpty()) {
candidate.setLastName(commonName.get("lastName"));
}
if (commonName.get("titleAfter") != null && !commonName.get("titleAfter").isEmpty()) {
candidate.setTitleAfter(commonName.get("titleAfter"));
}
}
// if names are separated, used them after
for (String attrName : attributes.keySet()) {
// if value not null or empty - set to candidate
if (attributes.get(attrName) != null && !attributes.get(attrName).isEmpty()) {
if (URN_USER_TITLE_BEFORE.equals(attrName)) {
candidate.setTitleBefore(attributes.get(attrName));
} else if (URN_USER_TITLE_AFTER.equals(attrName)) {
candidate.setTitleAfter(attributes.get(attrName));
} else if (URN_USER_FIRST_NAME.equals(attrName)) {
candidate.setFirstName(attributes.get(attrName));
} else if (URN_USER_LAST_NAME.equals(attrName)) {
candidate.setLastName(attributes.get(attrName));
} else if (URN_USER_MIDDLE_NAME.equals(attrName)) {
candidate.setMiddleName(attributes.get(attrName));
}
}
}
// free reserved logins so they can be set as attributes
jdbc.update("delete from application_reserved_logins where app_id=?", appId);
// create member and user
log.debug("[REGISTRAR] Trying to make member from candidate {}", candidate);
member = membersManager.createMember(sess, app.getVo(), app.getExtSourceName(), app.getExtSourceType(), app.getExtSourceLoa(), app.getCreatedBy(), candidate);
User u = usersManager.getUserById(registrarSession, member.getUserId());
if (app.getUser() != null) {
// if user was already known to perun, createMember() will set attributes
// via setAttributes() method so core attributes are skipped
// ==> updateNameTitles() in case of change in appForm.
updateUserNameTitles(app);
}
// set NEW user id back to application
app.setUser(u);
result = jdbc.update("update application set user_id=? where id=?", member.getUserId(), appId);
if (result == 0) {
throw new RegistrarException("User ID hasn't been associated with the application " + appId + ", because the application was not found!");
} else if (result > 1) {
throw new ConsistencyErrorException("User ID hasn't been associated with the application " + appId + ", because more than one application exists under the same ID.");
}
log.info("Member " + member.getId() + " created for: " + app.getCreatedBy() + " / " + app.getExtSourceName());
// unreserve new login if user already have login in same namespace
// also get back purely new logins
logins = unreserveNewLoginsFromSameNamespace(logins, u);
// store purely new logins to user
storeApplicationLoginAttributes(app);
for (Pair<String, String> pair : logins) {
// LOGIN IN NAMESPACE IS PURELY NEW => VALIDATE ENTRY IN KDC
// left = namespace, right = login
perun.getUsersManagerBl().validatePasswordAndSetExtSources(registrarSession, u, pair.getRight(), pair.getLeft());
}
// log
perun.getAuditer().log(sess, "{} created for approved {}.", member, app);
}
// FOR EXTENSION APPLICATION
} else if (AppType.EXTENSION.equals(app.getType())) {
// free reserved logins so they can be set as attributes
jdbc.update("delete from application_reserved_logins where app_id=?", app.getId());
member = membersManager.getMemberByUser(registrarSession, app.getVo(), app.getUser());
storeApplicationAttributes(app);
// extend user's membership
membersManager.extendMembership(registrarSession, member);
// unreserve new logins, if user already have login in same namespace
// also get back logins, which are purely new
logins = unreserveNewLoginsFromSameNamespace(logins, app.getUser());
// store purely new logins from application
storeApplicationLoginAttributes(app);
// validate purely new logins in KDC
for (Pair<String, String> pair : logins) {
// left = namespace, right = login
perun.getUsersManagerBl().validatePasswordAndSetExtSources(registrarSession, app.getUser(), pair.getRight(), pair.getLeft());
}
// update titles before/after users name if part of application !! USER MUST EXISTS !!
updateUserNameTitles(app);
// log
perun.getAuditer().log(sess, "Membership extended for {} in {} for approved {}.", member, app.getVo(), app);
}
if (module != null) {
module.approveApplication(sess, app);
}
getMailManager().sendMessage(app, MailType.APP_APPROVED_USER, null, null);
// return updated application
return app;
}
use of cz.metacentrum.perun.registrar.model.Application in project perun by CESNET.
the class RegistrarManagerImpl method autoApproveUsersGroupApplications.
/**
* Try to approve all group applications of user with auto-approval (even by user-ext-source)
* in specified VO.
*
* @param sess PerunSession
* @param vo VO to approve group applications in
* @param user user to approve applications for
*/
private void autoApproveUsersGroupApplications(PerunSession sess, Vo vo, User user) throws PerunException {
List<UserExtSource> ues = usersManager.getUserExtSources(registrarSession, user);
List<Application> applications = new ArrayList<Application>();
// get apps based on user
List<Application> apps = jdbc.query(APP_SELECT + " where a.vo_id=? and a.group_id is not null and a.state=?" + " and a.user_id=?", APP_MAPPER, vo.getId(), AppState.VERIFIED.toString(), user.getId());
if (apps != null)
applications.addAll(apps);
for (UserExtSource ue : ues) {
List<Application> apps2 = jdbc.query(APP_SELECT + " where a.vo_id=? and a.group_id is not null and a.state=?" + " and a.created_by=? and a.extsourcename=? and a.extsourcetype=?", APP_MAPPER, vo.getId(), AppState.VERIFIED.toString(), ue.getLogin(), ue.getExtSource().getName(), ue.getExtSource().getType());
if (apps2 != null)
applications.addAll(apps2);
}
for (Application a : applications) {
// if new => skipp user will approve automatically by verifying email
if (a.getState().equals(AppState.NEW))
continue;
// approve applications only for auto-approve forms
if (!getFormForGroup(a.getGroup()).isAutomaticApproval())
continue;
try {
registrarManager.approveApplicationInternal(sess, a.getId());
} catch (RegistrarException ex) {
// case when user have UNVERIFIED group application
// will be approved when user verify his email
log.error("[REGISTRAR] Can't auto-approve group application after vo app approval because of exception: {}", ex);
}
}
}
Aggregations