Jeden z úkolů který potřebujeme často řešit je přihlašování do webu. Přihlašování jsem zatím řešil na jednoduchém principu. Ten spočívá v kontrole uživatelského jména v sezení (session). Není-li v sezení definováno uživatelské jméno (username), přesměruji klienta na přihlašovací stránku login.kl1.
Ve stránce která je chráněna uvedu tedy následující od kontrolující přítomnost uživatelského jména v session.
<%
/* Check if user is logged in. Redirect to login if otherwise. */
username = session_get(session, "username");
if (!username) {
response_redirect(response, "login.kl1");
}
%>Stránka pro zadávání jména a hesla je v souboru login.kl1.
<%!
/*
* Přihlašovací formulář.
*/
static char *username = NULL;
static char *password = NULL;
%><%
/* get list of arguments */
vars_t *args = request_get_args(request);
username = vars_get_value(args, "username");
%>
<html>
<head>
<title>Login</title>
<link rel="stylesheet" href="kl.css" type="text/css" />
<meta http-equiv="content-type" content="text/html;charset=UTF-8" />
</head>
<body>
<h1>Login</h1>
<%
switch (vars_get_value_i(args, "action"))
{
case 1:
username = vars_get_value(args, "username");
password = vars_get_value(args, "password");
if (username && strlen(username) && password && strlen(password)) {
/* authenticate here */
session_set(session, "username", username);
response_redirect(response, "/index.kl1");
io_printf(out, "Do something with (username, password):" \
" (%s,%s)", username, password);
} else {
io_printf(out, "Bad (username, passwprd)");
}
}
%>
<form action="<%= SCRIPT_NAME %>" method="post">
<table rules="all" border="1">
<tr>
<th>username:</th>
<td><input type="text" name="username"/></td>
</tr>
<tr>
<th>password:</th>
<td><input type="password" name="password"/></td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="login"/></td>
</tr>
</table>
<input type="hidden" value="1" name="action"/>
</form>
</body>
</html>To be done: