com.google.appengine.api.users.UserServiceFactory Java Examples

The following examples show how to use com.google.appengine.api.users.UserServiceFactory. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: AppEngineAuthenticationTest.java    From appengine-java-vm-runtime with Apache License 2.0 6 votes vote down vote up
public void testAdminRequired_NoUser() throws Exception {
  String path = "/admin/blah";
  Request request = spy(new Request(null, null));
  //request.setServerPort(9999);
  HttpURI uri  =new HttpURI("http", SERVER_NAME,9999, path);
  HttpFields httpf = new HttpFields();
  MetaData.Request metadata = new MetaData.Request("GET", uri, HttpVersion.HTTP_2, httpf);
  request.setMetaData(metadata);
//  request.setAuthority(SERVER_NAME,9999);
  Response response = mock(Response.class);
  String output = runRequest(path, request, response);
  // Verify that the servlet never was run (there is no output).
  assertEquals("", output);
  // Verify that the request was redirected to the login url.
  String loginUrl = UserServiceFactory.getUserService()
      .createLoginURL(String.format("http://%s%s", SERVER_NAME + ":9999", path));
  verify(response).sendRedirect(loginUrl);
}
 
Example #2
Source File: UsersServlet.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
  UserService userService = UserServiceFactory.getUserService();

  String thisUrl = req.getRequestURI();

  resp.setContentType("text/html");
  if (req.getUserPrincipal() != null) {
    resp.getWriter()
        .println(
            "<p>Hello, "
                + req.getUserPrincipal().getName()
                + "!  You can <a href=\""
                + userService.createLogoutURL(thisUrl)
                + "\">sign out</a>.</p>");
  } else {
    resp.getWriter()
        .println(
            "<p>Please <a href=\"" + userService.createLoginURL(thisUrl) + "\">sign in</a>.</p>");
  }
}
 
Example #3
Source File: SignGuestbookServlet.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
  Greeting greeting;

  UserService userService = UserServiceFactory.getUserService();
  User user = userService.getCurrentUser(); // Find out who the user is.

  String guestbookName = req.getParameter("guestbookName");
  String content = req.getParameter("content");
  if (user != null) {
    greeting = new Greeting(guestbookName, content, user.getUserId(), user.getEmail());
  } else {
    greeting = new Greeting(guestbookName, content);
  }

  // Use Objectify to save the greeting and now() is used to make the call synchronously as we
  // will immediately get a new page using redirect and we want the data to be present.
  ObjectifyService.ofy().save().entity(greeting).now();

  resp.sendRedirect("/guestbook.jsp?guestbookName=" + guestbookName);
}
 
Example #4
Source File: LogoutFilter.java    From getting-started-java with Apache License 2.0 6 votes vote down vote up
@Override
public void doFilter(ServletRequest servletReq, ServletResponse servletResp, FilterChain chain)
    throws IOException, ServletException {
  HttpServletRequest req = (HttpServletRequest) servletReq;
  HttpServletResponse resp = (HttpServletResponse) servletResp;
  String path = req.getRequestURI();

  chain.doFilter(servletReq, servletResp);

  UserService userService = UserServiceFactory.getUserService();
  if (userService.isUserLoggedIn()) {
    resp.sendRedirect(userService.createLogoutURL("/logout"));
  } else if (path.startsWith("/logout")) {
    resp.sendRedirect("/books");
  }
}
 
Example #5
Source File: LoginServlet.java    From getting-started-java with Apache License 2.0 6 votes vote down vote up
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
    throws IOException, ServletException {

  UserService userService = UserServiceFactory.getUserService();
  if (userService.isUserLoggedIn()) {
    // Save the relevant profile info and store it in the session.
    User user = userService.getCurrentUser();
    req.getSession().setAttribute("userEmail", user.getEmail());
    req.getSession().setAttribute("userId", user.getUserId());

    String destination = (String) req.getSession().getAttribute("loginDestination");
    if (destination == null) {
      destination = "/books";
    }

    logger.log(Level.INFO, "logging destination " + destination);
    resp.sendRedirect(destination);
  } else {
    resp.sendRedirect(userService.createLoginURL("/login"));
    logger.log(Level.INFO, "logging destination /login");
  }
}
 
