com.orientechnologies.orient.core.metadata.security.OSecurityUser Java Examples

The following examples show how to use com.orientechnologies.orient.core.metadata.security.OSecurityUser. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: UserManager.java    From guice-persist-orient with MIT License 6 votes vote down vote up
/**
 * Changes current connection user. Affects only current transaction and can't be used outside of transaction
 * ({@link ODatabaseDocumentInternal#setUser(com.orientechnologies.orient.core.metadata.security.OSecurityUser)}).
 * <p>
 * Recursive user changes are not allowed, so attempt to change user under already changed user will
 * lead to error. The only exception is change to the same user (in this case change is ignored).
 * <p>
 * Action approach is important to explicitly define scope of specific user and
 * properly cleanup state (which may be not done in case of direct override).
 * <p>
 * Propagates runtime exceptions (orient exceptions).
 *
 * @param user       specific user
 * @param userAction logic to execute with specific user
 * @param <T>        type of returned result (may be Void)
 * @return action result (may be null)
 */
public <T> T executeWithTxUser(final OSecurityUser user, final SpecificUserAction<T> userAction) {
    final boolean userChanged = checkSpecificUserConditions(user.getName());
    final ODatabaseDocumentInternal db = (ODatabaseDocumentInternal) connectionProvider.get();
    final OSecurityUser original = db.getUser();
    if (userChanged) {
        // no need to track user change if user not changed
        specificTxUser.set(user);
        db.setUser(user);
    }
    T result = null;
    try {
        result = userAction.execute();
    } catch (Throwable th) {
        Throwables.throwIfUnchecked(th);
        throw new UserActionException(String.format("Failed to perform tx action with user '%s'",
                user.getName()), th);
    } finally {
        if (userChanged) {
            db.setUser(original);
            specificTxUser.remove();
        }
    }
    return result;
}
 
Example #2
Source File: DefaultRegistrationPanel.java    From Orienteer with Apache License 2.0 6 votes vote down vote up
/**
 * Create register button, which set user password and then calls {@link DefaultRegistrationPanel#onRegister(AjaxRequestTarget, IModel)}
 * @param id component id
 * @return register button
 */
private AjaxFormCommand<Void> createRegisterButton(String id) {
    return new AjaxFormCommand<Void>(id, "panel.registration.button.register") {
        @Override
        protected void onInstantiation() {
            super.onInstantiation();
            setBootstrapType(BootstrapType.PRIMARY);
        }

        @Override
        public void onSubmit(AjaxRequestTarget target) {
            super.onSubmit(target);
            OrienteerUser user = DefaultRegistrationPanel.this.getModelObject();
            user.setName(user.getEmail());
            user.setPassword(passwordModel.getObject());
            user.setAccountStatus(OSecurityUser.STATUSES.SUSPENDED);
            onRegister(target, DefaultRegistrationPanel.this.getModel());
        }
    };
}
 
Example #3
Source File: PerspectivesModule.java    From Orienteer with Apache License 2.0 6 votes vote down vote up
public ODocument getDefaultPerspective(ODatabaseDocument db, OSecurityUser user) {
	if (user != null) {
		if (user.getDocument().field(PROP_PERSPECTIVE) != null) {
			return ((OIdentifiable) user.getDocument().field(PROP_PERSPECTIVE)).getRecord();
		}

		Set<? extends OSecurityRole> roles = user.getRoles();
		for (OSecurityRole oRole : roles) {
			ODocument perspective = getPerspectiveForORole(oRole);
			if (perspective != null) {
				return perspective;
			}
		}
	}
	return getPerspectiveByAliasAsDocument(db, ALIAS_PERSPECTIVE_DEFAULT)
				// Restore default perspective if it was not found
			.orElseGet(() -> DBClosure.sudo((adminDb)->createDefaultPerspective(OSchemaHelper.bind(adminDb))));
}
 
