Search in sources :

Example 1 with LinkedAccount

use of com.serotonin.m2m2.vo.LinkedAccount in project ma-modules-public by infiniteautomation.

the class UserRestController method updateLinkedAccounts.

@RequestMapping(method = RequestMethod.PUT, value = "/linked-accounts/{username}")
public void updateLinkedAccounts(@PathVariable String username, @RequestBody List<LinkedAccountModel> linkedAccountModels, @AuthenticationPrincipal PermissionHolder currentUser) {
    User userToUpdate = service.get(username);
    List<LinkedAccount> linkedAccounts = linkedAccountModels.stream().map(a -> mapper.unMap(a, LinkedAccount.class, currentUser)).collect(Collectors.toList());
    service.updateLinkedAccounts(userToUpdate.getId(), linkedAccounts);
}
Also used : BadRequestException(com.infiniteautomation.mango.rest.latest.exception.BadRequestException) PathVariable(org.springframework.web.bind.annotation.PathVariable) UriComponentsBuilder(org.springframework.web.util.UriComponentsBuilder) RequestParam(org.springframework.web.bind.annotation.RequestParam) PreAuthorize(org.springframework.security.access.prepost.PreAuthorize) StreamedVORqlQueryWithTotal(com.infiniteautomation.mango.rest.latest.model.StreamedVORqlQueryWithTotal) Autowired(org.springframework.beans.factory.annotation.Autowired) ApiParam(io.swagger.annotations.ApiParam) Translations(com.serotonin.m2m2.i18n.Translations) PermissionHolder(com.serotonin.m2m2.vo.permission.PermissionHolder) RestModelMapper(com.infiniteautomation.mango.rest.latest.model.RestModelMapper) PatchVORequestBody(com.infiniteautomation.mango.rest.latest.patch.PatchVORequestBody) ApiOperation(io.swagger.annotations.ApiOperation) Map(java.util.Map) URI(java.net.URI) UserActionAndModel(com.infiniteautomation.mango.rest.latest.model.user.UserActionAndModel) RuntimeStatusModel(com.infiniteautomation.mango.rest.latest.model.datasource.RuntimeStatusModel) TemporaryResourceStatusUpdate(com.infiniteautomation.mango.rest.latest.temporaryResource.TemporaryResourceStatusUpdate) HttpHeaders(org.springframework.http.HttpHeaders) RQLUtils(com.infiniteautomation.mango.util.RQLUtils) RequestMethod(org.springframework.web.bind.annotation.RequestMethod) TranslatableMessage(com.serotonin.m2m2.i18n.TranslatableMessage) Collectors(java.util.stream.Collectors) RestController(org.springframework.web.bind.annotation.RestController) JsonStreamedArray(com.serotonin.json.type.JsonStreamedArray) List(java.util.List) UserModel(com.infiniteautomation.mango.rest.latest.model.user.UserModel) StreamedSeroJsonVORqlQuery(com.infiniteautomation.mango.rest.latest.model.StreamedSeroJsonVORqlQuery) ASTNode(net.jazdw.rql.parser.ASTNode) Environment(org.springframework.core.env.Environment) UsernamePasswordAuthenticationToken(org.springframework.security.authentication.UsernamePasswordAuthenticationToken) Authentication(org.springframework.security.core.Authentication) UserIndividualRequest(com.infiniteautomation.mango.rest.latest.model.user.UserIndividualRequest) User(com.serotonin.m2m2.vo.User) PermissionService(com.infiniteautomation.mango.spring.service.PermissionService) PatchIdField(com.infiniteautomation.mango.rest.latest.patch.PatchVORequestBody.PatchIdField) FilteredStreamWithTotal(com.infiniteautomation.mango.rest.latest.model.FilteredStreamWithTotal) VoAction(com.infiniteautomation.mango.rest.latest.bulk.VoAction) TemporaryResourceStatus(com.infiniteautomation.mango.rest.latest.temporaryResource.TemporaryResource.TemporaryResourceStatus) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) HashMap(java.util.HashMap) Function(java.util.function.Function) ArrayList(java.util.ArrayList) RequestBody(org.springframework.web.bind.annotation.RequestBody) UserModelMapping(com.infiniteautomation.mango.rest.latest.model.user.UserModelMapping) HttpServletRequest(javax.servlet.http.HttpServletRequest) UsersService(com.infiniteautomation.mango.spring.service.UsersService) MappingJacksonValue(org.springframework.http.converter.json.MappingJacksonValue) StreamedArrayWithTotal(com.infiniteautomation.mango.rest.latest.model.StreamedArrayWithTotal) Api(io.swagger.annotations.Api) UserIndividualResponse(com.infiniteautomation.mango.rest.latest.model.user.UserIndividualResponse) TemporaryResourceWebSocketHandler(com.infiniteautomation.mango.rest.latest.temporaryResource.TemporaryResourceWebSocketHandler) TemporaryResource(com.infiniteautomation.mango.rest.latest.temporaryResource.TemporaryResource) TranslatableExceptionI(com.infiniteautomation.mango.util.exception.TranslatableExceptionI) MangoSessionRegistry(com.serotonin.m2m2.web.mvc.spring.security.MangoSessionRegistry) MangoTaskTemporaryResourceManager(com.infiniteautomation.mango.rest.latest.temporaryResource.MangoTaskTemporaryResourceManager) Common(com.serotonin.m2m2.Common) LinkedAccount(com.serotonin.m2m2.vo.LinkedAccount) LinkedAccountModel(com.infiniteautomation.mango.rest.latest.model.user.LinkedAccountModel) BulkResponse(com.infiniteautomation.mango.rest.latest.bulk.BulkResponse) BulkRequest(com.infiniteautomation.mango.rest.latest.bulk.BulkRequest) HttpStatus(org.springframework.http.HttpStatus) ApprovedUsersModel(com.infiniteautomation.mango.rest.latest.model.user.ApprovedUsersModel) AuthenticationPrincipal(org.springframework.security.core.annotation.AuthenticationPrincipal) MediaTypes(com.serotonin.m2m2.web.MediaTypes) ResponseEntity(org.springframework.http.ResponseEntity) AbstractRestException(com.infiniteautomation.mango.rest.latest.exception.AbstractRestException) TemporaryResourceManager(com.infiniteautomation.mango.rest.latest.temporaryResource.TemporaryResourceManager) ApproveUsersModel(com.infiniteautomation.mango.rest.latest.model.user.ApproveUsersModel) PermissionException(com.serotonin.m2m2.vo.permission.PermissionException) User(com.serotonin.m2m2.vo.User) LinkedAccount(com.serotonin.m2m2.vo.LinkedAccount) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 2 with LinkedAccount

