Gets or create user.

@param principal the principal
@return the or create user
169583
@SneakyThrows
    public User getOrCreateUser(final Principal principal) {
        val attributes = principal.getAttributes();
        if (!attributes.containsKey(this.mailAttribute)) {
            throw new IllegalArgumentException("No email address found for " + principal.getId());
        }
        if (!attributes.containsKey(this.phoneAttribute)) {
            throw new IllegalArgumentException("No phone number found for " + principal.getId());
        }

        val email = attributes.get(this.mailAttribute).get(0).toString();
        val phone = attributes.get(this.phoneAttribute).get(0).toString();
        return this.authyUsers.createUser(email, phone, this.countryCode);
    }
211061
public User getUser(String name){
        ProtocolHeader header = new ProtocolHeader();
        header.setType(ProtocolType.GetUser);

        GetUserProtocol p = new GetUserProtocol(name);

        Response resp = connection.submitRequest(header, p, null);
        return ((GetUserResponse) resp).getUser();
    }
777844
private static PrincipalUser createDefaultUser() {
        PrincipalUser result = new PrincipalUser("default", "default@default.com");

        result.id = BigInteger.valueOf(2);
        result.setPrivileged(false);
        return result;
    }
308408
@Programmatic
    public ApplicationUser findOrCreateUserByUsername(
            final String username) {
        // slightly unusual to cache a function that modifies state, but safe because this is idempotent
        return queryResultsCache.execute(new Callable<ApplicationUser>() {
            @Override
            public ApplicationUser call() throws Exception {
                final ApplicationUser applicationUser = findByUsername(username);
                if (applicationUser != null) {
                    return applicationUser;
                }
                return newDelegateUser(username, null, null);
            }
        }, ApplicationUserRepository.class, "findOrCreateUserByUsername", username);
    }
1345432
public User getUser(String name, String password) {

        if (name == null) {
            name = "";
        }

        if (password == null) {
            password = "";
        }

        User user = get(name);

        user.checkPassword(password);

        return user;
    }
861764
public Optional<User> getOptionalUser(int userId) {
        try {
            return (Optional.ofNullable(getUser(userId)));
        } catch (GitLabApiException glae) {
            return (GitLabApi.createOptionalFromException(glae));
        }
    }
124742
private Principal createPrincipal(String schema, JsonNode principalNode) {
        if (schema.equalsIgnoreCase(PRINCIPAL_SCHEMA_USER)) {
            return new Principal(PRINCIPAL_SCHEMA_USER, principalNode.asText(), options.isStripAwsPrincipalIdHyphensEnabled());
        } else if (schema.equalsIgnoreCase(PRINCIPAL_SCHEMA_SERVICE)) {
            return new Principal(schema, principalNode.asText());
        } else if (schema.equalsIgnoreCase(PRINCIPAL_SCHEMA_FEDERATED)) {
            if (WebIdentityProviders.fromString(principalNode.asText()) != null) {
                return new Principal(WebIdentityProviders.fromString(principalNode.asText()));
            } else {
                return new Principal(PRINCIPAL_SCHEMA_FEDERATED, principalNode.asText());
            }
        }
        throw new SdkClientException("Schema " + schema + " is not a valid value for the principal.");
    }
1357247
public static String getType(I_CmsPrincipal principal) {

        if (principal == null) {
            return null;
        }
        if (principal.isGroup()) {
            return I_CmsPrincipal.PRINCIPAL_GROUP;
        } else {
            return I_CmsPrincipal.PRINCIPAL_USER;
        }
    }
958769
@Override
    public IAuthorizationPrincipal getPrincipal(IPermission permission)
            throws AuthorizationException {
        String principalString = permission.getPrincipal();
        int idx = principalString.indexOf(PRINCIPAL_SEPARATOR);
        Integer typeId = Integer.valueOf(principalString.substring(0, idx));
        Class type = EntityTypesLocator.getEntityTypes().getEntityTypeFromID(typeId);
        String key = principalString.substring(idx + 1);
        return newPrincipal(key, type);
    }
1326576
@Override
    public Node getPrincipal() {
        if (principal == null) {
            principal = new LdapUser();
            LdapUser p = (LdapUser) principal;
            p.setDn(Configuration.getProperty(instanceName + ".principal").trim());
            p.setUid(getUidForDN(p.getDn()));
        }
        return principal;
    }
899721
protected String getOrigin(Principal principal) {

        if (principal instanceof Authentication) {

            Authentication caller = (Authentication) principal;
            StringBuilder builder = new StringBuilder();
            if (caller instanceof OAuth2Authentication) {
                OAuth2Authentication oAuth2Authentication = (OAuth2Authentication) caller;
                builder.append("client=").append(oAuth2Authentication.getOAuth2Request().getClientId());
                if (!oAuth2Authentication.isClientOnly()) {
                    builder.append(", ").append("user=").append(oAuth2Authentication.getName());
                }
            }
            else {
                builder.append("caller=").append(caller.getName());
            }


            if (caller.getDetails() != null) {
                builder.append(", details=(");
                try {
                    @SuppressWarnings("unchecked")
                    Map<String, Object> map =
                        JsonUtils.readValue((String)caller.getDetails(), new TypeReference<Map<String,Object>>(){});
                    if (map.containsKey("remoteAddress")) {
                        builder.append("remoteAddress=").append(map.get("remoteAddress")).append(", ");
                    }
                    builder.append("type=").append(caller.getDetails().getClass().getSimpleName());
                } catch (Exception e) {
                    // ignore
                    builder.append(caller.getDetails());
                }
                appendTokenDetails(caller, builder);
                builder.append(")");
            }
            return builder.toString();

        }

        return principal == null ? null : principal.getName();

    }
