Skip to content

Commit

Permalink
Merge pull request #47 from microtherion/Dropbox
Browse files Browse the repository at this point in the history
Add support for Dropbox logins
  • Loading branch information
0xTim authored Mar 4, 2020
2 parents 06b932e + b43d501 commit 98fc3f2
Show file tree
Hide file tree
Showing 12 changed files with 248 additions and 12 deletions.
24 changes: 24 additions & 0 deletions Sources/Imperial/Services/Dropbox/Dropbox.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import Vapor

public class Dropbox: FederatedService {
public var tokens: FederatedServiceTokens
public var router: FederatedServiceRouter

@discardableResult
public required init(
router: Router,
authenticate: String,
authenticateCallback: ((Request)throws -> (Future<Void>))?,
callback: String,
scope: [String] = [],
completion: @escaping (Request, String)throws -> (Future<ResponseEncodable>)
) throws {
self.router = try DropboxRouter(callback: callback, completion: completion)
self.tokens = self.router.tokens

self.router.scope = scope
try self.router.configureRoutes(withAuthURL: authenticate, authenticateCallback: authenticateCallback, on: router)

OAuthService.register(.dropbox)
}
}
16 changes: 16 additions & 0 deletions Sources/Imperial/Services/Dropbox/DropboxAuth.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import Vapor

public class DropboxAuth: FederatedServiceTokens {
public static var idEnvKey: String = "DROPBOX_CLIENT_ID"
public static var secretEnvKey: String = "DROPBOX_CLIENT_SECRET"
public var clientID: String
public var clientSecret: String

public required init() throws {
let idError = ImperialError.missingEnvVar(DropboxAuth.idEnvKey)
let secretError = ImperialError.missingEnvVar(DropboxAuth.secretEnvKey)

self.clientID = try Environment.get(DropboxAuth.idEnvKey).value(or: idError)
self.clientSecret = try Environment.get(DropboxAuth.secretEnvKey).value(or: secretError)
}
}
19 changes: 19 additions & 0 deletions Sources/Imperial/Services/Dropbox/DropboxCallbackBody.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import Vapor

struct DropboxCallbackBody: Content {
let code: String
let clientId: String
let clientSecret: String
let redirectURI: String
let grantType: String = "authorization_code"

static var defaultContentType: MediaType = .urlEncodedForm

enum CodingKeys: String, CodingKey {
case code = "code"
case clientId = "client_id"
case clientSecret = "client_secret"
case redirectURI = "redirect_uri"
case grantType = "grant_type"
}
}
62 changes: 62 additions & 0 deletions Sources/Imperial/Services/Dropbox/DropboxRouter.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
import Vapor
import Foundation

