@Override
  public Authentication authenticate(Authentication authentication) throws AuthenticationException {

    Hashtable<Object, Object> env = new Hashtable<Object, Object>();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "weblogic.jndi.WLInitialContextFactory");
    env.put(Context.PROVIDER_URL, t3Dir);
    env.put(Context.SECURITY_PRINCIPAL, authentication.getName());
    env.put(Context.SECURITY_CREDENTIALS, authentication.getCredentials().toString());
    Context ctx;

    try {
      ctx = new InitialContext(env);

      User user =
          new User(
              authentication.getName(),
              authentication.getCredentials().toString(),
              true,
              true,
              true,
              true,
              authentication.getAuthorities());
      ArrayList<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
      authorities.add(new GrantedAuthorityImpl("ROLE_ADMIN"));

      return new UsernamePasswordAuthenticationToken(
          user, authentication.getCredentials(), authorities);
    } catch (NamingException e) {
      throw new BadCredentialsException("Login or password incorrect");
    }
  }
Ejemplo n.º 2
0
 public Authentication authenticate(Authentication auth) throws AuthenticationException {
   if (auth.getName().equals(auth.getCredentials())) {
     return new UsernamePasswordAuthenticationToken(
         auth.getName(), auth.getCredentials(), AUTHORITIES);
   }
   throw new BadCredentialsException("Bad Credentials");
 }
  @RequestMapping(
      value = "/{id}",
      method = RequestMethod.GET,
      produces = MimeTypeUtils.APPLICATION_JSON_VALUE)
  public String readResourceSet(@PathVariable("id") Long id, Model m, Authentication auth) {
    ensureOAuthScope(auth, SystemScopeService.UMA_PROTECTION_SCOPE);

    ResourceSet rs = resourceSetService.getById(id);

    if (rs == null) {
      m.addAttribute("code", HttpStatus.NOT_FOUND);
      m.addAttribute("error", "not_found");
      return JsonErrorView.VIEWNAME;
    } else {

      rs = validateScopes(rs);

      if (!auth.getName().equals(rs.getOwner())) {

        logger.warn(
            "Unauthorized resource set request from wrong user; expected "
                + rs.getOwner()
                + " got "
                + auth.getName());

        // it wasn't issued to this user
        m.addAttribute(HttpCodeView.CODE, HttpStatus.FORBIDDEN);
        return JsonErrorView.VIEWNAME;
      } else {
        m.addAttribute(JsonEntityView.ENTITY, rs);
        return ResourceSetEntityView.VIEWNAME;
      }
    }
  }
  @Override
  public Authentication attemptAuthentication(
      HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {

    try {
      // call to daoAuthenticationProvider
      Authentication auth = super.attemptAuthentication(request, response);

      // store currentUser in HttpSession
      UserCredentials currentUser = userService.findByName(auth.getName());
      request.getSession().setAttribute(Constants.CURRENT_USER, currentUser);

      // display info about currentUser
      Collection<GrantedAuthority> gs = auth.getAuthorities();
      StringBuilder sb =
          new StringBuilder("===== Authentification Succesful : userName = "******" with roles: ");
      for (GrantedAuthority x : gs) {
        sb.append(x.getAuthority()).append(",");
      }
      log.info(sb.toString());
      return auth;
    } catch (AuthenticationException e) {
      log.info("Login wasn't successful for " + obtainUsername(request));
      throw e;
    }
  }
  public Authentication authenticate(Authentication auth) throws UsernameNotFoundException {

    /** Init a database user object */
    try {
      employeeEntity = employeeDao.findByLogin(auth.getName());
    } catch (RuntimeException e) {
      throw new BadCredentialsException(
          this.messageSource.getMessage(
              "auth.no_user", new Object[] {"userName"}, "Access denied", Locale.getDefault()));
    }

    /** Checking if user account is active */
    if (employeeEntity.getActive() == 0) {
      throw new BadCredentialsException(
          this.messageSource.getMessage(
              "auth.expired", new Object[] {"active"}, "Access denied", Locale.getDefault()));
    }

    /** Compare passwords Make sure to encode the password first before comparing */
    if (!passwordEncoder.isPasswordValid(
        employeeEntity.getPassword(), (String) auth.getCredentials(), null)) {
      throw new BadCredentialsException(
          this.messageSource.getMessage(
              "auth.wrong", new Object[] {"password"}, "Access denied", Locale.getDefault()));
    }

    /**
     * main logic of Authentication manager
     *
     * @return UsernamePasswordAuthenticationToken
     */
    userAccessLogger.debug("User is located!");
    return new UsernamePasswordAuthenticationToken(
        auth.getName(), auth.getCredentials(), getAuthorities(employeeEntity.getAdmin()));
  }
 @Override
 public OAuth2AccessToken getAccessToken(
     OAuth2ProtectedResourceDetails resource, Authentication authentication) {
   if (authentication instanceof OAuth2Authentication) {
     OAuth2AccessToken token = tokenStore.getAccessToken((OAuth2Authentication) authentication);
     if (token != null) {
       logger.debug("Found token for OAuth2Authentication");
       return token;
     }
   }
   Collection<OAuth2AccessToken> tokens = tokenStore.findTokensByClientId(resource.getClientId());
   if (tokens == null || tokens.isEmpty()) {
     return null;
   }
   Iterator<OAuth2AccessToken> iter = tokens.iterator();
   while (iter.hasNext()) {
     OAuth2AccessToken token = iter.next();
     OAuth2Authentication oauth2Auth = tokenStore.readAuthentication(token);
     if (oauth2Auth != null
         && resource.getClientId().equals(oauth2Auth.getOAuth2Request().getClientId())
         && oauth2Auth.getName().equals(authentication.getName())) {
       logger.debug("token for user: "******" found");
       return token;
     }
   }
   logger.debug("token not found");
   return null;
 }
Ejemplo n.º 7
0
  @Override
  public Authentication authenticate(Authentication req) throws AuthenticationException {
    logger.debug("Processing authentication request for " + req.getName());

    if (req.getCredentials() == null) {
      BadCredentialsException e = new BadCredentialsException("No password supplied");
      publish(new AuthenticationFailureBadCredentialsEvent(req, e));
      throw e;
    }

    UaaUser user;
    try {
      user = userDatabase.retrieveUserByName(req.getName().toLowerCase(Locale.US));
    } catch (UsernameNotFoundException e) {
      user = dummyUser;
    }

    final boolean passwordMatches =
        encoder.matches((CharSequence) req.getCredentials(), user.getPassword());

    if (!accountLoginPolicy.isAllowed(user, req)) {
      logger.warn(
          "Login policy rejected authentication for "
              + user.getUsername()
              + ", "
              + user.getId()
              + ". Ignoring login request.");
      BadCredentialsException e =
          new BadCredentialsException("Login policy rejected authentication");
      publish(new AuthenticationFailureLockedEvent(req, e));
      throw e;
    }

    if (passwordMatches) {
      logger.debug("Password successfully matched");
      Authentication success =
          new UaaAuthentication(
              new UaaPrincipal(user),
              user.getAuthorities(),
              (UaaAuthenticationDetails) req.getDetails());
      publish(new UserAuthenticationSuccessEvent(user, success));

      return success;
    }

    if (user == dummyUser) {
      logger.debug("No user named '" + req.getName() + "' was found");
      publish(new UserNotFoundEvent(req));
    } else {
      logger.debug("Password did not match for user " + req.getName());
      publish(new UserAuthenticationFailureEvent(user, req));
    }
    BadCredentialsException e = new BadCredentialsException("Bad credentials");
    publish(new AuthenticationFailureBadCredentialsEvent(req, e));
    throw e;
  }
 @Override
 public String getCurrentUser() {
   try {
     Authentication auth = SecurityContextHolder.getContext().getAuthentication();
     if (auth.getName().equals("anonymousUser")) return null;
     return auth.getName();
   } catch (NullPointerException e) {
     return null;
   }
 }
  @RequestMapping(
      value = "/{id}",
      method = RequestMethod.PUT,
      consumes = MimeTypeUtils.APPLICATION_JSON_VALUE,
      produces = MimeTypeUtils.APPLICATION_JSON_VALUE)
  public String updateResourceSet(
      @PathVariable("id") Long id, @RequestBody String jsonString, Model m, Authentication auth) {
    ensureOAuthScope(auth, SystemScopeService.UMA_PROTECTION_SCOPE);

    ResourceSet newRs = parseResourceSet(jsonString);

    if (newRs == null // there was no resource set in the body
        || Strings.isNullOrEmpty(newRs.getName()) // there was no name (required)
        || newRs.getScopes() == null // there were no scopes (required)
        || newRs.getId() == null
        || !newRs.getId().equals(id) // the IDs didn't match
    ) {

      logger.warn("Resource set registration missing one or more required fields.");

      m.addAttribute(HttpCodeView.CODE, HttpStatus.BAD_REQUEST);
      m.addAttribute(
          JsonErrorView.ERROR_MESSAGE, "Resource request was missing one or more required fields.");
      return JsonErrorView.VIEWNAME;
    }

    ResourceSet rs = resourceSetService.getById(id);

    if (rs == null) {
      m.addAttribute(HttpCodeView.CODE, HttpStatus.NOT_FOUND);
      m.addAttribute(JsonErrorView.ERROR, "not_found");
      return JsonErrorView.VIEWNAME;
    } else {
      if (!auth.getName().equals(rs.getOwner())) {

        logger.warn(
            "Unauthorized resource set request from bad user; expected "
                + rs.getOwner()
                + " got "
                + auth.getName());

        // it wasn't issued to this user
        m.addAttribute(HttpCodeView.CODE, HttpStatus.FORBIDDEN);
        return JsonErrorView.VIEWNAME;
      } else {

        ResourceSet saved = resourceSetService.update(rs, newRs);

        m.addAttribute(JsonEntityView.ENTITY, saved);
        m.addAttribute(
            ResourceSetEntityAbbreviatedView.LOCATION, config.getIssuer() + URL + "/" + rs.getId());
        return ResourceSetEntityAbbreviatedView.VIEWNAME;
      }
    }
  }
  @RequestMapping(
      value = "/{id}",
      method = RequestMethod.DELETE,
      produces = MimeTypeUtils.APPLICATION_JSON_VALUE)
  public String deleteResourceSet(@PathVariable("id") Long id, Model m, Authentication auth) {
    ensureOAuthScope(auth, SystemScopeService.UMA_PROTECTION_SCOPE);

    ResourceSet rs = resourceSetService.getById(id);

    if (rs == null) {
      m.addAttribute(HttpCodeView.CODE, HttpStatus.NOT_FOUND);
      m.addAttribute(JsonErrorView.ERROR, "not_found");
      return JsonErrorView.VIEWNAME;
    } else {
      if (!auth.getName().equals(rs.getOwner())) {

        logger.warn(
            "Unauthorized resource set request from bad user; expected "
                + rs.getOwner()
                + " got "
                + auth.getName());

        // it wasn't issued to this user
        m.addAttribute(HttpCodeView.CODE, HttpStatus.FORBIDDEN);
        return JsonErrorView.VIEWNAME;
      } else if (auth instanceof OAuth2Authentication
          && !((OAuth2Authentication) auth)
              .getOAuth2Request()
              .getClientId()
              .equals(rs.getClientId())) {

        logger.warn(
            "Unauthorized resource set request from bad client; expected "
                + rs.getClientId()
                + " got "
                + ((OAuth2Authentication) auth).getOAuth2Request().getClientId());

        // it wasn't issued to this client
        m.addAttribute(HttpCodeView.CODE, HttpStatus.FORBIDDEN);
        return JsonErrorView.VIEWNAME;
      } else {

        // user and client matched
        resourceSetService.remove(rs);

        m.addAttribute(HttpCodeView.CODE, HttpStatus.NO_CONTENT);
        return HttpCodeView.VIEWNAME;
      }
    }
  }
 Authentication windowsAuthentication(final Authentication authentication) {
   String name = authentication.getName();
   String password = authentication.getCredentials().toString();
   WindowsAuthProviderImpl authenticationProvider = new WindowsAuthProviderImpl();
   IWindowsIdentity loggedOnUser = authenticationProvider.logonUser(name, password);
   return loggedOnUser.isGuest() ? getAuthentication(authentication) : null;
 }
Ejemplo n.º 12
0
  @RolesAllowed("ROLE_SAMPLE")
  public void logout() {
    final Authentication auth;

    auth = SecurityContextHolder.getContext().getAuthentication();
    log.info("Logout of user '" + auth.getName() + "'");
  }
  // 要不要PreApproval??
  @Override
  public AuthorizationRequest checkForPreApproval(
      AuthorizationRequest authorizationRequest, Authentication userAuthentication) {
    boolean approved = false;
    String clientId = authorizationRequest.getClientId();
    Set<String> scopes = authorizationRequest.getScope();

    OAuth2Request storedOAuth2Request = requestFactory.createOAuth2Request(authorizationRequest);

    OAuth2Authentication authentication =
        new OAuth2Authentication(storedOAuth2Request, userAuthentication);
    if (logger.isDebugEnabled()) {
      StringBuilder builder = new StringBuilder("Looking up existing token for ");
      builder.append("client_id=" + clientId);
      builder.append(", scope=" + scopes);
      builder.append(" and username="******"Existing access token=" + accessToken);
    if (accessToken != null && !accessToken.isExpired()) {
      logger.debug("User already approved with token=" + accessToken);
      approved = true;
    } else {
      logger.debug("Checking explicit approval");
      approved = userAuthentication.isAuthenticated() && approved;
    }

    authorizationRequest.setApproved(approved);
    return authorizationRequest;
  }
  @Override
  protected void onLoginSuccess(
      HttpServletRequest request,
      HttpServletResponse response,
      Authentication successfulAuthentication) {

    String login = successfulAuthentication.getName();

    log.debug("Creating new persistent login for user {}", login);
    PersistentToken token =
        userRepository
            .findOneByLogin(login)
            .map(
                u -> {
                  PersistentToken t = new PersistentToken();
                  t.setSeries(generateSeriesData());
                  t.setUser(u);
                  t.setTokenValue(generateTokenData());
                  t.setTokenDate(LocalDate.now());
                  t.setIpAddress(request.getRemoteAddr());
                  t.setUserAgent(request.getHeader("User-Agent"));
                  return t;
                })
            .orElseThrow(
                () ->
                    new UsernameNotFoundException(
                        "User " + login + " was not found in the database"));
    try {
      persistentTokenRepository.saveAndFlush(token);
      addCookie(token, request, response);
    } catch (DataAccessException e) {
      log.error("Failed to save persistent token ", e);
    }
  }
  @Override
  public UserDetails loadUserDetails(Authentication token) throws UsernameNotFoundException {
    ProfileUserDetails userDetails = null;
    String username = token.getName();
    String password = token.getCredentials().toString();

    try {
      String appToken =
          profileClient.getAppToken(crafterProfileAppUsername, crafterProfileAppPassword);
      // Tenant tenant = profileClient.getTenantByName(appToken, crafterProfileAppTenantName);
      // authenticate (if the user is inactive, this will also fail)
      profileClient.getTicket(appToken, username, password, crafterProfileAppTenantName);

      Profile profile =
          profileClient.getProfileByUsernameWithAllAttributes(
              appToken, username, crafterProfileAppTenantName);

      userDetails = new ProfileUserDetails(profile, getAuthorities(profile));

    } catch (AppAuthenticationFailedException e) {
      log.error("Error authenticating at app level=" + username);
      throw new BadCredentialsException("Error authenticating username="******"Error authenticating username="******"Error authenticating username=" + username, e);
    }

    return userDetails;
  }
  public Request init(Request request) {
    // see if we have an env map already parsed in the request
    Object obj = request.getKvp().get("env");
    Map<String, Object> envVars = null;
    if (obj instanceof Map) {
      envVars = (Map) obj;
    }

    // inject the current user in it
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    if (auth != null && !(auth instanceof AnonymousAuthenticationToken)) {
      String name = auth.getName();
      if (envVars == null) {
        envVars = new HashMap<String, Object>();
      }
      envVars.put("GSUSER", name);
    }

    // set it into the EnvFunction
    if (envVars != null) {
      EnvFunction.setLocalValues(envVars);
    }

    return request;
  }
  /**
   * Basic implementation just requires the authorization request to be explicitly approved and the
   * user to be authenticated.
   *
   * @param authorizationRequest The authorization request.
   * @param userAuthentication the current user authentication
   * @return Whether the specified request has been approved by the current user.
   */
  public boolean isApproved(
      AuthorizationRequest authorizationRequest, Authentication userAuthentication) {

    String flag = authorizationRequest.getApprovalParameters().get(approvalParameter);
    boolean approved = flag != null && flag.toLowerCase().equals("true");

    OAuth2Authentication authentication =
        new OAuth2Authentication(authorizationRequest, userAuthentication);
    if (logger.isDebugEnabled()) {
      StringBuilder builder = new StringBuilder("Looking up existing token for ");
      builder.append("client_id=" + authorizationRequest.getClientId());
      builder.append(", scope=" + authorizationRequest.getScope());
      builder.append(" and username="******"Existing access token=" + accessToken);
    if (accessToken != null && !accessToken.isExpired()) {
      logger.debug("User already approved with token=" + accessToken);
      // A token was already granted and is still valid, so this is already approved
      approved = true;
    } else {
      logger.debug("Checking explicit approval");
      approved = userAuthentication.isAuthenticated() && approved;
    }

    return approved;
  }
Ejemplo n.º 18
0
  @RequestMapping(
      value = {"/updateapplication/{id}"},
      method = {RequestMethod.POST})
  public ModelAndView updateapplication(
      @PathVariable Long id,
      @ModelAttribute("application") Application application,
      Model model,
      BindingResult bindingResult,
      HttpSession session,
      Authentication auth) {
    ModelAndView mav = new ModelAndView();
    Application application1 = mechanicService.getApplicationById(id);
    applicationValidator.validate(application, bindingResult);
    if (bindingResult.hasErrors()) {

      UserPrincipal user = userService.getUserByName(auth.getName());
      Number size1 = directorService.getSizeMechanicOnSto(application1.getSto());
      int size = Integer.parseInt(size1.toString());
      mav.addObject("application", application1);
      mav.addObject("statuss", directorService.getStatus());
      mav.addObject("mechanics", directorService.getMechanicsOnSto(application1.getSto(), 0, size));
      mav.addObject("user", user);
      mav.setViewName("director.updateapplication");
      return mav;
    }

    application1.setMechanic(application.getMechanic());
    application1.setStatus(application.getStatus());
    clientService.addOrUpdateApplication(application1);
    mav.setViewName("redirect:/home");
    return mav;
  }
Ejemplo n.º 19
0
  @PreAuthorize("isFullyAuthenticated()")
  @RequestMapping(value = "/getapplication", method = RequestMethod.GET)
  public ModelAndView getapplicationlist(
      @RequestParam(value = "page", required = false) Integer page,
      HttpSession session,
      Authentication auth) {
    ModelAndView mav = new ModelAndView();
    UserPrincipal user = userService.getUserByName(auth.getName());
    Status status = clientService.getStatusByName("zajavka ozhidaet obrabotku");
    if (page == null) page = 1;
    Integer pageSize = 3;
    Integer startPage = page;
    Integer endPage = page + 5;

    Number size1 = directorService.getSizeApplicationByStatus(status);
    int size = Integer.parseInt(size1.toString());

    Integer lastPage = (size + (pageSize - 1)) / pageSize;

    if (endPage >= lastPage) endPage = lastPage;
    if (endPage >= 5 && (endPage - startPage) < 5) startPage = endPage - 5;

    mav.addObject("page", page);
    mav.addObject("startpage", startPage);
    mav.addObject("endpage", endPage);

    mav.addObject("user", user);
    mav.addObject(
        "application",
        directorService.getApplicationByStatus(status, (page - 1) * pageSize, pageSize));
    mav.setViewName("director.applicationlist");
    return mav;
  };
Ejemplo n.º 20
0
  @Override
  public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    String name = authentication.getName();
    String password = authentication.getCredentials().toString();
    Authentication auth = null;

    Iterator<Shop> accounts =
        HibernateEntityHelper.all(Shop.class)
            .stream()
            .filter(a -> a.getLogin().equals(name))
            .iterator();

    while (accounts.hasNext()) {
      Shop account = accounts.next();
      Boolean check = false;
      try {
        check = PasswordHasher.validatePassword(password, account.getPasswordHash());
      } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
        // @TODO
        // Hoe vanuit hier een exception opvangen / communiceren naar gebruiker?
      }

      if (check) {
        List<GrantedAuthority> grantedAuths = new ArrayList();
        grantedAuths.add(new SimpleGrantedAuthority("ROLE_PHOTOGRAPHER"));
        auth = new UsernamePasswordAuthenticationToken(name, password, grantedAuths);
      }
    }

    return auth;
  }
Ejemplo n.º 21
0
  @RequestMapping(
      value = {"/updateapplicationdetail/{id}"},
      method = {RequestMethod.POST})
  public ModelAndView updateapplicationdetail(
      @PathVariable Long id,
      @ModelAttribute("applicationdetails") ApplicationDetail applicationDetail,
      BindingResult bindingResult,
      Model model,
      HttpSession session,
      Authentication auth) {
    ModelAndView mav = new ModelAndView();
    applicationDetailValidator.validate(applicationDetail, bindingResult);
    if (bindingResult.hasErrors()) {
      UserPrincipal user = userService.getUserByName(auth.getName());
      mav.addObject("statuss", directorService.getStatus());
      mav.addObject("applicationdetail", directorService.getApplicationDetailById(id));
      mav.addObject("user", user);
      mav.setViewName("director.updateapplicationdetail");
      return mav;
    }

    ApplicationDetail applicationDetail1 =
        directorService.getApplicationDetailById(applicationDetail.getId());
    applicationDetail1.setStatus(applicationDetail.getStatus());
    applicationDetail1.setDateDelivery(applicationDetail.getDateDelivery());
    // applicationDetail.setId(1l);
    directorService.saveApplicationDetail(applicationDetail1);
    mav.setViewName("redirect:/home");
    return mav;
  }
  @RequestMapping(method = RequestMethod.GET, produces = MimeTypeUtils.APPLICATION_JSON_VALUE)
  public String listResourceSets(Model m, Authentication auth) {
    ensureOAuthScope(auth, SystemScopeService.UMA_PROTECTION_SCOPE);

    String owner = auth.getName();

    Collection<ResourceSet> resourceSets = Collections.emptySet();
    if (auth instanceof OAuth2Authentication) {
      // if it's an OAuth mediated call, it's on behalf of a client, so look that up too
      OAuth2Authentication o2a = (OAuth2Authentication) auth;
      resourceSets =
          resourceSetService.getAllForOwnerAndClient(owner, o2a.getOAuth2Request().getClientId());
    } else {
      // otherwise get everything for the current user
      resourceSets = resourceSetService.getAllForOwner(owner);
    }

    // build the entity here and send to the display

    Set<String> ids = new HashSet<>();
    for (ResourceSet resourceSet : resourceSets) {
      ids.add(
          resourceSet
              .getId()
              .toString()); // add them all as strings so that gson renders them properly
    }

    m.addAttribute(JsonEntityView.ENTITY, ids);
    return JsonEntityView.VIEWNAME;
  }
Ejemplo n.º 23
0
  @PreAuthorize("isFullyAuthenticated()")
  @RequestMapping(value = "/mechaniclistbysto/{id}", method = RequestMethod.GET)
  public ModelAndView getmechaniclistbysto(
      @RequestParam(value = "page", required = false) Integer page,
      @PathVariable Long id,
      HttpSession session,
      Authentication auth) {
    ModelAndView mav = new ModelAndView();
    UserPrincipal user = userService.getUserByName(auth.getName());
    Sto sto = directorService.getStoById(id);
    Number size1 = directorService.getSizeMechanicOnSto(sto);
    int size = Integer.parseInt(size1.toString());
    System.out.println("Test test test" + sto.getName());
    if (page == null) page = 1;
    Integer pageSize = 3;
    Integer startPage = page;
    Integer endPage = page + 5;
    Integer lastPage = (size + (pageSize - 1)) / pageSize;

    if (endPage >= lastPage) endPage = lastPage;
    if (endPage >= 5 && (endPage - startPage) < 5) startPage = endPage - 5;

    mav.addObject("page", page);
    mav.addObject("startpage", startPage);
    mav.addObject("endpage", endPage);

    mav.addObject("user", user);
    mav.addObject(
        "mechanic", directorService.getMechanicsOnSto(sto, (page - 1) * pageSize, pageSize));
    mav.setViewName("director.mechaniclistbysto");
    return mav;
  };
Ejemplo n.º 24
0
  @PreAuthorize("isFullyAuthenticated()")
  @RequestMapping(value = "/getmechanics", method = RequestMethod.GET)
  public ModelAndView getmechaniclist(
      @RequestParam(value = "page", required = false) Integer page,
      HttpSession session,
      Authentication auth) {
    ModelAndView mav = new ModelAndView();
    UserPrincipal user = userService.getUserByName(auth.getName());
    if (page == null) page = 1;
    Integer pageSize = 4;
    Integer startPage = page;
    Integer endPage = page + 5;

    Number size1 = directorService.getSizeAllMechanic();
    int size = Integer.parseInt(size1.toString());

    Integer lastPage = (size + (pageSize - 1)) / pageSize;

    if (endPage >= lastPage) endPage = lastPage;
    if (endPage >= 5 && (endPage - startPage) < 5) startPage = endPage - 5;

    mav.addObject("page", page);
    mav.addObject("startpage", startPage);
    mav.addObject("endpage", endPage);

    mav.addObject("user", user);
    mav.addObject("mechanic", directorService.getMechanicsToPage((page - 1) * pageSize, pageSize));
    mav.setViewName("director.mechanicslist");
    return mav;
  };
Ejemplo n.º 25
0
  @RequestMapping(value = "/user", method = RequestMethod.PUT)
  @Transactional
  public ResponseEntity<Client> doIt(@RequestBody Client client, Authentication authentication) {

    List<String> errors = DomainValidator.checkForErrors(client);
    if (!errors.isEmpty()) {
      return new ResponseEntity<Client>(new Client(client, errors), HttpStatus.BAD_REQUEST);
    }
    HttpStatus status = null;

    List<GrantedAuthority> authorities = new ArrayList<>();
    authorities.add(new SimpleGrantedAuthority("USER"));

    if (ApplicationSecurity.isRoot(authentication)) {
      if (ApplicationSecurity.isRoot(client.getUsername())) {
        return new ResponseEntity<Client>(
            new Client(client, cannotChangeRootPassword), HttpStatus.BAD_REQUEST);
      }
      status = upsert(client, authorities);

    } else if (StringUtils.equals(client.getUsername(), authentication.getName())) {
      if (!userDetailsManager.userExists(client.getUsername())) {
        return new ResponseEntity<Client>(new Client(client, mustBeRoot), HttpStatus.BAD_REQUEST);
      }
      User user = new User(client.getUsername(), client.getPassword(), authorities);
      userDetailsManager.updateUser(user);
      status = HttpStatus.OK;

    } else {
      return new ResponseEntity<Client>(HttpStatus.FORBIDDEN);
    }

    return new ResponseEntity<Client>(new Client(client), status);
  }
Ejemplo n.º 26
0
 @Override
 public void onAuthenticationSuccess(
     HttpServletRequest request, HttpServletResponse response, Authentication auth)
     throws IOException, ServletException {
   response.setHeader("error", "0");
   response.getWriter().print("/MicroblogPL/userpage/" + auth.getName());
 }
Ejemplo n.º 27
0
  @RequestMapping(
      value = {"/updatesto/{id}"},
      method = {RequestMethod.POST})
  public ModelAndView updatesto(
      @PathVariable Long id,
      @ModelAttribute("sto") Sto sto,
      BindingResult bindingResult,
      Model model,
      HttpSession session,
      Authentication auth) {
    ModelAndView mav = new ModelAndView();
    rentValidator.validate(sto, bindingResult);
    if (bindingResult.hasErrors()) {
      logger.info("Returning updatesto.jsp page");
      UserPrincipal user = userService.getUserByName(auth.getName());
      mav.addObject("user", user);
      mav.addObject("sto", directorService.getStoById(id));
      mav.setViewName("director.updatesto");
      return mav;
    }

    Sto sto1 = directorService.getStoById(id);
    sto1.setName(sto.getName());
    sto1.setPrice(sto.getPrice());
    directorService.addSto(sto1);
    mav.setViewName("redirect:/home");
    return mav;
  }
Ejemplo n.º 28
0
  @RequestMapping(value = "/ajax_login_process", method = RequestMethod.POST)
  public HttpEntity<LoginStatus> loginAjax(
      @RequestParam("nick") final String username,
      @RequestParam("passwd") final String password,
      HttpServletRequest request,
      HttpServletResponse response) {
    UsernamePasswordAuthenticationToken token =
        new UsernamePasswordAuthenticationToken(username, password);
    try {
      UserDetailsImpl details = (UserDetailsImpl) userDetailsService.loadUserByUsername(username);
      token.setDetails(details);
      Authentication auth = authenticationManager.authenticate(token);
      UserDetailsImpl userDetails = (UserDetailsImpl) auth.getDetails();
      if (!userDetails.getUser().isActivated()) {
        return entity(new LoginStatus(false, "User not activated"));
      }
      SecurityContextHolder.getContext().setAuthentication(auth);
      rememberMeServices.loginSuccess(request, response, auth);
      AuthUtil.updateLastLogin(auth, userDao);

      return entity(new LoginStatus(auth.isAuthenticated(), auth.getName()));
    } catch (LockedException e) {
      return entity(new LoginStatus(false, "User locked"));
    } catch (UsernameNotFoundException e) {
      return entity(new LoginStatus(false, "Bad credentials"));
    } catch (BadCredentialsException e) {
      return entity(new LoginStatus(false, e.getMessage()));
    }
  }
Ejemplo n.º 29
0
  public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    String name = authentication.getName();
    String password = authentication.getCredentials().toString();

    User user = usersService.findByUserName(name);

    if (user == null) {
      throw new BadCredentialsException("Username not found");
    }

    if (!password.equals(user.getPassword())) {
      throw new BadCredentialsException("Wrong password");
    }

    List<UserRole> roles = usersService.getRoles(user);

    Collection<GrantedAuthorityImpl> impls = new ArrayList<GrantedAuthorityImpl>();

    for (UserRole ur : roles) impls.add(new GrantedAuthorityImpl(ur.getRole().getRolename()));

    UserDetails userDetails =
        new org.springframework.security.core.userdetails.User(name, password, impls);

    return new UsernamePasswordAuthenticationToken(userDetails, password, impls);
  }
Ejemplo n.º 30
0
 @RequestMapping(
     value = {"/addmechanic"},
     method = {RequestMethod.POST})
 public ModelAndView addmechanic(
     @ModelAttribute("mechanic") Mechanic mechanic,
     BindingResult bindingResult,
     Model model,
     HttpSession session,
     Authentication auth) {
   ModelAndView mav = new ModelAndView();
   mechanicValidator.validate(mechanic, bindingResult);
   if (bindingResult.hasErrors()) {
     UserPrincipal user = userService.getUserByName(auth.getName());
     mav.addObject("user", user);
     mav.addObject("stos", directorService.getSto());
     mav.setViewName("director.addmechanic");
     return mav;
   }
   mechanic.setLogin(mechanic.getName());
   mechanic.setRating((float) 0);
   mechanic.setRole(UserRole.MECHANIC);
   directorService.saveOrUpdateMechanic(mechanic);
   mav.setViewName("redirect:/home");
   return mav;
 }