Skip to content
This repository has been archived by the owner on Apr 20, 2024. It is now read-only.

Commit

Permalink
Merge pull request #89 from nodes-vapor/feature/request-creatable
Browse files Browse the repository at this point in the history
Submissions related update
  • Loading branch information
siemensikkema authored Feb 7, 2019
2 parents 4071e69 + 69b3563 commit a204e03
Show file tree
Hide file tree
Showing 15 changed files with 248 additions and 247 deletions.
6 changes: 3 additions & 3 deletions .circleci/config.yml
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ version: 2
jobs:
MacOS:
macos:
xcode: "10.0.0"
xcode: "10.1.0"
steps:
- checkout
- restore_cache:
Expand Down Expand Up @@ -36,7 +36,7 @@ jobs:
- checkout
- restore_cache:
keys:
- v2-spm-deps-{{ checksum "Package.swift" }}
- v3-spm-deps-{{ checksum "Package.swift" }}
- run:
name: Copy Package File
command: cp Package.swift res
Expand All @@ -49,7 +49,7 @@ jobs:
name: Restoring Package File
command: mv res Package.swift
- save_cache:
key: v2-spm-deps-{{ checksum "Package.swift" }}
key: v3-spm-deps-{{ checksum "Package.swift" }}
paths:
- .build
workflows:
Expand Down
36 changes: 1 addition & 35 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,9 @@
Update your `Package.swift` file.

```swift
.package(url: "https://github.com/nodes-vapor/sugar.git", from: "3.0.0-beta")
.package(url: "https://github.com/nodes-vapor/sugar.git", from: "4.0.0")
```


## Getting started 🚀

Make sure that you've imported Sugar everywhere when needed:
Expand All @@ -25,41 +24,10 @@ Make sure that you've imported Sugar everywhere when needed:
import Sugar
```


## Helpers

This package contains a lot of misc. functionality that might not fit into it's own package or that would best to get PR'ed into Vapor. Some examples of what this package contains:

#### How to use it in a package

To have your package register the tags to the shared config, you can do the following:

```swift
public func didBoot(_ container: Container) throws -> Future<Void> {
let tags: MutableLeafTagConfig = try container.make()
tags.use(MyTag(), as: "mytag")

return .done(on: container)
}
```

#### How to use it in a project

If you're using a package that uses the shared `MutableLeafTagConfig`, these tags will become available in your project automatically. If you have additional tags you want to add, these has to be registered in `boot.swift` instead of `configure.swift` to allow the different providers to have registered their tags to the config first. Here's how you could do it:

```swift
public func boot(_ app: Application) throws {
// Register Leaf tags using the shared config.
// This allows third party packages to register their own tags.
let tags: MutableLeafTagConfig = try app.make()
tags.use(MyAdditionalTag())
}
```

> You don't have to register `tags` when adding this in `boot.swift`.
In the case where multiple packages is registering a tag using the same name, the tags can be added manually by defining your own name for the tags.

### Environment variables

Access environment variables by writing
Expand Down Expand Up @@ -93,13 +61,11 @@ extension MyModel: Migration {
}
```


## 🏆 Credits

This package is developed and maintained by the Vapor team at [Nodes](https://www.nodesagency.com).
The package owner for this project is [Siemen](https://github.com/siemensikkema).


## 📄 License

This package is open-sourced software licensed under the [MIT license](http://opensource.org/licenses/MIT)
2 changes: 1 addition & 1 deletion Sources/Sugar/Authentication/HasReadablePassword.swift
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/// Types conforming to this protocol can be used for login or register requests.
public protocol HasReadablePassword: Decodable {
public protocol HasReadablePassword {
/// Key path to the readable password.
static var readablePasswordKey: KeyPath<Self, String> { get }
}
17 changes: 17 additions & 0 deletions Sources/Sugar/Authentication/JWTAuthenticatable.swift
Original file line number Diff line number Diff line change
Expand Up @@ -50,3 +50,20 @@ extension JWTAuthenticatable {
}.unwrap(or: AuthenticationError.signingError)
}
}

extension JWTAuthenticatable where
Self: Model,
Self.ID: LosslessStringConvertible
{
/// See `JWTAuthenticatable`.
public static func authenticate(
using payload: JWTPayload,
on connection: DatabaseConnectable
) throws -> Future<Self?> {
guard let id = ID(payload.sub.value) else {
throw Sugar.AuthenticationError.malformedPayload
}

return find(id, on: connection)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ public final class JWTAuthenticationMiddleware<A: JWTAuthenticatable>: Middlewar
jwt = try JWT<A.JWTPayload>(from: bearer.token, verifiedUsing: signer)
} catch let error as JWTError where error.identifier == "exp" {
return try Future
.transform(to: HTTPResponse.init(status: .unauthorized), on: req)
.transform(to: HTTPResponse(status: .unauthorized), on: req)
.encode(for: req)
}

Expand Down
67 changes: 67 additions & 0 deletions Sources/Sugar/Authentication/Loginable.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
import Authentication
import Vapor

/// Expresses the ability for a type (e.g. a user type) to be logged in.
public protocol Loginable {

/// Payload containing the information required to perform a login.
associatedtype Login: HasReadablePassword

/// Used to perform any pre-login steps such as validation.
///
/// - Parameter req: the request.
/// - Returns: a `Future<Void>` signaling success or failure.
static func preLogin(on req: Request) -> Future<Void>

/// Performs the actual login. Called after `preLogin(on:)`.
///
/// - Parameters:
/// - login: the login information.
/// - worker: a worker on which to perform any database related actions like user lookup.
/// - Returns: an instance of self in the `Future` on successful login.
static func logIn(with login: Login, on worker: DatabaseConnectable) -> Future<Self>
}

extension Loginable {

/// Default implementation that does nothing.
/// See `Loginable`.
public static func preLogin(on req: Request) -> Future<Void> {
return req.future()
}
}

extension Loginable where
Self: PasswordAuthenticatable,
Self.Login: HasReadableUsername
{
/// Default implementation that uses functionality provided by `PasswordAuthenticatable`.
/// See `Loginable`.
public static func logIn(with login: Login, on worker: DatabaseConnectable) -> Future<Self> {
return Self
.authenticate(
username: login[keyPath: Login.readableUsernameKey],
password: login[keyPath: Login.readablePasswordKey],
using: BCrypt,
on: worker
)
.unwrap(or: AuthenticationError.userNotFound)
}
}

extension Loginable where Self.Login: Decodable {

/// Convenience function that combines `preLogin` and `logIn`.
///
/// - Parameter req: the request.
/// - Returns: an instance of self in the `Future` on successful login.
public static func logIn(on req: Request) -> Future<Self> {
return preLogin(on: req)
.flatMap {
try req.content.decode(Login.self)
}
.flatMap(to: Self.self) { login in
Self.logIn(with: login, on: req)
}
}
}
187 changes: 0 additions & 187 deletions Sources/Sugar/Authentication/UserType.swift

This file was deleted.

Loading

0 comments on commit a204e03

Please sign in to comment.