private void loginUser(Authentication authentication) {
    if (authentication == null) return;

    if (!(authentication.getPrincipal() instanceof Person)) return;

    Person person = (Person) authentication.getPrincipal();
    String username = person.getUsername();
    String name = person.getName();

    if (authentication.getDetails() instanceof WebAuthenticationDetails) {
      WebAuthenticationDetails details = (WebAuthenticationDetails) authentication.getDetails();

      String ip = details.getRemoteAddress();
      String sessionId = details.getSessionId();

      if (onLineManager.getOnlineUser(sessionId) != null) return;

      onLineManager.loginUser(ip, sessionId, person);

      logManager.log(username, name, ip, "登录系统", "");

      if (logger.isDebugEnabled())
        logger.debug(
            "用户 {}[{}] 登录系统,登录IP:{},session:{}", new Object[] {name, username, ip, sessionId});
    }
  }
Ejemplo n.º 2
0
  @Override
  public UserProfile getUser(Authentication authentication) {
    Object userName = authentication.getPrincipal();
    String login;
    User auth = null;
    if (userName instanceof String) login = (String) userName;
    else {
      login = ((User) authentication.getPrincipal()).getUsername();
      auth = (User) authentication.getPrincipal();
    }

    UserProfile userProfile = new UserProfile();
    userProfile.setUserId(login);
    userProfile.setStatus("ENABLED");

    if (auth != null && !auth.getAuthorities().isEmpty()) {
      for (GrantedAuthority grantedAuthority : auth.getAuthorities()) {
        userProfile.addUserRole(grantedAuthority.getAuthority());
      }
    }
    if (auth != null) {
      SystemUser sysUser = systemUserService.findByLogin(login);
      if (sysUser != null) {
        userProfile.setApiKey(sysUser.getApiKey());
        userProfile.setCompany(sysUser.getCompany().getName());
      }
    }

    return userProfile;
  }
Ejemplo n.º 3
0
 @RequestMapping(produces = "text/html")
 public String index(ModelMap model, HttpServletRequest request, HttpServletResponse response) {
   User usr = getCurrentUser();
   HttpSession session = request.getSession();
   if (usr != null) {
     model.addAttribute("user", usr);
     model.addAttribute("team", usr.team);
     model.addAttribute("username", usr.getUsername());
     session.setAttribute("user", usr);
     session.setAttribute("team", usr.team);
     session.setAttribute("username", usr.getUsername());
   } else {
     Authentication auth = getCurrentAuthentication();
     model.addAttribute("username", auth.getPrincipal().toString());
     session.setAttribute("username", auth.getPrincipal().toString());
   }
   if (hasRole("ROLE_ADMIN")) {
     model.addAttribute("ROLE", "ROLE_ADMIN");
     session.setAttribute("ROLE", "ROLE_ADMIN");
   } else if (hasRole("ROLE_USER")) {
     model.addAttribute("ROLE", "ROLE_USER");
     session.setAttribute("ROLE", "ROLE_USER");
   } else {
     model.addAttribute("ROLE", "ROLE_VIEW");
     session.setAttribute("ROLE", "ROLE_VIEW");
   }
   return "index";
 }
