gpt4 book ai didi

swift - 具有完美身份验证和路由的服务器端 Swift

转载 作者:行者123 更新时间:2023-11-28 15:35:46 27 4
gpt4 key购买 nike

我有设置为上传文件的服务器端 swift 项目。我正在尝试对项目进行身份验证,以便只能通过有效登录访问文件。

ma​​in.swift

import PerfectLib
import PerfectHTTP
import PerfectHTTPServer

import StORM
import SQLiteStORM
import PerfectTurnstileSQLite
import PerfectRequestLogger
import TurnstilePerfect

//StORMdebug = true

// Used later in script for the Realm and how the user authenticates.
let pturnstile = TurnstilePerfectRealm()


// Set the connection vatiable
//connect = SQLiteConnect("./authdb")
SQLiteConnector.db = "./authdb"
RequestLogFile.location = "./http_log.txt"

// Set up the Authentication table
let auth = AuthAccount()
try? auth.setup()

// Connect the AccessTokenStore
tokenStore = AccessTokenStore()
try? tokenStore?.setup()

//let facebook = Facebook(clientID: "CLIENT_ID", clientSecret: "CLIENT_SECRET")
//let google = Google(clientID: "CLIENT_ID", clientSecret: "CLIENT_SECRET")

// Create HTTP server.
let server = HTTPServer()

// Register routes and handlers
let authWebRoutes = makeWebAuthRoutes()
let authJSONRoutes = makeJSONAuthRoutes("/api/v1")

// Add the routes to the server.
server.addRoutes(authWebRoutes)
server.addRoutes(authJSONRoutes)

// Adding a test route
var routes = Routes()
var postHandle: [[String: Any]] = [[String: Any]]()
routes.add(method: .get, uri: "/api/v1/test", handler: AuthHandlersJSON.testHandler)
routes.add(method: .post, uri: "/", handler: {
request, response in

// Context variable, which also initializes the "files" array
var context = ["files":[[String:String]]()]

// Process only if request.postFileUploads is populated
if let uploads = request.postFileUploads, uploads.count > 0 {

// iterate through the file uploads.
for upload in uploads {

// move file
let thisFile = File(upload.tmpFileName)
do {
let _ = try thisFile.moveTo(path: "./webroot/uploads/\(upload.fileName)", overWrite: true)
} catch {
print(error)
}
}
}

// Inspect the uploads directory contents
let d = Dir("./webroot/uploads")
do{
try d.forEachEntry(closure: {f in
context["files"]?.append(["name":f])
})
} catch {
print(error)
}


// Render the Mustache template, with context.
response.render(template: "index", context: context)
response.completed()
})
routes.add(method: .get, uri: "/", handler: {
request, response in

// Context variable, which also initializes the "files" array
var context = ["files":[[String:String]]()]

// Process only if request.postFileUploads is populated
if let uploads = request.postFileUploads, uploads.count > 0 {

// iterate through the file uploads.
for upload in uploads {

// move file
let thisFile = File(upload.tmpFileName)
do {
let _ = try thisFile.moveTo(path: "./webroot/uploads/\(upload.fileName)", overWrite: true)
} catch {
print(error)
}
}
}

// Inspect the uploads directory contents
let d = Dir("./webroot/uploads")
do{
try d.forEachEntry(closure: {f in
context["files"]?.append(["name":f])
})
} catch {
print(error)
}

var resp = [String: String]()
resp["authenticated"] = "AUTHED: \(request.user.authenticated)"
// Render the Mustache template, with context.
response.render(template: "index", context: resp)
response.completed()
})
routes.add(method: .get, uri: "/**", handler: try PerfectHTTPServer.HTTPHandler.staticFiles(data: ["documentRoot":"./webroot",
"allowResponseFilters":true]))


// An example route where authentication will be enforced
routes.add(method: .get, uri: "/api/v1/check", handler: {
request, response in
response.setHeader(.contentType, value: "application/json")

var resp = [String: String]()
resp["authenticated"] = "AUTHED: \(request.user.authenticated)"
resp["authDetails"] = "DETAILS: \(String(describing: request.user.authDetails))"

do {
try response.setBody(json: resp)
} catch {
print(error)
}
response.completed()
})


// An example route where auth will not be enforced
routes.add(method: .get, uri: "/api/v1/nocheck", handler: {
request, response in
response.setHeader(.contentType, value: "application/json")

var resp = [String: String]()
resp["authenticated"] = "AUTHED: \(request.user.authenticated)"
resp["authDetails"] = "DETAILS: \(String(describing: request.user.authDetails))"

do {
try response.setBody(json: resp)
} catch {
print(error)
}
response.completed()
})



