Search in sources :

Example 1 with OAuth2User

use of org.thingsboard.server.dao.oauth2.OAuth2User in project thingsboard by thingsboard.

the class AppleOAuth2ClientMapper method getOrCreateUserByClientPrincipal.

@Override
public SecurityUser getOrCreateUserByClientPrincipal(HttpServletRequest request, OAuth2AuthenticationToken token, String providerAccessToken, OAuth2Registration registration) {
    OAuth2MapperConfig config = registration.getMapperConfig();
    Map<String, Object> attributes = updateAttributesFromRequestParams(request, token.getPrincipal().getAttributes());
    String email = BasicMapperUtils.getStringAttributeByKey(attributes, config.getBasic().getEmailAttributeKey());
    OAuth2User oauth2User = BasicMapperUtils.getOAuth2User(email, attributes, config);
    return getOrCreateSecurityUserFromOAuth2User(oauth2User, registration);
}
Also used : OAuth2User(org.thingsboard.server.dao.oauth2.OAuth2User) OAuth2MapperConfig(org.thingsboard.server.common.data.oauth2.OAuth2MapperConfig)

Example 2 with OAuth2User

use of org.thingsboard.server.dao.oauth2.OAuth2User in project thingsboard by thingsboard.

the class CustomOAuth2ClientMapper method getOAuth2User.

private synchronized OAuth2User getOAuth2User(OAuth2AuthenticationToken token, String providerAccessToken, OAuth2CustomMapperConfig custom) {
    if (!StringUtils.isEmpty(custom.getUsername()) && !StringUtils.isEmpty(custom.getPassword())) {
        restTemplateBuilder = restTemplateBuilder.basicAuthentication(custom.getUsername(), custom.getPassword());
    }
    if (custom.isSendToken() && !StringUtils.isEmpty(providerAccessToken)) {
        restTemplateBuilder = restTemplateBuilder.defaultHeader(PROVIDER_ACCESS_TOKEN, providerAccessToken);
    }
    RestTemplate restTemplate = restTemplateBuilder.build();
    String request;
    try {
        request = json.writeValueAsString(token.getPrincipal());
    } catch (JsonProcessingException e) {
        log.error("Can't convert principal to JSON string", e);
        throw new RuntimeException("Can't convert principal to JSON string", e);
    }
    try {
        return restTemplate.postForEntity(custom.getUrl(), request, OAuth2User.class).getBody();
    } catch (Exception e) {
        log.error("There was an error during connection to custom mapper endpoint", e);
        throw new RuntimeException("Unable to login. Please contact your Administrator!");
    }
}
Also used : OAuth2User(org.thingsboard.server.dao.oauth2.OAuth2User) RestTemplate(org.springframework.web.client.RestTemplate) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException)

Example 3 with OAuth2User

use of org.thingsboard.server.dao.oauth2.OAuth2User in project thingsboard by thingsboard.

the class GithubOAuth2ClientMapper method getOrCreateUserByClientPrincipal.

@Override
public SecurityUser getOrCreateUserByClientPrincipal(HttpServletRequest request, OAuth2AuthenticationToken token, String providerAccessToken, OAuth2Registration registration) {
    OAuth2MapperConfig config = registration.getMapperConfig();
    Map<String, String> githubMapperConfig = oAuth2Configuration.getGithubMapper();
    String email = getEmail(githubMapperConfig.get(EMAIL_URL_KEY), providerAccessToken);
    Map<String, Object> attributes = token.getPrincipal().getAttributes();
    OAuth2User oAuth2User = BasicMapperUtils.getOAuth2User(email, attributes, config);
    return getOrCreateSecurityUserFromOAuth2User(oAuth2User, registration);
}
Also used : OAuth2User(org.thingsboard.server.dao.oauth2.OAuth2User) OAuth2MapperConfig(org.thingsboard.server.common.data.oauth2.OAuth2MapperConfig) ToString(lombok.ToString)

Example 4 with OAuth2User

use of org.thingsboard.server.dao.oauth2.OAuth2User in project thingsboard by thingsboard.