public class DropboxRouter: FederatedServiceRouter {
public let tokens: FederatedServiceTokens
public let callbackCompletion: (Request, String)throws -> (Future<ResponseEncodable>)
public var scope: [String] = []
public let callbackURL: String
public let accessTokenURL: String = "https://api.dropboxapi.com/oauth2/token"

public required init(callback: String, completion: @escaping (Request, String)throws -> (Future<ResponseEncodable>)) throws {
self.tokens = try DropboxAuth()
self.callbackURL = callback
self.callbackCompletion = completion
}

public func authURL(_ request: Request) throws -> String {
return "https://www.dropbox.com/oauth2/authorize?" +
"client_id=\(self.tokens.clientID)&" +
"redirect_uri=\(self.callbackURL)&" +
"response_type=code"
}

public func fetchToken(from request: Request)throws -> Future<String> {
let code: String
if let queryCode: String = try request.query.get(at: "code") {
code = queryCode
} else if let error: String = try request.query.get(at: "error") {
throw Abort(.badRequest, reason: error)
} else {
throw Abort(.badRequest, reason: "Missing 'code' key in URL query")
}

let body = DropboxCallbackBody(code: code, clientId: self.tokens.clientID, clientSecret: self.tokens.clientSecret, redirectURI: self.callbackURL)
return try body.encode(using: request).flatMap(to: Response.self) { request in
guard let url = URL(string: self.accessTokenURL) else {
throw Abort(.internalServerError, reason: "Unable to convert String '\(self.accessTokenURL)' to URL")
}
request.http.method = .POST
request.http.url = url
return try request.make(Client.self).send(request)
}.flatMap(to: String.self) { response in
// Dropbox returns a Content-Type of "text/javascript", which Vapor has difficulties dealing with
// even though it's just regular JSON
response.http.headers.replaceOrAdd(name: "Content-Type", value: "application/json")
return response.content.get(String.self, at: ["access_token"])
}
}

public func callback(_ request: Request)throws -> Future<Response> {
return try self.fetchToken(from: request).flatMap(to: ResponseEncodable.self) { accessToken in
let session = try request.session()

session.setAccessToken(accessToken)
try session.set("access_token_service", to: OAuthService.dropbox)

return try self.callbackCompletion(request, accessToken)
}.flatMap(to: Response.self) { response in
return try response.encode(for: request)
}
}
}
6 changes: 6 additions & 0 deletions Sources/Imperial/Services/Dropbox/Service+Dropbox.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
extension OAuthService {
public static let dropbox = OAuthService.init(
name: "dropbox",
endpoints: [:]
)
}
109 changes: 109 additions & 0 deletions docs/Dropbox/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
# Federated Login with Dropbox

