Skip to content

Commit a2ba8bc

Browse files
authored
Adding Documentation Snippets (firebase#145)
* Adding Java snippets for documentation * Added RTDB snippets * Added storage snippets
1 parent d6d574f commit a2ba8bc

5 files changed

Lines changed: 1372 additions & 0 deletions

File tree

Lines changed: 123 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,123 @@
1+
/*
2+
* Copyright 2018 Google Inc.
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
package com.google.firebase.snippets;
18+
19+
import com.google.auth.oauth2.GoogleCredentials;
20+
import com.google.firebase.FirebaseApp;
21+
import com.google.firebase.FirebaseOptions;
22+
import com.google.firebase.auth.FirebaseAuth;
23+
import com.google.firebase.database.FirebaseDatabase;
24+
import java.io.FileInputStream;
25+
import java.io.IOException;
26+
27+
/**
28+
* FirebaseApp initialization snippets for documentation.
29+
*/
30+
public class FirebaseAppSnippets {
31+
32+
public void initializeWithServiceAccount() throws IOException {
33+
// [START initialize_sdk_with_service_account]
34+
FileInputStream serviceAccount = new FileInputStream("path/to/serviceAccountKey.json");
35+
36+
FirebaseOptions options = new FirebaseOptions.Builder()
37+
.setCredentials(GoogleCredentials.fromStream(serviceAccount))
38+
.setDatabaseUrl("https://<DATABASE_NAME>.firebaseio.com/")
39+
.build();
40+
41+
FirebaseApp.initializeApp(options);
42+
// [END initialize_sdk_with_service_account]
43+
}
44+
45+
public void initializeWithDefaultCredentials() throws IOException {
46+
// [START initialize_sdk_with_application_default]
47+
FirebaseOptions options = new FirebaseOptions.Builder()
48+
.setCredentials(GoogleCredentials.getApplicationDefault())
49+
.setDatabaseUrl("https://<DATABASE_NAME>.firebaseio.com/")
50+
.build();
51+
52+
FirebaseApp.initializeApp(options);
53+
// [END initialize_sdk_with_application_default]
54+
}
55+
56+
public void initializeWithRefreshToken() throws IOException {
57+
// [START initialize_sdk_with_refresh_token]
58+
FileInputStream refreshToken = new FileInputStream("path/to/refreshToken.json");
59+
60+
FirebaseOptions options = new FirebaseOptions.Builder()
61+
.setCredentials(GoogleCredentials.fromStream(refreshToken))
62+
.setDatabaseUrl("https://<DATABASE_NAME>.firebaseio.com/")
63+
.build();
64+
65+
FirebaseApp.initializeApp(options);
66+
// [END initialize_sdk_with_refresh_token]
67+
}
68+
69+
public void initializeWithDefaultConfig() {
70+
// [START initialize_sdk_with_default_config]
71+
FirebaseApp.initializeApp();
72+
// [END initialize_sdk_with_default_config]
73+
}
74+
75+
public void initializeDefaultApp() throws IOException {
76+
FirebaseOptions defaultOptions = new FirebaseOptions.Builder()
77+
.setCredentials(GoogleCredentials.getApplicationDefault())
78+
.build();
79+
80+
// [START access_services_default]
81+
// Initialize the default app
82+
FirebaseApp defaultApp = FirebaseApp.initializeApp(defaultOptions);
83+
84+
System.out.println(defaultApp.getName()); // "[DEFAULT]"
85+
86+
// Retrieve services by passing the defaultApp variable...
87+
FirebaseAuth defaultAuth = FirebaseAuth.getInstance(defaultApp);
88+
FirebaseDatabase defaultDatabase = FirebaseDatabase.getInstance(defaultApp);
89+
90+
// ... or use the equivalent shorthand notation
91+
defaultAuth = FirebaseAuth.getInstance();
92+
defaultDatabase = FirebaseDatabase.getInstance();
93+
// [END access_services_default]
94+
}
95+
96+
public void initializeCustomApp() throws Exception {
97+
FirebaseOptions defaultOptions = new FirebaseOptions.Builder()
98+
.setCredentials(GoogleCredentials.getApplicationDefault())
99+
.build();
100+
FirebaseOptions otherAppConfig = new FirebaseOptions.Builder()
101+
.setCredentials(GoogleCredentials.getApplicationDefault())
102+
.build();
103+
104+
// [START access_services_nondefault]
105+
// Initialize the default app
106+
FirebaseApp defaultApp = FirebaseApp.initializeApp(defaultOptions);
107+
108+
// Initialize another app with a different config
109+
FirebaseApp otherApp = FirebaseApp.initializeApp(otherAppConfig, "other");
110+
111+
System.out.println(defaultApp.getName()); // "[DEFAULT]"
112+
System.out.println(otherApp.getName()); // "other"
113+
114+
// Use the shorthand notation to retrieve the default app's services
115+
FirebaseAuth defaultAuth = FirebaseAuth.getInstance();
116+
FirebaseDatabase defaultDatabase = FirebaseDatabase.getInstance();
117+
118+
// Use the otherApp variable to retrieve the other app's services
119+
FirebaseAuth otherAuth = FirebaseAuth.getInstance(otherApp);
120+
FirebaseDatabase otherDatabase = FirebaseDatabase.getInstance(otherApp);
121+
// [END access_services_nondefault]
122+
}
123+
}
Lines changed: 264 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,264 @@
1+
/*
2+
* Copyright 2018 Google Inc.
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
package com.google.firebase.snippets;
18+
19+
import com.google.firebase.auth.ExportedUserRecord;
20+
import com.google.firebase.auth.FirebaseAuth;
21+
import com.google.firebase.auth.FirebaseAuthException;
22+
import com.google.firebase.auth.FirebaseToken;
23+
import com.google.firebase.auth.ListUsersPage;
24+
import com.google.firebase.auth.UserRecord;
25+
import com.google.firebase.auth.UserRecord.CreateRequest;
26+
import com.google.firebase.auth.UserRecord.UpdateRequest;
27+
import com.google.firebase.database.DatabaseReference;
28+
import com.google.firebase.database.FirebaseDatabase;
29+
import java.util.HashMap;
30+
import java.util.Map;
31+
import java.util.concurrent.ExecutionException;
32+
33+
/**
34+
* Auth snippets for documentation.
35+
*/
36+
public class FirebaseAuthSnippets {
37+
38+
public static void getUserById(String uid) throws InterruptedException, ExecutionException {
39+
// [START get_user_by_id]
40+
UserRecord userRecord = FirebaseAuth.getInstance().getUserAsync(uid).get();
41+
// See the UserRecord reference doc for the contents of userRecord.
42+
System.out.println("Successfully fetched user data: " + userRecord.getUid());
43+
// [END get_user_by_id]
44+
}
45+
46+
public static void getUserByEmail(String email) throws InterruptedException, ExecutionException {
47+
// [START get_user_by_email]
48+
UserRecord userRecord = FirebaseAuth.getInstance().getUserByEmailAsync(email).get();
49+
// See the UserRecord reference doc for the contents of userRecord.
50+
System.out.println("Successfully fetched user data: " + userRecord.getEmail());
51+
// [END get_user_by_email]
52+
}
53+
54+
public static void getUserByPhoneNumber(
55+
String phoneNumber) throws InterruptedException, ExecutionException {
56+
// [START get_user_by_phone]
57+
UserRecord userRecord = FirebaseAuth.getInstance().getUserByPhoneNumberAsync(phoneNumber).get();
58+
// See the UserRecord reference doc for the contents of userRecord.
59+
System.out.println("Successfully fetched user data: " + userRecord.getPhoneNumber());
60+
// [END get_user_by_phone]
61+
}
62+
63+
public static void createUser() throws InterruptedException, ExecutionException {
64+
// [START create_user]
65+
CreateRequest request = new CreateRequest()
66+
.setEmail("[email protected]")
67+
.setEmailVerified(false)
68+
.setPassword("secretPassword")
69+
.setPhoneNumber("+11234567890")
70+
.setDisplayName("John Doe")
71+
.setPhotoUrl("http://www.example.com/12345678/photo.png")
72+
.setDisabled(false);
73+
74+
UserRecord userRecord = FirebaseAuth.getInstance().createUserAsync(request).get();
75+
System.out.println("Successfully created new user: " + userRecord.getUid());
76+
// [END create_user]
77+
}
78+
79+
public static void createUserWithUid() throws InterruptedException, ExecutionException {
80+
// [START create_user_with_uid]
81+
CreateRequest request = new CreateRequest()
82+
.setUid("some-uid")
83+
.setEmail("[email protected]")
84+
.setPhoneNumber("+11234567890");
85+
86+
UserRecord userRecord = FirebaseAuth.getInstance().createUserAsync(request).get();
87+
System.out.println("Successfully created new user: " + userRecord.getUid());
88+
// [END create_user_with_uid]
89+
}
90+
91+
public static void updateUser(String uid) throws InterruptedException, ExecutionException {
92+
// [START update_user]
93+
UpdateRequest request = new UpdateRequest(uid)
94+
.setEmail("[email protected]")
95+
.setPhoneNumber("+11234567890")
96+
.setEmailVerified(true)
97+
.setPassword("newPassword")
98+
.setDisplayName("Jane Doe")
99+
.setPhotoUrl("http://www.example.com/12345678/photo.png")
100+
.setDisabled(true);
101+
102+
UserRecord userRecord = FirebaseAuth.getInstance().updateUserAsync(request).get();
103+
System.out.println("Successfully updated user: " + userRecord.getUid());
104+
// [END update_user]
105+
}
106+
107+
public static void setCustomUserClaims(
108+
String uid) throws InterruptedException, ExecutionException {
109+
// [START set_custom_user_claims]
110+
// Set admin privilege on the user corresponding to uid.
111+
Map<String, Object> claims = new HashMap<>();
112+
claims.put("admin", true);
113+
FirebaseAuth.getInstance().setCustomUserClaimsAsync(uid, claims).get();
114+
// The new custom claims will propagate to the user's ID token the
115+
// next time a new one is issued.
116+
// [END set_custom_user_claims]
117+
118+
String idToken = "id_token";
119+
// [START verify_custom_claims]
120+
// Verify the ID token first.
121+
FirebaseToken decoded = FirebaseAuth.getInstance().verifyIdTokenAsync(idToken).get();
122+
if (Boolean.TRUE.equals(decoded.getClaims().get("admin"))) {
123+
// Allow access to requested admin resource.
124+
}
125+
// [END verify_custom_claims]
126+
127+
// [START read_custom_user_claims]
128+
// Lookup the user associated with the specified uid.
129+
UserRecord user = FirebaseAuth.getInstance().getUserAsync(uid).get();
130+
System.out.println(user.getCustomClaims().get("admin"));
131+
// [END read_custom_user_claims]
132+
}
133+
134+
public static void setCustomUserClaimsScript() throws InterruptedException, ExecutionException {
135+
// [START set_custom_user_claims_script]
136+
UserRecord user = FirebaseAuth.getInstance()
137+
.getUserByEmailAsync("[email protected]").get();
138+
// Confirm user is verified.
139+
if (user.isEmailVerified()) {
140+
Map<String, Object> claims = new HashMap<>();
141+
claims.put("admin", true);
142+
FirebaseAuth.getInstance().setCustomUserClaimsAsync(user.getUid(), claims).get();
143+
}
144+
// [END set_custom_user_claims_script]
145+
}
146+
147+
public static void setCustomUserClaimsInc() throws InterruptedException, ExecutionException {
148+
// [START set_custom_user_claims_incremental]
149+
UserRecord user = FirebaseAuth.getInstance()
150+
.getUserByEmailAsync("[email protected]").get();
151+
// Add incremental custom claim without overwriting the existing claims.
152+
Map<String, Object> currentClaims = user.getCustomClaims();
153+
if (Boolean.TRUE.equals(currentClaims.get("admin"))) {
154+
// Add level.
155+
currentClaims.put("level", 10);
156+
// Add custom claims for additional privileges.
157+
FirebaseAuth.getInstance().setCustomUserClaimsAsync(user.getUid(), currentClaims).get();
158+
}
159+
// [END set_custom_user_claims_incremental]
160+
}
161+
162+
public static void listAllUsers() throws InterruptedException, ExecutionException {
163+
// [START list_all_users]
164+
// Start listing users from the beginning, 1000 at a time.
165+
ListUsersPage page = FirebaseAuth.getInstance().listUsersAsync(null).get();
166+
while (page != null) {
167+
for (ExportedUserRecord user : page.getValues()) {
168+
System.out.println("User: " + user.getUid());
169+
}
170+
page = page.getNextPage();
171+
}
172+
173+
// Iterate through all users. This will still retrieve users in batches,
174+
// buffering no more than 1000 users in memory at a time.
175+
page = FirebaseAuth.getInstance().listUsersAsync(null).get();
176+
for (ExportedUserRecord user : page.iterateAll()) {
177+
System.out.println("User: " + user.getUid());
178+
}
179+
// [END list_all_users]
180+
}
181+
182+
public static void deleteUser(String uid) throws InterruptedException, ExecutionException {
183+
// [START delete_user]
184+
FirebaseAuth.getInstance().deleteUserAsync(uid).get();
185+
System.out.println("Successfully deleted user.");
186+
// [END delete_user]
187+
}
188+
189+
public static void createCustomToken() throws InterruptedException, ExecutionException {
190+
// [START custom_token]
191+
String uid = "some-uid";
192+
193+
String customToken = FirebaseAuth.getInstance().createCustomTokenAsync(uid).get();
194+
// Send token back to client
195+
// [END custom_token]
196+
System.out.println("Created custom token: " + customToken);
197+
}
198+
199+
public static void createCustomTokenWithClaims() throws InterruptedException, ExecutionException {
200+
// [START custom_token_with_claims]
201+
String uid = "some-uid";
202+
Map<String, Object> additionalClaims = new HashMap<String, Object>();
203+
additionalClaims.put("premiumAccount", true);
204+
205+
String customToken = FirebaseAuth.getInstance()
206+
.createCustomTokenAsync(uid, additionalClaims).get();
207+
// Send token back to client
208+
// [END custom_token_with_claims]
209+
System.out.println("Created custom token: " + customToken);
210+
}
211+
212+
public static void verifyIdToken(
213+
String idToken) throws InterruptedException, ExecutionException {
214+
// [START verify_id_token]
215+
// idToken comes from the client app (shown above)
216+
FirebaseToken decodedToken = FirebaseAuth.getInstance().verifyIdTokenAsync(idToken).get();
217+
String uid = decodedToken.getUid();
218+
// [END verify_id_token]
219+
System.out.println("Decoded ID token from user: " + uid);
220+
}
221+
222+
public static void verifyIdTokenCheckRevoked(String idToken) throws InterruptedException {
223+
// [START verify_id_token_check_revoked]
224+
try {
225+
// Verify the ID token while checking if the token is revoked by passing checkRevoked
226+
// as true.
227+
boolean checkRevoked = true;
228+
FirebaseToken decodedToken = FirebaseAuth.getInstance()
229+
.verifyIdTokenAsync(idToken, checkRevoked).get();
230+
// Token is valid and not revoked.
231+
String uid = decodedToken.getUid();
232+
} catch (ExecutionException e) {
233+
if (e.getCause() instanceof FirebaseAuthException) {
234+
FirebaseAuthException authError = (FirebaseAuthException) e.getCause();
235+
if (authError.getErrorCode().equals("id-token-revoked")) {
236+
// Token has been revoked. Inform the user to reauthenticate or signOut() the user.
237+
} else {
238+
// Token is invalid.
239+
}
240+
}
241+
}
242+
// [END verify_id_token_check_revoked]
243+
}
244+
245+
public static void revokeIdTokens(
246+
String idToken) throws InterruptedException, ExecutionException {
247+
String uid = "someUid";
248+
// [START revoke_tokens]
249+
FirebaseAuth.getInstance().revokeRefreshTokensAsync(uid).get();
250+
UserRecord user = FirebaseAuth.getInstance().getUserAsync(uid).get();
251+
// Convert to seconds as the auth_time in the token claims is in seconds too.
252+
long revocationSecond = user.getTokensValidAfterTimestamp() / 1000;
253+
System.out.println("Tokens revoked at: " + revocationSecond);
254+
// [END revoke_tokens]
255+
256+
// [START save_revocation_in_db]
257+
DatabaseReference ref = FirebaseDatabase.getInstance().getReference("metadata/" + uid);
258+
Map<String, Object> userData = new HashMap<>();
259+
userData.put("revokeTime", revocationSecond);
260+
ref.setValueAsync(userData).get();
261+
// [END save_revocation_in_db]
262+
263+
}
264+
}

0 commit comments

Comments
 (0)