Search in sources :

Example 26 with User

use of org.olat.core.id.User in project OpenOLAT by OpenOLAT.

the class LDAPLoginManagerImpl method createAndPersistUser.

/**
 * Creates User in OLAT and ads user to LDAP securityGroup Required Attributes
 * have to be checked before this method.
 *
 * @param userAttributes Set of LDAP Attribute of User to be created
 */
@Override
public Identity createAndPersistUser(Attributes userAttributes) {
    // Get and Check Config
    String[] reqAttrs = syncConfiguration.checkRequestAttributes(userAttributes);
    if (reqAttrs != null) {
        log.warn("Can not create and persist user, the following attributes are missing::" + ArrayUtils.toString(reqAttrs), null);
        return null;
    }
    String uid = getAttributeValue(userAttributes.get(syncConfiguration.getOlatPropertyToLdapAttribute(LDAPConstants.LDAP_USER_IDENTIFYER)));
    String email = getAttributeValue(userAttributes.get(syncConfiguration.getOlatPropertyToLdapAttribute(UserConstants.EMAIL)));
    // Lookup user
    if (securityManager.findIdentityByNameCaseInsensitive(uid) != null) {
        log.error("Can't create user with username='" + uid + "', this username does already exist in OLAT database", null);
        return null;
    }
    if (!MailHelper.isValidEmailAddress(email)) {
        // needed to prevent possibly an AssertException in findIdentityByEmail breaking the sync!
        log.error("Cannot try to lookup user " + uid + " by email with an invalid email::" + email, null);
        return null;
    }
    if (!userManager.isEmailAllowed(email)) {
        log.error("Can't create user with email='" + email + "', a user with that email does already exist in OLAT database", null);
        return null;
    }
    // Create User (first and lastname is added in next step)
    User user = userManager.createUser(null, null, email);
    // Set User Property's (Iterates over Attributes and gets OLAT Property out
    // of olatexconfig.xml)
    NamingEnumeration<? extends Attribute> neAttr = userAttributes.getAll();
    try {
        while (neAttr.hasMore()) {
            Attribute attr = neAttr.next();
            String olatProperty = mapLdapAttributeToOlatProperty(attr.getID());
            if (!attr.getID().equalsIgnoreCase(syncConfiguration.getOlatPropertyToLdapAttribute(LDAPConstants.LDAP_USER_IDENTIFYER))) {
                String ldapValue = getAttributeValue(attr);
                if (olatProperty == null || ldapValue == null)
                    continue;
                user.setProperty(olatProperty, ldapValue);
            }
        }
        // Add static user properties from the configuration
        Map<String, String> staticProperties = syncConfiguration.getStaticUserProperties();
        if (staticProperties != null && staticProperties.size() > 0) {
            for (Entry<String, String> staticProperty : staticProperties.entrySet()) {
                user.setProperty(staticProperty.getKey(), staticProperty.getValue());
            }
        }
    } catch (NamingException e) {
        log.error("NamingException when trying to create and persist LDAP user with username::" + uid, e);
        return null;
    } catch (Exception e) {
        // catch any exception here to properly log error
        log.error("Unknown exception when trying to create and persist LDAP user with username::" + uid, e);
        return null;
    }
    // Create Identity
    Identity identity = securityManager.createAndPersistIdentityAndUser(uid, null, user, LDAPAuthenticationController.PROVIDER_LDAP, uid);
    // Add to SecurityGroup LDAP
    SecurityGroup secGroup = securityManager.findSecurityGroupByName(LDAPConstants.SECURITY_GROUP_LDAP);
    securityManager.addIdentityToSecurityGroup(identity, secGroup);
    // Add to SecurityGroup OLATUSERS
    secGroup = securityManager.findSecurityGroupByName(Constants.GROUP_OLATUSERS);
    securityManager.addIdentityToSecurityGroup(identity, secGroup);
    log.info("Created LDAP user username::" + uid);
    return identity;
}
Also used : LDAPUser(org.olat.ldap.model.LDAPUser) User(org.olat.core.id.User) Attribute(javax.naming.directory.Attribute) BasicAttribute(javax.naming.directory.BasicAttribute) NamingException(javax.naming.NamingException) Identity(org.olat.core.id.Identity) SecurityGroup(org.olat.basesecurity.SecurityGroup) NamingException(javax.naming.NamingException) AuthenticationException(javax.naming.AuthenticationException)

Example 27 with User

use of org.olat.core.id.User in project OpenOLAT by OpenOLAT.

the class LecturesBlockSignaturePDFExport method getName.

private String getName(Identity identity) {
    StringBuilder sb = new StringBuilder();
    User user = identity.getUser();
    if (StringHelper.containsNonWhitespace(user.getFirstName())) {
        sb.append(user.getFirstName());
    }
    if (StringHelper.containsNonWhitespace(user.getLastName())) {
        if (sb.length() > 0)
            sb.append(" ");
        sb.append(user.getLastName());
    }
    String institutionalIdentifier = user.getProperty(UserConstants.INSTITUTIONALUSERIDENTIFIER, translator.getLocale());
    if (StringHelper.containsNonWhitespace(institutionalIdentifier)) {
        if (sb.length() > 0)
            sb.append(", ");
        sb.append(institutionalIdentifier);
    }
    return sb.toString();
}
Also used : User(org.olat.core.id.User)

Example 28 with User

use of org.olat.core.id.User in project OpenOLAT by OpenOLAT.

the class BusinessGroupServiceTest method setUp.

@Before
public void setUp() throws Exception {
    if (initialize)
        return;
    // Identities
    id1 = JunitTestHelper.createAndPersistIdentityAsUser("id1-bgs-" + UUID.randomUUID().toString());
    id2 = JunitTestHelper.createAndPersistIdentityAsUser("id2-bgs-" + UUID.randomUUID().toString());
    id3 = JunitTestHelper.createAndPersistIdentityAsUser("id3-bgs-" + UUID.randomUUID().toString());
    id4 = JunitTestHelper.createAndPersistIdentityAsUser("id4-bgs-" + UUID.randomUUID().toString());
    // buddyGroups without waiting-list: groupcontext is null
    List<BusinessGroup> l = businessGroupService.findBusinessGroupsOwnedBy(id1);
    if (l.size() == 0) {
        one = businessGroupService.createBusinessGroup(id1, oneName, oneDesc, -1, -1, false, false, null);
    } else {
        List<BusinessGroup> groups = businessGroupService.findBusinessGroupsOwnedBy(id1);
        for (BusinessGroup group : groups) {
            if (oneName.equals(group.getName())) {
                one = group;
            }
        }
    }
    l = businessGroupService.findBusinessGroupsOwnedBy(id2);
    if (l.size() == 0) {
        two = businessGroupService.createBusinessGroup(id2, twoName, twoDesc, -1, -1, false, false, null);
        businessGroupRelationDao.addRole(id3, two, GroupRoles.participant.name());
        businessGroupRelationDao.addRole(id4, two, GroupRoles.participant.name());
    } else {
        two = businessGroupService.findBusinessGroupsOwnedBy(id2).get(0);
    }
    l = businessGroupService.findBusinessGroupsOwnedBy(id3);
    if (l.size() == 0) {
        three = businessGroupService.createBusinessGroup(id3, threeName, threeDesc, -1, -1, false, false, null);
        businessGroupRelationDao.addRole(id2, three, GroupRoles.participant.name());
        businessGroupRelationDao.addRole(id1, three, GroupRoles.coach.name());
    } else {
        three = businessGroupService.findBusinessGroupsOwnedBy(id3).get(0);
    }
    /*
			 * Membership in ParticipiantGroups............................. id1
			 * owns BuddyGroup one with participiantGroup:={}........... id2 owns
			 * BuddyGroup two with participiantGroup:={id3,id4} id3 owns BuddyGroup
			 * three participiantGroup:={id2}, ownerGroup:={id3,id1}
			 */
    dbInstance.commitAndCloseSession();
    // create business-group with waiting-list
    String bgWithWaitingListName = "Group with WaitingList";
    String bgWithWaitingListDesc = "some short description for Group with WaitingList";
    Boolean enableWaitinglist = new Boolean(true);
    Boolean enableAutoCloseRanks = new Boolean(true);
    RepositoryEntry resource = JunitTestHelper.createAndPersistRepositoryEntry();
    System.out.println("testAddToWaitingListAndFireEvent: resource=" + resource);
    bgWithWaitingList = businessGroupService.createBusinessGroup(id1, bgWithWaitingListName, bgWithWaitingListDesc, -1, -1, enableWaitinglist, enableAutoCloseRanks, resource);
    bgWithWaitingList.setMaxParticipants(new Integer(2));
    // Identities
    String suffix = UUID.randomUUID().toString();
    User userWg1 = userManager.createUser("FirstName_" + suffix, "LastName_" + suffix, suffix + "_junittest@olat.unizh.ch");
    wg1 = securityManager.createAndPersistIdentityAndUser(suffix, null, userWg1, BaseSecurityModule.getDefaultAuthProviderIdentifier(), suffix, "wg1");
    dbInstance.commitAndCloseSession();
    initialize = true;
}
Also used : User(org.olat.core.id.User) BusinessGroup(org.olat.group.BusinessGroup) RepositoryEntry(org.olat.repository.RepositoryEntry) Before(org.junit.Before)

