Skip to content

Commit 1a0145a

Browse files
committed
Update Datastore sample to use auth-library-swift to get OAuth tokens.
1 parent b8dc92a commit 1a0145a

File tree

2 files changed

+33
-7
lines changed

2 files changed

+33
-7
lines changed

Examples/Datastore/PackageManager/Package.swift

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,8 @@ import PackageDescription
1717
let package = Package (
1818
name: "Datastore",
1919
dependencies: [
20-
.Package(url: "https://github.com/grpc/grpc-swift.git", Version(0,1,12)),
20+
.Package(url: "https://github.com/grpc/grpc-swift.git", Version(0,1,13)),
2121
.Package(url: "https://github.com/apple/swift-protobuf.git", Version(0,9,901)),
22+
.Package(url: "https://github.com/google/auth-library-swift.git", Version(0,2,0)),
2223
]
2324
)

Examples/Datastore/PackageManager/Sources/main.swift

Lines changed: 31 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -15,18 +15,40 @@
1515
*/
1616
import Foundation
1717
import gRPC
18+
import OAuth2
19+
20+
let CREDENTIALS = "google.yaml" // in $HOME/.credentials
21+
let TOKEN = "google.json" // local auth token storage
22+
23+
#if os(OSX)
24+
// On OS X, we use the local browser to help the user get a token.
25+
let tokenProvider = try BrowserTokenProvider(credentials:CREDENTIALS, token:TOKEN)
26+
if tokenProvider.token == nil {
27+
try tokenProvider.signIn(scopes:["profile",
28+
"https://www.googleapis.com/auth/contacts.readonly",
29+
"https://www.googleapis.com/auth/cloud-platform"])
30+
try tokenProvider.saveToken(TOKEN)
31+
}
32+
#else
33+
// On Linux, we can get a token if we are running in Google Cloud Shell
34+
// or in some other Google Cloud instance (GAE, GKE, GCE, etc).
35+
let tokenProvider = try GoogleTokenProvider()
36+
#endif
1837

1938
gRPC.initialize()
2039

21-
let authToken = "<YOUR AUTH TOKEN>"
40+
guard let authToken = tokenProvider.token?.accessToken else {
41+
print("ERROR: No OAuth token is avaiable.")
42+
exit(-1)
43+
}
2244

2345
let projectID = "<YOUR PROJECT ID>"
2446

2547
let certificateURL = URL(fileURLWithPath:"roots.pem")
2648
let certificates = try! String(contentsOf: certificateURL)
2749
let service = Google_Datastore_V1_DatastoreService(address:"datastore.googleapis.com",
28-
certificates:certificates,
29-
host:nil)
50+
certificates:certificates,
51+
host:nil)
3052

3153
service.metadata = Metadata(["authorization":"Bearer " + authToken])
3254

@@ -40,6 +62,9 @@ request.gqlQuery = query
4062

4163
print("\(request)")
4264

43-
let result = try service.runquery(request)
44-
45-
print("\(result)")
65+
do {
66+
let result = try service.runquery(request)
67+
print("\(result)")
68+
} catch (let error) {
69+
print("ERROR: \(error)")
70+
}

0 commit comments

Comments
 (0)