swifthttp-redirectperfectserver-side-swift

Unable to redirect to url using Server Side Swift Perfect


I'm using Server Side Swift Perfect framework for web services. Mustache module for serving static/dynamic content.

I want to implement login functionality following a redirect to the homepage on Successful authentication. "I searched everywhere but didn't find any such feature which redirects to a url"

Here is the code I'm using for implementing login-

func signin(request:HTTPRequest, response: HTTPResponse) {
    do {
        var errorMessage:String;
        var values = MustacheEvaluationContext.MapType()
        let email:String = request.param(name: "email")!
        let password:String = request.param(name: "password")!
        print("Email -> \(email) & Password -> \(password)")
        //After Authentication
        //Yay I want to go back to home page.
        mustacheRequest(request: request, response: response, handler: MustacheHelper(values: values), templatePath: webroot + "/index.html")
        // Sadly this doesn't work, it just renders the homepage without changing the url or 'without redirecting'
        response.completed()
} catch {
        print(error)
        logError(error.localizedDescription)
        response.setBody(string: "An error occured \(error)").completed()
    }
}

I think the company PerfectlySoft fogot to put this feature. May be I should report it. Anybody knows what could be the solution to my problem? Please tell. Thanks.


Solution

  • Finally I myself figured out the solution. This feature of url redirection is not included in PerfectHTTP or PerfectHTTPServer module itself. You have to import another module -> Perfect-OAuth2 by PerfectlySoft. 'redirect' method is directly declared under HTTPResponse extension. OR you can do it by adding your own like this,

    extension HTTPResponse {
        public func redirect(path: String) {
            self.status = .found
            self.setHeader(.location, value: path)
            self.completed()
        }
    }
    

    I hope this helps!