Example 29 with User

use of org.olat.core.id.User in project OpenOLAT by OpenOLAT.

the class ViteroManager method createVmsUser.

private final int createVmsUser(Identity identity) throws VmsNotAvailableException {
    String username = null;
    try {
        CreateUserRequest createRequest = new CreateUserRequest();
        Newusertype user = new Newusertype();
        // mandatory
        User olatUser = identity.getUser();
        username = "olat." + WebappHelper.getInstanceId() + "." + identity.getName();
        user.setUsername(username);
        user.setSurname(olatUser.getProperty(UserConstants.LASTNAME, null));
        user.setFirstname(olatUser.getProperty(UserConstants.FIRSTNAME, null));
        user.setEmail(olatUser.getProperty(UserConstants.EMAIL, null));
        user.setPassword("changeme");
        int customerId = viteroModule.getCustomerId();
        user.getCustomeridlist().add(new Integer(customerId));
        // optional
        String language = identity.getUser().getPreferences().getLanguage();
        if (StringHelper.containsNonWhitespace(language) && language.startsWith("de")) {
            user.setLocale("de");
        } else {
            user.setLocale("en");
        }
        user.setPcstate("NOT_TESTED");
        user.setTimezone(viteroModule.getTimeZoneId());
        String street = olatUser.getProperty(UserConstants.STREET, null);
        if (StringHelper.containsNonWhitespace(street)) {
            user.setStreet(street);
        }
        String zip = olatUser.getProperty(UserConstants.ZIPCODE, null);
        if (StringHelper.containsNonWhitespace(zip)) {
            user.setZip(zip);
        }
        String city = olatUser.getProperty(UserConstants.CITY, null);
        if (StringHelper.containsNonWhitespace(city)) {
            user.setCity(city);
        }
        String country = olatUser.getProperty(UserConstants.COUNTRY, null);
        if (StringHelper.containsNonWhitespace(country)) {
            user.setCountry(country);
        }
        String mobile = olatUser.getProperty(UserConstants.TELMOBILE, null);
        if (StringHelper.containsNonWhitespace(mobile)) {
            user.setMobile(mobile);
        }
        String phonePrivate = olatUser.getProperty(UserConstants.TELPRIVATE, null);
        if (StringHelper.containsNonWhitespace(phonePrivate)) {
            user.setPhone(phonePrivate);
        }
        String phoneOffice = olatUser.getProperty(UserConstants.TELOFFICE, null);
        if (StringHelper.containsNonWhitespace(phoneOffice)) {
            user.setPhone(phoneOffice);
        }
        String institution = olatUser.getProperty(UserConstants.INSTITUTIONALNAME, null);
        if (StringHelper.containsNonWhitespace(institution)) {
            user.setCompany(institution);
        }
        /*
			user.setTitle("");
			*/
        user.setTechnicalnote("Generated by OpenOLAT");
        createRequest.setUser(user);
        Userid userId = getUserWebService().createUser(createRequest);
        storePortrait(identity, userId.getUserid());
        return userId.getUserid();
    } catch (SOAPFaultException f) {
        ErrorCode code = handleAxisFault(f);
        switch(code) {
            default:
                logAxisError("Cannot create vms user.", f);
        }
        return -1;
    } catch (WebServiceException e) {
        if (e.getCause() instanceof ConnectException) {
            throw new VmsNotAvailableException();
        }
        log.error("Cannot create vms user.", e);
        return -1;
    }
}
Also used : BigInteger(java.math.BigInteger) Newusertype(de.vitero.schema.user.Newusertype) User(org.olat.core.id.User) ViteroUser(org.olat.modules.vitero.model.ViteroUser) WebServiceException(javax.xml.ws.WebServiceException) Userid(de.vitero.schema.user.Userid) SOAPFaultException(javax.xml.ws.soap.SOAPFaultException) CreateUserRequest(de.vitero.schema.user.CreateUserRequest) ErrorCode(org.olat.modules.vitero.model.ErrorCode) ConnectException(java.net.ConnectException)

Example 30 with User

use of org.olat.core.id.User in project OpenOLAT by OpenOLAT.

the class TunnelMapper method handle.

