Java Code Examples for com.google.appengine.api.users.UserService#isUserAdmin()

The following examples show how to use com.google.appengine.api.users.UserService#isUserAdmin() . 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: 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 2
Source File: AdminServiceImpl.java    From sc2gears with Apache License 2.0 5 votes vote down vote up
@Override
public RpcResult< List< NewAccountSuggestion > > getNewAccountSuggestionList() {
	LOGGER.fine( "" );
	
	final UserService userService = UserServiceFactory.getUserService();
	final User user = userService.getCurrentUser();
	if ( user == null )
		return RpcResult.createNotLoggedInErrorResult();
	if ( !userService.isUserAdmin() )
		return RpcResult.createNoPermissionErrorResult();
	
	PersistenceManager pm = null;
	try {
		pm = PMF.get().getPersistenceManager();
		
		final List< Visit > visitList = new JQBuilder<>( pm, Visit.class ).filter( "visitorKey==null", null ).desc( "date" ).range( 0, 20 ).get();
		
		final List< NewAccountSuggestion > newAccSuggestionList = new ArrayList< NewAccountSuggestion >( visitList.size() + 1 );
		if ( !visitList.isEmpty() )
			newAccSuggestionList.add( new NewAccountSuggestion() );
		
		for ( final Visit visit : visitList ) {
			final NewAccountSuggestion newAccSuggestion = new NewAccountSuggestion();
			
			newAccSuggestion.setGoogleAccount( visit.getUser().getEmail()                              );
			newAccSuggestion.setCountryCode  ( visit.getCountryCode()                                  );
			newAccSuggestion.setCountryName  ( ServerUtils.countryCodeToName( visit.getCountryCode() ) );
			
			newAccSuggestionList.add( newAccSuggestion );
		}
		
		return new RpcResult< List<NewAccountSuggestion> >( newAccSuggestionList );
	} finally {
		if ( pm != null )
			pm.close();
	}
}
 
Example 3
Source File: AdminServiceImpl.java    From sc2gears with Apache License 2.0 5 votes vote down vote up
@Override
public RpcResult< Void > recalculateFileInfoStats( final String googleAccount ) {
	LOGGER.fine( "For Google account: " + googleAccount );
	
	final UserService userService = UserServiceFactory.getUserService();
	final User user = userService.getCurrentUser();
	if ( user == null )
		return RpcResult.createNotLoggedInErrorResult();
	if ( !userService.isUserAdmin() )
		return RpcResult.createNoPermissionErrorResult();
	
	PersistenceManager pm = null;
	try {
		
		pm = PMF.get().getPersistenceManager();
		
		final Key accountKey = CachingService.getAccountKeyByUser( pm, new User( googleAccount, "gmail.com" ) );
		if ( accountKey == null )
			return RpcResult.createErrorResult( "Invalid Google account!" );
		
		TaskServlet.register_recalcFileStatsTask( accountKey );
		
		pm.makePersistent( new Event( accountKey, Type.FILE_STATS_RECALC_TRIGGERED, "By admin: " + user.getEmail() ) );
		
	} finally {
		if ( pm != null )
			pm.close();
	}
	
	return RpcResult.createInfoResult( "File stats recalculation has been kicked-off..." );
}
 
