Example usage for org.springframework.security.core Authentication getName

List of usage examples for org.springframework.security.core Authentication getName

Introduction

In this page you can find the example usage for org.springframework.security.core Authentication getName.

Prototype

public String getName();

Source Link

Document

Returns the name of this principal.

Usage

From source file:com.sonymobile.backlogtool.HomeController.java

/**
 * Checks if the user is allowed to make edits to this specific area.
 * @param areaName Area name to check//from w  w  w.j a v  a 2  s  .  c  om
 * @return disableEdits true if edits shall be disabled
 */
private boolean isDisableEdits(String areaName) {
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    if (!isLoggedIn()) {
        //Not logged in, edits must be disabled.
        return true;
    }
    String username = auth.getName();
    boolean disableEdits = true;

    Session session = sessionFactory.openSession();
    Transaction tx = null;
    try {
        tx = session.beginTransaction();

        User currentUser = (User) session.get(User.class, username);

        Area area = (Area) session.get(Area.class, areaName);
        if (area != null && (area.isAdmin(username) || area.isEditor(username))
                || (currentUser != null && currentUser.isMasterAdmin())) {
            disableEdits = false;
        }
        tx.commit();
    } catch (Exception e) {
        e.printStackTrace();
        if (tx != null) {
            tx.rollback();
        }
    } finally {
        session.close();
    }
    return disableEdits;
}

From source file:BSxSB.Controllers.AdminController.java

@RequestMapping(value = "/admin", method = RequestMethod.GET)
public String adminPage(Model model) {
    try {/*from   ww w . j a  v  a  2  s  .c o m*/
        Handler handler = new FileHandler("%tBSxSBAdminSchools.log", true);
        handler.setFormatter(new SimpleFormatter());
        logger.addHandler(handler);
        logger.info("Admin Viewing List of Schools.");
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        String name = auth.getName();
        Admins admin = AdminDAO.getAdmin(name);
        if (!admin.getLoggedin()) {
            AdminDAO.setLoggedIn(name);
        }
        SchoolDAO schoolDAO = new SchoolDAO();
        ScheduleBlockDAO scheduleBlockDAO = new ScheduleBlockDAO();
        List<Schools> schools = schoolDAO.allSchools();
        for (Schools school : schools) {
            List<Scheduleblocks> scheduleBlocks = scheduleBlockDAO
                    .getSchoolsScheduleBlocks(school.getSchoolid());
            String SB2Strings = "";
            for (Scheduleblocks sb : scheduleBlocks) {
                SB2Strings += sb.toString();
            }
            school.setScheduleblocks(SB2Strings);
        }
        model.addAttribute("school", schools);
        logger.info("Schools successfully updated to model.");
        handler.close();
        logger.removeHandler(handler);
    } catch (IOException ex) {
        logger.log(Level.SEVERE, null, ex);
    } catch (SecurityException ex) {
        logger.log(Level.SEVERE, null, ex);
    }
    return "admin";
}

From source file:de.blizzy.documentr.access.DocumentrPermissionEvaluator.java

private boolean hasRoleOnBranch(Authentication authentication, String projectName, String branchName,
        String roleName) throws IOException {

    if (authentication.isAuthenticated()) {
        List<RoleGrantedAuthority> authorities = userStore.getUserAuthorities(authentication.getName());
        for (RoleGrantedAuthority rga : authorities) {
            if (rga.getRoleName().equals(roleName)) {
                GrantedAuthorityTarget target = rga.getTarget();
                switch (target.getType()) {
                case APPLICATION:
                    return true;
                case PROJECT:
                    if (target.getTargetId().equals(projectName)) {
                        return true;
                    }/*from www.j a  v a  2  s  . c o m*/
                    break;
                case BRANCH:
                    if (target.getTargetId().equals(projectName + "/" + branchName)) { //$NON-NLS-1$
                        return true;
                    }
                    break;
                }
            }
        }
    }
    return false;
}

From source file:com.qpark.eip.core.spring.security.EipRoleVoter.java

/**
 * @see org.springframework.security.access.vote.RoleVoter#vote(org.springframework.security.core.Authentication,
 *      java.lang.Object, java.util.Collection)
 *//* w  w w. j a  v a2 s . co m*/