Example #6
Source File: ListByUserFilter.java    From getting-started-java with Apache License 2.0 6 votes vote down vote up
@Override
public void doFilter(ServletRequest servletReq, ServletResponse servletResp, FilterChain chain)
    throws IOException, ServletException {
  HttpServletRequest req = (HttpServletRequest) servletReq;
  HttpServletResponse resp = (HttpServletResponse) servletResp;

  // [START logStuff]
  String instanceId = System.getenv().containsKey("GAE_MODULE_INSTANCE")
      ? System.getenv("GAE_MODULE_INSTANCE") : "-1";
  logger.log(
      Level.INFO,
      "ListByUserFilter processing new request for path: " + req.getRequestURI()
      + " and instance: " + instanceId);
  // [END logStuff]

  UserService userService = UserServiceFactory.getUserService();
  if (userService.isUserLoggedIn()) {
    chain.doFilter(servletReq, servletResp);
  } else {
    logger.log(Level.INFO, "Not logged in, setting loginDestination to /books/mine");
    req.getSession().setAttribute("loginDestination", "/books/mine");
    resp.sendRedirect(userService.createLoginURL("/login"));
  }
}
 
Example #7
Source File: LogoutFilter.java    From getting-started-java with Apache License 2.0 6 votes vote down vote up
@Override
public void doFilter(ServletRequest servletReq, ServletResponse servletResp, FilterChain chain)
    throws IOException, ServletException {
  HttpServletRequest req = (HttpServletRequest) servletReq;
  HttpServletResponse resp = (HttpServletResponse) servletResp;
  String path = req.getRequestURI();

  chain.doFilter(servletReq, servletResp);

  UserService userService = UserServiceFactory.getUserService();
  if (userService.isUserLoggedIn()) {
    resp.sendRedirect(userService.createLogoutURL("/logout"));
  } else if (path.startsWith("/logout")) {
    resp.sendRedirect("/books");
  }
}
 
Example #8
Source File: GuestbookResource.java    From appengine-angular-guestbook-java with Apache License 2.0 6 votes vote down vote up
@POST
@Path("/{guestbookName}")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public GuestbookResponse signGuestbook(
    @DefaultValue("default") @PathParam("guestbookName") final String guestbookName,
    final Map<String, String> postData) {
  UserService userService = UserServiceFactory.getUserService();
  DatastoreService datastoreService = DatastoreServiceFactory.getDatastoreService();
  Key guestbookKey = KeyFactory.createKey("Guestbook", guestbookName);
  // We set the above parent key on each Greeting entity in order to make the queries strong
  // consistent. Please Note that as a trade off, we can not write to a single guestbook at a
  // rate more than 1 write/second.
  String content = postData.get("content");
  if (content != null && content.length() > 0) {
    Date date = new Date();
    Entity greeting = new Entity("Greeting", guestbookKey);
    greeting.setProperty("user", userService.getCurrentUser());
    greeting.setProperty("date", date);
    greeting.setProperty("content", content);
    datastoreService.put(greeting);
  }
  return new GuestbookResponse(guestbookName, getGreetings(guestbookName), null);
}
 
Example #9
Source File: SignGuestbookServlet.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
  Greeting greeting;

  UserService userService = UserServiceFactory.getUserService();
  User user = userService.getCurrentUser(); // Find out who the user is.

  String guestbookName = req.getParameter("guestbookName");
  String content = req.getParameter("content");
  if (user != null) {
    greeting = new Greeting(guestbookName, content, user.getUserId(), user.getEmail());
  } else {
    greeting = new Greeting(guestbookName, content);
  }

  greeting.save();

  resp.sendRedirect("/guestbook.jsp?guestbookName=" + guestbookName);
}
 
Example #10
Source File: UserServiceServlet.java    From appengine-tck with Apache License 2.0 6 votes vote down vote up
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    userService = UserServiceFactory.getUserService();
    user = userService.getCurrentUser();
    String env = SystemProperty.environment.value().toString();
    String responseMsg = env + ",";

    String method = req.getParameter("method");

    if (method == null) {
        resp.getWriter().print(responseMsg + "Error: Must set method parameter.");
        return;
    }

    if (method.equals("env")) {
        responseMsg += env;
        resp.getWriter().print(responseMsg);
        return;
    }

    responseMsg += callMethod(method);
    resp.getWriter().print(responseMsg);
}
 
