Search in sources :

Example 1 with Authenticator

use of org.bimserver.Authenticator in project BIMserver by opensourceBIM.

the class AddUserDatabaseAction method execute.

public User execute() throws UserException, BimserverDatabaseException, BimserverLockConflictException {
    String trimmedUserName = username.trim().toLowerCase();
    String trimmedName = name.trim();
    if (userType == UserType.SYSTEM && !createSystemUser) {
        throw new UserException("Cannot create system users");
    }
    if (selfRegistration && userType == UserType.ADMIN) {
        throw new UserException("Cannot create admin user with self registration");
    }
    if (trimmedUserName.equals("")) {
        throw new UserException("Invalid username");
    }
    if (!MailSystem.isValidEmailAddress(trimmedUserName) && !(trimmedUserName.equals("test") || trimmedUserName.equals("system"))) {
        throw new UserException("Username must be a valid e-mail address");
    }
    if (trimmedName.equals("")) {
        throw new UserException("Invalid name");
    }
    if (getUserByUserName(trimmedUserName) != null) {
        throw new UserException("A user with the username " + trimmedUserName + " already exists");
    }
    User actingUser = null;
    // if (bimServer.getServerSettingsCache() != null && !bimServer.getServerSettingsCache().getServerSettings().isAllowCreateValidatedUser()) {
    // if (authorization != null && !(authorization instanceof SystemAuthorization)) {
    // actingUser = getUserByUoid(authorization.getUoid());
    // if (actingUser == null || actingUser.getUserType() != UserType.SYSTEM) {
    // if (authorization.getUoid() != -1 && actingUser.getUserType() != UserType.ADMIN) {
    // throw new UserException("Only admin users can create other users");
    // }
    // }
    // }
    // }
    final User user = getDatabaseSession().create(User.class);
    if (password != null) {
        byte[] salt = new byte[32];
        secureRandom.nextBytes(salt);
        user.setPasswordHash(new Authenticator().createHash(password, salt));
        user.setPasswordSalt(salt);
    }
    user.setToken(GeneratorUtils.generateToken());
    user.setName(trimmedName);
    user.setUsername(trimmedUserName);
    user.setCreatedOn(new Date());
    user.setCreatedBy(actingUser);
    user.setUserType(userType);
    user.setLastSeen(null);
    final String token = GeneratorUtils.generateToken();
    user.setValidationToken(Hashers.getSha256Hash(token));
    user.setValidationTokenCreated(new Date());
    if (!createSystemUser) {
        final NewUserAdded newUserAdded = getDatabaseSession().create(NewUserAdded.class);
        newUserAdded.setUser(user);
        newUserAdded.setExecutor(actingUser);
        newUserAdded.setDate(new Date());
        newUserAdded.setAccessMethod(getAccessMethod());
        getDatabaseSession().store(newUserAdded);
        getDatabaseSession().addPostCommitAction(new PostCommitAction() {

            @Override
            public void execute() throws UserException {
                bimServer.getNotificationsManager().notify(new NewUserNotification(bimServer, user.getOid()));
            }
        });
        bimServer.updateUserSettings(getDatabaseSession(), user);
    }
    getDatabaseSession().store(user);
    if (bimServer != null && bimServer.getServerSettingsCache() != null) {
        // this is only null on server/database initialization
        final ServerSettings serverSettings = bimServer.getServerSettingsCache().getServerSettings();
        if (serverSettings.isSendConfirmationEmailAfterRegistration()) {
            getDatabaseSession().addPostCommitAction(new PostCommitAction() {

                @Override
                public void execute() throws UserException {
                    String body = null;
                    try {
                        if (MailSystem.isValidEmailAddress(user.getUsername())) {
                            EmailMessage message = bimServer.getMailSystem().createMessage();
                            String emailSenderAddress = serverSettings.getEmailSenderAddress();
                            InternetAddress addressFrom = new InternetAddress(emailSenderAddress);
                            message.setFrom(addressFrom);
                            InternetAddress[] addressTo = new InternetAddress[1];
                            addressTo[0] = new InternetAddress(user.getUsername());
                            message.setRecipients(Message.RecipientType.TO, addressTo);
                            Map<String, Object> context = new HashMap<String, Object>();
                            context.put("name", user.getName());
                            context.put("username", user.getUsername());
                            context.put("siteaddress", serverSettings.getSiteAddress());
                            context.put("validationlink", resetUrl + "&username=" + user.getUsername() + "&uoid=" + user.getOid() + "&validationtoken=" + token + "&address=" + bimServer.getServerSettingsCache().getServerSettings().getSiteAddress());
                            String subject = null;
                            if (selfRegistration) {
                                body = bimServer.getTemplateEngine().process(context, TemplateIdentifier.SELF_REGISTRATION_EMAIL_BODY);
                                subject = bimServer.getTemplateEngine().process(context, TemplateIdentifier.SELF_REGISTRATION_EMAIL_SUBJECT);
                            } else {
                                body = bimServer.getTemplateEngine().process(context, TemplateIdentifier.ADMIN_REGISTRATION_EMAIL_BODY);
                                subject = bimServer.getTemplateEngine().process(context, TemplateIdentifier.ADMIN_REGISTRATION_EMAIL_SUBJECT);
                            }
                            message.setContent(body, "text/html");
                            message.setSubject(subject.trim());
                            LOGGER.info("Sending registration e-mail to " + user.getUsername());
                            message.send();
                        }
                    } catch (Exception e) {
                        LOGGER.error(body);
                        LOGGER.error("", e);
                        throw new UserException(e);
                    }
                }
            });
        }
    }
    return user;
}
Also used : EmailMessage(org.bimserver.mail.EmailMessage) InternetAddress(javax.mail.internet.InternetAddress) User(org.bimserver.models.store.User) PostCommitAction(org.bimserver.database.PostCommitAction) NewUserAdded(org.bimserver.models.log.NewUserAdded) Date(java.util.Date) BimserverLockConflictException(org.bimserver.database.BimserverLockConflictException) UserException(org.bimserver.shared.exceptions.UserException) BimserverDatabaseException(org.bimserver.BimserverDatabaseException) ServerSettings(org.bimserver.models.store.ServerSettings) NewUserNotification(org.bimserver.notifications.NewUserNotification) UserException(org.bimserver.shared.exceptions.UserException) HashMap(java.util.HashMap) Map(java.util.Map) Authenticator(org.bimserver.Authenticator)

