分类 标签 存档 黑客派 订阅 搜索

Perfect Turnstile

64 浏览

Package.swift

// 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

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)")
}
评论  
留下你的脚步
推荐阅读