@Override
public int vote(final Authentication authentication, final Object object,
        final Collection<ConfigAttribute> attributes) {
    String channelName = getChannelName(object);
    this.logger.debug("+vote {} {}", channelName, authentication.getName());
    if (this.logger.isTraceEnabled()) {
        this.traceRoleSettings(authentication, channelName, attributes);
    }
    int result = super.vote(authentication, object, attributes);
    this.logger.debug(" vote {} {}: Role based vote is {}", channelName, authentication.getName(),
            getResultString(result));
    if (this.eipLimitedAccessDataProvider != null && (result == ACCESS_ABSTAIN || result == ACCESS_GRANTED)
            && channelName != null && channelName.startsWith("eip")
            && channelName.endsWith("WsChannelRequest")) {
        String userName = authentication.getName();
        String serviceName = getServiceName(channelName);
        String operationName = getOperationName(channelName, serviceName);
        int currentCalls = this.eipLimitedAccessDataProvider.getCurrentRequestNumber(userName, serviceName,
                operationName);
        int allowedCalls = this.eipLimitedAccessDataProvider.getAllowedRequestNumber(userName, serviceName,
                operationName);
        this.logger.trace(" vote {} {}: current calls={}, allowed calls={}", channelName,
                authentication.getName(), currentCalls, allowedCalls);
        if (currentCalls > allowedCalls) {
            result = ACCESS_DENIED;
        } else {
            result = ACCESS_GRANTED;
        }
        this.logger.debug(" vote {} {}: Limited access based vote is {}", channelName, authentication.getName(),
                getResultString(result));
    }
    /* Inform listeners. */
    this.channelInvocation(object, authentication.getName(), result);
    return result;
}

From source file:no.dusken.aranea.service.LoginDetailsServiceImpl.java

/**
 * Modify the current user's password. This should change the user's password in
 * the persistent user repository (datbase, LDAP etc) and should also modify the
 * current security context to contain the new password.
 *
 * @param oldPassword current password (for re-authentication if required)
 * @param newPassword the password to change to
 *//*from  w  ww  .  ja v  a2 s. c o m*/
public void changePassword(String oldPassword, String newPassword) {
    Authentication currentUser = SecurityContextHolder.getContext().getAuthentication();

    if (currentUser == null) {
        // This would indicate bad coding somewhere
        throw new AccessDeniedException(
                "Can't change password as no Authentication object found in context " + "for current user.");
    }
    String username = currentUser.getName();
    LoginDetails user = (LoginDetails) loadUserByUsername(username);
    // If an authentication manager has been set, reauthenticate the user with the supplied password.
    if (authenticationManager != null) {
        logger.info("Reauthenticating user '{}' for password change request.", username);

        authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(username, oldPassword));
    } else {
        logger.debug("No authentication manager set. Password won't be re-checked.");
    }
    logger.info("Changing password for user '{}'", username);
    String encoded = encoder.encodePassword(newPassword, username);
    user.setPassword(encoded);
    super.saveOrUpdate(user);
    //reauthenticating with the new password.
    UsernamePasswordAuthenticationToken newAuthentication = new UsernamePasswordAuthenticationToken(user,
            user.getPassword(), user.getAuthorities());
    newAuthentication.setDetails(currentUser.getDetails());
    SecurityContextHolder.getContext().setAuthentication(newAuthentication);
}

From source file:com.vivastream.security.oauth2.provider.DynamoDBUserDetailsManager.java

@Override
public void changePassword(String oldPassword, String newPassword) {
    Authentication currentUserAuth = SecurityContextHolder.getContext().getAuthentication();

    if (currentUserAuth == null) {
        // This would indicate bad coding somewhere
        throw new AccessDeniedException(
                "Can't change password as no Authentication object found in context " + "for current user.");
    }/*from  w  ww  .  j  a  v a  2  s  . co m*/

    String username = currentUserAuth.getName();
    UserDetails user = loadUserByUsername(username, true);

    logger.debug("Changing password for user '" + username + "'");

    // If an authentication manager has been set, re-authenticate the user with the supplied password.
    if (authenticationManager != null) {
        logger.debug("Reauthenticating user '" + username + "' for password change request.");

        authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(username, oldPassword));
    } else {
        logger.debug("No authentication manager set. Password won't be re-checked.");
    }

    Map<String, AttributeValueUpdate> updates = new HashMap<String, AttributeValueUpdate>();
    DynamoDBUtils.nullSafeUpdateS(updates, schema.getColumnPassword(), getPasswordToPersist(newPassword, user));
    client.updateItem(schema.getTableName(),
            Collections.singletonMap(schema.getColumnUsername(), new AttributeValue(username)), updates);

    SecurityContextHolder.getContext()
            .setAuthentication(createNewAuthentication(user, currentUserAuth, newPassword));
}

From source file:com.github.peholmst.springsecuritydemo.ui.LoginView.java

