Perfect Turnstile

Package.swift

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// swift-tools-version:4.0
// The swift-tools-version declares the minimum version of Swift required to build this package.

import PackageDescription

let package = Package(
name: "Test",
dependencies: [
// Dependencies declare other packages that this package depends on.
// .package(url: /* package url */, from: "1.0.0"),
.package(url: "https://github.com/PerfectlySoft/Perfect-Turnstile-MySQL.git", from: "3.0.0"),
.package(url: "https://github.com/PerfectlySoft/Perfect-RequestLogger.git", from: "3.0.0"),
],
targets: [
// Targets are the basic building blocks of a package. A target can define a module or a test suite.
// Targets can depend on other targets in this package, and on products in packages which this package depends on.
.target(
name: "Test",
dependencies: ["PerfectTurnstileMySQL", "PerfectRequestLogger"]),
]
)

main.swift

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
import PerfectLib
import PerfectHTTP
import PerfectHTTPServer

import StORM
import MySQLStORM
import PerfectTurnstileMySQL
import TurnstilePerfect
import PerfectRequestLogger

StORMdebug = true

//设置链接参数
MySQLConnector.host = "127.0.0.1"
MySQLConnector.username = "root"
MySQLConnector.password = "Jxt51921100%"
MySQLConnector.database = "test"
MySQLConnector.port = 3306

//用户域
let pturestile = TurnstilePerfectRealm()

//设置认证表
let auth = AuthAccount()
try? auth.setup()

//链接到令牌管理库
//let tokenStore = AccessTokenStore()
//try? tokenStore.setup()

tokenStore = AccessTokenStore()
try? tokenStore?.setup()

//创建HTTP服务器
var server = HTTPServer()

//let authWebRoutes = makeWebAuthRoutes()
let authJSONRoutes = makeJSONAuthRoutes("api/v1")

//server.addRoutes(authWebRoutes)
server.addRoutes(authJSONRoutes)

var routes = Routes()
routes.add(method: .get, uri: "/api/v1/hello") { (request, response) in
do {
try response.setBody(json: ["msg": "Hello world"])
} catch {
print(error)
}
response.completed()
}

server.addRoutes(routes)

RequestLogFile.location = "./requests.log"
let logger = RequestLogger()

//Authorization: Bearer SrEJbEEzeRRGfs9VZVbBnw

//增加验证路由
var authConfig = AuthenticationConfig()
authConfig.include("/api/v1/*")
authConfig.exclude(["/api/v1/login", "/api/v1/register"])

let authFilter = AuthFilter(authConfig)

server.setRequestFilters([pturestile.requestFilter])
server.setResponseFilters([pturestile.responseFilter])

server.setRequestFilters([(authFilter, .high)])

server.setRequestFilters([(logger, .high)])
server.setResponseFilters([(logger, .low)])

server.serverPort = 8181
server.documentRoot = "./webroot"

do {
try server.start()
} catch PerfectError.networkError(let code, let msg) {
print("Error code: \(code), Error msg: \(msg)")
}