Ejemplo n.º 4
0
  private StatusResponse createResponse(
      Authentication auth, HashMap<String, Connection<?>> connections, HttpSession session) {
    StatusResponse result = new StatusResponse();
    result.getConnections().clear();

    if (auth != null && auth.getPrincipal() != null && auth.getPrincipal() instanceof UserProfile) {
      UserProfile user = currentUser();
      result.setLogged(true);
      result.setProfile(user);
      result.setToken((String) session.getAttribute("nquire-it-token"));

      for (Map.Entry<String, Connection<?>> entry : connections.entrySet()) {
        if (entry.getValue() != null) {
          StatusConnectionResponse scr = new StatusConnectionResponse();
          scr.setProvider(entry.getKey());
          scr.setProviderProfileUrl(entry.getValue().getProfileUrl());
          result.getConnections().put(entry.getKey(), scr);
        }
      }
    } else {
      result.setLogged(false);
      result.setProfile(null);
    }

    return result;
  }
  @Override
  public Authentication authenticate(final Authentication authentication)
      throws AuthenticationException {

    Optional<User> u = Optional.absent();
    u = userManager.getInternalUser(authentication.getPrincipal().toString());

    if (!u.isPresent()) {
      throw new UsernameNotFoundException(
          "user not found: " + authentication.getPrincipal().toString());
    }
    boolean b =
        userManager.authenticate(
            authentication.getPrincipal().toString(), authentication.getCredentials().toString());
    if (!b) {
      throw new BadCredentialsException("invalid credentials");
    }

    List<GrantedAuthority> gaList = Lists.newArrayList();
    for (String role : u.get().getRoles()) {

      GrantedAuthority ga = new SimpleGrantedAuthority(role);
      gaList.add(ga);
    }

    UsernamePasswordAuthenticationToken upt =
        new UsernamePasswordAuthenticationToken(
            authentication.getPrincipal().toString(),
            authentication.getCredentials().toString(),
            gaList);
    return upt;
  }
 @Override
 public boolean hasPermission(
     Authentication authentication, Object targetDomainObject, Object permission) {
   if (targetDomainObject != null) {
     if (targetDomainObject instanceof UserAuthorizationRequest) {
       return ((UserAuthorizationRequest) targetDomainObject)
           .isLoggedIn(permission, authentication);
     }
     if (targetDomainObject instanceof UserKnowsPasswordAuthorizationRequest) {
       return ((UserKnowsPasswordAuthorizationRequest) targetDomainObject)
           .isLoggedInAndKnowsPassword(permission, authentication);
     }
     if (targetDomainObject instanceof AuthorizationRequest) {
       return ((AuthorizationRequest) targetDomainObject)
           .hasPermission(permission, authentication);
     }
     if (targetDomainObject instanceof UserSecurityResponseForResetPasswordRequest
         && permission instanceof ResetPasswordRequest) {
       return ((UserSecurityResponseForResetPasswordRequest) targetDomainObject)
           .isSecurityResponseValid((ResetPasswordRequest) permission);
     }
     if (targetDomainObject instanceof IpRangeActivationAuthorizationRequest
         && authentication.getDetails() instanceof HttpProxyAwareAuthenticationDetails) {
       return ((IpRangeActivationAuthorizationRequest) targetDomainObject)
           .withinClientAllowedRange(
               permission.toString(),
               (HttpProxyAwareAuthenticationDetails) authentication.getDetails());
     }
     if (targetDomainObject instanceof IpRangeResetAuthorizationRequest
         && authentication.getDetails() instanceof HttpProxyAwareAuthenticationDetails) {
       return ((IpRangeResetAuthorizationRequest) targetDomainObject)
           .withinClientAllowedRange(
               permission.toString(),
               (HttpProxyAwareAuthenticationDetails) authentication.getDetails());
     }
     if (targetDomainObject instanceof IpRangeValidateEmailAuthorizationRequest
         && authentication.getDetails() instanceof HttpProxyAwareAuthenticationDetails) {
       return ((IpRangeValidateEmailAuthorizationRequest) targetDomainObject)
           .withinClientAllowedRange(
               permission.toString(),
               (HttpProxyAwareAuthenticationDetails) authentication.getDetails());
     }
     if (targetDomainObject instanceof IpRangeAuthorizationRequest) {
       IpRangeAuthorizationRequest ipRangeAuthorizationRequest =
           (IpRangeAuthorizationRequest) targetDomainObject;
       if (authentication.getPrincipal() instanceof UserClient) {
         if (authentication.getDetails() instanceof HttpProxyAwareAuthenticationDetails) {
           return ipRangeAuthorizationRequest.withinClientAllowedRange(
               (UserClient) authentication.getPrincipal(),
               (HttpProxyAwareAuthenticationDetails) authentication.getDetails());
         } else {
           // don't check ip unless the details are specific
           return true;
         }
       }
     }
   }
   return super.hasPermission(authentication, targetDomainObject, permission);
 }
