Search in sources :

Example 1 with UserAuthDataChangedEvent

use of org.thingsboard.server.common.data.security.event.UserAuthDataChangedEvent in project thingsboard by thingsboard.

the class AuthController method resetPassword.

@ApiOperation(value = "Reset password (resetPassword)", notes = "Checks the password reset token and updates the password. " + "If token is valid, returns the object that contains [JWT](https://jwt.io/) access and refresh tokens. " + "If token is not valid, returns '404 Bad Request'.")
@RequestMapping(value = "/noauth/resetPassword", method = RequestMethod.POST)
@ResponseStatus(value = HttpStatus.OK)
@ResponseBody
public JwtTokenPair resetPassword(@ApiParam(value = "Reset password request.") @RequestBody ResetPasswordRequest resetPasswordRequest, HttpServletRequest request) throws ThingsboardException {
    try {
        String resetToken = resetPasswordRequest.getResetToken();
        String password = resetPasswordRequest.getPassword();
        UserCredentials userCredentials = userService.findUserCredentialsByResetToken(TenantId.SYS_TENANT_ID, resetToken);
        if (userCredentials != null) {
            systemSecurityService.validatePassword(TenantId.SYS_TENANT_ID, password, userCredentials);
            if (passwordEncoder.matches(password, userCredentials.getPassword())) {
                throw new ThingsboardException("New password should be different from existing!", ThingsboardErrorCode.BAD_REQUEST_PARAMS);
            }
            String encodedPassword = passwordEncoder.encode(password);
            userCredentials.setPassword(encodedPassword);
            userCredentials.setResetToken(null);
            userCredentials = userService.replaceUserCredentials(TenantId.SYS_TENANT_ID, userCredentials);
            User user = userService.findUserById(TenantId.SYS_TENANT_ID, userCredentials.getUserId());
            UserPrincipal principal = new UserPrincipal(UserPrincipal.Type.USER_NAME, user.getEmail());
            SecurityUser securityUser = new SecurityUser(user, userCredentials.isEnabled(), principal);
            String baseUrl = systemSecurityService.getBaseUrl(user.getTenantId(), user.getCustomerId(), request);
            String loginUrl = String.format("%s/login", baseUrl);
            String email = user.getEmail();
            mailService.sendPasswordWasResetEmail(loginUrl, email);
            eventPublisher.publishEvent(new UserAuthDataChangedEvent(securityUser.getId()));
            JwtToken accessToken = tokenFactory.createAccessJwtToken(securityUser);
            JwtToken refreshToken = refreshTokenRepository.requestRefreshToken(securityUser);
            return new JwtTokenPair(accessToken.getToken(), refreshToken.getToken());
        } else {
            throw new ThingsboardException("Invalid reset token!", ThingsboardErrorCode.BAD_REQUEST_PARAMS);
        }
    } catch (Exception e) {
        throw handleException(e);
    }
}
Also used : JwtToken(org.thingsboard.server.common.data.security.model.JwtToken) User(org.thingsboard.server.common.data.User) SecurityUser(org.thingsboard.server.service.security.model.SecurityUser) SecurityUser(org.thingsboard.server.service.security.model.SecurityUser) JwtTokenPair(org.thingsboard.server.service.security.model.JwtTokenPair) ThingsboardException(org.thingsboard.server.common.data.exception.ThingsboardException) UserCredentials(org.thingsboard.server.common.data.security.UserCredentials) UserAuthDataChangedEvent(org.thingsboard.server.common.data.security.event.UserAuthDataChangedEvent) UserPrincipal(org.thingsboard.server.service.security.model.UserPrincipal) URISyntaxException(java.net.URISyntaxException) ThingsboardException(org.thingsboard.server.common.data.exception.ThingsboardException) ResponseStatus(org.springframework.web.bind.annotation.ResponseStatus) ApiOperation(io.swagger.annotations.ApiOperation) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) ResponseBody(org.springframework.web.bind.annotation.ResponseBody)