Example 4
Source File: AdminServiceImpl.java    From sc2gears with Apache License 2.0 5 votes vote down vote up
@Override
public RpcResult< String > executeMiscFunction( final boolean autoTx, final String functionName, final String[] params ) {
	final StringBuilder paramsBuilder = new StringBuilder( "[" );
	for ( final String param : params ) {
		if ( paramsBuilder.length() > 1 )
			paramsBuilder.append( ", " );
		paramsBuilder.append( param );
	}
	paramsBuilder.append( ']' );
	LOGGER.fine( "Auto Tx: " + autoTx + ", Function name: " + functionName + ", params: " + paramsBuilder );
	
	final UserService userService = UserServiceFactory.getUserService();
	final User user = userService.getCurrentUser();
	if ( user == null )
		return RpcResult.createNotLoggedInErrorResult();
	if ( !userService.isUserAdmin() )
		return RpcResult.createNoPermissionErrorResult();
	
	final DatastoreTask miscFunction = miscFunctionMap.get( functionName );
	if ( miscFunction == null ) {
		LOGGER.warning( "Invalid function name!" );
		return RpcResult.createErrorResult( "Invalid function name!" );
	}
	
	PersistenceManager pm = null;
	try {
		
		pm = ( autoTx ? PMF.getAutoTx() : PMF.getNoAutoTx() ).getPersistenceManager();
		
		final long start = System.nanoTime();
		String result = miscFunction.execute( getThreadLocalRequest(), pm, params );
		final long end = System.nanoTime();
		
		return new RpcResult< String >( "[" + ServerUtils.DECIMAL_FORMAT.format( ( end - start ) / 1000000l ) + " ms] Execution result: " + result );
		
	} finally {
		if ( pm != null )
			pm.close();
	}
}
 
Example 5
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 6
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;
  }
}
 
Example 7
Source File: AdminServiceImpl.java    From sc2gears with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public RpcResult< Void > createAccount( final AccountInfo accountInfo ) {
	LOGGER.fine( "For Google account: " + accountInfo.getGoogleAccount() );
	
	final UserService userService = UserServiceFactory.getUserService();
	final User user = userService.getCurrentUser();
	if ( user == null )
		return RpcResult.createNotLoggedInErrorResult();
	if ( !userService.isUserAdmin() )
		return RpcResult.createNoPermissionErrorResult();
	
	PersistenceManager pm = null;
	try {
		
		pm = PMF.get().getPersistenceManager();
		
		// Perform checks
		if ( accountInfo.getGoogleAccount() == null || accountInfo.getGoogleAccount().isEmpty() )
			return RpcResult.createErrorResult( "Google account is required!" );
		
		if ( !ServerUtils.isEmailValid( accountInfo.getGoogleAccount() ) )
			return RpcResult.createErrorResult( "Invalid Google account!" );
		if ( accountInfo.getContactEmail() != null && !accountInfo.getContactEmail().isEmpty() )
			if ( !ServerUtils.isEmailValid( accountInfo.getContactEmail() ) )
				return RpcResult.createErrorResult( "Invalid contact email!" );
		
		final User newUser = new User( accountInfo.getGoogleAccount(), "gmail.com" );
		if ( accountInfo.isApiAccount() ) {
			if ( !( (List< ? >) pm.newQuery( "select key from " + ApiAccount.class.getName() + " where user==:1" ).execute( newUser ) ).isEmpty() )
				return RpcResult.createErrorResult( "There is already an API account with this Google account!" );
			
			// Create and save API account
			final ApiAccount apiAccount = new ApiAccount( newUser );
			apiAccount.setApiKey( ServerUtils.generateRandomStringKey() );
			// We have to make sure the API key is unique:
			if ( !( (List< Key >) pm.newQuery( "select key from " + ApiAccount.class.getName() + " where apiKey==:1" ).execute( apiAccount.getApiKey() ) ).isEmpty() ) {
				// This will (likely) never happen, but just in case this will ensure that the same key will not be associated with multiple API accounts.
				throw new RuntimeException( "Failed to save new API key, please try again." );
			}
			if ( accountInfo.getContactEmail() != null && !accountInfo.getContactEmail().isEmpty() )
				apiAccount.setContactEmail( accountInfo.getContactEmail() );
			if ( accountInfo.getName() != null && !accountInfo.getName().isEmpty() )
				apiAccount.setName( accountInfo.getName() );
			if ( accountInfo.getCountry() != null && !accountInfo.getCountry().isEmpty() )
				apiAccount.setCountry( accountInfo.getCountry() );
			if ( accountInfo.getComment() != null )
				apiAccount.setComment( accountInfo.getComment() );
			apiAccount.setNotificationAvailOps( 2000 ); // Default notification available Ops
			pm.makePersistent( apiAccount );
			
			// Notification Email will be sent when API payment is registered 
		}
		else {
			if ( !( (List< ? >) pm.newQuery( "select key from " + Account.class.getName() + " where user==:1" ).execute( newUser ) ).isEmpty() )
				return RpcResult.createErrorResult( "There is already an account with this Google account!" );
			
			// Create and save account
			final Account account = new Account( newUser );
			ServerUtils.initializeNewAccount( pm, account );
			if ( accountInfo.getContactEmail() != null && !accountInfo.getContactEmail().isEmpty() )
				account.setContactEmail( accountInfo.getContactEmail() );
			if ( accountInfo.getName() != null && !accountInfo.getName().isEmpty() )
				account.setName( accountInfo.getName() );
			if ( accountInfo.getCountry() != null && !accountInfo.getCountry().isEmpty() )
				account.setCountry( accountInfo.getCountry() );
			if ( accountInfo.getComment() != null && !accountInfo.getComment().isEmpty())
				account.setComment( accountInfo.getComment() );
			pm.makePersistent( account );
			
			if ( accountInfo.isFreeAccount() ) {
				// Email will be sent by the TaskServlet:
				TaskServlet.register_updatePackageTask( account.getKey() );
			}
			// Else notification Email will be sent when payment is registered 
		}
		
	} finally {
		if ( pm != null )
			pm.close();
	}
	
	return RpcResult.createInfoResult( ( accountInfo.isApiAccount() ? "New API" : "New " ) + "Account created successfully." );
}
 
