nulla/lib/nulla_web/controllers/auth_controller.ex
2025-06-21 14:31:37 +02:00

64 lines
1.8 KiB
Elixir

defmodule NullaWeb.AuthController do
use NullaWeb, :controller
alias Nulla.Models.User
alias Nulla.Models.Actor
alias Nulla.Models.InstanceSettings
def sign_in(conn, %{"email" => email, "password" => password}) do
user = User.get_user(email: email)
if user do
if Argon2.verify_pass(password, user.password) do
conn
|> put_session(:user_id, user.id)
|> redirect(to: "/")
else
conn
|> put_flash(:error, "Invalid login or password.")
|> redirect(to: ~p"/auth/sign_in")
end
else
conn
|> put_flash(:error, "User not exist.")
|> redirect(to: ~p"/auth/sign_in")
end
end
def sign_out(conn, _params) do
conn
|> configure_session(drop: true)
|> put_flash(:info, "You have been logged out.")
|> redirect(to: "/")
end
def sign_up(conn, %{"username" => username, "email" => email, "password" => password}) do
instance_settings = InstanceSettings.get_instance_settings!()
if not instance_settings.registration do
redirect(conn, to: "/")
end
domain = instance_settings.domain
hashed_password = Argon2.hash_pwd_salt(password)
{publicKeyPem, privateKeyPem} = Nulla.KeyGen.gen()
with {:ok, actor} <- Actor.create_actor_minimal(username, domain, publicKeyPem),
{:ok, user} <-
User.create_user(%{
id: actor.id,
email: email,
password: hashed_password,
privateKeyPem: privateKeyPem,
last_active_at: DateTime.utc_now()
}) do
conn
|> put_session(:user_id, user.id)
|> put_flash(:info, "You're registred!")
|> redirect(to: "/")
else
{:error, %Ecto.Changeset{} = changeset} ->
render(conn, "sign_up.html", changeset: changeset)
end
end
end