Example 2 with UserAuthDataChangedEvent

use of org.thingsboard.server.common.data.security.event.UserAuthDataChangedEvent in project thingsboard by thingsboard.

the class UserServiceImpl method deleteUser.

@Override
public void deleteUser(TenantId tenantId, UserId userId) {
    log.trace("Executing deleteUser [{}]", userId);
    validateId(userId, INCORRECT_USER_ID + userId);
    UserCredentials userCredentials = userCredentialsDao.findByUserId(tenantId, userId.getId());
    userCredentialsDao.removeById(tenantId, userCredentials.getUuidId());
    deleteEntityRelations(tenantId, userId);
    userDao.removeById(tenantId, userId.getId());
    eventPublisher.publishEvent(new UserAuthDataChangedEvent(userId));
}
Also used : UserCredentials(org.thingsboard.server.common.data.security.UserCredentials) UserAuthDataChangedEvent(org.thingsboard.server.common.data.security.event.UserAuthDataChangedEvent)

Example 3 with UserAuthDataChangedEvent

use of org.thingsboard.server.common.data.security.event.UserAuthDataChangedEvent in project thingsboard by thingsboard.

the class UserController method setUserCredentialsEnabled.

@ApiOperation(value = "Enable/Disable User credentials (setUserCredentialsEnabled)", notes = "Enables or Disables user credentials. Useful when you would like to block user account without deleting it. " + PAGE_DATA_PARAMETERS + TENANT_AUTHORITY_PARAGRAPH)
@PreAuthorize("hasAnyAuthority('SYS_ADMIN', 'TENANT_ADMIN')")
@RequestMapping(value = "/user/{userId}/userCredentialsEnabled", method = RequestMethod.POST)
@ResponseBody
public void setUserCredentialsEnabled(@ApiParam(value = USER_ID_PARAM_DESCRIPTION) @PathVariable(USER_ID) String strUserId, @ApiParam(value = "Disable (\"true\") or enable (\"false\") the credentials.", defaultValue = "true") @RequestParam(required = false, defaultValue = "true") boolean userCredentialsEnabled) throws ThingsboardException {
    checkParameter(USER_ID, strUserId);
    try {
        UserId userId = new UserId(toUUID(strUserId));
        User user = checkUserId(userId, Operation.WRITE);
        TenantId tenantId = getCurrentUser().getTenantId();
        userService.setUserCredentialsEnabled(tenantId, userId, userCredentialsEnabled);
        if (!userCredentialsEnabled) {
            eventPublisher.publishEvent(new UserAuthDataChangedEvent(userId));
        }
    } catch (Exception e) {
        throw handleException(e);
    }
}
Also used : TenantId(org.thingsboard.server.common.data.id.TenantId) SecurityUser(org.thingsboard.server.service.security.model.SecurityUser) User(org.thingsboard.server.common.data.User) UserId(org.thingsboard.server.common.data.id.UserId) UserAuthDataChangedEvent(org.thingsboard.server.common.data.security.event.UserAuthDataChangedEvent) ThingsboardException(org.thingsboard.server.common.data.exception.ThingsboardException) ApiOperation(io.swagger.annotations.ApiOperation) PreAuthorize(org.springframework.security.access.prepost.PreAuthorize) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) ResponseBody(org.springframework.web.bind.annotation.ResponseBody)

Example 4 with UserAuthDataChangedEvent

use of org.thingsboard.server.common.data.security.event.UserAuthDataChangedEvent in project thingsboard by thingsboard.

the class AuthController method changePassword.