Example #4
Source File: GoogleUserManager.java    From Orienteer with Apache License 2.0 6 votes vote down vote up
@Override
public OrienteerUser createUser(ODatabaseDocument db, JsonNode node) {
    String email = node.get(FIELD_EMAIL).textValue();

    OrienteerUser user = new OrienteerUser();
    user.setFirstName(node.get(FIELD_GIVEN_NAME).textValue())
            .setLastName(node.get(FIELD_FAMILY_NAME).textValue())
            .setEmail(email);
    user.setName(email);
    user.setPassword(UUID.randomUUID().toString());
    user.setAccountStatus(OSecurityUser.STATUSES.ACTIVE);
    user.save();

    OUsersCommonUtils.createOUserSocialNetworkIfNotExists(db, OAuth2Provider.GOOGLE, getGoogleId(node), user);

    return user;
}
 
Example #5
Source File: RegistrationResource.java    From Orienteer with Apache License 2.0 5 votes vote down vote up
@Override
protected ResourceResponse newResourceResponse(Attributes attrs) {
    ResourceResponse response = new ResourceResponse();
    if (response.dataNeedsToBeWritten(attrs)) {
        if (OrienteerUserModuleRepository.isRegistrationActive()) {
            PageParameters params = attrs.getParameters();
            String id = params.get(PARAMETER_ID).toOptionalString();

            if (!Strings.isNullOrEmpty(id)) {
                DBClosure.sudoConsumer(db -> {
                    OrienteerUserRepository.getUserById(id)
                            .filter(user -> user.getAccountStatus() != OSecurityUser.STATUSES.ACTIVE)
                            .ifPresent(user -> {
                                user.setAccountStatus(OSecurityUser.STATUSES.ACTIVE);
                                user.save();
                                response.setWriteCallback(createCallback(true));
                            });
                });
            }
        }

        if (response.getWriteCallback() == null) {
            response.setWriteCallback(createCallback(false));
        }
    }

    return response;
}
 
Example #6
Source File: OrienteerBasePage.java    From Orienteer with Apache License 2.0 5 votes vote down vote up
private Form<String> createSearchForm(String id, IModel<String> queryModel) {
	return new Form<String>(id, queryModel) {
		@Override
		protected void onInitialize() {
			super.onInitialize();
			add(new TextField<>("query", queryModel, String.class));
			add(new AjaxButton("search") {});
		}

		@Override
		protected void onConfigure() {
			super.onConfigure();
               OSecurityUser user = OrienteerWebSession.get().getUser();
               if (user != null) {
				OSecurityRole allowedRole = user.checkIfAllowed(OSecurityHelper.FEATURE_RESOURCE, SearchPage.SEARCH_FEATURE,
						OrientPermission.READ.getPermissionFlag());
                   setVisible(allowedRole != null);
               } else {
                   setVisible(false);
               }
           }

		@Override
		protected void onSubmit() {
			setResponsePage(new SearchPage(queryModel));
		}
	};
}
 
Example #7
Source File: RestorePasswordTest.java    From Orienteer with Apache License 2.0 5 votes vote down vote up
@Before
public void init() {
    DBClosure.sudoConsumer(db -> {
        user = new OrienteerUser(OUser.CLASS_NAME);
        user.setName(UUID.randomUUID().toString())
                .setPassword(UUID.randomUUID().toString())
                .setAccountStatus(OSecurityUser.STATUSES.ACTIVE);
        user.setEmail(UUID.randomUUID().toString() + "@gmail.com");
        user.save();

        OProperty property = user.getDocument().getSchemaClass().getProperty(OrienteerUser.PROP_RESTORE_ID);
        OrienteerUsersModule.REMOVE_CRON_RULE.setValue(property, "0/7 0/1 * 1/1 * ? *");
        OrienteerUsersModule.REMOVE_SCHEDULE_START_TIMEOUT.setValue(property, "3000");
    });
}
 