use of com.serotonin.m2m2.vo.LinkedAccount in project ma-core-public by infiniteautomation.

the class UserImporter method linkAccounts.

@SuppressWarnings("unchecked")
protected void linkAccounts(int userId) throws JsonException {
    TypeDefinition listOfAccountsType = new TypeDefinition(List.class, OAuth2LinkedAccount.class);
    JsonArray linkedAccounts = json.getJsonArray("linkedAccounts");
    if (linkedAccounts != null) {
        List<LinkedAccount> accounts = (List<LinkedAccount>) ctx.getReader().read(listOfAccountsType, linkedAccounts);
        usersService.updateLinkedAccounts(userId, accounts);
    }
}
Also used : JsonArray(com.serotonin.json.type.JsonArray) List(java.util.List) TypeDefinition(com.serotonin.json.util.TypeDefinition) LinkedAccount(com.serotonin.m2m2.vo.LinkedAccount) OAuth2LinkedAccount(com.serotonin.m2m2.vo.OAuth2LinkedAccount)

Example 3 with LinkedAccount

use of com.serotonin.m2m2.vo.LinkedAccount in project ma-core-public by infiniteautomation.

the class UserDao method linkAccount.

public void linkAccount(int userId, LinkedAccount account) {
    if (account instanceof OAuth2LinkedAccount) {
        OAuth2LinkedAccount oAuth2Account = (OAuth2LinkedAccount) account;
        create.insertInto(oauth).set(oauth.userId, userId).set(oauth.issuer, oAuth2Account.getIssuer()).set(oauth.subject, oAuth2Account.getSubject()).execute();
    } else {
        throw new UnsupportedOperationException();
    }
}
Also used : OAuth2LinkedAccount(com.serotonin.m2m2.vo.OAuth2LinkedAccount)

Example 4 with LinkedAccount

use of com.serotonin.m2m2.vo.LinkedAccount in project ma-core-public by infiniteautomation.

the class UserDao method updateLinkedAccounts.

public void updateLinkedAccounts(int userId, Iterable<? extends LinkedAccount> accounts) {
    this.doInTransaction(txStatus -> {
        create.deleteFrom(oauth).where(oauth.userId.equal(userId)).execute();
        InsertValuesStep3<OAuth2UsersRecord, Integer, String, String> insert = create.insertInto(oauth, oauth.userId, oauth.issuer, oauth.subject);
        for (LinkedAccount account : accounts) {
            if (account instanceof OAuth2LinkedAccount) {
                OAuth2LinkedAccount oAuth2Account = (OAuth2LinkedAccount) account;
                insert = insert.values(userId, oAuth2Account.getIssuer(), oAuth2Account.getSubject());
            } else {
                throw new UnsupportedOperationException();
            }
        }
        insert.execute();
    });
}
Also used : OAuth2LinkedAccount(com.serotonin.m2m2.vo.OAuth2LinkedAccount) OAuth2UsersRecord(com.infiniteautomation.mango.db.tables.records.OAuth2UsersRecord) OAuth2LinkedAccount(com.serotonin.m2m2.vo.OAuth2LinkedAccount) LinkedAccount(com.serotonin.m2m2.vo.LinkedAccount)