@SuppressWarnings("serial")
protected void init() {
    final Panel loginPanel = new Panel();
    loginPanel.setCaption(getApplication().getMessage("login.title"));
    ((VerticalLayout) loginPanel.getContent()).setSpacing(true);

    final TextField username = new TextField(getApplication().getMessage("login.username"));
    username.setWidth("100%");
    loginPanel.addComponent(username);//from  w w w  .  j a  v  a2s .c om

    final TextField password = new TextField(getApplication().getMessage("login.password"));
    password.setSecret(true);
    password.setWidth("100%");
    loginPanel.addComponent(password);

    final Button loginButton = new Button(getApplication().getMessage("login.button"));
    loginButton.setStyleName("primary");
    // TODO Make it possible to submit the form by pressing <Enter> in any
    // of the text fields
    loginPanel.addComponent(loginButton);
    ((VerticalLayout) loginPanel.getContent()).setComponentAlignment(loginButton, Alignment.MIDDLE_RIGHT);
    loginButton.addListener(new Button.ClickListener() {

        @Override
        public void buttonClick(ClickEvent event) {
            final Authentication auth = new UsernamePasswordAuthenticationToken(username.getValue(),
                    password.getValue());
            try {
                if (logger.isDebugEnabled()) {
                    logger.debug("Attempting authentication for user '" + auth.getName() + "'");
                }
                Authentication returned = getAuthenticationManager().authenticate(auth);
                if (logger.isDebugEnabled()) {
                    logger.debug("Authentication for user '" + auth.getName() + "' succeeded");
                }
                fireEvent(new LoginEvent(LoginView.this, returned));
            } catch (BadCredentialsException e) {
                if (logger.isDebugEnabled()) {
                    logger.debug("Bad credentials for user '" + auth.getName() + "'", e);
                }
                getWindow().showNotification(getApplication().getMessage("login.badCredentials.title"),
                        getApplication().getMessage("login.badCredentials.descr"),
                        Notification.TYPE_WARNING_MESSAGE);
            } catch (DisabledException e) {
                if (logger.isDebugEnabled()) {
                    logger.debug("Account disabled for user '" + auth.getName() + "'", e);
                }
                getWindow().showNotification(getApplication().getMessage("login.disabled.title"),
                        getApplication().getMessage("login.disabled.descr"), Notification.TYPE_WARNING_MESSAGE);
            } catch (LockedException e) {
                if (logger.isDebugEnabled()) {
                    logger.debug("Account locked for user '" + auth.getName() + "'", e);
                }
                getWindow().showNotification(getApplication().getMessage("login.locked.title"),
                        getApplication().getMessage("login.locked.descr"), Notification.TYPE_WARNING_MESSAGE);
            } catch (Exception e) {
                if (logger.isErrorEnabled()) {
                    logger.error("Error while attempting authentication for user '" + auth.getName() + "'");
                }
                ExceptionUtils.handleException(getWindow(), e);
            }
        }
    });

    HorizontalLayout languages = new HorizontalLayout();
    languages.setSpacing(true);
    final Button.ClickListener languageListener = new Button.ClickListener() {

        @Override
        public void buttonClick(ClickEvent event) {
            Locale locale = (Locale) event.getButton().getData();
            if (logger.isDebugEnabled()) {
                logger.debug("Changing locale to [" + locale + "] and restarting the application");
            }
            getApplication().setLocale(locale);
            getApplication().close();
        }
    };
    for (Locale locale : getApplication().getSupportedLocales()) {
        if (!getLocale().equals(locale)) {
            final Button languageButton = new Button(getApplication().getLocaleDisplayName(locale));
            languageButton.setStyleName(Button.STYLE_LINK);
            languageButton.setData(locale);
            languageButton.addListener(languageListener);
            languages.addComponent(languageButton);
        }
    }
    loginPanel.addComponent(languages);

    loginPanel.setWidth("300px");

    final HorizontalLayout viewLayout = new HorizontalLayout();
    viewLayout.addComponent(loginPanel);
    viewLayout.setComponentAlignment(loginPanel, Alignment.MIDDLE_CENTER);
    viewLayout.setSizeFull();
    viewLayout.setMargin(true);

    setCompositionRoot(viewLayout);
    setSizeFull();
}

From source file:software.coolstuff.springframework.owncloud.service.impl.rest.OwncloudRestResourceServiceImpl.java

private URI getUserRoot() {
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    return getResolvedRootUri(authentication.getName());
}

From source file:cherry.sqlapp.controller.sqltool.load.SqltoolLoadIdControllerImpl.java

@Override
public ModelAndView execute(int id, SqltoolLoadForm form, BindingResult binding, Authentication auth,
        Locale locale, SitePreference sitePref, HttpServletRequest request, RedirectAttributes redirAttr) {

    if (binding.hasErrors()) {
        ModelAndView mav = new ModelAndView(PathDef.VIEW_SQLTOOL_LOAD_ID_INIT);
        mav.addObject(PathDef.PATH_VAR_ID, id);
        return mav;
    }//from w ww  .j a v  a  2s. c  o m

    long asyncId = asyncProcessFacade.launchFileProcess(auth.getName(), "SqltoolLoadIdController",
            form.getFile(), "execLoadFileProcessHandler", form.getDatabaseName(), form.getSql());

    redirAttr.addFlashAttribute(ASYNC_PARAM, asyncId);

    UriComponents uc = fromMethodCall(
            on(SqltoolLoadIdController.class).finish(id, auth, locale, sitePref, request)).build();

    ModelAndView mav = new ModelAndView();
    mav.setView(new RedirectView(uc.toUriString(), true));
    return mav;
}