@Override
public MediaResource handle(String relPath, HttpServletRequest hreq) {
    String method = hreq.getMethod();
    String uri = relPath;
    HttpUriRequest meth = null;
    try {
        URIBuilder builder = new URIBuilder();
        builder.setScheme(proto).setHost(host).setPort(port.intValue());
        if (uri == null) {
            uri = (startUri == null) ? "" : startUri;
        }
        if (uri.length() > 0 && uri.charAt(0) != '/') {
            uri = "/" + uri;
        }
        if (StringHelper.containsNonWhitespace(uri)) {
            builder.setPath(uri);
        }
        if (method.equals("GET")) {
            String queryString = hreq.getQueryString();
            if (StringHelper.containsNonWhitespace(queryString)) {
                builder.setCustomQuery(queryString);
            }
            meth = new HttpGet(builder.build());
        } else if (method.equals("POST")) {
            Map<String, String[]> params = hreq.getParameterMap();
            HttpPost pmeth = new HttpPost(builder.build());
            List<BasicNameValuePair> pairs = new ArrayList<>();
            for (String key : params.keySet()) {
                String[] vals = params.get(key);
                for (String val : vals) {
                    pairs.add(new BasicNameValuePair(key, val));
                }
            }
            HttpEntity entity = new UrlEncodedFormEntity(pairs, "UTF-8");
            pmeth.setEntity(entity);
            meth = pmeth;
        }
        // test page e.g. http://cgi.algonet.se/htbin/cgiwrap/ug/test.py
        if ("enabled".equals(CoreSpringFactory.getImpl(BaseSecurityModule.class).getUserInfosTunnelCourseBuildingBlock())) {
            User u = ident.getUser();
            meth.addHeader("X-OLAT-USERNAME", ident.getName());
            meth.addHeader("X-OLAT-LASTNAME", u.getProperty(UserConstants.LASTNAME, null));
            meth.addHeader("X-OLAT-FIRSTNAME", u.getProperty(UserConstants.FIRSTNAME, null));
            meth.addHeader("X-OLAT-EMAIL", u.getProperty(UserConstants.EMAIL, null));
            meth.addHeader("X-OLAT-USERIP", ipAddress);
        }
        HttpResponse response = httpClient.execute(meth);
        if (response == null) {
            // error
            return new NotFoundMediaResource();
        }
        // get or post successfully
        Header responseHeader = response.getFirstHeader("Content-Type");
        if (responseHeader == null) {
            // error
            EntityUtils.consumeQuietly(response.getEntity());
            return new NotFoundMediaResource();
        }
        return new HttpRequestMediaResource(response);
    } catch (ClientProtocolException | URISyntaxException e) {
        log.error("", e);
        return null;
    } catch (IOException e) {
        log.error("Error loading URI: " + (meth == null ? "???" : meth.getURI()), e);
        return null;
    }
}
Also used : HttpUriRequest(org.apache.http.client.methods.HttpUriRequest) NotFoundMediaResource(org.olat.core.gui.media.NotFoundMediaResource) HttpPost(org.apache.http.client.methods.HttpPost) HttpRequestMediaResource(org.olat.core.gui.media.HttpRequestMediaResource) User(org.olat.core.id.User) HttpEntity(org.apache.http.HttpEntity) HttpGet(org.apache.http.client.methods.HttpGet) HttpResponse(org.apache.http.HttpResponse) UrlEncodedFormEntity(org.apache.http.client.entity.UrlEncodedFormEntity) URISyntaxException(java.net.URISyntaxException) IOException(java.io.IOException) URIBuilder(org.apache.http.client.utils.URIBuilder) ClientProtocolException(org.apache.http.client.ClientProtocolException) Header(org.apache.http.Header) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) ArrayList(java.util.ArrayList) List(java.util.List) Map(java.util.Map)

Aggregations

User (org.olat.core.id.User)260 Identity (org.olat.core.id.Identity)126 Test (org.junit.Test)82 UserPropertyHandler (org.olat.user.propertyhandlers.UserPropertyHandler)52 HashMap (java.util.HashMap)28 Translator (org.olat.core.gui.translator.Translator)26 SecurityGroup (org.olat.basesecurity.SecurityGroup)20 Date (java.util.Date)18 ArrayList (java.util.ArrayList)16 Locale (java.util.Locale)16 FormItem (org.olat.core.gui.components.form.flexible.FormItem)16 File (java.io.File)14 VelocityContext (org.apache.velocity.VelocityContext)14 MailTemplate (org.olat.core.util.mail.MailTemplate)12 LDAPUser (org.olat.ldap.model.LDAPUser)12 UserManager (org.olat.user.UserManager)12 IOException (java.io.IOException)10 Map (java.util.Map)10 List (java.util.List)8 CloseableModalController (org.olat.core.gui.control.generic.closablewrapper.CloseableModalController)8