|
Mix.install [:plug, :bandit] |
|
defmodule Sess.Router do |
|
use Plug.Router |
|
|
|
plug(Plug.Logger) |
|
|
|
plug(Plug.Session, |
|
store: :cookie, |
|
key: "_sess_session", |
|
max_age: 24*60*60*30, # 30 days |
|
signing_salt: "not_a_secret", |
|
# The secret key base should not be configured in plain text |
|
secret_key_base: "this should be a secret and at least 64 bytes =============================" |
|
) |
|
|
|
plug(:fetch_session) |
|
plug(:match) |
|
plug(:dispatch) |
|
|
|
get "/login" do |
|
html = login_html() |
|
|
|
conn |
|
|> put_resp_header("content-type", "text/html; charset=utf-8") |
|
|> send_resp(200, html) |
|
end |
|
|
|
get "/auth" do |
|
conn = fetch_query_params(conn) |
|
%{"password" => pass, "username" => username} = conn.query_params |
|
|
|
if username == "admin" and pass == "admin" do |
|
# може да мислите за put_session с cookie като |
|
# съхранение на данните не локално, а в браузъра на потребителя. |
|
conn |
|
|> put_session("authenticated?", true) |
|
|> send_resp(200, "You've been authenticated!") |
|
else |
|
conn |
|
|> send_resp(401, "Unauthorized") |
|
end |
|
end |
|
|
|
get "/secret" do |
|
# `get` инжектира conn имплицитно. При използване на Phoenix |
|
# тези неща става експлицитни и доста по-разбираеми. |
|
if conn.private.plug_session["authenticated?"] do |
|
conn |
|
|> send_resp(200, "A secret has been revealed to you!") |
|
else |
|
conn |
|
|> send_resp(200, "Look away!") |
|
end |
|
end |
|
|
|
match(_, do: send_resp(conn, 404, "not found")) |
|
|
|
defp login_html() do |
|
""" |
|
<form action="/auth"> |
|
<input type="name" name="username" placeholder="Username" /><br /> |
|
<input type="password" name="password" placeholder="Password" /><br /> |
|
<input type="submit" value="Login"> |
|
</form> |
|
""" |
|
end |
|
end |
|
|
|
webserver = {Bandit, plug: Sess.Router, scheme: :http, port: 4000} |
|
Supervisor.start_link([webserver], strategy: :one_for_one, name: Sess.Supervisor) |