Search in sources :

Example 11 with UserManager

use of org.olat.user.UserManager in project OpenOLAT by OpenOLAT.

the class RegistrationWebService method register.

/**
 * Register with the specified email
 * @response.representation.200.doc Registration successful
 * @response.representation.304.doc Already registered, HTTP-Header location set to redirect
 * @response.representation.400.doc Email address not allowed
 * @param email The email address
 * @param request The HTTP Request
 * @return
 */
@PUT
public Response register(@QueryParam("email") String email, @Context HttpServletRequest request) {
    if (!CoreSpringFactory.getImpl(RegistrationModule.class).isSelfRegistrationEnabled()) {
        return Response.serverError().status(Status.NOT_FOUND).build();
    }
    ResponseBuilder response;
    Locale locale = getLocale(request);
    Translator translator = getTranslator(locale);
    MailManager mailM = CoreSpringFactory.getImpl(MailManager.class);
    UserManager userManager = UserManager.getInstance();
    RegistrationManager rm = CoreSpringFactory.getImpl(RegistrationManager.class);
    boolean foundUser = userManager.findUniqueIdentityByEmail(email) != null;
    boolean noNewUserWithEmail = !userManager.isEmailAllowed(email);
    String serverpath = Settings.getServerContextPathURI();
    if (foundUser && noNewUserWithEmail) {
        // redirect
        URI redirectUri = UriBuilder.fromUri(Settings.getServerContextPathURI()).build();
        response = Response.ok().status(Status.NOT_MODIFIED).location(redirectUri);
    } else if (userManager.isEmailAllowed(email)) {
        String ip = request.getRemoteAddr();
        TemporaryKey tk = null;
        UserModule userModule = CoreSpringFactory.getImpl(UserModule.class);
        if (userModule.isEmailUnique()) {
            tk = rm.loadTemporaryKeyByEmail(email);
        }
        if (tk == null) {
            tk = rm.loadOrCreateTemporaryKeyByEmail(email, ip, RegistrationManager.REGISTRATION);
        }
        String today = DateFormat.getDateInstance(DateFormat.LONG, locale).format(new Date());
        String[] bodyAttrs = new String[] { serverpath, tk.getRegistrationKey(), CoreSpringFactory.getImpl(I18nModule.class).getLocaleKey(locale) };
        String[] whereFromAttrs = new String[] { serverpath, today, ip };
        String body = translator.translate("reg.body", bodyAttrs) + SEPARATOR + translator.translate("reg.wherefrom", whereFromAttrs);
        try {
            MailBundle bundle = new MailBundle();
            bundle.setTo(email);
            bundle.setContent(translator.translate("reg.subject"), body);
            MailerResult result = mailM.sendExternMessage(bundle, null, true);
            if (result.isSuccessful()) {
                response = Response.ok();
            } else {
                response = Response.serverError().status(Status.INTERNAL_SERVER_ERROR);
            }
        } catch (Exception e) {
            response = Response.serverError().status(Status.INTERNAL_SERVER_ERROR);
            log.error("", e);
        }
    } else {
        response = Response.serverError().status(Status.BAD_REQUEST);
    }
    return response.build();
}
Also used : Locale(java.util.Locale) RestSecurityHelper.getLocale(org.olat.restapi.security.RestSecurityHelper.getLocale) RegistrationManager(org.olat.registration.RegistrationManager) MailerResult(org.olat.core.util.mail.MailerResult) TemporaryKey(org.olat.registration.TemporaryKey) URI(java.net.URI) Date(java.util.Date) Translator(org.olat.core.gui.translator.Translator) UserManager(org.olat.user.UserManager) MailManager(org.olat.core.util.mail.MailManager) UserModule(org.olat.user.UserModule) ResponseBuilder(javax.ws.rs.core.Response.ResponseBuilder) MailBundle(org.olat.core.util.mail.MailBundle) PUT(javax.ws.rs.PUT)

Example 12 with UserManager

use of org.olat.user.UserManager in project OpenOLAT by OpenOLAT.

the class UserWebService method getUserListQuery.

