Search in sources :

Example 1 with JwtTokenPair

use of org.thingsboard.server.service.security.model.JwtTokenPair in project thingsboard by thingsboard.

the class AuthController method activateUser.

@ApiOperation(value = "Activate User", notes = "Checks the activation token and updates corresponding user password in the database. " + "Now the user may start using his password to login. " + "The response already contains the [JWT](https://jwt.io) activation and refresh tokens, " + "to simplify the user activation flow and avoid asking user to input password again after activation. " + "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/activate", method = RequestMethod.POST)
@ResponseStatus(value = HttpStatus.OK)
@ResponseBody
public JwtTokenPair activateUser(@ApiParam(value = "Activate user request.") @RequestBody ActivateUserRequest activateRequest, @RequestParam(required = false, defaultValue = "true") boolean sendActivationMail, HttpServletRequest request) throws ThingsboardException {
    try {
        String activateToken = activateRequest.getActivateToken();
        String password = activateRequest.getPassword();
        systemSecurityService.validatePassword(TenantId.SYS_TENANT_ID, password, null);
        String encodedPassword = passwordEncoder.encode(password);
        UserCredentials credentials = userService.activateUserCredentials(TenantId.SYS_TENANT_ID, activateToken, encodedPassword);
        User user = userService.findUserById(TenantId.SYS_TENANT_ID, credentials.getUserId());
        UserPrincipal principal = new UserPrincipal(UserPrincipal.Type.USER_NAME, user.getEmail());
        SecurityUser securityUser = new SecurityUser(user, credentials.isEnabled(), principal);
        userService.setUserCredentialsEnabled(user.getTenantId(), user.getId(), true);
        String baseUrl = systemSecurityService.getBaseUrl(user.getTenantId(), user.getCustomerId(), request);
        String loginUrl = String.format("%s/login", baseUrl);
        String email = user.getEmail();
        if (sendActivationMail) {
            try {
                mailService.sendAccountActivatedEmail(loginUrl, email);
            } catch (Exception e) {
                log.info("Unable to send account activation email [{}]", e.getMessage());
            }
        }
        sendEntityNotificationMsg(user.getTenantId(), user.getId(), EdgeEventActionType.CREDENTIALS_UPDATED);
        JwtToken accessToken = tokenFactory.createAccessJwtToken(securityUser);
        JwtToken refreshToken = refreshTokenRepository.requestRefreshToken(securityUser);
        return new JwtTokenPair(accessToken.getToken(), refreshToken.getToken());
    } 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) UserCredentials(org.thingsboard.server.common.data.security.UserCredentials) 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 JwtTokenPair

use of org.thingsboard.server.service.security.model.JwtTokenPair 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 3 with JwtTokenPair

use of org.thingsboard.server.service.security.model.JwtTokenPair in project thingsboard by thingsboard.

the class UserController method getUserToken.

@ApiOperation(value = "Get User Token (getUserToken)", notes = "Returns the token of the User based on the provided User Id. " + "If the user who performs the request has the authority of 'SYS_ADMIN', it is possible to get the token of any tenant administrator. " + "If the user who performs the request has the authority of 'TENANT_ADMIN', it is possible to get the token of any customer user that belongs to the same tenant. ")
@PreAuthorize("hasAnyAuthority('SYS_ADMIN', 'TENANT_ADMIN')")
@RequestMapping(value = "/user/{userId}/token", method = RequestMethod.GET)
@ResponseBody
public JwtTokenPair getUserToken(@ApiParam(value = USER_ID_PARAM_DESCRIPTION) @PathVariable(USER_ID) String strUserId) throws ThingsboardException {
    checkParameter(USER_ID, strUserId);
    try {
        if (!userTokenAccessEnabled) {
            throw new ThingsboardException(YOU_DON_T_HAVE_PERMISSION_TO_PERFORM_THIS_OPERATION, ThingsboardErrorCode.PERMISSION_DENIED);
        }
        UserId userId = new UserId(toUUID(strUserId));
        SecurityUser authUser = getCurrentUser();
        User user = checkUserId(userId, Operation.READ);
        UserPrincipal principal = new UserPrincipal(UserPrincipal.Type.USER_NAME, user.getEmail());
        UserCredentials credentials = userService.findUserCredentialsByUserId(authUser.getTenantId(), userId);
        SecurityUser securityUser = new SecurityUser(user, credentials.isEnabled(), principal);
        JwtToken accessToken = tokenFactory.createAccessJwtToken(securityUser);
        JwtToken refreshToken = refreshTokenRepository.requestRefreshToken(securityUser);
        return new JwtTokenPair(accessToken.getToken(), refreshToken.getToken());
    } catch (Exception e) {
        throw handleException(e);
    }
}
Also used : JwtToken(org.thingsboard.server.common.data.security.model.JwtToken) SecurityUser(org.thingsboard.server.service.security.model.SecurityUser) SecurityUser(org.thingsboard.server.service.security.model.SecurityUser) User(org.thingsboard.server.common.data.User) JwtTokenPair(org.thingsboard.server.service.security.model.JwtTokenPair) UserId(org.thingsboard.server.common.data.id.UserId) ThingsboardException(org.thingsboard.server.common.data.exception.ThingsboardException) UserCredentials(org.thingsboard.server.common.data.security.UserCredentials) UserPrincipal(org.thingsboard.server.service.security.model.UserPrincipal) 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)

Aggregations

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