Example #11
Source File: MoveServlet.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
  String gameId = request.getParameter("gameKey");
  Objectify ofy = ObjectifyService.ofy();
  Game game = ofy.load().type(Game.class).id(gameId).safe();

  UserService userService = UserServiceFactory.getUserService();
  String currentUserId = userService.getCurrentUser().getUserId();

  int cell = new Integer(request.getParameter("cell"));
  if (!game.makeMove(cell, currentUserId)) {
    response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
  } else {
    ofy.save().entity(game).now();
  }
}
 
Example #12
Source File: LogoutServlet.java    From appinventor-extensions with Apache License 2.0 6 votes vote down vote up
@Override
  public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException {
//    req.getSession().invalidate();
    Cookie cookie = new Cookie("AppInventor", null);
    cookie.setPath("/");
    cookie.setMaxAge(0);        // This should cause it to be tossed immediately
    res.addCookie(cookie);

    // The code below is how you logout of Google. We have commented it out
    // here because in LoginServlet.java we are now destroying the ACSID Cookie
    // which effectively logs you out from Google's point of view, without effecting
    // other Google Systems that the user might be using.

    // Note: The code below will logout you out of ALL Google services
    // (which can be pretty annoying
    if (useGoogle.get() == true) {
      res.sendRedirect(UserServiceFactory.getUserService().createLogoutURL("/"));
      res.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
    } else {
      res.sendRedirect("/");
    }
  }
 
Example #13
Source File: UserServiceTest.java    From appengine-tck with Apache License 2.0 6 votes vote down vote up
@Test
public void testCreateLoginUrlDomainProd() throws Exception {
    assumeEnvironment(Environment.APPSPOT);

    String start = "https://www.google.com/accounts/ServiceLogin?service=ah";
    String authDomain = "othergaetcktest.org";
    String createdURL = UserServiceFactory.getUserService().createLoginURL(DEST_URL, authDomain);

    // TODO: verify how to check for the authDomain.

    String failMsgStartsWith = "Prod url should start with: " + start + " but was: " + createdURL;
    Assert.assertTrue(failMsgStartsWith, createdURL.startsWith(start));

    String failMsgContains = "Prod url should contain: " + DEST_URL_ENCODED_DOUBLE + " but was: " + createdURL;
    Assert.assertTrue(failMsgContains, createdURL.contains(DEST_URL_ENCODED_DOUBLE));
}
 
Example #14
Source File: AppEngineAuthenticationTest.java    From appengine-java-vm-runtime with Apache License 2.0 6 votes vote down vote up
public void testUserRequired_NoUser() throws Exception {
  String path = "/user/blah";
  Request request = spy(new Request(null, null));
  //request.setServerPort(9999);
      HttpURI uri  =new HttpURI("http", SERVER_NAME,9999, path);
  HttpFields httpf = new HttpFields();
  MetaData.Request metadata = new MetaData.Request("GET", uri, HttpVersion.HTTP_2, httpf);
  request.setMetaData(metadata);
 // request.setAuthority(SERVER_NAME,9999);
  Response response = mock(Response.class);
  String output = runRequest(path, request, response);
  // Verify that the servlet never was run (there is no output).
  assertEquals("", output);
  // Verify that the request was redirected to the login url.
  String loginUrl = UserServiceFactory.getUserService()
      .createLoginURL(String.format("http://%s%s", SERVER_NAME + ":9999", path));
  verify(response).sendRedirect(loginUrl);
}
 
Example #15
Source File: AdminServiceImpl.java    From sc2gears with Apache License 2.0 6 votes vote down vote up
@Override
public RpcResult< List< MiscFunctionInfo > > getMiscFunctionInfoList() {
	LOGGER.fine( "" );
	
	final UserService userService = UserServiceFactory.getUserService();
	final User user = userService.getCurrentUser();
	if ( user == null )
		return RpcResult.createNotLoggedInErrorResult();
	if ( !userService.isUserAdmin() )
		return RpcResult.createNoPermissionErrorResult();
	
	final List< MiscFunctionInfo > miscFunctionInfoList = new ArrayList< MiscFunctionInfo >( miscFunctionMap.size() );
	
	for ( final Entry< String, DatastoreTask > entry : miscFunctionMap.entrySet() )
		miscFunctionInfoList.add( new MiscFunctionInfo( entry.getKey(), entry.getValue().getParamNames() ) );
	
	Collections.sort( miscFunctionInfoList, new Comparator< MiscFunctionInfo >() {
		@Override
           public int compare( final MiscFunctionInfo i1, final MiscFunctionInfo i2 ) {
            return i1.getName().compareTo( i2.getName() );
           }
	} );
	
	return new RpcResult< List< MiscFunctionInfo > >( miscFunctionInfoList );
}
 
Example #16
Source File: SignGuestbookServlet.java    From appengine-modules-sample-java with Apache License 2.0 6 votes vote down vote up
@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp)
    throws IOException {
  final UserService userService = UserServiceFactory.getUserService();
  final User user = userService.getCurrentUser();

  final String guestbookName = req.getParameter("guestbookName");
  final Key guestbookKey = KeyFactory.createKey("Guestbook", guestbookName);
  final String content = req.getParameter("content");
  final Date date = new Date();
  final Entity greeting = new Entity("Greeting", guestbookKey);
  greeting.setProperty("user", user);
  greeting.setProperty("date", date);
  greeting.setProperty("content", content);

  final DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
  datastore.put(greeting);

  resp.sendRedirect("/guestbook.jsp?guestbookName=" + guestbookName);
}
 
Example #17
Source File: GuestbookServlet.java    From appengine-java-guestbook-multiphase with Apache License 2.0 6 votes vote down vote up
@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp)
    throws IOException {
  if (req.getParameter("testing") != null) {
    resp.setContentType("text/plain");
    resp.getWriter().println("Hello, this is a testing servlet. \n\n");
    Properties p = System.getProperties();
    p.list(resp.getWriter());

  } else {
    UserService userService = UserServiceFactory.getUserService();
    User currentUser = userService.getCurrentUser();

    if (currentUser != null) {
      resp.setContentType("text/plain");
      resp.getWriter().println("Hello, " + currentUser.getNickname());
    } else {
      resp.sendRedirect(userService.createLoginURL(req.getRequestURI()));
    }
  }
}
 
Example #18
Source File: UserServiceTest.java    From appengine-tck with Apache License 2.0 6 votes vote down vote up
@Test
public void testCreateLoginUrlFederatedNotSetProd() throws Exception {
    assumeEnvironment(Environment.APPSPOT);

    // Assuming Authentication Type set to Google Accounts, so org should be blank.
    String userOrg = ApiProxy.getCurrentEnvironment()
        .getAttributes()
        .get("com.google.appengine.api.users.UserService.user_organization").toString();
    Assert.assertEquals("", userOrg);

    String authDomain = "othergaetcktest.org";
    String federatedIdentity = "FedIdentTest";
    Set<String> attrRequest = new HashSet<>();

    // throws IllegalArgumentException since not set to Federated Identity.
    Exception thrownException = null;
    try {
        UserServiceFactory.getUserService().createLoginURL(DEST_URL, authDomain, federatedIdentity, attrRequest);
    } catch (Exception e) {
        thrownException = e;
    }
    // Testing exception like this since we cannot use the junit annotation in this case.
    Assert.assertEquals(IllegalArgumentException.class, thrownException.getClass());

}
 
Example #19
Source File: UserServiceImpl.java    From sc2gears with Apache License 2.0 5 votes vote down vote up
@Override
public RpcResult< Void > saveReplayComment( final String sharedAccount, final String sha1, final String comment ) {
	LOGGER.fine( ( sharedAccount == null ? "" : "Shared account: " + sharedAccount + ", " ) + "sha1: " + sha1 );
	
	final UserService userService = UserServiceFactory.getUserService();
	final User user = userService.getCurrentUser();
	if ( user == null )
		return RpcResult.createNotLoggedInErrorResult();
	
	PersistenceManager pm = null;
	try {
		
		pm = PMF.get().getPersistenceManager();
		
		final Key accountKey = ServerUtils.getAccountKey( pm, sharedAccount, user, Permission.VIEW_UPDATE_REP_COMMENTS );
		if ( accountKey == null )
			return RpcResult.createNoPermissionErrorResult();
		
		final List< Rep > replayList = new JQBuilder<>( pm, Rep.class ).filter( "ownerk==p1 && sha1==p2", "KEY p1, String p2" ).get( accountKey, sha1 );
		if ( replayList.isEmpty() )
			return RpcResult.createNoPermissionErrorResult();
		
		final Rep replay = replayList.get( 0 );
		replay.setComment( comment == null || comment.isEmpty() ? null : InfoServletApi.trimPrivateRepComment( comment ) );
		
	} finally {
		if ( pm != null )
			pm.close();
	}
	
	return RpcResult.createInfoResult( "Comment saved." );
}
 
Example #20
Source File: UserServiceImpl.java    From sc2gears with Apache License 2.0 5 votes vote down vote up
@Override
public RpcResult< List< String > > saveLabelNames( final String sharedAccount, final List< String > labelNames ) {
	LOGGER.fine( sharedAccount == null ? "" : "Shared account: " + sharedAccount );
	
	final UserService userService = UserServiceFactory.getUserService();
	final User user = userService.getCurrentUser();
	if ( user == null )
		return RpcResult.createNotLoggedInErrorResult();
	
	PersistenceManager pm = null;
	try {
		
		pm = PMF.get().getPersistenceManager();
		
		final Account account = ServerUtils.getAccount( pm, sharedAccount, user );
		if ( account == null )
			return RpcResult.createNoPermissionErrorResult();
		if ( sharedAccount != null && !account.isPermissionGranted( user, Permission.RENAME_LABELS ) )
			return RpcResult.createNoPermissionErrorResult();
		
		// Restore default names for empty strings
		final List< String > checkedNames = new ArrayList< String >( Consts.DEFAULT_REPLAY_LABEL_LIST.size() );
		for ( int i = 0; i < Consts.DEFAULT_REPLAY_LABEL_LIST.size(); i++ )
			checkedNames.add( i >= labelNames.size() || Consts.DEFAULT_REPLAY_LABEL_LIST.get( i ).equals( labelNames.get( i ) ) ? "" : ServletApi.trimStringLength( labelNames.get( i ), 500 ) );
		
		account.setLabelNames( checkedNames );
		
		final RpcResult< List< String > > rpcResult = new RpcResult< List< String > >( ServerUtils.getLabelNames( account ) );
		rpcResult.setInfoMsg( "Label names saved." );
		
		return rpcResult;
		
	} finally {
		if ( pm != null )
			pm.close();
	}
}
 
Example #21
Source File: UserServiceImpl.java    From sc2gears with Apache License 2.0 5 votes vote down vote up
@Override
public RpcResult< Void > saveReplayLabels( final String sharedAccount, final String sha1, final List< Integer > labels ) {
	LOGGER.fine( ( sharedAccount == null ? "" : "Shared account: " + sharedAccount + ", " ) + "sha1: " + sha1 );
	
	final UserService userService = UserServiceFactory.getUserService();
	final User user = userService.getCurrentUser();
	if ( user == null )
		return RpcResult.createNotLoggedInErrorResult();
	
	PersistenceManager pm = null;
	try {
		
		pm = PMF.get().getPersistenceManager();
		
		final Key accountKey = ServerUtils.getAccountKey( pm, sharedAccount, user, Permission.CHANGE_REP_LABELS );
		if ( accountKey == null )
			return RpcResult.createNoPermissionErrorResult();
		
		final List< Rep > replayList = new JQBuilder<>( pm, Rep.class ).filter( "ownerk==p1 && sha1==p2", "KEY p1, String p2" ).get( accountKey, sha1 );
		if ( replayList.isEmpty() )
			return RpcResult.createNoPermissionErrorResult();
		
		final Rep replay = replayList.get( 0 );
		replay.setLabels( labels );
		
	} finally {
		if ( pm != null )
			pm.close();
	}
	
	return RpcResult.createInfoResult( "Labels saved." );
}
 
Example #22
Source File: AppEngineServletUtils.java    From google-oauth-java-client with Apache License 2.0 5 votes vote down vote up
/**
 * Return the user id for the currently logged in user.
 */
static final String getUserId() {
  UserService userService = UserServiceFactory.getUserService();
  User loggedIn = userService.getCurrentUser();
  Preconditions.checkState(loggedIn != null, "This servlet requires the user to be logged in.");
  return loggedIn.getUserId();
}
 
Example #23
Source File: AppContext.java    From solutions-photo-sharing-demo-java with Apache License 2.0 5 votes vote down vote up
public DemoUser getCurrentUser() {
  DemoUserManager demoUserManager = entityManagerFactory.getDemoUserManager();
  User user = UserServiceFactory.getUserService().getCurrentUser();
  DemoUser demoUser = demoUserManager.getUser(user.getUserId());
  if (demoUser == null) {
    demoUser = demoUserManager.newUser(user.getUserId());
    demoUser.setEmail(user.getEmail());
    demoUser.setNickname(user.getNickname());
    demoUserManager.upsertEntity(demoUser);
  }
  return demoUser;
}
 
Example #24
Source File: ApiUserServiceImpl.java    From sc2gears with Apache License 2.0 5 votes vote down vote up
@Override
public RpcResult< Void > saveSettings( final String sharedApiAccount, final SettingsInfo settingsInfo ) {
	LOGGER.fine( "sharedApiAccount: " + sharedApiAccount );
	
	final UserService userService = UserServiceFactory.getUserService();
	final User user = userService.getCurrentUser();
	if ( user == null )
		return RpcResult.createNotLoggedInErrorResult();
	
	PersistenceManager pm = null;
	try {
		
		pm = PMF.get().getPersistenceManager();
		
		final ApiAccount apiAccount = getApiAccount( pm, sharedApiAccount, user );
		if ( apiAccount == null )
			return RpcResult.createNoPermissionErrorResult();
		
		if ( settingsInfo.getContactEmail() != null && !settingsInfo.getContactEmail().isEmpty() )
			if ( !ServerUtils.isEmailValid( settingsInfo.getContactEmail() ) )
				return RpcResult.createErrorResult( "Invalid contact email!" );
		
		if ( settingsInfo.getNotificationAvailOps() < 0 )
			return RpcResult.createErrorResult( "Invalid notification available ops! (Must be equal to or greater than 0!)" );
		
		apiAccount.setContactEmail        ( settingsInfo.getContactEmail() == null || settingsInfo.getContactEmail().isEmpty() ? null : ServletApi.trimStringLength( settingsInfo.getContactEmail(), 500 ) );
		apiAccount.setName                ( settingsInfo.getUserName    () == null || settingsInfo.getUserName    ().isEmpty() ? null : ServletApi.trimStringLength( settingsInfo.getUserName    (), 500 ) );
		apiAccount.setNotificationAvailOps( settingsInfo.getNotificationAvailOps() );
		
	} finally {
		if ( pm != null )
			pm.close();
	}
	
	return RpcResult.createInfoResult( "Settings saved successfully." );
}
 
Example #25
Source File: UserTest.java    From appengine-tck with Apache License 2.0 5 votes vote down vote up
@Test
@UserIsLoggedIn(email = "${user.login.email:${appengine.userId:[email protected]}}", isAdmin = true)
public void testLoggedAdmin() {
    UserService service = UserServiceFactory.getUserService();
    User user = service.getCurrentUser();
    assertNotNull(user);
    assertTrue(service.isUserAdmin());
}
 
Example #26
Source File: AppEngineAuthentication.java    From appengine-java-vm-runtime with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new AppEngineUserIdentity based on information retrieved from the Users API.
 *
 * @return A AppEngineUserIdentity if a user is logged in, or null otherwise.
 */
private AppEngineUserIdentity loadUser() {
  UserService userService = UserServiceFactory.getUserService();
  User engineUser = userService.getCurrentUser();
  if (engineUser == null){
    return null;
  }
  return new AppEngineUserIdentity(new AppEnginePrincipal(engineUser));
}
 
Example #27
Source File: UserServiceTest.java    From appengine-tck with Apache License 2.0 5 votes vote down vote up
@Test
public void testCreateLogoutUrlProd() throws Exception {
    assumeEnvironment(Environment.APPSPOT);

    String contains1 = "https://www.google.com/accounts/Logout";
    String createdURL = UserServiceFactory.getUserService().createLogoutURL(DEST_URL);

    String failMsgContains1 = "Prod url should contain: " + contains1 + " but was: " + createdURL;
    Assert.assertTrue(failMsgContains1, createdURL.contains(contains1));

    String failMsgContains2 = "Prod url should contain: " + DEST_URL_ENCODED_TRIPLE + " but was: " + createdURL;
    Assert.assertTrue(failMsgContains2, createdURL.contains(DEST_URL_ENCODED_TRIPLE));
}
 