Ejemplo n.º 7
0
 /**
  * Return the current user, or throws an exception, if the user is not authenticated yet.
  *
  * @return the current user
  */
 public static CustomUserDetails getCurrentUser() {
   SecurityContext securityContext = SecurityContextHolder.getContext();
   Authentication authentication = securityContext.getAuthentication();
   if (authentication != null && authentication.getPrincipal() instanceof CustomUserDetails) {
     return (CustomUserDetails) authentication.getPrincipal();
   }
   throw new IllegalStateException("User not found!");
 }
Ejemplo n.º 8
0
  /** Retrieve the current UserDetails bound to the current thread by Spring Security, if any. */
  public static UserDetails getUserDetails() {
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();

    if ((auth != null) && (auth.getPrincipal() instanceof UserDetails)) {
      return ((UserDetails) auth.getPrincipal());
    }

    return null;
  }
Ejemplo n.º 9
0
 /**
  * If the current user has a specific authority (security role).
  *
  * <p>The name of this method comes from the isUserInRole() method in the Servlet API
  */
 public static boolean isUserInRole(String authority) {
   SecurityContext securityContext = SecurityContextHolder.getContext();
   Authentication authentication = securityContext.getAuthentication();
   if (authentication != null && authentication.getPrincipal() instanceof UserDetails) {
     UserDetails springSecurityUser = (UserDetails) authentication.getPrincipal();
     return springSecurityUser.getAuthorities().contains(new SimpleGrantedAuthority(authority));
   }
   return false;
 }
 @Override
 public UserInfo getAuthenticatedUserInfo() {
   Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
   if (authentication != null && authentication.getPrincipal() != null) {
     User user = (User) authentication.getPrincipal();
     return userService.findByUsername(user.getUsername());
   }
   return null;
 }
Ejemplo n.º 11
0
  public User getCurrentUser() throws SQLException, NothingWasFoundException, NotLoggedInException {
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();

    if (auth.getPrincipal().equals("anonymousUser")) {
      throw new NotLoggedInException("You are not logged in.");
    }

    return this.get((String) auth.getPrincipal());
  }
Ejemplo n.º 12
0
  @Override
  public User getCurrentSignedUser() {

    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    if (auth != null && auth.getPrincipal() instanceof User) {
      return (User) auth.getPrincipal();
    }

    return null;
  }
Ejemplo n.º 13
0
 /**
  * Return the current user, or throws an exception, if the user is not authenticated yet.
  *
  * @return the current user
  */
 public static User getCurrentUser() {
   SecurityContext securityContext = SecurityContextHolder.getContext();
   Authentication authentication = securityContext.getAuthentication();
   if (authentication != null) {
     if (authentication.getPrincipal() instanceof User) {
       return (User) authentication.getPrincipal();
     }
   }
   throw new IllegalStateException("User not found!");
 }
Ejemplo n.º 14
0
  /** {@inheritDoc} */
  @Override
  public void attributeReplaced(HttpSessionBindingEvent event) {
    if (event.getName().equals(EVENT_KEY) && !isAnonymous()) {
      Authentication auth = ((SecurityContext) event.getValue()).getAuthentication();

      if (auth != null && auth.getPrincipal() instanceof User) {
        addUser((User) auth.getPrincipal(), event.getSession().getServletContext());
      }
    }
  }
Ejemplo n.º 15
0
 @Override
 public boolean isLogin() {
   Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
   if (authentication.getPrincipal() instanceof String) {
     String principal = (String) authentication.getPrincipal();
     if (principal.equals("anonymousUser")) {
       return false;
     }
   }
   return true;
 }
Ejemplo n.º 16
0
  public String getCurrentUsername() {
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

    if (authentication == null
        || authentication.getPrincipal() instanceof String) { // Usuario anónimo
      return null;
    }
    UserDetails u = (UserDetails) (authentication == null ? null : authentication.getPrincipal());
    if (u != null) {
      return u.getUsername();
    }
    return null;
  }