the class AbstractOAuth2ClientMapper method getOrCreateSecurityUserFromOAuth2User.

protected SecurityUser getOrCreateSecurityUserFromOAuth2User(OAuth2User oauth2User, OAuth2Registration registration) {
    OAuth2MapperConfig config = registration.getMapperConfig();
    UserPrincipal principal = new UserPrincipal(UserPrincipal.Type.USER_NAME, oauth2User.getEmail());
    User user = userService.findUserByEmail(TenantId.SYS_TENANT_ID, oauth2User.getEmail());
    if (user == null && !config.isAllowUserCreation()) {
        throw new UsernameNotFoundException("User not found: " + oauth2User.getEmail());
    }
    if (user == null) {
        userCreationLock.lock();
        try {
            user = userService.findUserByEmail(TenantId.SYS_TENANT_ID, oauth2User.getEmail());
            if (user == null) {
                user = new User();
                if (oauth2User.getCustomerId() == null && StringUtils.isEmpty(oauth2User.getCustomerName())) {
                    user.setAuthority(Authority.TENANT_ADMIN);
                } else {
                    user.setAuthority(Authority.CUSTOMER_USER);
                }
                TenantId tenantId = oauth2User.getTenantId() != null ? oauth2User.getTenantId() : getTenantId(oauth2User.getTenantName());
                user.setTenantId(tenantId);
                CustomerId customerId = oauth2User.getCustomerId() != null ? oauth2User.getCustomerId() : getCustomerId(user.getTenantId(), oauth2User.getCustomerName());
                user.setCustomerId(customerId);
                user.setEmail(oauth2User.getEmail());
                user.setFirstName(oauth2User.getFirstName());
                user.setLastName(oauth2User.getLastName());
                ObjectNode additionalInfo = objectMapper.createObjectNode();
                if (!StringUtils.isEmpty(oauth2User.getDefaultDashboardName())) {
                    Optional<DashboardId> dashboardIdOpt = user.getAuthority() == Authority.TENANT_ADMIN ? getDashboardId(tenantId, oauth2User.getDefaultDashboardName()) : getDashboardId(tenantId, customerId, oauth2User.getDefaultDashboardName());
                    if (dashboardIdOpt.isPresent()) {
                        additionalInfo.put("defaultDashboardFullscreen", oauth2User.isAlwaysFullScreen());
                        additionalInfo.put("defaultDashboardId", dashboardIdOpt.get().getId().toString());
                    }
                }
                if (registration.getAdditionalInfo() != null && registration.getAdditionalInfo().has("providerName")) {
                    additionalInfo.put("authProviderName", registration.getAdditionalInfo().get("providerName").asText());
                }
                user.setAdditionalInfo(additionalInfo);
                user = userService.saveUser(user);
                if (config.isActivateUser()) {
                    UserCredentials userCredentials = userService.findUserCredentialsByUserId(user.getTenantId(), user.getId());
                    userService.activateUserCredentials(user.getTenantId(), userCredentials.getActivateToken(), passwordEncoder.encode(""));
                }
            }
        } catch (Exception e) {
            log.error("Can't get or create security user from oauth2 user", e);
            throw new RuntimeException("Can't get or create security user from oauth2 user", e);
        } finally {
            userCreationLock.unlock();
        }
    }
    try {
        SecurityUser securityUser = new SecurityUser(user, true, principal);
        return (SecurityUser) new UsernamePasswordAuthenticationToken(securityUser, null, securityUser.getAuthorities()).getPrincipal();
    } catch (Exception e) {
        log.error("Can't get or create security user from oauth2 user", e);
        throw new RuntimeException("Can't get or create security user from oauth2 user", e);
    }
}
Also used : UsernameNotFoundException(org.springframework.security.core.userdetails.UsernameNotFoundException) OAuth2User(org.thingsboard.server.dao.oauth2.OAuth2User) User(org.thingsboard.server.common.data.User) SecurityUser(org.thingsboard.server.service.security.model.SecurityUser) ObjectNode(com.fasterxml.jackson.databind.node.ObjectNode) OAuth2MapperConfig(org.thingsboard.server.common.data.oauth2.OAuth2MapperConfig) UsernamePasswordAuthenticationToken(org.springframework.security.authentication.UsernamePasswordAuthenticationToken) CustomerId(org.thingsboard.server.common.data.id.CustomerId) DashboardId(org.thingsboard.server.common.data.id.DashboardId) UserPrincipal(org.thingsboard.server.service.security.model.UserPrincipal) UsernameNotFoundException(org.springframework.security.core.userdetails.UsernameNotFoundException) IOException(java.io.IOException) TenantId(org.thingsboard.server.common.data.id.TenantId) SecurityUser(org.thingsboard.server.service.security.model.SecurityUser) UserCredentials(org.thingsboard.server.common.data.security.UserCredentials)