Example 8
Source File: AdminServiceImpl.java    From sc2gears with Apache License 2.0 4 votes vote down vote up
@Override
public RpcResult< List< VisitInfo > > getVisitInfoList( final VisitType type, final int hours, final Boolean hasAccount ) {
	LOGGER.fine( "Type: " + type.name() + ", hours: " + hours + ", has account: " + hasAccount );
	
	final UserService userService = UserServiceFactory.getUserService();
	final User user = userService.getCurrentUser();
	if ( user == null )
		return RpcResult.createNotLoggedInErrorResult();
	if ( !userService.isUserAdmin() )
		return RpcResult.createNoPermissionErrorResult();
	
	if ( hours < 1 || hours > 336 )
		return RpcResult.createErrorResult( "Invalid hours (must be between 1 and 336)!" );
	
	PersistenceManager pm = null;
	try {
		
		pm = PMF.get().getPersistenceManager();
		
		final Date fromDate = new Date( System.currentTimeMillis() - hours * 60L * 60 * 1000l );
		
		final List< VisitInfo > visitInfoList = new ArrayList< VisitInfo >();
		
		// "visitorKey==null" filter is OK, but can't append "visitorKey!=null" inequality filter
		// because that would require to sort by it (but we want to sort by date), I'll handle that manually.
		final JQBuilder< ? extends BaseVisit > q = new JQBuilder<>( pm, type == VisitType.VISIT ? Visit.class : ApiVisit.class ).desc( "date" ).range( 0, 1000 )
				.filter( hasAccount == null || hasAccount ? "date>p1" : "date>p1 && visitorKey==null", "DATE p1" );
		
		while ( true ) {
			final List< ? extends BaseVisit > visitList = q.get( fromDate );
			for ( final BaseVisit visit : visitList ) {
				if ( Boolean.TRUE.equals( hasAccount ) && visit.getVisitorKey() == null )
					continue;
				
				final VisitInfo visitInfo = new VisitInfo();
				
				visitInfo.setDate         ( visit.getDate()               );
				visitInfo.setGoogleAccount( visit.getUser().getEmail()    );
				visitInfo.setLocation     ( visit.getCountry()            );
				visitInfo.setIp           ( visit.getIp()                 );
				visitInfo.setHasAccount   ( visit.getVisitorKey() != null );
				visitInfo.setUserAgent    ( visit.getUserAgent()          );
				
				visitInfoList.add( visitInfo );
			}
			
			if ( visitList.size() < 1000 )
				break;
			
			q.cursor( visitList );
		}
		
		return new RpcResult< List< VisitInfo > >( visitInfoList );
		
	} finally {
		if ( pm != null )
			pm.close();
	}
}
 
