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:cherry.sqlapp.controller.sqltool.statement.SqltoolStatementControllerImpl.java

@Override
public SqltoolStatementForm getForm(Integer ref, Authentication auth) {
    if (ref != null) {
        SqltoolMetadata md = metadataService.findById(ref, auth.getName());
        if (md != null) {
            SqltoolStatement record = statementService.findById(ref);
            if (record != null) {
                return formUtil.getForm(record);
            }/*from   w  w w  .j a  v  a  2s .  com*/
        }
    }
    SqltoolStatementForm form = new SqltoolStatementForm();
    form.setDatabaseName(dataSourceDef.getDefaultName());
    return form;
}

From source file:com.spfsolutions.ioms.auth.UserAuthenticationProvider.java

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    try {//from ww w.  ja v a 2s .c o m
        UserEntity userEntity = userDao.queryForFirst(
                userDao.queryBuilder().where().eq("Username", authentication.getName()).prepare());

        String inputHash = MD5.encrypt(authentication.getCredentials().toString());
        if (userEntity == null || !userEntity.getPassword().equals(inputHash)) {
            throw new BadCredentialsException("Username or password incorrect.");
        } else if (!userEntity.isEnabled()) {
            throw new DisabledException("The username is disabled. Please contact your System Administrator.");
        }
        userEntity.setLastSuccessfulLogon(new DateTime(DateTimeZone.UTC).toDate());

        userDao.createOrUpdate(userEntity);

        Collection<SimpleGrantedAuthority> authorities = buildRolesFromUser(userEntity);
        UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(
                authentication.getName(), authentication.getCredentials(), authorities);

        return token;
    } catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } finally {
        userDao.getConnectionSource().closeQuietly();
    }
    return null;

}

From source file:scratch.cucumber.example.security.servlet.UserAuthenticationFactoryTest.java

@Test
public void Can_add_an_authentication_to_a_response() {

    final Authentication authentication = mock(Authentication.class);
    final HttpServletResponse response = mock(HttpServletResponse.class);

    final String username = someString();

    // Given//from   w w  w .  j ava2s .  com
    given(authentication.getName()).willReturn(username);

    // When
    userAuthenticationFactory.add(response, authentication);

    // Then
    verify(usernameFactory).add(response, username);
}

From source file:com.sf.springsecurityregistration1.web.controllers.AnnouncementDetailsController.java

/**
* This method creates a new announcement.
*
* @return the model with default announcement
*
*//*from  w  w w .ja va 2 s.c om*/
@RequestMapping(value = "/customer/announcement/create", method = { RequestMethod.GET })
public ModelAndView prepareCreation() {
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    String name = auth.getName(); //get logged in username
    Announcements announcement = new Announcements(null, name, new Timestamp((new Date()).getTime()), "", "",
            "");
    ModelAndView model = new ModelAndView("/customer/announcement/create");
    model.addObject("announcements", announcement);
    Set<Category> headers = new HashSet<>();
    headers.addAll(this.announcementService.findAllCategories());
    model.addObject("categories", headers);
    System.out.println("/customer/announcement/create " + announcement.getContent());
    return model;
}

From source file:com.alehuo.wepas2016projekti.controller.DefaultController.java

/**
 * Sovelluksen etusivu/*from  w  w w .  j  av  a2  s.  c o  m*/
 *
 * @param a Autentikointi
 * @param m Malli
 * @param l
 * @return
 */
@RequestMapping("/")
public String index(Authentication a, Model m, Locale l) {
    List<Image> images = imageRepo.findTop10ByVisibleTrueOrderByIdDesc();
    UserAccount u = userService.getUserByUsername(a.getName());
    m.addAttribute("user", u);
    m.addAttribute("images", images);
    return "index";
}

From source file:com.cami.persistence.service.impl.CautionService.java

@Override
public List<Caution> filterByAppelOffre(final Long appelOffreId) {
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    final Role userConnected = roleDao.retrieveAUser(auth.getName()); // get the current logged user
    if (userConnected.getRole().equals("ROLE_COMMERCIAL")) {
        return dao.filterByAppelOffreAndUser(appelOffreId, userConnected.getId());
    } else {//from   w ww  .  j a  va2s .  com
        return dao.filterByAppelOffre(appelOffreId);
    }
}

From source file:com.sonymobile.backlogtool.permission.AdminPermission.java

@Override
/**/*www  . ja  v  a 2s  . c o m*/
 * Checks if authenticated user is allowed to edit targetDomain area.
 */
public boolean isAllowed(Authentication authentication, Object targetDomainObject) {
    if (authentication == null) {
        return false;
    }
    String areaName = targetDomainObject.toString();
    String username = authentication.getName();
    boolean hasPermission = false;

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

        User user = (User) session.get(User.class, username);
        Area area = (Area) session.get(Area.class, areaName);

        if ((area != null && area.isAdmin(username)) || (user != null && user.isMasterAdmin())) {
            //TODO: Check the area for LDAP groups here as well
            hasPermission = true;
            System.out.println(
                    "approved admin-permission for user " + authentication.getName() + " area: " + areaName);
        } else {
            hasPermission = false;
            System.out.println(
                    "DENIED admin-permission for user " + authentication.getName() + " area: " + areaName);
        }
        tx.commit();
    } catch (Exception e) {
        e.printStackTrace();
        if (tx != null) {
            tx.rollback();
        }
    } finally {
        session.close();
    }

    return hasPermission;
}

From source file:cs545.proj.controller.MemberController.java

@RequestMapping(value = "/detail", method = RequestMethod.GET)
public String getMemberByUsername(Model model, Principal principal) {
    if (principal == null)
        return "redirect:/loginPage";

    Authentication authentication = (Authentication) principal;
    Member member = memberService.getMemberByUsername(authentication.getName());
    if (member.getUser().getRoleSet().contains(UserRole.ROLE_ORGANIZATION))
        model.addAttribute("hasCertified", true);
    model.addAttribute("member", member);
    model.addAttribute("licensePath", licensePath);
    return "memberDetailTile";
}

From source file:org.musicrecital.webapp.services.impl.SpringSecurityContext.java

public boolean isLoggedIn() {

    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    if (authentication != null && authentication.getPrincipal() != null) {
        if ("anonymousUser".equals(authentication.getName())) {
            return false;
        }//from   w  ww.java  2s.c om
        return authentication.isAuthenticated();
    }
    return false;
}

From source file:com.sonymobile.backlogtool.permission.EditPermission.java

@Override
/**/*  ww  w  . j a v a  2 s. c o  m*/
 * Checks if authenticated user is allowed to edit targetDomain area.
 */
public boolean isAllowed(Authentication authentication, Object targetDomainObject) {
    if (authentication == null) {
        return false;
    }
    String areaName = targetDomainObject.toString();
    String username = authentication.getName();
    boolean hasPermission = false;

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

        User user = (User) session.get(User.class, username);
        Area area = (Area) session.get(Area.class, areaName);

        if ((area != null && (area.isAdmin(username) || area.isEditor(username)))
                || (user != null && user.isMasterAdmin())) {
            //TODO: Check the area for LDAP groups here as well
            hasPermission = true;
            System.out.println(
                    "approved edit-permission for user " + authentication.getName() + " area: " + areaName);
        } else {
            hasPermission = false;
            System.out.println(
                    "DENIED edit-permission for user " + authentication.getName() + " area: " + areaName);
        }
        tx.commit();
    } catch (Exception e) {
        e.printStackTrace();
        if (tx != null) {
            tx.rollback();
        }
    } finally {
        session.close();
    }

    return hasPermission;
}