Example #28
Source File: LoginServlet.java    From appengine-java-vm-runtime with Apache License 2.0 5 votes vote down vote up
public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException {
  res.setContentType("text/html");
  res.getWriter().println("<html>");
  res.getWriter().println("<head>");
  res.getWriter().println("<title>whoami</title>");
  res.getWriter().println("</head>");
  res.getWriter().println("<body>");

  UserService userService = UserServiceFactory.getUserService();

  if (userService.isUserLoggedIn()) {
    User user = userService.getCurrentUser();

    res.getWriter().println("<h1>You are " + user.getNickname() + ".</h1>");

    if (userService.isUserAdmin()) {
      res.getWriter().println("<h2>You are an admin! :)</h2>");
    } else {
      res.getWriter().println("<h2>You are not an admin... :(</h2>");
    }

    res.getWriter().println("<h1>Your user ID is " + user.getUserId() + ".</h1>");
  } else {
    res.getWriter().println("<h1>You are not logged in.</h1>");
  }

  String destURL = "/whoami";
  String loginURL = userService.createLoginURL(destURL);
  String logoutURL = userService.createLogoutURL(destURL);

  res.getWriter().println("<br>");
  res.getWriter().println("<a href=\"" + loginURL + "\">login</a>");
  res.getWriter().println("<br>");
  res.getWriter().println("<a href=\"" + logoutURL + "\">logout</a>");
  res.getWriter().println("</body>");
  res.getWriter().println("</html>");
}
 
Example #29
Source File: UserServiceImpl.java    From sc2gears with Apache License 2.0 5 votes vote down vote up
@Override
public RpcResult< Void > recalcFileStats( final String sharedAccount ) {
	LOGGER.fine( sharedAccount == null ? "" : "Shared account: " + sharedAccount );
	
	final UserService userService = UserServiceFactory.getUserService();
	final User user = userService.getCurrentUser();
	if ( user == null )
		return RpcResult.createNotLoggedInErrorResult();
	
	PersistenceManager pm = null;
	try {
		
		pm = PMF.get().getPersistenceManager();
		
		final Key accountKey = ServerUtils.getAccountKey( pm, sharedAccount, user, Permission.VIEW_QUOTA );
		if ( accountKey == null )
			return RpcResult.createNoPermissionErrorResult();
		
		final Event lastRecalcEvent = ServerUtils.getLastEvent( accountKey, Type.FILE_STATS_RECALC_TRIGGERED );
		if ( lastRecalcEvent != null && System.currentTimeMillis() - lastRecalcEvent.getDate().getTime() < 24L*60*60*1000 ) {
			final int hours = (int) ( ( System.currentTimeMillis() - lastRecalcEvent.getDate().getTime() ) / (1000L*60*60) );
			return RpcResult.createErrorResult( "Recalculation can only be requested once per 24 hours"
				+ " (last was " + hours + ( hours == 1 ? " hour ago)!" : " hours ago)!" ) );
		}
		
		TaskServlet.register_recalcFileStatsTask( accountKey );
		
		pm.makePersistent( new Event( accountKey, Type.FILE_STATS_RECALC_TRIGGERED ) );
		
	} finally {
		if ( pm != null )
			pm.close();
	}
	
	return RpcResult.createInfoResult( "File stats recalculation has been kicked-off, check back in a short time..." );
}
 
Example #30
Source File: AppEngineAuthentication.java    From appengine-java-vm-runtime with Apache License 2.0 5 votes vote down vote up
@Override
public boolean isUserInRole(String role, Scope unusedScope) {
  UserService userService = UserServiceFactory.getUserService();
  log.fine("Checking if principal " + userPrincipal + " is in role " + role);
  if (userPrincipal == null) {
    log.info("isUserInRole() called with null principal.");
    return false;
  }

  if (USER_ROLE.equals(role)) {
    return true;
  }

  if (ADMIN_ROLE.equals(role)) {
    User user = userPrincipal.getUser();
    if (user.equals(userService.getCurrentUser())) {
      return userService.isUserAdmin();
    } else {
      // TODO(user): I'm not sure this will happen in
      // practice. If it does, we may need to pass an
      // application's admin list down somehow.
      log.severe("Cannot tell if non-logged-in user " + user + " is an admin.");
      return false;
    }
  } else {
    log.warning("Unknown role: " + role + ".");
    return false;
  }
}