@ApiOperation(value = "Change password for current User (changePassword)", notes = "Change the password for the User which credentials are used to perform this REST API call. Be aware that previously generated [JWT](https://jwt.io/) tokens will be still valid until they expire.")
@PreAuthorize("isAuthenticated()")
@RequestMapping(value = "/auth/changePassword", method = RequestMethod.POST)
@ResponseStatus(value = HttpStatus.OK)
public ObjectNode changePassword(@ApiParam(value = "Change Password Request") @RequestBody ChangePasswordRequest changePasswordRequest) throws ThingsboardException {
    try {
        String currentPassword = changePasswordRequest.getCurrentPassword();
        String newPassword = changePasswordRequest.getNewPassword();
        SecurityUser securityUser = getCurrentUser();
        UserCredentials userCredentials = userService.findUserCredentialsByUserId(TenantId.SYS_TENANT_ID, securityUser.getId());
        if (!passwordEncoder.matches(currentPassword, userCredentials.getPassword())) {
            throw new ThingsboardException("Current password doesn't match!", ThingsboardErrorCode.BAD_REQUEST_PARAMS);
        }
        systemSecurityService.validatePassword(securityUser.getTenantId(), newPassword, userCredentials);
        if (passwordEncoder.matches(newPassword, userCredentials.getPassword())) {
            throw new ThingsboardException("New password should be different from existing!", ThingsboardErrorCode.BAD_REQUEST_PARAMS);
        }
        userCredentials.setPassword(passwordEncoder.encode(newPassword));
        userService.replaceUserCredentials(securityUser.getTenantId(), userCredentials);
        sendEntityNotificationMsg(getTenantId(), userCredentials.getUserId(), EdgeEventActionType.CREDENTIALS_UPDATED);
        eventPublisher.publishEvent(new UserAuthDataChangedEvent(securityUser.getId()));
        ObjectNode response = JacksonUtil.newObjectNode();
        response.put("token", tokenFactory.createAccessJwtToken(securityUser).getToken());
        response.put("refreshToken", tokenFactory.createRefreshToken(securityUser).getToken());
        return response;
    } catch (Exception e) {
        throw handleException(e);
    }
}
Also used : SecurityUser(org.thingsboard.server.service.security.model.SecurityUser) ObjectNode(com.fasterxml.jackson.databind.node.ObjectNode) ThingsboardException(org.thingsboard.server.common.data.exception.ThingsboardException) UserCredentials(org.thingsboard.server.common.data.security.UserCredentials) UserAuthDataChangedEvent(org.thingsboard.server.common.data.security.event.UserAuthDataChangedEvent) URISyntaxException(java.net.URISyntaxException) ThingsboardException(org.thingsboard.server.common.data.exception.ThingsboardException) ResponseStatus(org.springframework.web.bind.annotation.ResponseStatus) ApiOperation(io.swagger.annotations.ApiOperation) PreAuthorize(org.springframework.security.access.prepost.PreAuthorize) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Aggregations

UserAuthDataChangedEvent (org.thingsboard.server.common.data.security.event.UserAuthDataChangedEvent)4 ApiOperation (io.swagger.annotations.ApiOperation)3 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)3 ThingsboardException (org.thingsboard.server.common.data.exception.ThingsboardException)3 UserCredentials (org.thingsboard.server.common.data.security.UserCredentials)3 SecurityUser (org.thingsboard.server.service.security.model.SecurityUser)3 URISyntaxException (java.net.URISyntaxException)2 PreAuthorize (org.springframework.security.access.prepost.PreAuthorize)2 ResponseBody (org.springframework.web.bind.annotation.ResponseBody)2 ResponseStatus (org.springframework.web.bind.annotation.ResponseStatus)2 User (org.thingsboard.server.common.data.User)2 ObjectNode (com.fasterxml.jackson.databind.node.ObjectNode)1 TenantId (org.thingsboard.server.common.data.id.TenantId)1 UserId (org.thingsboard.server.common.data.id.UserId)1 JwtToken (org.thingsboard.server.common.data.security.model.JwtToken)1 JwtTokenPair (org.thingsboard.server.service.security.model.JwtTokenPair)1 UserPrincipal (org.thingsboard.server.service.security.model.UserPrincipal)1