// Add the routes to the server.
server.addRoutes(routes)


// Setup logging
let myLogger = RequestLogger()

// add routes to be checked for auth
var authenticationConfig = AuthenticationConfig()
authenticationConfig.include("/api/v1/check")
authenticationConfig.exclude("/api/v1/login")
authenticationConfig.exclude("/api/v1/register")

let authFilter = AuthFilter(authenticationConfig)

// Note that order matters when the filters are of the same priority level
server.setRequestFilters([pturnstile.requestFilter])
server.setResponseFilters([pturnstile.responseFilter])

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

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

// Set a listen port of 8181
server.serverPort = 8181

// Where to serve static files from
server.documentRoot = "./webroot"

do {
// Launch the HTTP server.
try server.start()
} catch PerfectError.networkError(let err, let msg) {
print("Network error thrown: \(err) \(msg)")
}

如果我将 context: 更改为 context,我就会陷入循环,就像我在成功登录后仍未登录一样。如果我更改 context: resp,我会一直处于登录状态,并且看不到文件。

    var resp = [String: String]()
resp["authenticated"] = "AUTHED: \(request.user.authenticated)"
// Render the Mustache template, with context.
response.render(template: "index", context: resp)
response.completed()

index.mustache

{{>header}}

{{^authenticated}}
<h1>Hi! Sign up today!</h1>
{{/authenticated}}
{{#authenticated}}
<h1>Hi! {{username}}</h1>
<p>Your ID is: <code>{{accountID}}</code></p>
<h2>File uploads</h2>
<form method="POST" enctype="multipart/form-data" action="">
File to upload: <input type="file" name="fileup"><br>
<input type="submit" value="Upload files now.">
</form>

<h3>Files:</h3>
{{#files}}<a href="/uploads/{{name}}">{{name}}</a><br>{{/files}}
{{/authenticated}}



{{>footer}}

更新

我即将让网站按照我希望的方式运行。代码展示了我所做的更改以及我需要克服的新障碍。哪个是如何在同一 render 中使用两个不同的上下文?

routes.add(method: .get, uri: "/", handler: { request, response in

if request.user.authenticated == true {
guard let accountID = request.user.authDetails?.account.uniqueID else { return }

do {
let newDir = Dir("./webroot/uploads/\(String(describing: accountID))")
let _ = try newDir.create()
} catch {

}
// Context variable, which also initializes the "files" array
var context = ["files":[[String:String]]()]

// Process only if request.postFileUploads is populated
if let uploads = request.postFileUploads, uploads.count > 0 {

// iterate through the file uploads.
for upload in uploads {

// move file
let thisFile = File(upload.tmpFileName)
do {
let _ = try thisFile.moveTo(path: "./webroot/uploads/\(String(describing: accountID))/\(upload.fileName)", overWrite: true)
} catch {
print(error)
}
}
}

// Inspect the uploads directory contents
let d = Dir("./webroot/uploads/\(String(describing: accountID))")
do{
try d.forEachEntry(closure: {f in
context["files"]?.append(["name":f])
})
} catch {
print(error)
}
let setID = [["accountID": accountID]]
var dic = [String: String]()
for item in setID {
for (kind, value) in item {
dic.updateValue(value, forKey: kind)
}
}

var context1 = ["files":String()]
context1.updateValue(accountID, forKey: "accountID")
// Render the Mustache template, with context.
response.render(template: "loggedin", context: context) // I only get this context info.
response.render(template: "loggedin", context: context1) // This is ignored unless I comment out the line above.
response.completed()

} else {
response.render(template: "index")
response.completed()

}
})

也改了这一段代码。

var authenticationConfig = AuthenticationConfig()
authenticationConfig.include("/api/v1/check")
authenticationConfig.include("/loggedin") // Added this line
authenticationConfig.exclude("/api/v1/login")
authenticationConfig.exclude("/api/v1/register")

最佳答案

如果您查看以下部分:

var authenticationConfig = AuthenticationConfig()
authenticationConfig.include("/api/v1/check")
authenticationConfig.exclude("/api/v1/login")
authenticationConfig.exclude("/api/v1/register")

您可以在此处主动包括或排除对身份验证状态的检查。

你想从授权检查中排除的路由应该总是有一个主路由和一个登录/注册。然后您可以专门包含路由,或使用通配符。

关于swift - 具有完美身份验证和路由的服务器端 Swift,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44290848/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com