track usages

This commit is contained in:
byte[] 2019-12-16 21:49:17 -05:00
parent 13765ca7da
commit a3e4706597

View file

@ -1,7 +1,12 @@
defmodule PhilomenaWeb.ReloadUserPlug do
alias Plug.Conn
alias Pow.Plug
alias Philomena.Users
alias Philomena.UserIps.UserIp
alias Philomena.UserFingerprints.UserFingerprint
alias Philomena.Repo
def init(opts), do: opts
def call(conn, _opts) do
@ -12,9 +17,37 @@ defmodule PhilomenaWeb.ReloadUserPlug do
conn
user ->
spawn fn -> update_usages(conn, user) end
reloaded_user = Users.get_by(id: user.id)
Plug.assign_current_user(conn, reloaded_user, config)
end
end
# TODO: move this to a background server instead of spawning
# off for every connection
defp update_usages(conn, user) do
conn = Conn.fetch_cookies(conn)
{:ok, ip} = EctoNetwork.INET.cast(conn.remote_ip)
fp = conn.cookies["_ses"]
if ip do
Repo.insert_all(
UserIp,
[%{user_id: user.id, ip: ip, uses: 1}],
conflict_target: [:user_id, :ip],
on_conflict: [inc: [uses: 1]]
)
end
if fp do
Repo.insert_all(
UserFingerprint,
[%{user_id: user.id, fingerprint: fp, uses: 1}],
conflict_target: [:user_id, :fingerprint],
on_conflict: [inc: [uses: 1]]
)
end
end
end