Ejemplo n.º 17
0
  private void init() {
    SecurityContext context = SecurityContextHolder.getContext();
    if (context instanceof SecurityContext) {
      Authentication authentication = context.getAuthentication();
      if (authentication instanceof Authentication) {
        if (!authentication.getPrincipal().equals("anonymousUser")) {
          this.setMatriculaUser(((User) authentication.getPrincipal()).getUsername());

          logger.info("Login: " + this.getMatriculaUser());
        }
      }
    }
  }
Ejemplo n.º 18
0
 /** Get the login of the current user. */
 public static String getCurrentUserLogin() {
   SecurityContext securityContext = SecurityContextHolder.getContext();
   Authentication authentication = securityContext.getAuthentication();
   String userName = null;
   if (authentication != null) {
     if (authentication.getPrincipal() instanceof UserDetails) {
       UserDetails springSecurityUser = (UserDetails) authentication.getPrincipal();
       userName = springSecurityUser.getUsername();
     } else if (authentication.getPrincipal() instanceof String) {
       userName = (String) authentication.getPrincipal();
     }
   }
   return userName;
 }
Ejemplo n.º 19
0
  /**
   * @param permission
   * @return
   * @throws AccessDeniedException
   */
  public boolean hasPermission(String permission) throws AccessDeniedException {
    final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    if (!(authentication.getPrincipal() instanceof User)) {
      return false;
    }

    final User user = (User) authentication.getPrincipal();

    for (Permissao systemRole : user.getProfile().getPermissaos()) {
      if (systemRole.getName().equals(permission)) {
        return true;
      }
    }
    return false;
  }
Ejemplo n.º 20
0
  @RequestMapping(
      value = {"/pay_success_url"},
      method = RequestMethod.POST)
  public void successURL(
      @RequestParam(value = "OutSum", required = true) String outSum,
      @RequestParam(value = "InvId", required = true) String invId,
      @RequestParam(value = "SignatureValue", required = true) String signatureValue,
      @RequestParam(value = "Culture", required = false) String culture)
      throws Exception {

    double _money = Double.parseDouble(outSum);
    long _id = Long.parseLong(invId);

    String md5String = md5SignatureValue(_money, _id, password2, ":Shp_item=" + shp_item);
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    UserDetails userDetail = (UserDetails) auth.getPrincipal();
    Users u = userService.getRepository().findUsersByLogin(userDetail.getUsername());

    PaymentSystems ps =
        (PaymentSystems) paymentService.getRepository().findPaymentSystemsByUserId(u.getId());
    if (md5String.equals(ps.getKey())) {
      u.setSummaryCash(u.getSummaryCash() + _money);
      userService.getRepository().save(u);
    }
    HttpGet method = new HttpGet(url.concat("?OK").concat(invId));
    HttpClient client = new DefaultHttpClient();
    client.execute(method);
  }