Example 2 with Authenticator

use of org.bimserver.Authenticator in project BIMserver by opensourceBIM.

the class ChangePasswordDatabaseAction method changePassword.

private boolean changePassword(DatabaseSession databaseSession, User actingUser, boolean skipCheck) throws BimserverLockConflictException, BimserverDatabaseException, UserException {
    User user = getUserByUoid(uoid);
    Authenticator authenticator = new Authenticator();
    if (skipCheck || authenticator.validate(oldPassword, user.getPasswordHash(), user.getPasswordSalt())) {
        byte[] salt = new byte[32];
        new java.security.SecureRandom().nextBytes(salt);
        user.setPasswordHash(authenticator.createHash(newPassword, salt));
        user.setPasswordSalt(salt);
        final PasswordChanged passwordchanged = databaseSession.create(PasswordChanged.class);
        passwordchanged.setAccessMethod(getAccessMethod());
        passwordchanged.setDate(new Date());
        passwordchanged.setExecutor(actingUser);
        passwordchanged.setUser(user);
        getDatabaseSession().addPostCommitAction(new PostCommitAction() {

            @Override
            public void execute() throws UserException {
                bimServer.getNotificationsManager().notify(new SConverter().convertToSObject(passwordchanged));
            }
        });
        databaseSession.store(user);
        return true;
    } else {
        throw new UserException("Old password does not match user's password");
    }
}
Also used : User(org.bimserver.models.store.User) PasswordChanged(org.bimserver.models.log.PasswordChanged) SConverter(org.bimserver.interfaces.SConverter) PostCommitAction(org.bimserver.database.PostCommitAction) UserException(org.bimserver.shared.exceptions.UserException) Authenticator(org.bimserver.Authenticator) Date(java.util.Date)

Example 3 with Authenticator

use of org.bimserver.Authenticator in project BIMserver by opensourceBIM.

the class LoginDatabaseAction method execute.

