Skip to content

Commit

Permalink
vibe.web.web: Add session convenience getter
Browse files Browse the repository at this point in the history
  • Loading branch information
wilzbach committed Nov 30, 2017
1 parent 714e6bc commit 0ae60e8
Showing 1 changed file with 48 additions and 0 deletions.
48 changes: 48 additions & 0 deletions web/vibe/web/web.d
Original file line number Diff line number Diff line change
Expand Up @@ -480,6 +480,52 @@ body
}
}

/**
Returns the current session object.
If no session exists, a new session is started.
Note that this may only be called from a function/method
registered using registerWebInterface.
See_Also: $(LREF terminateSession)
*/
auto session() @safe
{
auto ctx = getRequestContext();
assert(request !is null, "session() used outside of a web interface request!");
auto _session = ctx.req.session;
if (!_session)
_session = ctx.res.startSession;
return _session;
}

///
@safe unittest {
class WebService {
// GET /me
Json getMe() {
enforceHTTP(session.isKeySet("username"), HTTPStatus.forbidden, "Not authorized to perform this action!");

return Json(["username": session.get!string("username").Json]);
}

// POST
void postLogin(string username) {
session.set("username", username);
}
}

void run()
{
auto router = new URLRouter;
router.registerWebInterface(new WebService);

auto settings = new HTTPServerSettings;
settings.sessionStore = new MemorySessionStore();
settings.port = 8080;
listenHTTP(settings, router);
}
}
/**
Returns the agreed upon language.
Expand Down Expand Up @@ -574,6 +620,8 @@ body
Note that this may only be called from a function/method
registered using registerWebInterface.
See_Also: $(LREF session)
*/
void terminateSession()
@safe {
Expand Down

0 comments on commit 0ae60e8

Please sign in to comment.