Ejemplo n.º 21
0
  @Override
  public void savePayrolls(EmployeePayrollList payrolls) {
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    User user = (User) auth.getPrincipal();

    String savePayrollsQuery =
        "insert into employee_payroll(reg_no, emp_name, date, basic_salary, gross_pay, loan_deduction, other_deduction, created_by, created_on, net_salary, last_updated_by, last_updated_on) values(?,?,?,?,?,?,?,?,?,?,?,?)";
    System.out.println(payrolls.getMonth() + " " + payrolls.getYear());
    for (int i = 0; i < payrolls.getPayrolls().size(); i++) {
      EmployeePayroll payroll = payrolls.getPayrolls().get(i);
      jdbcTemplate.update(
          savePayrollsQuery,
          new Object[] {
            payroll.getRegNum(),
            payroll.getName(),
            payrolls.getMonth() + " " + payrolls.getYear(),
            payroll.getBasicSalary(),
            payroll.getGrossPay(),
            payroll.getLoanDeduction(),
            payroll.getOtherDeduction(),
            payroll.getCreatedBy(),
            payroll.getCreatedOn(),
            payroll.getNetSalary(),
            user.getUsername(),
            user.getUsername()
          });
    }
  }
 @BeforeClass
 public void setUpBeforeClass() {
   AUTHENTICATION_PREVIOUS = SecurityContextHolder.getContext().getAuthentication();
   authentication = mock(Authentication.class);
   when(authentication.getPrincipal()).thenReturn(USERNAME_USER);
   SecurityContextHolder.getContext().setAuthentication(authentication);
 }
  @Override
  public Authentication authenticate(Authentication a) throws AuthenticationException {
    FacebookUserDTO fud = (FacebookUserDTO) a.getPrincipal();
    String credentials = (String) a.getCredentials();

    // fetch user from our DB
    FacebookUser user = usersService.getByFacebookId(fud.getFacebookProfileId());

    // checking according to spring security documentation
    if (user.isDisabled()) {
      logger.info("Account disabled: " + user);
      throw new DisabledException("Konto wyłączone");
    }
    if (user.isLocked()) {
      logger.info("Account locked: " + user);
      throw new LockedException("Konto zablokowane");
    }

    // if user is allowed to access - allow him :)
    List<GrantedAuthority> authorities = usersService.getUsersAuthorities(user);
    logger.info("User granted authorities=" + authorities);

    // fetch profile of logged user and fill information from his profile
    Facebook facebook = new FacebookTemplate(fud.getAccessToken());
    FacebookProfile facebookProfile = facebook.userOperations().getUserProfile();
    fillUserData(user, facebookProfile);
    user.setAccessToken(fud.getAccessToken());

    Authentication auth = new UsernamePasswordAuthenticationToken(user, credentials, authorities);
    logger.info("Authentication completed: " + auth);
    return auth;
  }
Ejemplo n.º 24
0
  public static UserAccount getPrincipal() {
    UserAccount result;
    SecurityContext context;
    Authentication authentication;
    Object principal;

    // If the asserts in this method fail, then you're
    // likely to have your Tomcat's working directory
    // corrupt. Please, clear your browser's cache, stop
    // Tomcat, update your Maven's project configuration,
    // clean your project, clean Tomcat's working directory,
    // republish your project, and start it over.

    context = SecurityContextHolder.getContext();
    Assert.notNull(context);
    authentication = context.getAuthentication();
    Assert.notNull(authentication);
    principal = authentication.getPrincipal();
    Assert.isTrue(principal instanceof UserAccount);
    result = (UserAccount) principal;
    Assert.notNull(result);
    Assert.isTrue(result.getId() != 0);

    return result;
  }
Ejemplo n.º 25
0
  @RequestMapping(
      value = {"/", "/welcome**"},
      method = RequestMethod.GET)
  public ModelAndView defaultPage() {
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    ModelAndView model = new ModelAndView();
    if (!(auth instanceof AnonymousAuthenticationToken)) {
      UserDetails userDetail = (UserDetails) auth.getPrincipal();
      model.addObject("nextBeers", nextBeerDAO.getBeers(userDetail.getUsername()));
      model.addObject(
          "hasBeersWithoutDate", nextBeerDAO.hasBeersWithoutDate(userDetail.getUsername()));
      model.setViewName("homeLogged");
    } else {
      model.setViewName("home");
    }
    NextBeer nextestBeer = nextBeerDAO.getNextBeer();
    Calendar today = Calendar.getInstance();
    today.set(Calendar.HOUR_OF_DAY, 23);
    today.set(Calendar.MINUTE, 59);
    if (nextestBeer != null && today.before(nextestBeer.getDateToPay())) {
      model.addObject("dateToPayNextBeers", nextestBeer.getDateToPay());
    }
    model.addObject("allNextBeers", nextBeerDAO.getAllNextBeers());

    return model;
  }
Ejemplo n.º 26
0
 @RequestMapping("/reminder")
 public String displayPage() {
   System.out.println("getting reminder page");
   Authentication auth = SecurityContextHolder.getContext().getAuthentication();
   CurrentUser currentUser = (CurrentUser) auth.getPrincipal(); // get user id
   return "redirect:/a/" + currentUser.getId() + "/reminder";
 }
Ejemplo n.º 27
0
  // 커뮤니티 상세보기의 정보 수정
  @RequestMapping(value = "/insertUserComtBasicInfo")
  public void setInsertUserComtBasicInfo(
      @RequestParam Map<String, Object> paramMap,
      HttpServletResponse response,
      Authentication authentication)
      throws IOException {
    // Spring Security의 Authentication 객를 주입
    MemberInfo memberInfo = (MemberInfo) authentication.getPrincipal();
    paramMap.put("compId", memberInfo.getCompId());
    paramMap.put("userId", memberInfo.getUserId());
    String txtMastGubun = (String) paramMap.get("txtMastGubun");
    String[] mg_arr = ((String) paramMap.get("txtMastGubun")).split(",");

    int rows = 0;
    int cntRw = 0;
    cntRw = communityService.getInserComtBasicInfoNm(paramMap);

    if (cntRw > 0) {
      rows = 99;
    } else {
      rows = communityService.setInsertUserComtBasicInfo(paramMap);
    }

    try {
      ObjectMapper mapper = new ObjectMapper();
      response.setContentType("application/json");
      mapper.writeValue(response.getOutputStream(), rows);
    } catch (Exception e) {
      throw e;
    }
  }
Ejemplo n.º 28
0
  @RequestMapping(value = "/comtMain")
  public String getCumtMain(
      @RequestParam Map<String, Object> paramMap, ModelMap model, Authentication authentication)
      throws Throwable {
    // Spring Security의 Authentication 객를 주입
    MemberInfo memberInfo = (MemberInfo) authentication.getPrincipal();

    // cumt left 메뉴 조회
    List<ComtVo> list = getCumntUserJoinList(memberInfo);
    model.addAttribute("comtlist", list);
    model.addAttribute("memberInfo", memberInfo);

    model.put("compId", memberInfo.getCompId());

    // 커뮤니티내의 게시글 조회(전체)
    paramMap.put("allYn", "");
    paramMap.put("compId", memberInfo.getCompId());
    int total = 0;
    List<ComtBoardVo> boardList = communityService.getComtBoardNewList(paramMap);
    if (boardList != null && boardList.size() > 0) {
      total = boardList.size();
    }

    model.put("comtBdList", boardList);
    model.put("total", total);

    return "/cumtMainLayout/left_community/comtMain";
  }
Ejemplo n.º 29
0
  @RequestMapping(value = "/group/create/invite", method = RequestMethod.POST)
  public String grpCrtInvite(
      @ModelAttribute("rootData") RootBean bean, Model model, Principal principal)
      throws Exception {

    initilize.exec();

    // ログインアカウントのUserNameを取得
    Authentication authentication = (Authentication) principal;
    UserDetails userDetails = (UserDetails) authentication.getPrincipal();
    String userName = userDetails.getUsername();

    /*グループを新規作成(MEMBERには、ログインアカウントのみをセット)し、
    ログインアカウント以外のーザを取得*/
    grpCrtInviteCommand.preProc(bean);
    grpCrtInviteCommand.exec(userName);
    this.bean = grpCrtInviteCommand.postProc();

    // ログインアカウント以外のユーザを画面にセット
    model.addAttribute("rootData", bean);

    finalize.exec(bean, CommonConstants.VIEW_INVITE_MEMBER);

    return "groupInviteMember";
  }
 protected org.springframework.security.core.Authentication getAuthentification(
     javax.servlet.http.HttpServletRequest request,
     javax.servlet.http.HttpServletResponse response) {
   Authentication auth = mock(Authentication.class);
   when(auth.getPrincipal()).thenReturn(new SecuredUser(getTestUser(), null));
   return auth;
 };