/**
 * Search users and return them in a simple form (without user properties). User properties
 * can be added two the query parameters. If the authUsername and the authProvider are set,
 * the search is made only with these two parameters because they are sufficient to return
 * a single user.<br>
 * The search with login and user properties are made default with wild cards. If an exact
 * match is needed, the parameter msut be quoted:<br>
 * users?login="username"<br>
 * Don't forget the right escaping in the URL!<br>
 * You can make a search with the user properties like this:<br>
 * users?telMobile=39847592&login=test
 * <br >/ The lookup is possible for authors, usermanagers and system administrators. Normal
 * users are not allowed to use the lookup service.
 *
 * @response.representation.200.qname {http://www.example.com}userVO
 * @response.representation.200.mediaType application/xml, application/json
 * @response.representation.200.doc The list of all users in the OLAT system
 * @response.representation.200.example {@link org.olat.user.restapi.Examples#SAMPLE_USERVOes}
 * @response.representation.401.doc The roles of the authenticated user are not sufficient
 * @param login The login (search with like)
 * @param authProvider An authentication provider (optional)
 * @param authUsername An specific username from the authentication provider
 * @param uriInfo The URI infos
 * @param httpRequest The HTTP request
 * @return An array of users
 */
@GET
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
public Response getUserListQuery(@QueryParam("login") String login, @QueryParam("authProvider") String authProvider, @QueryParam("authUsername") String authUsername, @QueryParam("statusVisibleLimit") String statusVisibleLimit, @Context UriInfo uriInfo, @Context HttpServletRequest httpRequest) {
    // User lookup allowed for authors, usermanagers and admins. For
    // usernamanger and up are considered "administrative" when it comes to
    // lookup of the user properties
    boolean isAdministrativeUser = isUserManager(httpRequest);
    if (!isAdministrativeUser && !isAuthor(httpRequest)) {
        return Response.serverError().status(Status.UNAUTHORIZED).build();
    }
    MultivaluedMap<String, String> params = uriInfo.getQueryParameters();
    List<Identity> identities;
    // make only a search by authUsername
    if (StringHelper.containsNonWhitespace(authProvider) && StringHelper.containsNonWhitespace(authUsername)) {
        Authentication auth = BaseSecurityManager.getInstance().findAuthenticationByAuthusername(authUsername, authProvider);
        if (auth == null) {
            identities = Collections.emptyList();
        } else {
            identities = Collections.singletonList(auth.getIdentity());
        }
    } else {
        String[] authProviders = null;
        if (StringHelper.containsNonWhitespace(authProvider)) {
            authProviders = new String[] { authProvider };
        }
        // retrieve and convert the parameters value
        Map<String, String> userProps = new HashMap<String, String>();
        if (!params.isEmpty()) {
            UserManager um = UserManager.getInstance();
            Locale locale = getLocale(httpRequest);
            List<UserPropertyHandler> propertyHandlers = um.getUserPropertyHandlersFor(PROPERTY_HANDLER_IDENTIFIER, isAdministrativeUser);
            for (UserPropertyHandler handler : propertyHandlers) {
                if (!params.containsKey(handler.getName()))
                    continue;
                List<String> values = params.get(handler.getName());
                if (values.isEmpty())
                    continue;
                String value = formatDbUserProperty(values.get(0), handler, locale);
                userProps.put(handler.getName(), value);
            }
        }
        Integer status = Identity.STATUS_VISIBLE_LIMIT;
        if (isAdministrativeUser && "all".equalsIgnoreCase(statusVisibleLimit)) {
            status = null;
        }
        identities = BaseSecurityManager.getInstance().getIdentitiesByPowerSearch(login, userProps, true, null, null, authProviders, null, null, null, null, status);
    }
    int count = 0;
    UserVO[] userVOs = new UserVO[identities.size()];
    for (Identity identity : identities) {
        userVOs[count++] = get(identity);
    }
    return Response.ok(userVOs).build();
}
Also used : Locale(java.util.Locale) RestSecurityHelper.getLocale(org.olat.restapi.security.RestSecurityHelper.getLocale) HashMap(java.util.HashMap) Authentication(org.olat.basesecurity.Authentication) UserManager(org.olat.user.UserManager) RestSecurityHelper.isUserManager(org.olat.restapi.security.RestSecurityHelper.isUserManager) Identity(org.olat.core.id.Identity) RestSecurityHelper.getIdentity(org.olat.restapi.security.RestSecurityHelper.getIdentity) UserPropertyHandler(org.olat.user.propertyhandlers.UserPropertyHandler) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET)

