Created
March 27, 2019 11:27
-
-
Save Andrew-Lees11/2f1c9bf4f181044298f00ff48545ec03 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
import Kitura | |
import LoggerAPI | |
import Configuration | |
import CloudEnvironment | |
import KituraContracts | |
import Health | |
import KituraSession | |
public let projectPath = ConfigurationManager.BasePath.project.path | |
public let health = Health() | |
struct UserCredentials: Codable { | |
let username: String | |
let password: String | |
} | |
struct TypeSafeUser: TypeSafeMiddleware, Codable { | |
let userName: String | |
let extraInfo: String | |
static func handle(request: RouterRequest, response: RouterResponse, completion: @escaping (TypeSafeUser?, RequestError?) -> Void) { | |
guard let user: String = request.session?["User"] else { | |
return completion(nil, .unauthorized) | |
} | |
// If we have user they are logged in via the session | |
// Validate user is valid here using a database and retrieve extra info | |
let typeSafeUser = TypeSafeUser(userName: user, extraInfo: "extraInfo") | |
completion(typeSafeUser, nil) | |
} | |
} | |
public class App { | |
let router = Router() | |
let cloudEnv = CloudEnv() | |
let session = Session(secret: "Some secret", cookie: [.name("KituraLoginCookie")], store: nil) | |
public init() throws { | |
// Run the metrics initializer | |
initializeMetrics(router: router) | |
} | |
func postInit() throws { | |
// Endpoints | |
initializeHealthRoutes(app: self) | |
router.all(middleware: session) | |
router.post("/login") { request, response, next in | |
let credentials = try request.read(as: UserCredentials.self) | |
// Authenticate user using Credentials, if they fail reject the request | |
request.session?["User"] = credentials.username | |
let _ = response.send(status: HTTPStatusCode.OK) | |
next() | |
} | |
router.get("/me") { (user: TypeSafeUser, completion: (TypeSafeUser?, RequestError?) -> Void) in | |
print("User: \(user.userName) logged in and verified via session") | |
completion(user, nil) | |
} | |
} | |
public func run() throws { | |
try postInit() | |
Kitura.addHTTPServer(onPort: cloudEnv.port, with: router) | |
Kitura.run() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment