public O2MSyncDataLoader getPendingDataLoader() { O2MSyncDataLoader loader = null; Document document = syncEventDoc.findOneAndUpdate( Filters.and(Filters.eq(SyncAttrs.STATUS, SyncStatus.PENDING), Filters.eq(SyncAttrs.EVENT_TYPE, String.valueOf(EventType.System))), Updates.set(SyncAttrs.STATUS, SyncStatus.IN_PROGRESS), new FindOneAndUpdateOptions().returnDocument(ReturnDocument.AFTER) .projection(Projections.include(SyncAttrs.SOURCE_DB_NAME, SyncAttrs.SOURCE_USER_NAME))); if (document != null && !document.isEmpty()) { Object interval = document.get(SyncAttrs.INTERVAL); String appName = document.getString(SyncAttrs.APPLICATION_NAME); if(interval!=null && interval instanceof Long){ loader = new O2MSyncDataLoader((Long)interval, appName); }else{ loader = new O2MSyncDataLoader(120000, appName); } loader.setEventId(document.getObjectId(SyncAttrs.ID)); loader.setDbName(document.getString(SyncAttrs.SOURCE_DB_NAME)); loader.setDbUserName(document.getString(SyncAttrs.SOURCE_USER_NAME)); loader.setStatus(document.getString(SyncAttrs.STATUS)); } return loader; }
public SyncEvent retryEvent(ObjectId eventId, boolean retryFailed, boolean retryEntire, boolean dropCollection) { Document updateQuery = new Document(); updateQuery.append("$set", new Document(SyncAttrs.STATUS, SyncStatus.PENDING).append(SyncAttrs.IS_RETRY, true)) .append("$unset", new Document(SyncAttrs.ERRORS, true).append(SyncAttrs.MARKER, true)); if (retryFailed) { syncEvents.updateMany( Filters.and(Filters.eq(SyncAttrs.PARENT_EVENT_ID, eventId), Filters.eq(SyncAttrs.STATUS, SyncStatus.FAILED), Filters.ne(SyncAttrs.ID, eventId)), updateQuery); syncEvents.updateOne(Filters.eq(SyncAttrs.ID, eventId), Updates.set(SyncAttrs.STATUS, SyncStatus.IN_PROGRESS)); } else { if (retryEntire) { syncEvents.updateMany(Filters.eq(SyncAttrs.PARENT_EVENT_ID, eventId), Updates.set(SyncAttrs.STATUS, SyncStatus.CANCELLED)); syncEvents.updateOne(Filters.eq(SyncAttrs.ID, eventId), updateQuery); } } return getEvent(eventId); }
/** * update a person documents in mongo server * <p> * using db {@link Params#TEST_MONGO} and collection {@link Params#PERSON} * </p> * * @param mongoIP the ip of the mongo server * @param mongoPort the port of the mongo server * @param mongoHttpPort the port for the rest api of the mongo server * @param oldName the old name of the person to update * @param newName the new name of the person to update */ public static void update1Person(String mongoIP, int mongoPort, int mongoHttpPort, int oldName, int newName) { MongoClient mongoClient = new MongoClient(mongoIP, mongoPort); MongoDatabase database = mongoClient.getDatabase(Params.TEST_MONGO); MongoCollection<Document> collection = database.getCollection(Params.PERSON); collection.updateOne(Filters.eq(Params.NAME, oldName), Updates .set(Params.NAME, newName)); mongoClient.close(); // verify // http://10.10.10.3:28017/testmongo/person/?filter_name=sadf String base_uri = Params.HTTP + mongoIP; // content type is not that precise from mongo-http interface RestAssured.registerParser(Params.MIME_TYPE_TEXT_PLAIN, Parser.JSON); RestAssured.given().log().path().contentType(ContentType.JSON).baseUri(base_uri).port(mongoHttpPort) .queryParam(Params.FILTER + Params.UNDERLINE + Params.NAME, newName) .get(Params.TEST_MONGO_PERSON_PATH).then().assertThat().statusCode(HttpStatus.SC_OK). //contentType(ContentType.JSON). body("total_rows", Matchers.equalTo(1)); RestAssured.unregisterParser("text/plain"); }
@ExtDirectMethod public UserDetailDto getAuthUser( @AuthenticationPrincipal MongoUserDetails userDetails) { if (userDetails != null) { User user = userDetails.getUser(this.mongoDb); UserDetailDto userDetailDto = new UserDetailDto(userDetails, user, null); if (!userDetails.isPreAuth()) { this.mongoDb.getCollection(User.class).updateOne( Filters.eq(CUser.id, userDetails.getUserDbId()), Updates.set(CUser.lastAccess, new Date())); } return userDetailDto; } return null; }
@ExtDirectMethod(ExtDirectMethodType.FORM_POST) public ExtDirectFormPostResult resetRequest( @RequestParam("email") String emailOrLoginName) { String token = UUID.randomUUID().toString(); User user = this.mongoDb.getCollection(User.class).findOneAndUpdate( Filters.and( Filters.or(Filters.eq(CUser.email, emailOrLoginName), Filters.eq(CUser.loginName, emailOrLoginName)), Filters.eq(CUser.deleted, false)), Updates.combine( Updates.set(CUser.passwordResetTokenValidUntil, Date.from(ZonedDateTime.now(ZoneOffset.UTC).plusHours(4) .toInstant())), Updates.set(CUser.passwordResetToken, token)), new FindOneAndUpdateOptions().returnDocument(ReturnDocument.AFTER) .upsert(false)); if (user != null) { this.mailService.sendPasswortResetEmail(user); } return new ExtDirectFormPostResult(); }
@Test public void testUnkownIgnore() { MongoDatabase db = connect(); UnknownIgnorePojo pojo = new UnknownIgnorePojo(); pojo.setName("ralph"); MongoCollection<UnknownIgnorePojo> coll = db.getCollection(COLL_NAME, UnknownIgnorePojo.class); coll.insertOne(pojo); db.getCollection(COLL_NAME).updateOne(Filters.eq("_id", pojo.getId()), Updates.set("newField", "new")); UnknownIgnorePojo readPojo = coll.find().first(); assertThat(readPojo).isEqualToComparingFieldByField(pojo); Document doc = db.getCollection(COLL_NAME).find().first(); assertThat(doc).hasSize(3); assertThat(doc.get("_id")).isEqualTo(pojo.getId()); assertThat(doc.get("name")).isEqualTo("ralph"); assertThat(doc.get("newField")).isEqualTo("new"); }
public static <TItem> Bson optionalSet(final String fieldName, final TItem value) { if (value == null) { return null; } else { return Updates.set(fieldName, value); } }
public SyncEvent getPendingEvent(List<String> eventTypes) { return syncEvents.findOneAndUpdate( Filters.and(Filters.eq(SyncAttrs.STATUS, SyncStatus.PENDING), Filters.in(SyncAttrs.EVENT_TYPE, eventTypes)), Updates.set(SyncAttrs.STATUS, SyncStatus.IN_PROGRESS), new FindOneAndUpdateOptions().returnDocument(ReturnDocument.AFTER)); }
public SyncNode getFailedNode(long lastPingTime) { SyncNode failedNode = syncNodeMapping.findOneAndUpdate( Filters.and(Filters.lte(SyncAttrs.LAST_PING_TIME, lastPingTime), Filters.eq(SyncAttrs.LIFE_CYCLE, SyncConfig.INSTANCE.getDbProperty(SyncConstants.LIFE))), Updates.set(SyncAttrs.LAST_PING_TIME, System.currentTimeMillis()), new FindOneAndUpdateOptions().upsert(false).returnDocument(ReturnDocument.BEFORE)); if (failedNode != null && failedNode.getFailureTime() == 0) { syncNodeMapping.findOneAndUpdate(Filters.eq(SyncAttrs.ID, failedNode.getId()), Updates.set(SyncAttrs.FAILURE_TIME, failedNode.getLastPingTime())); } return failedNode; }
private void processEventLogFlow() throws InterruptedException { FindIterable<O2MSyncEventLog> it = getCursor(); retryCount = 0; it.forEach(new Block<O2MSyncEventLog>() { @Override public void apply(O2MSyncEventLog eventLog) { try { if (marker.isFailed()) { releaseReources(); return; } logCollection.findOneAndUpdate(Filters.eq(SyncAttrs.ID, eventLog.getLogId()), Updates.set(O2MSyncEventLogCodec.STATUS, O2MSyncEventLogCodec.RUNNING)); logger.info("Processing filter : "+eventLog.getEventFilters()); if (eventLog.getOperation().equals(SyncConstants.DELETE)) { processDeletedDoc(eventLog); }else{ processMongoObject(map.getMapObject(), true, null, map.getMapObject().getCollectionName(), eventLog); } logCollection.findOneAndUpdate(Filters.eq(SyncAttrs.ID, eventLog.getLogId()), Updates.set(O2MSyncEventLogCodec.STATUS, O2MSyncEventLogCodec.COMPLETE)); logger.info("Processed filter : "+eventLog.getEventFilters()); } catch (SyncError e) { logger.error("Error in O2M replication", e); Mailer.sendmail(eventId, null, e, Mailer.FAILURE); } } }); }
@Override public boolean putIfAbsent(String key, V value) { try { Bson query = Filters.eq(DrillMongoConstants.ID, key); Bson update = Updates.set(pKey, bytes(value)); UpdateResult updateResult = collection.updateOne(query, update, new UpdateOptions().upsert(true)); return updateResult.getModifiedCount() == 1; } catch (Exception e) { logger.error(e.getMessage(), e); throw new DrillRuntimeException(e.getMessage(), e); } }
@Test void update() { List<TestMongoEntity> entities = testEntities(); collection.bulkInsert(entities); long updatedCount = collection.update(Filters.eq("string_field", entities.get(0).stringField), Updates.set("enum_field", TestMongoEntity.TestEnum.VALUE2)); assertThat(updatedCount).isEqualTo(1); assertThat(collection.get(entities.get(0).id)).get().satisfies(loadedEntity -> assertThat(loadedEntity.enumField).isEqualTo(TestMongoEntity.TestEnum.VALUE2)); }
@Scheduled(cron = "0 0 5 * * *") public void doCleanup() { // Inactivate users that have a lastAccess timestamp that is older than one year ZonedDateTime oneYearAgo = ZonedDateTime.now(ZoneOffset.UTC).minusYears(1); this.mongoDb.getCollection(User.class).updateMany( Filters.lte(CUser.lastAccess, Date.from(oneYearAgo.toInstant())), Updates.set(CUser.enabled, false)); }
@ExtDirectMethod public String enable2f(@AuthenticationPrincipal MongoUserDetails userDetails) { String randomSecret = TotpAuthUtil.randomSecret(); this.mongoDb.getCollection(User.class).updateOne( Filters.eq(CUser.id, userDetails.getUserDbId()), Updates.set(CUser.secret, randomSecret)); return randomSecret; }
@ExtDirectMethod(STORE_MODIFY) public ValidationMessagesResult<User> update(User updatedEntity, Locale locale) { List<ValidationMessages> violations = validateEntity(updatedEntity, locale); violations.addAll(checkIfLastAdmin(updatedEntity, locale)); if (violations.isEmpty()) { List<Bson> updates = new ArrayList<>(); updates.add(Updates.set(CUser.loginName, updatedEntity.getLoginName())); updates.add(Updates.set(CUser.email, updatedEntity.getEmail())); updates.add(Updates.set(CUser.firstName, updatedEntity.getFirstName())); updates.add(Updates.set(CUser.lastName, updatedEntity.getLastName())); updates.add(Updates.set(CUser.locale, updatedEntity.getLocale())); updates.add(Updates.set(CUser.enabled, updatedEntity.isEnabled())); if (updatedEntity.getAuthorities() != null && !updatedEntity.getAuthorities().isEmpty()) { updates.add( Updates.set(CUser.authorities, updatedEntity.getAuthorities())); } else { updates.add(Updates.unset(CUser.authorities)); } updates.add(Updates.setOnInsert(CUser.deleted, false)); this.mongoDb.getCollection(User.class).updateOne( Filters.eq(CUser.id, updatedEntity.getId()), Updates.combine(updates), new UpdateOptions().upsert(true)); if (!updatedEntity.isEnabled()) { deletePersistentLogins(updatedEntity.getId()); } return new ValidationMessagesResult<>(updatedEntity); } ValidationMessagesResult<User> result = new ValidationMessagesResult<>( updatedEntity); result.setValidations(violations); return result; }
@ExtDirectMethod public void sendPassordResetEmail(String userId) { String token = UUID.randomUUID().toString(); User user = this.mongoDb.getCollection(User.class).findOneAndUpdate( Filters.eq(CUser.id, userId), Updates.combine( Updates.set(CUser.passwordResetTokenValidUntil, Date.from(ZonedDateTime.now(ZoneOffset.UTC).plusHours(4) .toInstant())), Updates.set(CUser.passwordResetToken, token)), new FindOneAndUpdateOptions().returnDocument(ReturnDocument.AFTER)); this.mailService.sendPasswortResetEmail(user); }
@Override public void onApplicationEvent(InteractiveAuthenticationSuccessEvent event) { Object principal = event.getAuthentication().getPrincipal(); if (principal instanceof MongoUserDetails) { String userId = ((MongoUserDetails) principal).getUserDbId(); this.mongoDb.getCollection(User.class).updateOne(Filters.eq(CUser.id, userId), Updates.combine(Updates.unset(CUser.lockedOutUntil), Updates.set(CUser.failedLogins, 0))); } }
@Override public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException { Map<String, Object> result = new HashMap<>(); result.put("success", true); MongoUserDetails userDetails = (MongoUserDetails) authentication.getPrincipal(); if (userDetails != null) { User user; if (!userDetails.isPreAuth()) { user = this.mongoDb.getCollection(User.class).findOneAndUpdate( Filters.eq(CUser.id, userDetails.getUserDbId()), Updates.set(CUser.lastAccess, new Date()), new FindOneAndUpdateOptions() .returnDocument(ReturnDocument.AFTER)); } else { user = this.mongoDb.getCollection(User.class) .find(Filters.eq(CUser.id, userDetails.getUserDbId())).first(); } result.put(SecurityService.AUTH_USER, new UserDetailDto(userDetails, user, CsrfController.getCsrfToken(request))); } response.setCharacterEncoding("UTF-8"); response.getWriter().print(this.objectMapper.writeValueAsString(result)); response.getWriter().flush(); }
@Test public void testUnkownFail() { MongoDatabase db = connect(); UnknownFailPojo pojo = new UnknownFailPojo(); pojo.setName("john"); MongoCollection<UnknownFailPojo> coll = db.getCollection(COLL_NAME, UnknownFailPojo.class); coll.insertOne(pojo); db.getCollection(COLL_NAME).updateOne(Filters.eq("_id", pojo.getId()), Updates.set("anotherNewField", "theNewValue")); try { @SuppressWarnings("unused") UnknownFailPojo readPojo = coll.find().first(); } catch (BSONException e) { assertThat(e.getMessage()).isEqualTo( "ch.rasc.bsoncodec.test.unknown.UnknownFailPojoCodec does not contain a matching property for the field 'anotherNewField'"); } Document doc = db.getCollection(COLL_NAME).find().first(); assertThat(doc).hasSize(3); assertThat(doc.get("_id")).isEqualTo(pojo.getId()); assertThat(doc.get("name")).isEqualTo("john"); assertThat(doc.get("anotherNewField")).isEqualTo("theNewValue"); }
public void updateEventStatus(ObjectId eventId, String status) { syncEvents.updateOne(Filters.eq(SyncAttrs.ID, eventId), Updates.set(SyncAttrs.STATUS, status)); }
public void updateMarker(ObjectId eventId, SyncMarker marker) { syncEvents.findOneAndUpdate(Filters.eq(SyncAttrs.ID, eventId), Updates.set(SyncAttrs.MARKER, marker)); }
public void updateErrors(ObjectId eventId, List<SyncError> errors) { syncEvents.findOneAndUpdate(Filters.eq(SyncAttrs.ID, eventId), Updates.set(SyncAttrs.ERRORS, errors)); }
public void pushError(ObjectId eventId, SyncError error) { syncEvents.findOneAndUpdate(Filters.eq(SyncAttrs.ID, eventId), Updates.push(SyncAttrs.ERRORS, error)); markEventAsFailed(eventId); }
public void updateLastReadTime(ObjectId eventId, BsonTimestamp lastReadTime) { syncEvents.findOneAndUpdate(Filters.eq(SyncAttrs.ID, eventId), Updates.set(SyncAttrs.LAST_READ_TIME, lastReadTime)); }
public SyncEvent cancelEvent(ObjectId eventId) { syncEvents.updateMany( Filters.or(Filters.eq(SyncAttrs.PARENT_EVENT_ID, eventId), Filters.eq(SyncAttrs.ID, eventId)), Updates.set(SyncAttrs.STATUS, SyncStatus.CANCELLED)); return getEvent(eventId); }
public void updateLastReadTime(ObjectId eventId, Date lastReadTime) { syncEvents.findOneAndUpdate(Filters.eq(SyncAttrs.ID, eventId), Updates.set("pollInfo.lastReadTime", lastReadTime)); }
public void setEncryptedPassword(ObjectId id , byte[] pass) { connectionInfo.findOneAndUpdate( Filters.and(Filters.eq(String.valueOf(ConnectionInfoAttributes._id), id)), Updates.set(String.valueOf(ConnectionInfoAttributes.password), pass), new FindOneAndUpdateOptions().returnDocument(ReturnDocument.AFTER)); }
public SyncNode getNodeDetails(SyncNode nodeMapper) { Bson filter = Filters.eq(SyncAttrs.UUID, nodeMapper.getUUID()); logger.info("Getting node with filter " + filter); return syncNodeMapping.findOneAndUpdate(filter, Updates.unset(SyncAttrs.FAILURE_TIME), new FindOneAndUpdateOptions().returnDocument(ReturnDocument.AFTER)); }
public static MongodbUpdates combine(MongodbUpdates... updates) { return new MongodbUpdates( Updates.combine(Arrays.stream(updates) .map(update -> update.getUpdates()) .collect(Collectors.toList()))); }
public static MongodbUpdates combine(List<MongodbUpdates> updatesList) { return new MongodbUpdates(Updates.combine(updatesList.stream() .map(u -> u.getUpdates()) .collect(Collectors.toList()))); }
public static MongodbUpdates popFirst(final String fieldName) { return new MongodbUpdates(Updates.popFirst(fieldName)); }
public static MongodbUpdates popLast(final String fieldName) { return new MongodbUpdates(Updates.popLast(fieldName)); }
private static void createServers(MongoCollection<Document> servers) { for (int server = 1; server < 9; ++server) { for (int env = 1; env < 5; ++env) { final Document serverDoc = Document.parse( "{\"hostname\": \"vltweb" + server + "\"," + "\"fqdn\": \"vltweb" + server + ".test" + env + ".se\"," + "\"environment\": \"test" + env + "\"," + "\"description\": \"Runs all important applications.\n\"" + "\"os\": {" + "\"name\": \"RedHat Enterprise Linux\"," + "\"type\": " + ((server % 2 == 0) ? "\"Linux\"" : "\"Windows\",") + "\"version\": \"6.2\"" + "}," + "\"network\": {" + "\"ipv4Address\": \"10.0.0.1\"," + "\"attributes\": {" + "\"test\": 1" + "}" + "}}") .append("deployments", Lists.newArrayList( new Document().append("applicationId", "webapp3-service").append("version", "1.0.0"), new Document().append("applicationId", "webapp1-service").append("version", "0.0.1-patch2") )).append("attributes", new Document() .append("Param1", "Value1") .append("Param2", new Document() .append("Param3", "Value3") ).append("env-id", env) .append("server-id", server) ).append("meta", defaultMeta()); final int version = server % 3 + 1; if (server % 2 == 0 && env % 2 != 0) { serverDoc.append("deployments", Lists.newArrayList( new Document().append("applicationId", "webapp3-service").append("version", version + ".0.0"), new Document().append("applicationId", "webapp1-service").append("version", "0.0.1-patch" + version) )); } else if (env % 2 == 0) { serverDoc.append("deployments", Lists.newArrayList( new Document().append("applicationId", "webapp2-web").append("version", version + ".0.0"), new Document().append("applicationId", "webapp1-web").append("version", "0.0.1-patch" + version) )); } servers.insertOne(serverDoc); } } final Document qaServer = createServer("qa"); qaServer.append("deployments", Lists.newArrayList( new Document().append("applicationId", "webapp1-web").append("version", "1.0.0"), new Document().append("applicationId", "webapp1-service").append("version", "2.0.0") )); servers.insertOne(qaServer); final Document stageServer = createServer("stage"); stageServer.append("deployments", Lists.newArrayList( new Document().append("applicationId", "webapp1-web").append("version", "1.0.0"), new Document().append("applicationId", "webapp1-service").append("version", "2.0.0") )); servers.insertOne(stageServer); final Document prodServer = createServer("prod"); prodServer.append("deployments", Lists.newArrayList( new Document().append("applicationId", "webapp1-web").append("version", "1.0.0"), new Document().append("applicationId", "webapp1-service").append("version", "2.0.0") )); servers.insertOne(prodServer); final Document internalprodServer = createServer("internalprod"); internalprodServer.append("deployments", Lists.newArrayList( new Document().append("applicationId", "webapp1-web").append("version", "1.0.0"), new Document().append("applicationId", "webapp1-service").append("version", "2.0.0") )); servers.insertOne(internalprodServer); servers.updateOne(Filters.eq("fqdn", "vltweb1.test1.se"), Updates.set("description", "This server runs Webapp1.")); servers.updateOne(Filters.eq("fqdn", "vltweb2.test1.se"), Updates.set("description", "This server runs Webapp1 and Webapp2")); servers.updateOne(Filters.eq("fqdn", "vltweb1.test2.se"), Updates.set("description", "This server runs Webapp3 and Webapp4")); servers.updateOne(Filters.eq("fqdn", "vltweb2.test2.se"), Updates.set("description", "This server runs Webapp3 and Webapp4")); }
@ExtDirectMethod public void disable2f(@AuthenticationPrincipal MongoUserDetails userDetails) { this.mongoDb.getCollection(User.class).updateOne( Filters.eq(CUser.id, userDetails.getUserDbId()), Updates.unset(CUser.secret)); }
@ExtDirectMethod public void unlock(String userId) { this.mongoDb.getCollection(User.class).updateOne(Filters.eq(CUser.id, userId), Updates.combine(Updates.unset(CUser.lockedOutUntil), Updates.set(CUser.failedLogins, 0))); }
@ExtDirectMethod public void disableTwoFactorAuth(String userId) { this.mongoDb.getCollection(User.class).updateOne(Filters.eq(CUser.id, userId), Updates.unset(CUser.secret)); }
@ExtDirectMethod(ExtDirectMethodType.FORM_POST) @PreAuthorize("hasAuthority('PRE_AUTH')") public ExtDirectFormPostResult signin2fa(HttpServletRequest request, @AuthenticationPrincipal MongoUserDetails userDetails, @RequestParam("code") int code) { User user = userDetails.getUser(this.mongoDb); if (user != null) { if (TotpAuthUtil.verifyCode(user.getSecret(), code, 3)) { this.mongoDb.getCollection(User.class).updateOne( Filters.eq(CUser.id, userDetails.getUserDbId()), Updates.set(CUser.lastAccess, new Date())); userDetails.grantAuthorities(); Authentication newAuth = new UsernamePasswordAuthenticationToken( userDetails, null, userDetails.getAuthorities()); SecurityContextHolder.getContext().setAuthentication(newAuth); ExtDirectFormPostResult result = new ExtDirectFormPostResult(); result.addResultProperty(AUTH_USER, new UserDetailDto(userDetails, user, CsrfController.getCsrfToken(request))); return result; } BadCredentialsException excp = new BadCredentialsException( "Bad verification code"); AuthenticationFailureBadCredentialsEvent event = new AuthenticationFailureBadCredentialsEvent( SecurityContextHolder.getContext().getAuthentication(), excp); this.applicationEventPublisher.publishEvent(event); user = userDetails.getUser(this.mongoDb); if (user.getLockedOutUntil() != null) { HttpSession session = request.getSession(false); if (session != null) { Application.logger.debug("Invalidating session: " + session.getId()); session.invalidate(); } SecurityContext context = SecurityContextHolder.getContext(); context.setAuthentication(null); SecurityContextHolder.clearContext(); } } return new ExtDirectFormPostResult(false); }
private void updateLockedProperties(AuthenticationFailureBadCredentialsEvent event) { Object principal = event.getAuthentication().getPrincipal(); if (this.loginLockAttempts != null && (principal instanceof String || principal instanceof MongoUserDetails)) { User user = null; if (principal instanceof String) { user = this.mongoDb.getCollection(User.class).findOneAndUpdate( Filters.and(Filters.eq(CUser.loginName, principal), Filters.eq(CUser.deleted, false)), Updates.inc(CUser.failedLogins, 1), new FindOneAndUpdateOptions() .returnDocument(ReturnDocument.AFTER).upsert(false)); } else { user = this.mongoDb.getCollection(User.class).findOneAndUpdate( Filters.eq(CUser.id, ((MongoUserDetails) principal).getUserDbId()), Updates.inc(CUser.failedLogins, 1), new FindOneAndUpdateOptions() .returnDocument(ReturnDocument.AFTER).upsert(false)); } if (user != null) { if (user.getFailedLogins() >= this.loginLockAttempts) { if (this.loginLockMinutes != null) { this.mongoDb.getCollection(User.class).updateOne( Filters.eq(CUser.id, user.getId()), Updates.set(CUser.lockedOutUntil, Date.from(ZonedDateTime.now(ZoneOffset.UTC) .plusMinutes(this.loginLockMinutes) .toInstant()))); } else { this.mongoDb.getCollection(User.class) .updateOne(Filters.eq(CUser.id, user.getId()), Updates.set(CUser.lockedOutUntil, Date.from(ZonedDateTime .now(ZoneOffset.UTC) .plusYears(1000).toInstant()))); } } } else { Application.logger.warn("Unknown user login attempt: {}", principal); } } else { Application.logger.warn("Invalid login attempt: {}", principal); } }
/** * 设置字段值 * @param fieldName 字段名 * @param value 值 * @param <T> 数据类型 * @return */ public static <T> MongodbUpdates set(final String fieldName, T value) { return new MongodbUpdates(Updates.set(fieldName, value)); }
/** * 去掉指定字段 * @param fieldName 字段名 * @return */ public static MongodbUpdates unset(final String fieldName) { return new MongodbUpdates(Updates.unset(fieldName)); }