Example 13 with UserManager

use of org.olat.user.UserManager in project OpenOLAT by OpenOLAT.

the class UserWebService method validateUser.

private List<ErrorVO> validateUser(User user, UserVO userVo, HttpServletRequest request) {
    UserManager um = UserManager.getInstance();
    Locale locale = getLocale(request);
    List<ErrorVO> errors = new ArrayList<>();
    List<UserPropertyHandler> propertyHandlers = um.getUserPropertyHandlersFor(PROPERTY_HANDLER_IDENTIFIER, false);
    validateProperty(user, UserConstants.FIRSTNAME, userVo.getFirstName(), propertyHandlers, errors, um, locale);
    validateProperty(user, UserConstants.LASTNAME, userVo.getLastName(), propertyHandlers, errors, um, locale);
    validateProperty(user, UserConstants.EMAIL, userVo.getEmail(), propertyHandlers, errors, um, locale);
    for (UserPropertyHandler propertyHandler : propertyHandlers) {
        if (!UserConstants.FIRSTNAME.equals(propertyHandler.getName()) && !UserConstants.LASTNAME.equals(propertyHandler.getName()) && !UserConstants.EMAIL.equals(propertyHandler.getName())) {
            validateProperty(user, userVo, propertyHandler, errors, um, locale);
        }
    }
    return errors;
}
Also used : Locale(java.util.Locale) RestSecurityHelper.getLocale(org.olat.restapi.security.RestSecurityHelper.getLocale) ErrorVO(org.olat.restapi.support.vo.ErrorVO) UserManager(org.olat.user.UserManager) RestSecurityHelper.isUserManager(org.olat.restapi.security.RestSecurityHelper.isUserManager) ArrayList(java.util.ArrayList) UserPropertyHandler(org.olat.user.propertyhandlers.UserPropertyHandler)

Example 14 with UserManager

use of org.olat.user.UserManager in project openolat by klemens.

the class FileSystemExport method fsToZip.

/**
 * Exports a given filesystem as Zip-Outputstream
 *
 * @param zout the Zip-Outputstream
 * @param sourceFolder the source folder
 * @param pfNode the PFCourseNode
 * @param identities
 * @param translator
 * @throws IOException Signals that an I/O exception has occurred.
 */
public static boolean fsToZip(ZipOutputStream zout, final Path sourceFolder, PFCourseNode pfNode, List<Identity> identities, Translator translator) {
    String targetPath = translator.translate("participant.folder") + "/";
    UserManager userManager = CoreSpringFactory.getImpl(UserManager.class);
    Set<String> idKeys = new HashSet<>();
    if (identities != null) {
        for (Identity identity : identities) {
            idKeys.add(identity.getKey().toString());
        }
    } else {
        File[] listOfFiles = sourceFolder.toFile().listFiles();
        if (listOfFiles != null) {
            for (File file : listOfFiles) {
                if (file.isDirectory()) {
                    idKeys.add(file.getName());
                }
            }
        }
    }
    try {
        Files.walkFileTree(sourceFolder, new SimpleFileVisitor<Path>() {

            // contains identity check  and changes identity key to user display name
            private String containsID(String relPath) {
                for (String key : idKeys) {
                    // additional check if folder is a identity-key (coming from fs)
                    if (relPath.contains(key) && StringHelper.isLong(key)) {
                        String exportFolderName = userManager.getUserDisplayName(Long.parseLong(key)).replace(", ", "_") + "_" + key;
                        return relPath.replace(key.toString(), exportFolderName);
                    }
                }
                return null;
            }

            // checks module config and translates folder name
            private String boxesEnabled(String relPath) {
                if (pfNode.hasParticipantBoxConfigured() && relPath.contains(PFManager.FILENAME_DROPBOX)) {
                    return relPath.replace(PFManager.FILENAME_DROPBOX, translator.translate("drop.box"));
                } else if (pfNode.hasCoachBoxConfigured() && relPath.contains(PFManager.FILENAME_RETURNBOX)) {
                    return relPath.replace(PFManager.FILENAME_RETURNBOX, translator.translate("return.box"));
                } else {
                    return null;
                }
            }

            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                String relPath = sourceFolder.relativize(file).toString();
                if ((relPath = containsID(relPath)) != null && (relPath = boxesEnabled(relPath)) != null) {
                    zout.putNextEntry(new ZipEntry(targetPath + relPath));
                    Files.copy(file, zout);
                    zout.closeEntry();
                }
                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
                String relPath = sourceFolder.relativize(dir).toString() + "/";
                if ((relPath = containsID(relPath)) != null && (relPath = boxesEnabled(relPath)) != null) {
                    zout.putNextEntry(new ZipEntry(targetPath + relPath));
                    zout.closeEntry();
                }
                return FileVisitResult.CONTINUE;
            }
        });
        zout.close();
        return true;
    } catch (IOException e) {
        log.error("Unable to export zip", e);
        return false;
    }
}
Also used : Path(java.nio.file.Path) ZipEntry(java.util.zip.ZipEntry) FileVisitResult(java.nio.file.FileVisitResult) IOException(java.io.IOException) UserManager(org.olat.user.UserManager) Identity(org.olat.core.id.Identity) File(java.io.File) BasicFileAttributes(java.nio.file.attribute.BasicFileAttributes) HashSet(java.util.HashSet)