Start by going to the [Dropbox App console page](https://dropbox.com/developers/apps/). Click the 'Create App' button. Choose your API, access type, and name, then click 'Create App':

![Create the app](create-application.png)

Fill in the rest of the app information, particularly the Redirect URIs:

![Redirect URI](callback-url.png)

Now that we have an OAuth application registered with Dropbox, we can add Imperial to our project (We will not be going over how to create the project, as I will assume that you have already done that).

Add the following line of code to your `dependencies` array in your package manifest file:

```swift
.package(url: "https://github.com/vapor-community/Imperial.git", from: "0.5.3")
```

**Note:** There might be a later version of the package available, in which case you will want to use that version.

You will also need to add the package as a dependency for the targets you will be using it in:

```swift
.target(name: "App", dependencies: ["Vapor", "Imperial"],
exclude: [
"Config",
"Database",
"Public",
"Resources"
]),
```

Then run `vapor update` or `swift package update`. Make sure you regenerate your Xcode project afterwards if you are using Xcode.

Now that Imperial is installed, we need to add `SessionMiddleware` to our middleware configuration:

```swift
public func configure(
_ config: inout Config,
_ env: inout Environment,
_ services: inout Services
) throws {
//...

// Register middleware
var middlewares = MiddlewareConfig() // Create _empty_ middleware config
// Other Middleware...
middlewares.use(SessionsMiddleware.self)
services.register(middlewares)

//...
}

```

Now, when you run your app and you are using `FluentSQLite`, you will probably get the following error:

```
⚠️ [ServiceError.ambiguity: Please choose which KeyedCache you prefer, multiple are available: MemoryKeyedCache, FluentCache<SQLiteDatabase>.] [Suggested fixes: `config.prefer(MemoryKeyedCache.self, for: KeyedCache.self)`. `config.prefer(FluentCache<SQLiteDatabase>.self, for: KeyedCache.self)`.]
```

Just pick one of the listed suggestions and place it at the top of your `configure` function. If you want your data to persist across server reboots, use `config.prefer(FluentCache<SQLiteDatabase>.self, for: KeyedCache.self)`

Imperial uses environment variables to access the client ID and secret to authenticate with Dropbox. To allow Imperial to access these tokens, you will create these variables, called `DROPBOX_CLIENT_ID` and `DROPBOX_CLIENT_SECRET`, with the App key and App secret assigned to them. Imperial can then access these vars and use their values to authenticate with GitHub.

Now, all we need to do is register the Dropbox service in your main router method, like this:

```swift
try router.oAuth(from: Dropbox.self, authenticate: "dropbox-login", callback: "dropbox-auth-complete") { (request, token) in
print(token)
return Future(request.redirect(to: "/"))
}
```

If you just want to redirect, without doing anything else in the callback, you can use the helper `Route.oAuth` method that takes in a redirect string:

```swift
try router.oAuth(from: GitHub.self, authenticate: "dropbox-login", callback: "dropbox-auth-complete", redirect: "/")
```

The `authenticate` argument is the path you will go to when you want to authenticate the user. The `callback` argument has to be the same path that you entered when you registered your application on Dropbox:

![The callback path for Dropbox OAuth](callback-url.png)

The completion handler is fired when the callback route is called by the OAuth provider. The access token is passed in and a response is returned.

If you ever want to get the `access_token` in a route, you can use a helper method for the `Request` type that comes with Imperial:

```swift
let token = try request.accessToken()
```

Now that you are authenticating the user, you will want to protect certain routes to make sure the user is authenticated. You can do this by adding the `ImperialMiddleware` to a router group (or maybe your middleware config):

```swift
let protected = router.grouped(ImperialMiddleware())
```

Then, add your protected routes to the `protected` group:

```swift
protected.get("me", handler: me)
```

The `ImperialMiddleware` by default passes the errors it finds onto `ErrorMiddleware` where they are caught, but you can initialize it with a redirect path to go to if the user is not authenticated:

```swift
let protected = router.grouped(ImperialMiddleware(redirect: "/"))
```
Binary file added docs/Dropbox/callback-url.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added docs/Dropbox/create-application.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
4 changes: 2 additions & 2 deletions docs/GitHub/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ public func configure(
// Other Middleware...
middlewares.use(SessionsMiddleware.self)
services.register(middlewares)

//...
}

Expand All @@ -57,7 +57,7 @@ Now, when you run your app and you are using `FluentSQLite`, you will probably g

Just pick one of the listed suggestions and place it at the top of your `configure` function. If you want your data to persist across server reboots, use `config.prefer(FluentCache<SQLiteDatabase>.self, for: KeyedCache.self)`

Imperial uses environment variables to access the client ID and secret to authenticate with GitHub. To allow Imperial to access these tokens, you will create these variables, called `GITHUB_CLIENT_ID` and `GITHUB_CLIENT_SECRET`, with the client ID and secret assigned to them. Imperial can then access these vars and use there values to authenticate with GitHub.
Imperial uses environment variables to access the client ID and secret to authenticate with GitHub. To allow Imperial to access these tokens, you will create these variables, called `GITHUB_CLIENT_ID` and `GITHUB_CLIENT_SECRET`, with the client ID and secret assigned to them. Imperial can then access these vars and use their values to authenticate with GitHub.

Now, all we need to do is register the GitHub service in your main router method, like this:

Expand Down
4 changes: 2 additions & 2 deletions docs/Google/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ public func configure(
// Other Middleware...
middlewares.use(SessionsMiddleware.self)
services.register(middlewares)

//...
}

Expand All @@ -63,7 +63,7 @@ Now, when you run your app and you are using `FluentSQLite`, you will probably g

Just pick one of the listed suggestions and place it at the top of your `configure` function. If you want your data to persist across server reboots, use `config.prefer(FluentCache<SQLiteDatabase>.self, for: KeyedCache.self)`

Imperial uses environment variables to access the client ID and secret to authenticate with Google. To allow Imperial to access these tokens, you will create these variables, called `GOOGLE_CLIENT_ID` and `GOOGLE_CLIENT_SECRET`, with the client ID and secret assigned to them. Imperial can then access these vars and use there values to authenticate with Google.
Imperial uses environment variables to access the client ID and secret to authenticate with Google. To allow Imperial to access these tokens, you will create these variables, called `GOOGLE_CLIENT_ID` and `GOOGLE_CLIENT_SECRET`, with the client ID and secret assigned to them. Imperial can then access these vars and use their values to authenticate with Google.

Now, all we need to do is register the Google service in your main router method, like this:

Expand Down
4 changes: 2 additions & 2 deletions docs/Keycloak/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ public func configure(
// Other Middleware...
middlewares.use(SessionsMiddleware.self)
services.register(middlewares)

//...
}

Expand All @@ -61,7 +61,7 @@ Now, when you run your app and you are using `FluentSQLite`, you will probably g

Just pick one of the listed suggestions and place it at the top of your `configure` function. If you want your data to persist across server reboots, use `config.prefer(FluentCache<SQLiteDatabase>.self, for: KeyedCache.self)`

Imperial uses environment variables to access the client ID and secret to authenticate with Keycloak. To allow Imperial to access these tokens, you will create these variables, called `KEYCLOAK_CLIENT_ID`, `KEYCLOAK_CLIENT_SECRET`, `KEYCLOAK_ACCESS_TOKEN_URL` and `KEYCLOAK_AUTH_URL`, with the client ID and secret assigned to them. Imperial can then access these vars and use there values to authenticate with Keycloak.
Imperial uses environment variables to access the client ID and secret to authenticate with Keycloak. To allow Imperial to access these tokens, you will create these variables, called `KEYCLOAK_CLIENT_ID`, `KEYCLOAK_CLIENT_SECRET`, `KEYCLOAK_ACCESS_TOKEN_URL` and `KEYCLOAK_AUTH_URL`, with the client ID and secret assigned to them. Imperial can then access these vars and use their values to authenticate with Keycloak.

In many case, `KEYCLOAK_ACCESS_TOKEN_URL` have the current patern `http://localhost:8080/auth/realms/{realmName]/protocol/openid-connect/token` (but may vary if you use a proxy). And `KEYCLOAK_AUTH_URL` is generally `http://localhost:8080/auth/realms/{realmName}/protocol/openid-connect`.

Expand Down
12 changes: 6 additions & 6 deletions docs/Shopify/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ public func configure(
// Other Middleware...
middlewares.use(SessionsMiddleware.self)
services.register(middlewares)

//...
}

Expand All @@ -57,7 +57,7 @@ Now, when you run your app and you are using `FluentSQLite`, you will probably g

Just pick one of the listed suggestions and place it at the top of your `configure` function. If you want your data to persist across server reboots, use `config.prefer(FluentCache<SQLiteDatabase>.self, for: KeyedCache.self)`

Imperial uses environment variables to access the client ID and secret to authenticate with Shopify. To allow Imperial to access these tokens, you will create these variables, called `SHOPIFY_CLIENT_ID` and `SHOPIFY_CLIENT_SECRET`, with the *API key* and *API secret key* found in the App credentials in the Partner Dashboard. Imperial can then access these vars and use there values to authenticate with Shopify.
Imperial uses environment variables to access the client ID and secret to authenticate with Shopify. To allow Imperial to access these tokens, you will create these variables, called `SHOPIFY_CLIENT_ID` and `SHOPIFY_CLIENT_SECRET`, with the *API key* and *API secret key* found in the App credentials in the Partner Dashboard. Imperial can then access these vars and use their values to authenticate with Shopify.

![](configure-app-creds.png)

Expand All @@ -66,10 +66,10 @@ Now, all we need to do is register the Shopify service in your main router metho
```swift
import Imperial

try router.oAuth(from: Shopify.self,
authenticate: "login-shopify",
callback: "http://localhost:8080/auth",
scope: ["read_products", "read_orders"],
try router.oAuth(from: Shopify.self,
authenticate: "login-shopify",
callback: "http://localhost:8080/auth",
scope: ["read_products", "read_orders"],
redirect: "/")
```

Expand Down

0 comments on commit 98fc3f2

Please sign in to comment.