Example #8
Source File: RegistrationComponentTest.java    From Orienteer with Apache License 2.0 5 votes vote down vote up
@Before
public void init() {
    testUser = usersService.createUser();
    testUser.setFirstName("FirstName")
            .setLastName("LastName")
            .setEmail(UUID.randomUUID() + "@gmail.com");

    testUser.setName(testUser.getEmail())
            .setPassword("1234567890")
            .setAccountStatus(OSecurityUser.STATUSES.SUSPENDED);
}
 
Example #9
Source File: RestorePasswordComponentTest.java    From Orienteer with Apache License 2.0 5 votes vote down vote up
@Before
public void init() {
    testUser = usersService.createUser();
    testUser.setFirstName("FirstName")
            .setLastName("LastName")
            .setEmail(UUID.randomUUID() + "@gmail.com");

    testUser.setName(testUser.getEmail())
            .setPassword(UUID.randomUUID().toString())
            .setAccountStatus(OSecurityUser.STATUSES.ACTIVE);

    DBClosure.sudoSave(testUser);

    usersService.restoreUserPassword(testUser);
}
 
Example #10
Source File: FacebookUserManager.java    From Orienteer with Apache License 2.0 5 votes vote down vote up
@Override
public OrienteerUser createUser(ODatabaseDocument db, JsonNode node) {
    OrienteerUser user = new OrienteerUser();
    user.setFirstName(node.get(FIELD_FIRST_NAME).textValue())
            .setLastName(node.get(FIELD_LAST_NAME).textValue())
            .setEmail(node.get(FIELD_EMAIL) != null ? node.get(FIELD_EMAIL).textValue() : null);
    user.setName(createUsername(node.get(FIELD_SHORT_NAME).textValue(), node.get(FIELD_ID).textValue()));
    user.setPassword(UUID.randomUUID().toString());
    user.setAccountStatus(OSecurityUser.STATUSES.ACTIVE);
    user.save();

    OUsersCommonUtils.createOUserSocialNetworkIfNotExists(db, OAuth2Provider.FACEBOOK, getFacebookId(node), user);

    return user;
}
 
Example #11
Source File: GitHubUserManager.java    From Orienteer with Apache License 2.0 5 votes vote down vote up
@Override
public OrienteerUser createUser(ODatabaseDocument db, JsonNode node) {
    String name = node.get(FIELD_NAME).textValue();
    String firstName;
    String lastName;

    if (!Strings.isNullOrEmpty(name) && name.contains(" ")) {
        String[] firstAndLastName = name.split(" ");
        firstName = firstAndLastName[0];
        lastName = firstAndLastName[1];
    } else {
        firstName = name;
        lastName = null;
    }

    String login = node.get(FIELD_LOGIN).textValue();

    OrienteerUser user = new OrienteerUser();

    user.setName(login);
    user.setPassword(UUID.randomUUID().toString());

    user.setEmail(node.get(FIELD_EMAIL).textValue())
            .setFirstName(firstName)
            .setLastName(lastName)
            .setAccountStatus(OSecurityUser.STATUSES.ACTIVE);
    user.save();

    OUsersCommonUtils.createOUserSocialNetworkIfNotExists(db, OAuth2Provider.GITHUB, getGitHubId(node), user);

    return user;
}
 
Example #12
Source File: UserManager.java    From guice-persist-orient with MIT License 5 votes vote down vote up
private boolean checkSpecificUserConditions(final String login) {
    Preconditions.checkState(transactionManager.isTransactionActive(),
            "Tx user can't be changed outside of transaction");
    final ODatabaseDocument db = connectionProvider.get();
    final OSecurityUser original = db.getUser();
    final boolean userChanged = !original.getName().equals(login);
    Preconditions.checkState(specificTxUser.get() == null || !userChanged,
            "Specific user already defined for transaction as '%s'",
            specificTxUser.get() == null ? null : specificTxUser.get().getName());
    return userChanged;
}
 
Example #13
Source File: TestRestApi.java    From wicket-orientdb with Apache License 2.0 5 votes vote down vote up
@Test
public void testQueryCoding() throws Exception
{
	OSecurityUser currentUser = wicket.getTester().getDatabase().getUser();
	ODocument userDoc = currentUser.getDocument();
	String rid = userDoc.getIdentity().toString();
	String sql = "select * from OUser where @rid = "+rid;
	String url = "orientdb/query/db/sql/"+URLEncoder.encode(sql, "UTF8");
	String ret = wicket.getTester().executeUrl(url, "GET", null);
	assertTrue(ret.contains(userDoc.getIdentity().toString()));
	assertTrue(ret.contains((String)userDoc.field("name")));
	assertTrue(ret.contains((String)userDoc.field("password")));
}
 
Example #14
Source File: TransactionRequestCycleListener.java    From wicket-orientdb with Apache License 2.0 5 votes vote down vote up
@Override
public void start(RequestCycle cycle) {
	OrientDbWebSession session = OrientDbWebSession.get();
	ODatabaseDocumentInternal db = session.getDatabase();
	//It's required to have ability to check security rights locally
	OSecurityUser oUser = session.getUser();
	OSecurityUser dbUser = db.getUser();
	if(oUser!=null && oUser.getDocument()!=null 
			&& oUser.getDocument().getIdentity()!=null 
			&& (!oUser.getDocument().getIdentity().isValid() || dbUser==null || !Objects.equal(dbUser.getName(), oUser.getName())))
	{
		db.setUser(db.getMetadata().getSecurity().getUser(oUser.getName()));
	}
	db.begin();
}
 
Example #15
Source File: OrientDbWebApplication.java    From wicket-orientdb with Apache License 2.0 5 votes vote down vote up
@Override
public boolean checkResource(ResourceGeneric resource, String specific, int iOperation) {
	OSecurityUser user = OrientDbWebSession.get().getEffectiveUser();
	if(Strings.isEmpty(specific)) specific = null;
	if(user.checkIfAllowed(resource, specific, iOperation)!=null) return true;
	while(!Strings.isEmpty(specific=Strings.beforeLastPathComponent(specific, '.')))
	{
		if(user.checkIfAllowed(resource, specific+"."+ODatabaseSecurityResources.ALL, iOperation)!=null) return true;
	}
	return false;
}
 
Example #16
Source File: UserOnlineModule.java    From Orienteer with Apache License 2.0 4 votes vote down vote up
public void updateSessionUser(final OSecurityUser user, final String sessionId) {
	updateUserFieldAndGetUser(user, PROP_LAST_SESSION_FIELD, sessionId);
}
 
Example #17
Source File: UserOnlineModule.java    From Orienteer with Apache License 2.0 4 votes vote down vote up
public ODocument updateOnlineUser(final OSecurityUser user, final boolean online) {
    return updateUserFieldAndGetUser(user, PROP_ONLINE, online);
}
 
Example #18
Source File: OrienteerBasePage.java    From Orienteer with Apache License 2.0 4 votes vote down vote up
private Label createUsernameLabel(String id) {
	OSecurityUser user = OrienteerWebSession.get().getUser();

	return new Label(id, Model.of(user != null ? user.getName() : null));
}
 
Example #19
Source File: RestorePasswordResource.java    From Orienteer with Apache License 2.0 4 votes vote down vote up
public static String getLinkForUser(OSecurityUser user) {
    return getLinkForUser(user.getDocument());
}
 
Example #20
Source File: OrientDbWebSession.java    From wicket-orientdb with Apache License 2.0 4 votes vote down vote up
/**
 * @return currently signed in {@link OUser}. Returns null in case of no user was signed in.
 */
public OSecurityUser getUser()
{
	ODocument userDoc = getUserAsODocument();
	return userDoc!=null?new OUser(userDoc):null;
}
 
Example #21
Source File: OrientDbWebSession.java    From wicket-orientdb with Apache License 2.0 4 votes vote down vote up
public OSecurityUser getEffectiveUser()
{
	OSecurityUser ret = getUser();
	return ret!=null?ret:getDatabase().getUser();
}