Example 15 with UserManager

use of org.olat.user.UserManager in project openolat by klemens.

the class CourseHandler method readyToDelete.

@Override
public boolean readyToDelete(RepositoryEntry entry, Identity identity, Roles roles, Locale locale, ErrorList errors) {
    ReferenceManager refM = CoreSpringFactory.getImpl(ReferenceManager.class);
    String referencesSummary = refM.getReferencesToSummary(entry.getOlatResource(), locale);
    if (referencesSummary != null) {
        Translator translator = Util.createPackageTranslator(RepositoryManager.class, locale);
        errors.setError(translator.translate("details.delete.error.references", new String[] { referencesSummary, entry.getDisplayname() }));
        return false;
    }
    /*
		 * make an archive of the course nodes with valuable data
		 */
    UserManager um = UserManager.getInstance();
    String charset = um.getUserCharset(identity);
    try {
        CourseFactory.archiveCourse(entry.getOlatResource(), charset, locale, identity, roles);
    } catch (CorruptedCourseException e) {
        log.error("The course is corrupted, cannot archive it: " + entry, e);
    }
    return true;
}
Also used : CorruptedCourseException(org.olat.course.CorruptedCourseException) Translator(org.olat.core.gui.translator.Translator) UserManager(org.olat.user.UserManager) ReferenceManager(org.olat.resource.references.ReferenceManager)

Aggregations

UserManager (org.olat.user.UserManager)64 UserPropertyHandler (org.olat.user.propertyhandlers.UserPropertyHandler)22 Locale (java.util.Locale)12 Identity (org.olat.core.id.Identity)12 Date (java.util.Date)10 FormItem (org.olat.core.gui.components.form.flexible.FormItem)10 Translator (org.olat.core.gui.translator.Translator)10 User (org.olat.core.id.User)10 ArrayList (java.util.ArrayList)8 File (java.io.File)6 SingleSelection (org.olat.core.gui.components.form.flexible.elements.SingleSelection)6 RestSecurityHelper.getLocale (org.olat.restapi.security.RestSecurityHelper.getLocale)6 IOException (java.io.IOException)4 HashSet (java.util.HashSet)4 ValidationError (org.olat.core.gui.components.form.ValidationError)4 SelectionElement (org.olat.core.gui.components.form.flexible.elements.SelectionElement)4 ItemValidatorProvider (org.olat.core.gui.components.form.flexible.impl.elements.ItemValidatorProvider)4 AssertException (org.olat.core.logging.AssertException)4 ICourse (org.olat.course.ICourse)4 RestSecurityHelper.isUserManager (org.olat.restapi.security.RestSecurityHelper.isUserManager)4