@GetMapping public String init(Model model) { model.addAttribute("username", userAccountService.getCurrentUser().getUsername()); return "view-jobs"; }
@GetMapping(TEMP_USER_END_POINT) @ApiOperation(value = "Get all users", response = Collection.class) @ResponseBody @PreAuthorize("hasAnyRole('SU', 'MANAGER')") public Collection<UserResponse> getUsers() { return userService .getUsers() .stream() .filter(u -> !u.getUsername().equals("anonymous")) .map(UserResponse::fromEntity) .collect(Collectors.toList()); }
/** Loads the questionnaire view */ @GetMapping("/**") public String initView(Model model) { super.init(model, ID); model.addAttribute("username", super.userAccountService.getCurrentUser().getUsername()); return QUESTIONNAIRE_VIEW; }
@Override @PreAuthorize("hasAnyRole('ROLE_SU', 'ROLE_USER')") @Transactional public void updateCurrentUser(User updatedCurrentUser) { String currentUsername = SecurityUtils.getCurrentUsername(); if (!currentUsername.equals(updatedCurrentUser.getUsername())) { throw new RuntimeException("Updated user differs from the current user"); } User currentUser = userService.getUser(currentUsername); if (currentUser == null) { throw new RuntimeException("User does not exist [" + currentUsername + "]"); } userService.update(updatedCurrentUser); }
static UserResponse fromEntity(User user) { return new AutoValue_UserResponse(user.getId(), user.getUsername()); } }
@RunAsSystem public Collection<? extends GrantedAuthority> getAuthorities(User user) { Set<GrantedAuthority> authorities = new LinkedHashSet<>(); if (user.isSuperuser() != null && user.isSuperuser()) { authorities.add(new SimpleGrantedAuthority(SecurityUtils.AUTHORITY_SU)); } if (user.getUsername().equals(SecurityUtils.ANONYMOUS_USERNAME)) { authorities.add(new SimpleGrantedAuthority(SecurityUtils.AUTHORITY_ANONYMOUS)); } else { authorities.add(new SimpleGrantedAuthority(AUTHORITY_USER)); } dataService .query(ROLE_MEMBERSHIP, RoleMembership.class) .eq(USER, user) .findAll() .filter(RoleMembership::isCurrent) .map(RoleMembership::getRole) .map(Role::getName) .map(SidUtils::createRoleAuthority) .map(SimpleGrantedAuthority::new) .forEach(authorities::add); return grantedAuthoritiesMapper.mapAuthorities(authorities); } }
/** * Find a user by a security token * * @param token security token * @return the user or null if not found or token is expired */ @Override @Transactional(readOnly = true) @RunAsSystem public UserDetails findUserByToken(String token) { Token molgenisToken = getMolgenisToken(token); return userDetailsService.loadUserByUsername(molgenisToken.getUser().getUsername()); }
@PostMapping("/threshold/{sortaJobExecutionId}") public String updateThreshold( @RequestParam(value = "threshold") String threshold, @PathVariable String sortaJobExecutionId, Model model) { if (!StringUtils.isEmpty(threshold)) { SortaJobExecution sortaJobExecution = findSortaJobExecution(sortaJobExecutionId); try { User currentUser = userAccountService.getCurrentUser(); if (currentUser.isSuperuser() || Objects.equal(sortaJobExecution.getUser().get(), currentUser.getUsername())) { RunAsSystemAspect.runAsSystem( () -> { Double thresholdValue = Double.parseDouble(threshold); sortaJobExecution.setThreshold(thresholdValue); dataService.update(SORTA_JOB_EXECUTION, sortaJobExecution); }); } } catch (NumberFormatException e) { model.addAttribute(MODEL_KEY_MESSAGE, threshold + " is illegal threshold value!"); } catch (Exception other) { model.addAttribute(MODEL_KEY_MESSAGE, "Error updating threshold: " + other.getMessage()); } } return matchResult(sortaJobExecutionId, model); }
private String createActivationEmailText(User user, URI activationUri) { return "User registration for " + appSettings.getTitle() + '\n' + "User name: " + user.getUsername() + " Full name: " + user.getFirstName() + ' ' + user.getLastName() + '\n' + "In order to activate the user visit the following URL:" + '\n' + activationUri + '\n' + '\n'; }
private List<SortaJobExecution> getJobsForCurrentUser() { final List<SortaJobExecution> jobs = new ArrayList<>(); User currentUser = userAccountService.getCurrentUser(); Query<SortaJobExecution> query = dataService .query(SORTA_JOB_EXECUTION, SortaJobExecution.class) .eq(JobExecutionMetaData.USER, currentUser.getUsername()); query.sort().on(JobExecutionMetaData.START_DATE, DESC); RunAsSystemAspect.runAsSystem( () -> query .findAll() .forEach( job -> { // TODO: fetch the user as well job.set(JobExecutionMetaData.USER, currentUser.getUsername()); jobs.add(job); })); return jobs; }
private MappedOidcUser createOidcUser(OidcUser oidcUser, OidcUserRequest userRequest) { User user = oidcUserMapper.toUser(oidcUser, userRequest); String userNameAttributeName = getUserNameAttributeName(userRequest); Set<GrantedAuthority> authorities = new HashSet<>(userDetailsService.getAuthorities(user)); return new MappedOidcUser( authorities, oidcUser.getIdToken(), oidcUser.getUserInfo(), userNameAttributeName, user.getUsername()); }
@Override @RunAsSystem public UserDetails loadUserByUsername(String username) { User user = dataService .query(UserMetaData.USER, User.class) .eq(UserMetaData.USERNAME, username) .findOne(); if (user == null) { throw new UsernameNotFoundException("unknown user '" + username + "'"); } Collection<? extends GrantedAuthority> authorities = getAuthorities(user); return new org.springframework.security.core.userdetails.User( user.getUsername(), user.getPassword(), user.isActive(), true, true, true, authorities); }
@PostMapping("/delete/{sortaJobExecutionId}") @ResponseStatus(value = HttpStatus.OK) public String deleteResult( @PathVariable("sortaJobExecutionId") String sortaJobExecutionId, Model model) { SortaJobExecution sortaJobExecution = findSortaJobExecution(sortaJobExecutionId); if (sortaJobExecution != null) { User currentUser = userAccountService.getCurrentUser(); if (currentUser.isSuperuser() || Objects.equal(sortaJobExecution.getUser().get(), currentUser.getUsername())) { RunAsSystemAspect.runAsSystem( () -> dataService.deleteById(SORTA_JOB_EXECUTION, sortaJobExecution.getIdentifier())); tryDeleteRepository(sortaJobExecution.getResultEntityName()); tryDeleteRepository(sortaJobExecution.getSourceEntityName()); } } return init(model); }
@GetMapping(value = "/latest", produces = MediaType.APPLICATION_JSON_VALUE) @ResponseBody public List<Entity> findLastJobs() { final List<Entity> jobs = new ArrayList<>(); Instant weekAgo = Instant.now().minus(7, ChronoUnit.DAYS).truncatedTo(ChronoUnit.DAYS); User currentUser = userAccountService.getCurrentUser(); dataService .getMeta() .getEntityTypes() .filter(this::isAllowedJobExecutionEntityType) .forEach( e -> { Query<Entity> q = dataService.query(e.getId()).ge(JobExecutionMetaData.SUBMISSION_DATE, weekAgo); if (!currentUser.isSuperuser()) { q.and().eq(USER, currentUser.getUsername()); } dataService.findAll(e.getId(), q).forEach(jobs::add); }); jobs.sort( (job1, job2) -> job2.getInstant(SUBMISSION_DATE).compareTo(job1.getInstant(SUBMISSION_DATE))); if (jobs.size() > MAX_JOBS_TO_RETURN) { return jobs.subList(0, MAX_JOBS_TO_RETURN); } return jobs; }
throws UsernameAlreadyExistsException, EmailAlreadyExistsException { if (userService.getUser(user.getUsername()) != null) { throw new UsernameAlreadyExistsException( "Username '" + user.getUsername() + "' already exists."); if (activationEmailAddress == null || activationEmailAddress.isEmpty()) throw new MolgenisDataException( "User '" + user.getUsername() + "' is missing required email address"); activationEmailAddresses = singletonList(activationEmailAddress); user.setActive(false); dataService.add(USER, user); LOG.debug("created user {}", user.getUsername()); LOG.debug( "send activation email for user {} to {}", user.getUsername(), StringUtils.join(activationEmailAddresses, ','));
tokenService.generateAndStoreToken(authentication.getName(), "REST API login"); return new LoginResponse( token, user.getUsername(), user.getFirstName(), user.getLastName()); });
private UserSecret getSecret() { User user = getUser(); UserSecret secret = runAsSystem( () -> dataService .query(USER_SECRET, UserSecret.class) .eq(UserSecretMetaData.USER_ID, user.getId()) .findOne()); if (secret != null) { return secret; } else { throw new InternalAuthenticationServiceException( format( "Secret not found, user: [{0}] is not configured for two factor authentication", user.getUsername())); } }
UserViewData(User mu) { this(mu.getId(), mu.getUsername()); firstName = (null == mu.getFirstName() ? "" : mu.getFirstName()); middleName = (null == mu.getMiddleNames() ? "" : mu.getMiddleNames()); lastName = (null == mu.getLastName() ? "" : mu.getLastName()); fullName = firstName + ' ' + middleName + ' ' + lastName; this.active = mu.isActive(); this.superuser = mu.isSuperuser(); }