2019-11-17 19:18:21 +01:00
|
|
|
defmodule PhilomenaWeb.ReloadUserPlug do
|
2019-12-17 03:49:17 +01:00
|
|
|
alias Plug.Conn
|
2019-10-31 18:57:39 +01:00
|
|
|
alias Pow.Plug
|
2019-12-16 23:50:15 +01:00
|
|
|
alias Philomena.Users
|
2019-10-31 18:57:39 +01:00
|
|
|
|
2019-12-17 03:49:17 +01:00
|
|
|
alias Philomena.UserIps.UserIp
|
|
|
|
alias Philomena.UserFingerprints.UserFingerprint
|
|
|
|
alias Philomena.Repo
|
2019-12-17 06:44:24 +01:00
|
|
|
import Ecto.Query
|
2019-12-17 03:49:17 +01:00
|
|
|
|
2019-10-31 18:57:39 +01:00
|
|
|
def init(opts), do: opts
|
|
|
|
|
|
|
|
def call(conn, _opts) do
|
|
|
|
config = Plug.fetch_config(conn)
|
|
|
|
|
|
|
|
case Plug.current_user(conn, config) do
|
|
|
|
nil ->
|
|
|
|
conn
|
|
|
|
|
|
|
|
user ->
|
2019-12-17 03:49:17 +01:00
|
|
|
spawn fn -> update_usages(conn, user) end
|
2019-12-16 23:50:15 +01:00
|
|
|
reloaded_user = Users.get_by(id: user.id)
|
2019-10-31 18:57:39 +01:00
|
|
|
|
|
|
|
Plug.assign_current_user(conn, reloaded_user, config)
|
|
|
|
end
|
|
|
|
end
|
2019-12-17 03:49:17 +01:00
|
|
|
|
|
|
|
# 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
|
2019-12-17 06:44:24 +01:00
|
|
|
update = update(UserIp, inc: [uses: 1], set: [updated_at: fragment("now()")])
|
|
|
|
|
2019-12-17 03:49:17 +01:00
|
|
|
Repo.insert_all(
|
|
|
|
UserIp,
|
|
|
|
[%{user_id: user.id, ip: ip, uses: 1}],
|
|
|
|
conflict_target: [:user_id, :ip],
|
2019-12-17 06:44:24 +01:00
|
|
|
on_conflict: update
|
2019-12-17 03:49:17 +01:00
|
|
|
)
|
|
|
|
end
|
|
|
|
|
|
|
|
if fp do
|
2019-12-17 06:44:24 +01:00
|
|
|
update = update(UserFingerprint, inc: [uses: 1], set: [updated_at: fragment("now()")])
|
|
|
|
|
2019-12-17 03:49:17 +01:00
|
|
|
Repo.insert_all(
|
|
|
|
UserFingerprint,
|
|
|
|
[%{user_id: user.id, fingerprint: fp, uses: 1}],
|
|
|
|
conflict_target: [:user_id, :fingerprint],
|
2019-12-17 06:44:24 +01:00
|
|
|
on_conflict: update
|
2019-12-17 03:49:17 +01:00
|
|
|
)
|
|
|
|
end
|
|
|
|
end
|
2019-12-16 23:50:15 +01:00
|
|
|
end
|