Skip to content

Commit

Permalink
feat: add login
Browse files Browse the repository at this point in the history
  • Loading branch information
zvonimirr committed Jun 15, 2024
1 parent bc5edfa commit cb6ae65
Show file tree
Hide file tree
Showing 4 changed files with 56 additions and 0 deletions.
14 changes: 14 additions & 0 deletions lib/swipex/user.ex
Original file line number Diff line number Diff line change
Expand Up @@ -9,4 +9,18 @@ defmodule Swipex.User do
password: password
})
end

def login(name, password) do
conn = Bolt.Sips.conn()

with {:ok, %Bolt.Sips.Response{results: [%{"u" => %{properties: user}}]}} <-
Bolt.Sips.query(conn, "MATCH (u:User {name: $name, password: $password}) RETURN u", %{
name: name,
password: password
}) do
{:ok, user}
else
_ -> {:error, "Invalid name or password."}
end
end
end
26 changes: 26 additions & 0 deletions lib/swipex_web/controllers/page.ex
Original file line number Diff line number Diff line change
Expand Up @@ -29,4 +29,30 @@ defmodule SwipexWeb.PageController do
|> put_flash(:error, "Invalid name or password.")
|> redirect(to: "/register")
end

def login(conn, _params) do
render(conn, :login)
end

def do_login(conn, %{
"name" => name,
"password" => password
}) do
with true <- String.length(name) > 0,
true <- String.length(password) > 0,
{:ok, user} <- Swipex.User.login(name, password) do
conn
|> put_flash(:info, "Logged in successfully!")
|> put_session(:user_id, user["id"])
|> redirect(to: "/")
else
_ -> do_login(conn, %{})
end
end

def do_login(conn, _params) do
conn
|> put_flash(:error, "Invalid name or password.")
|> redirect(to: "/login")
end
end
14 changes: 14 additions & 0 deletions lib/swipex_web/controllers/page_html.ex
Original file line number Diff line number Diff line change
Expand Up @@ -25,4 +25,18 @@ defmodule SwipexWeb.PageHTML do
</div>
"""
end

def login(assigns) do
~H"""
<div class="max-w-md mx-auto">
<p>Login to Swipex</p>
<form action="/login" method="post" class="flex flex-col gap-4">
<input type="text" name="name" placeholder="Name" />
<input type="password" name="password" placeholder="Password" />
<%= csrf_input_tag("/login") %>
<input type="submit" value="Login" />
</form>
</div>
"""
end
end
2 changes: 2 additions & 0 deletions lib/swipex_web/router.ex
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@ defmodule SwipexWeb.Router do
get "/", PageController, :index
get "/register", PageController, :register
post "/register", PageController, :do_register
get "/login", PageController, :login
post "/login", PageController, :do_login

# live_session :default, on_mount: [{SwipexWeb.Profile, :current_user}] do
# live "/", ProfileLive, :index
Expand Down

0 comments on commit cb6ae65

Please sign in to comment.