Example 9
Source File: AdminServiceImpl.java    From sc2gears with Apache License 2.0 4 votes vote down vote up
@Override
public RpcResult< List< ApiCallStatInfo > > getApiActivity( final String firstDay, final String lastDay ) {
	LOGGER.fine( "First day: " + firstDay + ", last day: " + lastDay );
	
	final UserService userService = UserServiceFactory.getUserService();
	final User user = userService.getCurrentUser();
	if ( user == null )
		return RpcResult.createNotLoggedInErrorResult();
	if ( !userService.isUserAdmin() )
		return RpcResult.createNoPermissionErrorResult();
	
	PersistenceManager pm = null;
	try {
		
		pm = PMF.get().getPersistenceManager();
		
		// To keep track of total
		final ApiCallStatInfo totalApiCallStatInfo = new ApiCallStatInfo();
		totalApiCallStatInfo.setGoogleAccount( "TOTAL: ∑ ALL" );
		
		final Map< Key, ApiCallStatInfo > apiAccountKeyApiCallStatInfoMap  = new HashMap< Key, ApiCallStatInfo >();
		
		final JQBuilder< ApiCallStat > q = new JQBuilder<>( pm, ApiCallStat.class ).filter( "day>=p1 && day<=p2", "String p1, String p2" ).range( 0, 1000 );
		
		while ( true ) {
			final List< ApiCallStat > apiCallStatList = q.get( firstDay, lastDay );
			
			for ( final ApiCallStat apiCallStat : apiCallStatList ) {
				ApiCallStatInfo apiCallStatInfo = apiAccountKeyApiCallStatInfoMap.get( apiCallStat.getOwnerKey() );
				if ( apiCallStatInfo == null ) {
					apiAccountKeyApiCallStatInfoMap.put( apiCallStat.getOwnerKey(), apiCallStatInfo = new ApiCallStatInfo() );
					final ApiAccount apiAccount = pm.getObjectById( ApiAccount.class, apiCallStat.getOwnerKey() );
					apiCallStatInfo.setGoogleAccount( apiAccount.getUser().getEmail() );
					apiCallStatInfo.setPaidOps      ( apiAccount.getPaidOps        () );
					// Integrate paid Ops into totals, ONCE only per API account
					totalApiCallStatInfo.setPaidOps( totalApiCallStatInfo.getPaidOps() + apiCallStatInfo.getPaidOps() );
				}
				
				ServerUtils.integrateApiCallStatIntoInfo( apiCallStatInfo, apiCallStat );
				
				// Keep track of totals
				ServerUtils.integrateApiCallStatIntoInfo( totalApiCallStatInfo, apiCallStat );
			}
			
			if ( apiCallStatList.size() < 1000 )
				break;
			
			q.cursor( apiCallStatList );
		}
		
		final List< ApiCallStatInfo > apiCallStatInfoList = new ArrayList< ApiCallStatInfo >( apiAccountKeyApiCallStatInfoMap.size() + 1 );
		// First add the total info record (sorting will not move it even if only 1 stat record which will have the same used ops)
		apiCallStatInfoList.add( totalApiCallStatInfo );
		apiCallStatInfoList.addAll( apiAccountKeyApiCallStatInfoMap.values() );
		
		Collections.sort( apiCallStatInfoList, new Comparator< ApiCallStatInfo >() {
			@Override
			public int compare( final ApiCallStatInfo i1, final ApiCallStatInfo i2 ) {
				return new Long( i2.getUsedOps() ).compareTo( i1.getUsedOps() );
			}
		} );
		
		return new RpcResult< List<ApiCallStatInfo> >( apiCallStatInfoList );
		
	} finally {
		if ( pm != null )
			pm.close();
	}
}
 
