Package com.erudika.para.core

Examples of com.erudika.para.core.User


    HttpServletResponse response = (HttpServletResponse) res;

    if (RestRequestMatcher.INSTANCE.matches(request)) {
      Authentication auth = SecurityContextHolder.getContext().getAuthentication();
      if (auth != null && auth.getPrincipal() instanceof User) {
        User u = SecurityUtils.getAuthenticatedUser();
        if (u == null || !u.getActive()) {
          RestUtils.returnStatusResponse(response, HttpServletResponse.SC_FORBIDDEN, "User is invalid.");
          return;
        }
      } else {
        String appid = RestUtils.extractAccessKey(request);
View Full Code Here


   * @see org.springframework.security.web.csrf.CsrfTokenRepository#saveToken(org.springframework.security.web.csrf.CsrfToken, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
   */
  public void saveToken(CsrfToken token, HttpServletRequest request,
      HttpServletResponse response) {
    if (token != null) {
      User u = SecurityUtils.getAuthenticatedUser();
      if (u != null && !cache.contains(Config.APP_NAME_NS, u.getIdentifier().concat(parameterName))) {
        if (Config.CACHE_ENABLED) {
          cache.put(Config.APP_NAME_NS, u.getIdentifier().concat(parameterName), token, Config.SESSION_TIMEOUT_SEC);
        } else {
          String key = Config.APP_NAME_NS.concat(u.getIdentifier()).concat(parameterName);
          localCache.put(key, new Object[]{token, System.currentTimeMillis()});
        }
      }
    }
  }
View Full Code Here

  @Override
  public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
      throws IOException {
    final String requestURI = request.getRequestURI();
    Authentication userAuth = null;
    User user = null;

    if (requestURI.endsWith(OPENID_ACTION)) {
      Authentication oidAuth = super.attemptAuthentication(request, response);

      if (oidAuth == null) {
        // hang on... redirecting to openid provider
        return null;
      } else {
        //success!
        user = (User) oidAuth.getPrincipal();
        userAuth = new UserAuthentication(user);
      }
    }

    if (userAuth == null || user == null || user.getIdentifier() == null) {
      throw new BadCredentialsException("Bad credentials.");
    } else if (!user.isEnabled()) {
      throw new LockedException("Account is locked.");
    }
    return userAuth;
  }
View Full Code Here

  @Override
  public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
      throws IOException {
    final String requestURI = request.getRequestURI();
    Authentication userAuth = null;
    User user = new User();

    if (requestURI.endsWith(GOOGLE_ACTION)) {
      String authCode = request.getParameter("code");
      if (!StringUtils.isBlank(authCode)) {
        String entity = Utils.formatMessage(PAYLOAD,
            URLEncoder.encode(authCode, "UTF-8"),
            URLEncoder.encode(request.getRequestURL().toString(), "UTF-8"),
            Config.GPLUS_APP_ID, Config.GPLUS_SECRET);

        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpPost tokenPost = new HttpPost(TOKEN_URL);
        tokenPost.setHeader(HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded");
        tokenPost.setEntity(new StringEntity(entity, "UTF-8"));
        CloseableHttpResponse resp1 = httpclient.execute(tokenPost);
        ObjectReader jreader = Utils.getJsonReader(Map.class);

        if (resp1 != null && resp1.getEntity() != null) {
          Map<String, Object> token = jreader.readValue(resp1.getEntity().getContent());
          if (token != null && token.containsKey("access_token")) {
            // got valid token
            HttpGet profileGet = new HttpGet(PROFILE_URL);
            profileGet.setHeader(HttpHeaders.AUTHORIZATION, "Bearer " + token.get("access_token"));
            CloseableHttpResponse resp2 = httpclient.execute(profileGet);
            HttpEntity respEntity = resp2.getEntity();
            String ctype = resp2.getFirstHeader(HttpHeaders.CONTENT_TYPE).getValue();

            if (respEntity != null && Utils.isJsonType(ctype)) {
              Map<String, Object> profile = jreader.readValue(resp2.getEntity().getContent());

              if (profile != null && profile.containsKey("sub")) {
                String googleSubId = (String) profile.get("sub");
                String pic = (String) profile.get("picture");
                String email = (String) profile.get("email");
                String name = (String) profile.get("name");

                user.setIdentifier(Config.GPLUS_PREFIX.concat(googleSubId));
                user = User.readUserForIdentifier(user);
                if (user == null) {
                  //user is new
                  user = new User();
                  user.setEmail(StringUtils.isBlank(email) ? "email@domain.com" : email);
                  user.setName(StringUtils.isBlank(name) ? "No Name" : name);
                  user.setPassword(new UUID().toString());
                  user.setIdentifier(Config.GPLUS_PREFIX.concat(googleSubId));
                  if (user.getPicture() == null) {
                    if (pic != null) {
                      if (pic.indexOf("?") > 0) {
                        // user picture migth contain size parameters - remove them
                        user.setPicture(pic.substring(0, pic.indexOf("?")));
                      } else {
                        user.setPicture(pic);
                      }
                    } else {
                      user.setPicture("http://www.gravatar.com/avatar?d=mm&size=200");
                    }
                  }

                  String id = user.create();
                  if (id == null) {
                    throw new AuthenticationServiceException("Authentication failed: cannot create new user.");
                  }
                }
                userAuth = new UserAuthentication(user);
              }
              EntityUtils.consumeQuietly(resp2.getEntity());
            }
            EntityUtils.consumeQuietly(resp1.getEntity());
          }
        }
      }
    }

    if (userAuth == null || user == null || user.getIdentifier() == null) {
      throw new BadCredentialsException("Bad credentials.");
    } else if (!user.isEnabled()) {
      throw new LockedException("Account is locked.");
    }
    return userAuth;
  }
View Full Code Here

  @Override
  public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
      throws IOException {
    final String requestURI = request.getRequestURI();
    Authentication userAuth = null;
    User user = new User();

    if (requestURI.endsWith(LINKEDIN_ACTION)) {
      String authCode = request.getParameter("code");
      if (!StringUtils.isBlank(authCode)) {
        String url = Utils.formatMessage(TOKEN_URL, authCode,
            request.getRequestURL().toString(), Config.LINKEDIN_APP_ID, Config.LINKEDIN_SECRET);

        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpPost tokenPost = new HttpPost(url);
        CloseableHttpResponse resp1 = httpclient.execute(tokenPost);
        ObjectReader jreader = Utils.getJsonReader(Map.class);

        if (resp1 != null && resp1.getEntity() != null) {
          Map<String, Object> token = jreader.readValue(resp1.getEntity().getContent());
          if (token != null && token.containsKey("access_token")) {
            // got valid token
            HttpGet profileGet = new HttpGet(PROFILE_URL + token.get("access_token"));
            CloseableHttpResponse resp2 = httpclient.execute(profileGet);
            HttpEntity respEntity = resp2.getEntity();
            String ctype = resp2.getFirstHeader(HttpHeaders.CONTENT_TYPE).getValue();

            if (respEntity != null && Utils.isJsonType(ctype)) {
              Map<String, Object> profile = jreader.readValue(resp2.getEntity().getContent());

              if (profile != null && profile.containsKey("id")) {
                String linkedInID = (String) profile.get("id");
                String email = (String) profile.get("emailAddress");
                String pic = (String) profile.get("pictureUrl");
                String fName = (String) profile.get("firstName");
                String lName = (String) profile.get("lastName");
                String name = fName + " " + lName;

                user.setIdentifier(Config.LINKEDIN_PREFIX.concat(linkedInID));
                user = User.readUserForIdentifier(user);
                if (user == null) {
                  //user is new
                  user = new User();
                  user.setEmail(StringUtils.isBlank(email) ? "email@domain.com" : email);
                  user.setName(StringUtils.isBlank(name) ? "No Name" : name);
                  user.setPassword(new UUID().toString());
                  user.setIdentifier(Config.LINKEDIN_PREFIX.concat(linkedInID));
                  if (user.getPicture() == null) {
                    if (pic != null) {
                      user.setPicture(pic);
                    } else {
                      user.setPicture("http://www.gravatar.com/avatar?d=mm&size=200");
                    }
                  }

                  String id = user.create();
                  if (id == null) {
                    throw new AuthenticationServiceException("Authentication failed: cannot create new user.");
                  }
                }
                userAuth = new UserAuthentication(user);
              }
              EntityUtils.consumeQuietly(resp2.getEntity());
            }
            EntityUtils.consumeQuietly(resp1.getEntity());
          }
        }
      }
    }

    if (userAuth == null || user == null || user.getIdentifier() == null) {
      throw new BadCredentialsException("Bad credentials.");
    } else if (!user.isEnabled()) {
      throw new LockedException("Account is locked.");
    }
    return userAuth;
  }
View Full Code Here

   * Loads a user from the data store.
   * @param ident the user identifier
   * @return a user object or null if user is not found
   */
  public UserDetails loadUserByUsername(String ident) {
    User user = new User();
    user.setIdentifier(ident);
    user = loadUser(user);

    if (user == null) {
      throw new UsernameNotFoundException(ident);
    }
View Full Code Here

  public UserDetails loadUserDetails(OpenIDAuthenticationToken token) {
    if (token == null) {
      return null;
    }

    User user = new User();
    user.setIdentifier(token.getIdentityUrl());
    user = loadUser(user);

    if (user == null) {
      // create new OpenID user
      String email = "email@domain.com";
      String firstName = null, lastName = null, fullName = null;
      List<OpenIDAttribute> attributes = token.getAttributes();

      for (OpenIDAttribute attribute : attributes) {
        if (attribute.getName().equals("email")) {
          email = attribute.getValues().get(0);
        }
        if (attribute.getName().equals("firstname")) {
          firstName = attribute.getValues().get(0);
        }
        if (attribute.getName().equals("lastname")) {
          lastName = attribute.getValues().get(0);
        }
        if (attribute.getName().equals("fullname")) {
          fullName = attribute.getValues().get(0);
        }
      }

      if (fullName == null) {
        if (firstName == null) {
          firstName = "No";
        }
        if (lastName == null) {
          lastName = "Name";
        }
        fullName = firstName.concat(" ").concat(lastName);
      }

      user = new User();
      user.setEmail(email);
      user.setName(fullName);
      user.setPassword(new UUID().toString());
      user.setIdentifier(token.getIdentityUrl());
      if (user.getPicture() == null) {
        if (email != null) {
          String emailHash = DigestUtils.md5DigestAsHex(email.getBytes());
          user.setPicture("http://www.gravatar.com/avatar/" + emailHash + "?size=200&d=mm&r=pg");
        } else {
          user.setPicture("http://www.gravatar.com/avatar?d=mm&size=200");
        }
      }
      String id = user.create();
      if (id == null) {
        throw new BadCredentialsException("Authentication failed: cannot create new user.");
      }
    }
View Full Code Here

  /**
   * Extracts a User object from the security context
   * @return an authenticated user or null if a user is not authenticated
   */
  public static User getAuthenticatedUser() {
    User u = null;
    if (SecurityContextHolder.getContext().getAuthentication() != null) {
      Authentication auth = SecurityContextHolder.getContext().getAuthentication();
      if (auth.isAuthenticated() && auth.getPrincipal() instanceof User) {
        u = (User) auth.getPrincipal();
      }
View Full Code Here

  @SuppressWarnings("unchecked")
  public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
      throws IOException {
    final String requestURI = request.getRequestURI();
    Authentication userAuth = null;
    User user = new User();

    if (requestURI.endsWith(FACEBOOK_ACTION)) {
      String authCode = request.getParameter("code");
      if (!StringUtils.isBlank(authCode)) {
        String url = Utils.formatMessage(TOKEN_URL, authCode,
            request.getRequestURL().toString(), Config.FB_APP_ID, Config.FB_SECRET);

        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpGet tokenPost = new HttpGet(url);
        CloseableHttpResponse resp1 = httpclient.execute(tokenPost);
        ObjectReader jreader = Utils.getJsonReader(Map.class);

        if (resp1 != null && resp1.getEntity() != null) {
          String token = EntityUtils.toString(resp1.getEntity(), Config.DEFAULT_ENCODING);
          if (token != null && token.startsWith("access_token")) {
            // got valid token
            String accessToken = token.substring(token.indexOf("=") + 1, token.indexOf("&"));
            HttpGet profileGet = new HttpGet(PROFILE_URL + accessToken);
            CloseableHttpResponse resp2 = httpclient.execute(profileGet);
            HttpEntity respEntity = resp2.getEntity();
            String ctype = resp2.getFirstHeader(HttpHeaders.CONTENT_TYPE).getValue();

            if (respEntity != null && Utils.isJsonType(ctype)) {
              Map<String, Object> profile = jreader.readValue(resp2.getEntity().getContent());

              if (profile != null && profile.containsKey("id")) {
                String fbId = (String) profile.get("id");
                Map<String, Object> pic = (Map<String, Object>) profile.get("picture");
                String email = (String) profile.get("email");
                String name = (String) profile.get("name");

                user.setIdentifier(Config.FB_PREFIX.concat(fbId));
                user = User.readUserForIdentifier(user);
                if (user == null) {
                  //user is new
                  user = new User();
                  user.setEmail(StringUtils.isBlank(email) ? "email@domain.com" : email);
                  user.setName(StringUtils.isBlank(name) ? "No Name" : name);
                  user.setPassword(new UUID().toString());
                  user.setIdentifier(Config.FB_PREFIX.concat(fbId));
                  if (user.getPicture() == null && pic != null) {
                    Map<String, Object> data = (Map<String, Object>) pic.get("data");
                    // try to get the direct url to the profile pic
                    if (data != null && data.containsKey("url")) {
                      user.setPicture((String) data.get("url"));
                    } else {
                      user.setPicture("http://graph.facebook.com/" + fbId +
                          "/picture?width=400&height=400&type=square");
                    }
                  }

                  String id = user.create();
                  if (id == null) {
                    throw new AuthenticationServiceException("Authentication failed: cannot create new user.");
                  }
                }
                userAuth = new UserAuthentication(user);
              }
              EntityUtils.consumeQuietly(resp2.getEntity());
            }
            EntityUtils.consumeQuietly(resp1.getEntity());
          }
        }
      }
    }

    if (userAuth == null || user == null || user.getIdentifier() == null) {
      throw new BadCredentialsException("Bad credentials.");
    } else if (!user.isEnabled()) {
      throw new LockedException("Account is locked.");
    }
    return userAuth;
  }
View Full Code Here

   * @see org.springframework.security.web.csrf.CsrfTokenRepository#saveToken(org.springframework.security.web.csrf.CsrfToken, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
   */
  public void saveToken(CsrfToken token, HttpServletRequest request,
      HttpServletResponse response) {
    if (token != null) {
      User u = SecurityUtils.getAuthenticatedUser();
      if (u != null && !cache.contains(Config.APP_NAME_NS, u.getIdentifier().concat(parameterName))) {
        cache.put(Config.APP_NAME_NS, u.getIdentifier().concat(parameterName), token, Config.SESSION_TIMEOUT_SEC);
      }
    }
  }
View Full Code Here

TOP

Related Classes of com.erudika.para.core.User

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.