Example 5 with OAuth2User

use of org.thingsboard.server.dao.oauth2.OAuth2User in project thingsboard by thingsboard.

the class BasicMapperUtils method getOAuth2User.

public static OAuth2User getOAuth2User(String email, Map<String, Object> attributes, OAuth2MapperConfig config) {
    OAuth2User oauth2User = new OAuth2User();
    oauth2User.setEmail(email);
    oauth2User.setTenantName(getTenantName(email, attributes, config));
    if (!StringUtils.isEmpty(config.getBasic().getLastNameAttributeKey())) {
        String lastName = getStringAttributeByKey(attributes, config.getBasic().getLastNameAttributeKey());
        oauth2User.setLastName(lastName);
    }
    if (!StringUtils.isEmpty(config.getBasic().getFirstNameAttributeKey())) {
        String firstName = getStringAttributeByKey(attributes, config.getBasic().getFirstNameAttributeKey());
        oauth2User.setFirstName(firstName);
    }
    if (!StringUtils.isEmpty(config.getBasic().getCustomerNamePattern())) {
        StrSubstitutor sub = new StrSubstitutor(attributes, START_PLACEHOLDER_PREFIX, END_PLACEHOLDER_PREFIX);
        String customerName = sub.replace(config.getBasic().getCustomerNamePattern());
        oauth2User.setCustomerName(customerName);
    }
    oauth2User.setAlwaysFullScreen(config.getBasic().isAlwaysFullScreen());
    if (!StringUtils.isEmpty(config.getBasic().getDefaultDashboardName())) {
        oauth2User.setDefaultDashboardName(config.getBasic().getDefaultDashboardName());
    }
    return oauth2User;
}
Also used : OAuth2User(org.thingsboard.server.dao.oauth2.OAuth2User) StrSubstitutor(org.apache.commons.lang3.text.StrSubstitutor)

Aggregations

OAuth2User (org.thingsboard.server.dao.oauth2.OAuth2User)7 OAuth2MapperConfig (org.thingsboard.server.common.data.oauth2.OAuth2MapperConfig)5 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)1 ObjectNode (com.fasterxml.jackson.databind.node.ObjectNode)1 IOException (java.io.IOException)1 ToString (lombok.ToString)1 StrSubstitutor (org.apache.commons.lang3.text.StrSubstitutor)1 UsernamePasswordAuthenticationToken (org.springframework.security.authentication.UsernamePasswordAuthenticationToken)1 UsernameNotFoundException (org.springframework.security.core.userdetails.UsernameNotFoundException)1 RestTemplate (org.springframework.web.client.RestTemplate)1 User (org.thingsboard.server.common.data.User)1 CustomerId (org.thingsboard.server.common.data.id.CustomerId)1 DashboardId (org.thingsboard.server.common.data.id.DashboardId)1 TenantId (org.thingsboard.server.common.data.id.TenantId)1 UserCredentials (org.thingsboard.server.common.data.security.UserCredentials)1 SecurityUser (org.thingsboard.server.service.security.model.SecurityUser)1 UserPrincipal (org.thingsboard.server.service.security.model.UserPrincipal)1