Example 10
Source File: AdminServiceImpl.java    From sc2gears with Apache License 2.0 4 votes vote down vote up
@Override
public RpcResult< List< ApiCallStatInfo > > getApiCallStatInfoList( final String googleAccount ) {
	LOGGER.fine( "For Google account: " + googleAccount);
	
	final UserService userService = UserServiceFactory.getUserService();
	final User user = userService.getCurrentUser();
	if ( user == null )
		return RpcResult.createNotLoggedInErrorResult();
	if ( !userService.isUserAdmin() )
		return RpcResult.createNoPermissionErrorResult();
	
	PersistenceManager pm = null;
	try {
		
		pm = PMF.get().getPersistenceManager();
		
		final JQBuilder< ApiCallStat > q = new JQBuilder<>( pm, ApiCallStat.class ).range( 0, 1000 );
		
		final Object[] queryParams;
		if ( googleAccount != null && !googleAccount.isEmpty() ) {
			@SuppressWarnings( "unchecked" )
			final List< Key > apiAccountKey = (List< Key >) pm.newQuery( "select key from " + ApiAccount.class.getName() + " where user==:1" ).execute( new User( googleAccount, "gmail.com" ) );
			if ( apiAccountKey.isEmpty() )
				return new RpcResult< List<ApiCallStatInfo> >( new ArrayList< ApiCallStatInfo >( 0 ) );
			
			q.filter( "ownerKey==p1 && day==p2", "KEY p1, String p2" );
			queryParams = new Object[] { apiAccountKey.get( 0 ), ApiCallStat.DAY_TOTAL };
		}
		else {
			q.filter( "day==p1", "String p1" );
			queryParams = new Object[] { ApiCallStat.DAY_TOTAL };
		}
		
		// To keep track of total
		final ApiCallStatInfo totalApiCallStatInfo = new ApiCallStatInfo();
		totalApiCallStatInfo.setGoogleAccount( "TOTAL: ∑ ALL" );
		
		final List< ApiCallStatInfo > apiCallStatInfoList = new ArrayList< ApiCallStatInfo >();
		// First add the total info record
		apiCallStatInfoList.add( totalApiCallStatInfo );
		
		while ( true ) {
			final List< ApiCallStat > apiCallStatList = q.get( queryParams );
			
			for ( final ApiCallStat apiCallStat : apiCallStatList ) {
				final ApiCallStatInfo info = new ApiCallStatInfo();
				
				final ApiAccount apiAccount  = pm.getObjectById( ApiAccount.class, apiCallStat.getOwnerKey() );
				info.setGoogleAccount   ( apiAccount .getUser().getEmail () );
				info.setPaidOps         ( apiAccount .getPaidOps         () );
				ServerUtils.integrateApiCallStatIntoInfo( info, apiCallStat );
				apiCallStatInfoList.add( info );
				
				// Keep track of totals
				totalApiCallStatInfo.integrateApiCallStat( info );
				totalApiCallStatInfo.setPaidOps( totalApiCallStatInfo.getPaidOps() + info.getPaidOps() );
			}
			
			if ( apiCallStatList.size() < 1000 )
				break;
			
			q.cursor( apiCallStatList );
		}
		
		Collections.sort( apiCallStatInfoList, new Comparator< ApiCallStatInfo >() {
			@Override
			public int compare( final ApiCallStatInfo i1, final ApiCallStatInfo i2 ) {
				return new Long( i2.getUsedOps() ).compareTo( i1.getUsedOps() );
			}
		} );
		
		return new RpcResult< List<ApiCallStatInfo> >( apiCallStatInfoList );
		
	} finally {
		if ( pm != null )
			pm.close();
	}
}
 
Example 11
Source File: AppengineEnvironmentDriver.java    From yawp with MIT License 4 votes vote down vote up
@Override
public boolean isAdmin() {
    UserService userService = UserServiceFactory.getUserService();
    return userService.isUserLoggedIn() && userService.isUserAdmin();
}