1346371
public User getUser(String userName) {
        User result = null;
        for (User item : getUsersList()) {
            if (item.getName().equals(userName)) {
                result = item;
            }
        }
        return result;
    }
1292641
protected List<Principal> createRolePrincipals(UnixUser username) {
        ArrayList<Principal> principals = new ArrayList<Principal>();
        if (null != supplementalRoles) {
            for (String supplementalRole : supplementalRoles) {
                Principal rolePrincipal = createRolePrincipal(supplementalRole);
                if (null != rolePrincipal) {
                    principals.add(rolePrincipal);
                }
            }
        }
        if (useUnixGroups) {
            for (String s : username.getGroups()) {
                Principal rolePrincipal = createRolePrincipal(s);
                if (null != rolePrincipal) {
                    principals.add(rolePrincipal);
                }
            }
        }
        return principals;
    }
492989
@GET
    @Produces(MediaType.APPLICATION_JSON)
    @Path("/userinfo")
    @Description("Returns the user info of the user who is logged in.")
    public PrincipalUserDto userInfo(@Context HttpServletRequest req) {
        String userName=findUserByToken(req);
        PrincipalUser user = _uService.findUserByUsername(userName);
        return PrincipalUserDto.transformToDto(user);
    }
801377
public static Principal getPrincipalForPassword(final PropertyKey<String> key, final String value, final String password) throws AuthenticationException, TooManyFailedLoginAttemptsException, PasswordChangeRequiredException {

		Principal principal  = null;

		final String superuserName = Settings.SuperUserName.getValue();
		final String superUserPwd  = Settings.SuperUserPassword.getValue();

		if (StringUtils.isEmpty(value)) {

			logger.info("Empty value for key {}", key.dbName());
			throw new AuthenticationException(STANDARD_ERROR_MSG);
		}

		if (StringUtils.isEmpty(password)) {

			logger.info("Empty password");
			throw new AuthenticationException(STANDARD_ERROR_MSG);
		}

		if (superuserName.equals(value) && superUserPwd.equals(password)) {

			// logger.info("############# Authenticated as superadmin! ############");

			principal = new SuperUser();

		} else {

			try {

				principal = StructrApp.getInstance().nodeQuery(Principal.class).and().or(key, value).or(AbstractNode.name, value).disableSorting().getFirst();

			} catch (FrameworkException fex) {

				logger.warn("", fex);
			}

			if (principal == null) {

				logger.info("No principal found for {} {}", key.dbName(), value);

				throw new AuthenticationException(STANDARD_ERROR_MSG);

			} else {

				if (principal.isBlocked()) {

					logger.info("Principal {} is blocked", principal);

					throw new AuthenticationException(STANDARD_ERROR_MSG);
				}

				// let Principal decide how to check password
				final boolean passwordValid = principal.isValidPassword(password);

				if (!passwordValid) {

					AuthHelper.incrementFailedLoginAttemptsCounter(principal);
				}

				AuthHelper.checkTooManyFailedLoginAttempts(principal);

				if (!passwordValid) {

					throw new AuthenticationException(STANDARD_ERROR_MSG);

				} else {

					AuthHelper.handleForcePasswordChange(principal);
					AuthHelper.resetFailedLoginAttemptsCounter(principal);

					// allow external users (LDAP etc.) to update group membership
					principal.onAuthenticate();
				}
			}
		}

		return principal;
	}
1318761
public I_CmsPrincipal lookupPrincipal(CmsDbContext dbc, String principalName) {

        try {
            CmsGroup group = getUserDriver(dbc).readGroup(dbc, principalName);
            if (group != null) {
                return group;
            }
        } catch (Exception e) {
            // ignore this exception
        }

        try {
            CmsUser user = readUser(dbc, principalName);
            if (user != null) {
                return user;
            }
        } catch (Exception e) {
            // ignore this exception
        }

        return null;
    }
579495
def get_principals(
        self, role, anonymous=True, users=True, groups=True, object=None, as_list=True
    ):
        """"""
        if not isinstance(role, Role):
            role = Role(role)
        assert role
        assert users or groups
        query = RoleAssignment.query.filter_by(role=role)

        if not anonymous:
            query = query.filter(RoleAssignment.anonymous == False)
        if not users:
            query = query.filter(RoleAssignment.user == None)
        elif not groups:
            query = query.filter(RoleAssignment.group == None)

        query = query.filter(RoleAssignment.object == object)
        principals = {(ra.user or ra.group) for ra in query.all()}

        if object is not None and role in (Creator, Owner):
            p = object.creator if role == Creator else object.owner
            if p:
                principals.add(p)

        if not as_list:
            return principals

        return list(principals)