artyom-beilis / cppcms

CppCMS Framework
Other
443 stars 107 forks source link

Need a bit of help with sessions #88

Closed jpelizza closed 2 years ago

jpelizza commented 2 years ago

Hi, I've recently started learning web development and took interest in this project, I'm using it to learn a bit. I'm not sure if it's a bug or a concept I'm not aware of, I just made a small example for myself on how to use sessions, it goes like this: main.cpp is a basic copy paste from the examples.

int main(int argc,char ** argv){  
    try {
        cppcms::service srv(argc,argv);
        srv.applications_pool().mount(cppcms::applications_factory<hello>());
        std::cout << "Server started\n";
        srv.run();  
    }  
    catch(std::exception const &e) {  
        std::cerr << e.what() << std::endl;  
    }
}

hello.cpp is where my problem lies, on welcomePage every time I refresh the page the sessions starts blank, the response is "hi" and by the end it prints "Session ends: 1" on the terminal, from my understanding the idea is that a session is kept between pages, so I can easily fetch information like user login data, but I can't seem to save the changes made.

hello::hello(cppcms::service &srv) : cppcms::application(srv){
    dispatcher().assign("",&hello::welcomePage,this);  
    mapper().assign("");

    mapper().root("/hello");  
}

void hello::welcomePage(){
    std::cout << "Session starts:" << session()["helloSession"] << std::endl;

    //If Session is different then 1, say "hi", else say "bye"
    if(session().get("helloSession")!="1"){
        response().out() << "hi";
    }
    else{
        response().out() << "bye";
    }

    //If session == "1" then session = "0", else session = "1"
    if(session().get("helloSession")!="1"){
        session().set("helloSession","0");
    }
    else{
        session().set("helloSession","1");
    }

    std::cout << "Session ends:" << (session()["helloSession"]) << std::endl;
    return;
}

here is the config file, also taken from the examples:

{  
    "service" : {  
        "api" : "http",  
        "port" : 8080  
    },  
    "http" : {  
        "script_names" : [ "/hello" ]  
    },
    "session" : {  
        "expire" : "renew",  
        "timeout" : 604800,  
        "location" : "client",  
        "client" :      {  
            "hmac" :        "sha1",  
            "hmac_key" :    "3891bbf7f845fd4277008a63d72640fc13bb9a31"  
        }      
    }  
}  

Thanks for your time.

artyom-beilis commented 2 years ago

You must do all changes in session before you generate any output or request response().out()

Session is saved upon output stream request - since at this point all cookies must be send (HTTP headers prior to content) Once you write some output session is saved and you can't modify one.

jpelizza commented 2 years ago

Will keep that in mind, thanks.