Example 5 with LinkedAccount

use of com.serotonin.m2m2.vo.LinkedAccount in project ma-core-public by infiniteautomation.

the class DefaultUserMapper method mapUser.

@Override
public User mapUser(OAuth2UserRequest userRequest, OAuth2User oAuth2User) {
    if (log.isDebugEnabled()) {
        log.debug("Syncing OAuth2 user {} to Mango user", oAuth2User);
    }
    ClientRegistration clientRegistration = userRequest.getClientRegistration();
    StandardClaimAccessor accessor = toAccessor(oAuth2User);
    String registrationId = clientRegistration.getRegistrationId();
    EnvironmentPropertyMapper userMapping = mapperFactory.forRegistrationId(registrationId, "userMapping.");
    Optional<String> issuerOptional = userMapping.map("issuer.fixed");
    if (!issuerOptional.isPresent()) {
        issuerOptional = userMapping.map("issuer", accessor::getClaimAsString);
    }
    String issuer = issuerOptional.orElseThrow(() -> new IllegalStateException("Issuer is required"));
    String subject = userMapping.map("subject", accessor::getClaimAsString).orElseThrow(() -> new IllegalStateException("Subject is required"));
    LinkedAccount linkedAccount = new OAuth2LinkedAccount(issuer, subject);
    User user = usersService.getUserForLinkedAccount(linkedAccount).orElseGet(() -> {
        // only synchronize the username when creating the user
        String usernamePrefix = userMapping.map("username.prefix").orElse("");
        String usernameSuffix = userMapping.map("username.suffix").orElse("");
        String username = userMapping.map("username", accessor::getClaimAsString).map(un -> usernamePrefix + un + usernameSuffix).orElse(// user will get a random XID for a username if claim is missing
        null);
        User newUser = new User();
        newUser.setUsername(username);
        newUser.setPassword(LOCKED_PASSWORD);
        // in case role sync is not turned on
        newUser.setRoles(Collections.singleton(PermissionHolder.USER_ROLE));
        return newUser;
    });
    String emailPrefix = userMapping.map("email.prefix").orElse("");
    String emailSuffix = userMapping.map("email.suffix").orElse("");
    String email = userMapping.map("email", accessor::getClaimAsString).map(e -> emailPrefix + e + emailSuffix).orElse(// validation will fail if email is not set
    null);
    user.setEmail(email);
    userMapping.map("name", accessor::getClaimAsString).ifPresent(user::setName);
    userMapping.map("phone", accessor::getClaimAsString).ifPresent(user::setPhone);
    userMapping.map("locale", accessor::getClaimAsString).ifPresent(user::setLocale);
    userMapping.map("timezone", accessor::getClaimAsString).ifPresent(user::setTimezone);
    if (userMapping.map("oauth2.client.default.userMapping.roles.sync", Boolean.class).orElse(true)) {
        String rolePrefix = userMapping.map("roles.prefix").orElse("");
        String roleSuffix = userMapping.map("roles.suffix").orElse("");
        Set<String> ignoreRoles = Arrays.stream(userMapping.map("roles.ignore", String[].class).orElse(new String[0])).collect(Collectors.toSet());
        Stream<String> oauthRoles = userMapping.map("roles", accessor::getClaimAsStringList).orElseGet(ArrayList::new).stream().filter(r -> !ignoreRoles.contains(r)).map(r -> userMapping.map("roles.map." + r).orElse(rolePrefix + r + roleSuffix));
        Stream<String> addRoles = Arrays.stream(userMapping.map("roles.add", String[].class).orElse(new String[0]));
        Set<Role> roles = Stream.concat(oauthRoles, addRoles).map(roleService::getOrInsert).map(RoleVO::getRole).collect(Collectors.toCollection(HashSet::new));
        // ensure user role is present
        roles.add(PermissionHolder.USER_ROLE);
        user.setRoles(roles);
    }
    if (user.isNew()) {
        usersService.insertUserForLinkedAccount(user, linkedAccount);
    } else {
        usersService.update(user.getId(), user);
    }
    return user;
}
Also used : Arrays(java.util.Arrays) OidcUser(org.springframework.security.oauth2.core.oidc.user.OidcUser) Role(com.serotonin.m2m2.vo.role.Role) OAuth2UserRequest(org.springframework.security.oauth2.client.userinfo.OAuth2UserRequest) LoggerFactory(org.slf4j.LoggerFactory) Autowired(org.springframework.beans.factory.annotation.Autowired) PermissionHolder(com.serotonin.m2m2.vo.permission.PermissionHolder) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) UsersService(com.infiniteautomation.mango.spring.service.UsersService) RoleVO(com.serotonin.m2m2.vo.role.RoleVO) StandardClaimAccessor(org.springframework.security.oauth2.core.oidc.StandardClaimAccessor) Logger(org.slf4j.Logger) LinkedAccount(com.serotonin.m2m2.vo.LinkedAccount) Set(java.util.Set) Collectors(java.util.stream.Collectors) ClientRegistration(org.springframework.security.oauth2.client.registration.ClientRegistration) Component(org.springframework.stereotype.Component) Stream(java.util.stream.Stream) EnvironmentPropertyMapper(com.infiniteautomation.mango.util.EnvironmentPropertyMapper) ConditionalOnProperty(com.infiniteautomation.mango.spring.ConditionalOnProperty) OAuth2User(org.springframework.security.oauth2.core.user.OAuth2User) Optional(java.util.Optional) LOCKED_PASSWORD(com.serotonin.m2m2.db.dao.UserDao.LOCKED_PASSWORD) OAuth2LinkedAccount(com.serotonin.m2m2.vo.OAuth2LinkedAccount) Collections(java.util.Collections) User(com.serotonin.m2m2.vo.User) RoleService(com.infiniteautomation.mango.spring.service.RoleService) OidcUser(org.springframework.security.oauth2.core.oidc.user.OidcUser) OAuth2User(org.springframework.security.oauth2.core.user.OAuth2User) User(com.serotonin.m2m2.vo.User) LinkedAccount(com.serotonin.m2m2.vo.LinkedAccount) OAuth2LinkedAccount(com.serotonin.m2m2.vo.OAuth2LinkedAccount) OAuth2LinkedAccount(com.serotonin.m2m2.vo.OAuth2LinkedAccount) Role(com.serotonin.m2m2.vo.role.Role) StandardClaimAccessor(org.springframework.security.oauth2.core.oidc.StandardClaimAccessor) EnvironmentPropertyMapper(com.infiniteautomation.mango.util.EnvironmentPropertyMapper) ClientRegistration(org.springframework.security.oauth2.client.registration.ClientRegistration)

Aggregations

LinkedAccount (com.serotonin.m2m2.vo.LinkedAccount)4 OAuth2LinkedAccount (com.serotonin.m2m2.vo.OAuth2LinkedAccount)4 UsersService (com.infiniteautomation.mango.spring.service.UsersService)2 List (java.util.List)2 OAuth2UsersRecord (com.infiniteautomation.mango.db.tables.records.OAuth2UsersRecord)1 BulkRequest (com.infiniteautomation.mango.rest.latest.bulk.BulkRequest)1 BulkResponse (com.infiniteautomation.mango.rest.latest.bulk.BulkResponse)1 VoAction (com.infiniteautomation.mango.rest.latest.bulk.VoAction)1 AbstractRestException (com.infiniteautomation.mango.rest.latest.exception.AbstractRestException)1 BadRequestException (com.infiniteautomation.mango.rest.latest.exception.BadRequestException)1 FilteredStreamWithTotal (com.infiniteautomation.mango.rest.latest.model.FilteredStreamWithTotal)1 RestModelMapper (com.infiniteautomation.mango.rest.latest.model.RestModelMapper)1 StreamedArrayWithTotal (com.infiniteautomation.mango.rest.latest.model.StreamedArrayWithTotal)1 StreamedSeroJsonVORqlQuery (com.infiniteautomation.mango.rest.latest.model.StreamedSeroJsonVORqlQuery)1 StreamedVORqlQueryWithTotal (com.infiniteautomation.mango.rest.latest.model.StreamedVORqlQueryWithTotal)1 RuntimeStatusModel (com.infiniteautomation.mango.rest.latest.model.datasource.RuntimeStatusModel)1 ApproveUsersModel (com.infiniteautomation.mango.rest.latest.model.user.ApproveUsersModel)1 ApprovedUsersModel (com.infiniteautomation.mango.rest.latest.model.user.ApprovedUsersModel)1 LinkedAccountModel (com.infiniteautomation.mango.rest.latest.model.user.LinkedAccountModel)1 UserActionAndModel (com.infiniteautomation.mango.rest.latest.model.user.UserActionAndModel)1