@Override
public String execute() throws UserException, BimserverLockConflictException, BimserverDatabaseException, ServerException {
    BimDatabaseAction<User> action = new GetUserByUserNameDatabaseAction(getDatabaseSession(), getAccessMethod(), username);
    User user = action.execute();
    if (user != null) {
        if (user.getPasswordHash() == null || user.getPasswordHash().length == 0) {
            throw new UserException("Your email address has not been validated yet");
        }
        if (new Authenticator().validate(password, user.getPasswordHash(), user.getPasswordSalt())) {
            if (user.getState() == ObjectState.DELETED) {
                throw new UserException("User account has been deleted");
            } else if (user.getUserType() == UserType.SYSTEM) {
                throw new UserException("System user cannot login");
            }
            Authorization authorization = null;
            int sessionTimeOutSeconds = 60 * 10;
            boolean migrationRequired = bimServer.getDatabase().getMigrator().migrationRequired();
            if (!migrationRequired) {
                sessionTimeOutSeconds = bimServer.getServerSettingsCache().getServerSettings().getSessionTimeOutSeconds();
            }
            if (user.getUserType() == UserType.ADMIN) {
                authorization = new AdminAuthorization(sessionTimeOutSeconds, TimeUnit.SECONDS);
            } else if (user.getUserType() == UserType.MONITOR) {
                authorization = new MonitorAuthorization(sessionTimeOutSeconds, TimeUnit.SECONDS);
            } else {
                authorization = new UserAuthorization(sessionTimeOutSeconds, TimeUnit.SECONDS);
            }
            authorization.setUoid(user.getOid());
            authorization.setUsername(user.getUsername());
            String asHexToken = authorization.asHexToken(bimServer.getEncryptionKey());
            serviceMap.setAuthorization(authorization);
            bimServer.getAuthCache().store(asHexToken, authorization);
            if (!migrationRequired && bimServer.getServerSettingsCache().getServerSettings().isStoreLastLogin()) {
                user.setLastSeen(new Date());
                getDatabaseSession().store(user);
            }
            return asHexToken;
        }
    }
    try {
        // Adding a random sleep to prevent timing attacks
        Thread.sleep(DEFAULT_LOGIN_ERROR_TIMEOUT + new java.security.SecureRandom().nextInt(1000));
    } catch (InterruptedException e) {
        LOGGER.error("", e);
    }
    throw new UserException("Invalid username/password combination");
}
Also used : User(org.bimserver.models.store.User) UserAuthorization(org.bimserver.webservices.authorization.UserAuthorization) MonitorAuthorization(org.bimserver.webservices.authorization.MonitorAuthorization) Date(java.util.Date) UserAuthorization(org.bimserver.webservices.authorization.UserAuthorization) AdminAuthorization(org.bimserver.webservices.authorization.AdminAuthorization) Authorization(org.bimserver.webservices.authorization.Authorization) MonitorAuthorization(org.bimserver.webservices.authorization.MonitorAuthorization) UserException(org.bimserver.shared.exceptions.UserException) Authenticator(org.bimserver.Authenticator) AdminAuthorization(org.bimserver.webservices.authorization.AdminAuthorization)

Example 4 with Authenticator

use of org.bimserver.Authenticator in project BIMserver by opensourceBIM.

the class ValidateUserDatabaseAction method execute.

@Override
public User execute() throws UserException, BimserverLockConflictException, BimserverDatabaseException {
    User user = getUserByUoid(uoid);
    if (user.getValidationToken() == null || user.getValidationTokenCreated() == null) {
        throw new UserException("This account is already validated and no password reset has been requested");
    }
    if (user.getValidationTokenCreated().getTime() + VALIDATION_TOKEN_EXPIRE_MILLIS < new Date().getTime()) {
        throw new UserException("The validation period of this validation token has expired, please contact your administrator or request the password reset again");
    }
    if (!Arrays.equals(user.getValidationToken(), Hashers.getSha256Hash(token))) {
        throw new UserException("The given token is not correct");
    }
    if (password == null || password.trim().equals("")) {
        throw new UserException("Invalid new password");
    }
    byte[] salt = new byte[32];
    new java.security.SecureRandom().nextBytes(salt);
    user.setPasswordHash(new Authenticator().createHash(password, salt));
    user.setPasswordSalt(salt);
    user.setValidationToken(null);
    user.setValidationTokenCreated(null);
    getDatabaseSession().store(user);
    return user;
}
Also used : User(org.bimserver.models.store.User) UserException(org.bimserver.shared.exceptions.UserException) Date(java.util.Date) Authenticator(org.bimserver.Authenticator)

Aggregations

Date (java.util.Date)4 Authenticator (org.bimserver.Authenticator)4 User (org.bimserver.models.store.User)4 UserException (org.bimserver.shared.exceptions.UserException)4 PostCommitAction (org.bimserver.database.PostCommitAction)2 HashMap (java.util.HashMap)1 Map (java.util.Map)1 InternetAddress (javax.mail.internet.InternetAddress)1 BimserverDatabaseException (org.bimserver.BimserverDatabaseException)1 BimserverLockConflictException (org.bimserver.database.BimserverLockConflictException)1 SConverter (org.bimserver.interfaces.SConverter)1 EmailMessage (org.bimserver.mail.EmailMessage)1 NewUserAdded (org.bimserver.models.log.NewUserAdded)1 PasswordChanged (org.bimserver.models.log.PasswordChanged)1 ServerSettings (org.bimserver.models.store.ServerSettings)1 NewUserNotification (org.bimserver.notifications.NewUserNotification)1 AdminAuthorization (org.bimserver.webservices.authorization.AdminAuthorization)1 Authorization (org.bimserver.webservices.authorization.Authorization)1 MonitorAuthorization (org.bimserver.webservices.authorization.MonitorAuthorization)1 UserAuthorization (org.bimserver.webservices.authorization.UserAuthorization)1