Last active
January 6, 2017 15:59
-
-
Save christian-smith/04f2386c89b24e551dd6d25cc4ed6574 to your computer and use it in GitHub Desktop.
Create a Pre-signed URL for Google Storage in Swift using Vapor
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
import Vapor | |
import Core | |
import VaporJWT | |
class GoogleCloud { | |
func generatePreSignedURL() -> String? { | |
let accessId = "project@project-xxxxx.iam.gserviceaccount.com" | |
let bucketName = "bucketname" | |
let expiry = (1000*60) + Int(Date().timeIntervalSince1970) | |
let key = "file.txt" | |
let policyString = "GET\n\n\n\(expiry)\n/\(bucketName)/\(key)" | |
let policyData = policyString.data(using: .utf8)! | |
do { | |
let privateKey = try DataFile().load(path: "private.der") | |
let signer = RS256(key: privateKey) | |
let policyBytes = [UInt8](policyData) | |
let signatureBytes = try signer.sign(policyBytes) | |
let rfc3986Reserved = NSCharacterSet(charactersIn:"!*'();:@&=+$,/?#[]") | |
let escapedSignatureString = signatureBytes.base64String.addingPercentEncoding(withAllowedCharacters: rfc3986Reserved.inverted)! | |
let signedUrlString = "https://storage.googleapis.com/\(bucketName)/\(key)?GoogleAccessId=\(accessId)&Expires=\(expiry)&Signature=\(escapedSignatureString)" | |
return signedUrlString | |
} catch { | |
print(error.localizedDescription) | |
return nil | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment