Um Zugriff auf seinen Einkaufwagen zu bekommen, muss sich ein Kunde mit E-Mail-Adresse und einem Kennwort identifizieren.
# login.rbx
require "cgi"
cgi = CGI.new("html3")
cgi.out {
cgi.html {
cgi.head { cgi.title{"Wenig & Teuer"} } +
cgi.body {
cgi.form("get", "eingang") {
cgi.hr + cgi.h1 { "E-Mail und Kennwort:" } +
cgi.text_field("benutzer") +
cgi.password_field("password") +
cgi.br + cgi.submit("Los gehts!")
}}}}
Nach erfolgreicher Anmeldung wird die den Einkaufswagen bestimmende E-Mail-Adresse in einem Cookie gespeichert.
# eingang.rbx
require "cgi"; require "mysql"; require "cart"
def reaktion(cgi, email, passwort)
if passwort_ok?(email, passwort)
cookie = CGI::Cookie::new("cart", email)
text = cgi.h2 { "Willkommen!" } + cgi.br +
cgi.a({"HREF" =>"liste"}) {
"Zum Einkaufen in den Shop."
}
else
cookie = CGI::Cookie::new("cart", "Not logged in")
text = "Anmeldung fehlgeschlagen."
end
return cookie, text
end
cgi = CGI.new("html3")
email = cgi['benutzer'][0]
passwort = cgi['password'][0]
cookie, text = reaktion(cgi, email, passwort)
cgi.out ({"cookie" => cookie }) {
cgi.html{
cgi.head { cgi.title{"Wenig & Teuer"} } +
cgi.body { text }
}}
Die verwendete Bibliothek cart.rb liegt im
gleichen Verzeichnis wie die ausführbaren .rbx-Dateien
und enthält Folgendes:
# cart.rb
def with_mysql_connection(&block)
m = Mysql.new("localhost", "einkauf", "swagen")
m.query("use Einkaufswagen;")
res = block.call(m)
m.close
res
end
def passwort_ok?(email, password)
with_mysql_connection { |m|
res = m.query("SELECT kennwort FROM kunden " +
"WHERE email = '#{email}';")
password == res.fetch_row[0]
}
end
def logged_in?(cgi)
cookie = cgi.cookies['cart']
cookie && cookie[0] != 'Not logged in'
end
def email(cgi)
cookie1=cgi.cookies['cart']
cookie1[0].to_s
end
# aus dem CGI-Kapitel übernommen
class CGI
def table2(tbl)
table {
tbl.collect { |row|
tr { row.collect { |item| td { item }}}}}
end
end
def fill_table(cgi, table, page, res)
res.each { |row|
row[0] = cgi.a({"HREF" => page +
"?artikel=#{row[0]}"}) { row[0] }
table << row
}
cgi.table2(table)
end