You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
analytics/lib/plausible/auth/user.ex

272 lines
7.8 KiB
Elixir

7 years ago
defimpl Bamboo.Formatter, for: Plausible.Auth.User do
def format_email_address(user, _opts) do
{user.name, user.email}
end
end
defimpl FunWithFlags.Actor, for: Plausible.Auth.User do
def id(%{id: id}) do
"user:#{id}"
end
end
7 years ago
defmodule Plausible.Auth.User do
use Plausible
7 years ago
use Ecto.Schema
import Ecto.Changeset
@type t() :: %__MODULE__{}
Implement better user password validation (#3344) * Add zxcvbn dependency * Change password length range requirement from 6-64 to 12-128 * Reimplement register form in LV * Implement server-side check for password strength * Add rudimentary strength meter * Make password input with strength a separate component and improve it * Fix existing tests to provide strong enough password * Apply formatting * Replace existing registration form with new one * Hide built-in label in `.input` component when none provided * Crop password to first 32 chars for analysis by zxcvbn * Add tests for new form components * Integrate hCaptcha into LV * Fix existing AuthController tests * Add tests for Live.RegisterForm * Hide strength meter when password input is empty * Randomize client IP in headers during tests to avoid hitting rate limit * Apply auxilliary formatting fixes to AuthController * Integrate registration from invitation into LV registration logic * Fix existing password set and reset forms * Make `password_length_hint` component more customizable * Optimize `Auth.User.set_password/2` * Remove unnecessary attribute from registration form * Move password set and reset forms to LV * Add tests for SetPasswordForm LV component * Add tests for password checks in `Auth.User` * Document code a bit * Implement simpler approach to hCaptcha integration * Update CHANGELOG.md * Improve consistency of color scheme * Introduce debounce across all text inputs in registration and password forms * Fix email input background in register form * Ensure only single error is rendered for empty password confirmation case * Remove `/password` form entirely in favor of preferred password reset * Remove unnecessary `router` option from `live_render` calls * Make expensive assigns in LV with `assign_new` (h/t @aerosol) * Accept passwords longer than 32 bytes uniformly as very strong * Avoid displaying blank error side by side with weak password error * Make register actions handle errors gracefully * Render only a single piece of feedback to reduce noise * Make register and password reset forms pw manager friendly (h/t @cnkk) * Move registration forms to live routes * Delete no longer used deadviews * Adjust registration form in accordance to changes in #3290 * Reintroduce dogfood page path for invitation form from #3290 * Use alternative approach to submitting plausible metrics from LV form * Rename metrics events and extend tests to account for them
3 years ago
@required [:email, :name, :password]
@trial_accept_traffic_until_offset_days 14
@susbscription_accept_traffic_until_offset_days 30
7 years ago
schema "users" do
field :email, :string
field :password_hash
field :password, :string, virtual: true
field :password_confirmation, :string, virtual: true
7 years ago
field :name, :string
field :last_seen, :naive_datetime
field :trial_expiry_date, :date
field :theme, Ecto.Enum, values: [:system, :light, :dark]
field :email_verified, :boolean
field :previous_email, :string
field :accept_traffic_until, :date
# A field only used as a manual override - allow subscribing
# to any plan, even when exceeding its pageview limit
field :allow_next_upgrade_override, :boolean
# Fields for TOTP authentication. See `Plausible.Auth.TOTP`.
field :totp_enabled, :boolean, default: false
field :totp_secret, Plausible.Auth.TOTP.EncryptedBinary
Implement UI for 2FA setup and verification (#3541) * Add 2FA actions to `AuthController` * Hook up new `AuthController` actions to router * Add `qr_code` to project dependencies * Implement generic `qr_code` component rendering SVG QR code from text * Implement enabled and disabled 2FA setting state in user settings view * Implement view for initiating 2FA setup * Implement view for verifying 2FA setup * Implement view for rendering generated 2FA recovery codes * Implement view for verifying 2FA code * Implement view for verifying 2FA recovery code * Improve `input_with_clipboard` component * Improve view for initiating 2FA setup * Improve verify 2FA setup view * Implement `verify_2fa_input` component * Improve view for verifying 2FA setup * Improve view rendering generated 2FA recovery codes * Use `verify_2fa_input` component in verify 2FA view * Do not render PA contact on self-hosted instances * Improve flash message phrasing on generated recovery codes * Add byline with a warning to disable 2FA modal * Extract modal to component and move 2FA components to dedicated module * First pass on loading state for "generate new codes" * Adjust modal button logic * Fix button in verify_2fa_input component * Use button component in activate view * Implement wait states for recovery code related actions properly * Apply rate limiting to 2FA verification * Log failed 2FA code input attempts * Add ability to trust device and skip 2FA for 30 days * Improve styling in dark mode * Fix waiting state under Chrome and Safari * Delete trust cookie when disabling 2FA * Put 2FA behind a feature flag * Extract 2FA cookie deletion * ff fixup * Improve session management during 2FA login * Extract part of 2FA controller logic to a separate module and clean up a bit * Clear 2FA user session when rate limit hit * Add id to form in verify 2FA setup view * Add controller tests for 2FA actions and login action * Update CHANGELOG.md * Use `full_build?()` instead of `@is_selfhost` removed after rebase * Update `Auth.TOTP` moduledoc * Add TOTP token management and make `TOTP.enable` more test-friendly * Use TOTP token for device trust feature * Use zero-deps `eqrcode` instead of deps-heavy `qr_code` * Improve flash messages copy Co-authored-by: hq1 <hq@mtod.org> * Make one more copy improvement Co-authored-by: hq1 <hq@mtod.org> * Fix copy in remaining spots * Change redirect after login to accept URLs from #3560 (h/t @aerosol) * Add tests checking handling login_dest on login and 2FA verification * Fix regression in email activation form submit button behavior * Rename `PlausibleWeb.TwoFactor` -> `PlausibleWeb.TwoFactor.Session` * Move `qr_code` component under `Components.TwoFactor` * Set domain and secure options for new cookies --------- Co-authored-by: hq1 <hq@mtod.org>
3 years ago
field :totp_token, :string
field :totp_last_used_at, :naive_datetime
embeds_one :grace_period, Plausible.Auth.GracePeriod, on_replace: :update
7 years ago
has_many :site_memberships, Plausible.Site.Membership
has_many :sites, through: [:site_memberships, :site]
has_many :api_keys, Plausible.Auth.ApiKey
7 years ago
has_one :google_auth, Plausible.Site.GoogleAuth
has_one :subscription, Plausible.Billing.Subscription
has_one :enterprise_plan, Plausible.Billing.EnterprisePlan
7 years ago
timestamps()
end
def new(attrs \\ %{}) do
%Plausible.Auth.User{}
|> cast(attrs, @required)
|> validate_required(@required)
Implement better user password validation (#3344) * Add zxcvbn dependency * Change password length range requirement from 6-64 to 12-128 * Reimplement register form in LV * Implement server-side check for password strength * Add rudimentary strength meter * Make password input with strength a separate component and improve it * Fix existing tests to provide strong enough password * Apply formatting * Replace existing registration form with new one * Hide built-in label in `.input` component when none provided * Crop password to first 32 chars for analysis by zxcvbn * Add tests for new form components * Integrate hCaptcha into LV * Fix existing AuthController tests * Add tests for Live.RegisterForm * Hide strength meter when password input is empty * Randomize client IP in headers during tests to avoid hitting rate limit * Apply auxilliary formatting fixes to AuthController * Integrate registration from invitation into LV registration logic * Fix existing password set and reset forms * Make `password_length_hint` component more customizable * Optimize `Auth.User.set_password/2` * Remove unnecessary attribute from registration form * Move password set and reset forms to LV * Add tests for SetPasswordForm LV component * Add tests for password checks in `Auth.User` * Document code a bit * Implement simpler approach to hCaptcha integration * Update CHANGELOG.md * Improve consistency of color scheme * Introduce debounce across all text inputs in registration and password forms * Fix email input background in register form * Ensure only single error is rendered for empty password confirmation case * Remove `/password` form entirely in favor of preferred password reset * Remove unnecessary `router` option from `live_render` calls * Make expensive assigns in LV with `assign_new` (h/t @aerosol) * Accept passwords longer than 32 bytes uniformly as very strong * Avoid displaying blank error side by side with weak password error * Make register actions handle errors gracefully * Render only a single piece of feedback to reduce noise * Make register and password reset forms pw manager friendly (h/t @cnkk) * Move registration forms to live routes * Delete no longer used deadviews * Adjust registration form in accordance to changes in #3290 * Reintroduce dogfood page path for invitation form from #3290 * Use alternative approach to submitting plausible metrics from LV form * Rename metrics events and extend tests to account for them
3 years ago
|> validate_length(:password, min: 12, message: "has to be at least 12 characters")
|> validate_length(:password, max: 128, message: "cannot be longer than 128 characters")
|> validate_confirmation(:password, required: true)
|> validate_password_strength()
|> hash_password()
|> start_trial()
|> set_email_verification_status()
|> unique_constraint(:email)
end
def settings_changeset(user, attrs \\ %{}) do
user
|> cast(attrs, [:email, :name, :theme])
|> validate_required([:email, :name, :theme])
|> unique_constraint(:email)
end
def email_changeset(user, attrs \\ %{}) do
user
|> cast(attrs, [:email, :password])
|> validate_required([:email, :password])
|> validate_email_changed()
|> check_password()
|> unique_constraint(:email)
|> set_email_verification_status()
|> put_change(:previous_email, user.email)
end
def cancel_email_changeset(user) do
if user.previous_email do
user
|> change()
|> unique_constraint(:email)
|> put_change(:email_verified, true)
|> put_change(:email, user.previous_email)
|> put_change(:previous_email, nil)
else
# It shouldn't happen under normal circumstances
raise "Previous email is empty for user #{user.id} (#{user.email}) when it shouldn't."
end
end
7 years ago
def changeset(user, attrs \\ %{}) do
user
|> cast(attrs, [
:email,
:name,
:email_verified,
:theme,
:trial_expiry_date,
:allow_next_upgrade_override,
:accept_traffic_until
])
|> validate_required([:email, :name, :email_verified])
|> maybe_bump_accept_traffic_until()
7 years ago
|> unique_constraint(:email)
end
defp maybe_bump_accept_traffic_until(changeset) do
expiry_change = get_change(changeset, :trial_expiry_date)
if expiry_change do
put_change(
changeset,
:accept_traffic_until,
Date.add(expiry_change, @trial_accept_traffic_until_offset_days)
)
else
changeset
end
end
7 years ago
def set_password(user, password) do
user
|> cast(%{password: password}, [:password])
Implement better user password validation (#3344) * Add zxcvbn dependency * Change password length range requirement from 6-64 to 12-128 * Reimplement register form in LV * Implement server-side check for password strength * Add rudimentary strength meter * Make password input with strength a separate component and improve it * Fix existing tests to provide strong enough password * Apply formatting * Replace existing registration form with new one * Hide built-in label in `.input` component when none provided * Crop password to first 32 chars for analysis by zxcvbn * Add tests for new form components * Integrate hCaptcha into LV * Fix existing AuthController tests * Add tests for Live.RegisterForm * Hide strength meter when password input is empty * Randomize client IP in headers during tests to avoid hitting rate limit * Apply auxilliary formatting fixes to AuthController * Integrate registration from invitation into LV registration logic * Fix existing password set and reset forms * Make `password_length_hint` component more customizable * Optimize `Auth.User.set_password/2` * Remove unnecessary attribute from registration form * Move password set and reset forms to LV * Add tests for SetPasswordForm LV component * Add tests for password checks in `Auth.User` * Document code a bit * Implement simpler approach to hCaptcha integration * Update CHANGELOG.md * Improve consistency of color scheme * Introduce debounce across all text inputs in registration and password forms * Fix email input background in register form * Ensure only single error is rendered for empty password confirmation case * Remove `/password` form entirely in favor of preferred password reset * Remove unnecessary `router` option from `live_render` calls * Make expensive assigns in LV with `assign_new` (h/t @aerosol) * Accept passwords longer than 32 bytes uniformly as very strong * Avoid displaying blank error side by side with weak password error * Make register actions handle errors gracefully * Render only a single piece of feedback to reduce noise * Make register and password reset forms pw manager friendly (h/t @cnkk) * Move registration forms to live routes * Delete no longer used deadviews * Adjust registration form in accordance to changes in #3290 * Reintroduce dogfood page path for invitation form from #3290 * Use alternative approach to submitting plausible metrics from LV form * Rename metrics events and extend tests to account for them
3 years ago
|> validate_required([:password])
|> validate_length(:password, min: 12, message: "has to be at least 12 characters")
|> validate_length(:password, max: 128, message: "cannot be longer than 128 characters")
|> validate_password_strength()
|> hash_password()
7 years ago
end
def hash_password(%{errors: [], changes: changes} = changeset) do
hash = Plausible.Auth.Password.hash(changes[:password])
change(changeset, password_hash: hash)
end
def hash_password(changeset), do: changeset
def remove_trial_expiry(user) do
change(user, trial_expiry_date: nil)
end
def start_trial(user) do
trial_expiry = trial_expiry()
change(user,
trial_expiry_date: trial_expiry,
accept_traffic_until: Date.add(trial_expiry, @trial_accept_traffic_until_offset_days)
)
end
def end_trial(user) do
change(user, trial_expiry_date: Timex.today() |> Timex.shift(days: -1))
end
Implement better user password validation (#3344) * Add zxcvbn dependency * Change password length range requirement from 6-64 to 12-128 * Reimplement register form in LV * Implement server-side check for password strength * Add rudimentary strength meter * Make password input with strength a separate component and improve it * Fix existing tests to provide strong enough password * Apply formatting * Replace existing registration form with new one * Hide built-in label in `.input` component when none provided * Crop password to first 32 chars for analysis by zxcvbn * Add tests for new form components * Integrate hCaptcha into LV * Fix existing AuthController tests * Add tests for Live.RegisterForm * Hide strength meter when password input is empty * Randomize client IP in headers during tests to avoid hitting rate limit * Apply auxilliary formatting fixes to AuthController * Integrate registration from invitation into LV registration logic * Fix existing password set and reset forms * Make `password_length_hint` component more customizable * Optimize `Auth.User.set_password/2` * Remove unnecessary attribute from registration form * Move password set and reset forms to LV * Add tests for SetPasswordForm LV component * Add tests for password checks in `Auth.User` * Document code a bit * Implement simpler approach to hCaptcha integration * Update CHANGELOG.md * Improve consistency of color scheme * Introduce debounce across all text inputs in registration and password forms * Fix email input background in register form * Ensure only single error is rendered for empty password confirmation case * Remove `/password` form entirely in favor of preferred password reset * Remove unnecessary `router` option from `live_render` calls * Make expensive assigns in LV with `assign_new` (h/t @aerosol) * Accept passwords longer than 32 bytes uniformly as very strong * Avoid displaying blank error side by side with weak password error * Make register actions handle errors gracefully * Render only a single piece of feedback to reduce noise * Make register and password reset forms pw manager friendly (h/t @cnkk) * Move registration forms to live routes * Delete no longer used deadviews * Adjust registration form in accordance to changes in #3290 * Reintroduce dogfood page path for invitation form from #3290 * Use alternative approach to submitting plausible metrics from LV form * Rename metrics events and extend tests to account for them
3 years ago
def password_strength(changeset) do
case get_field(changeset, :password) do
nil ->
%{suggestions: [], warning: "", score: 0}
# Passwords past (approximately) 32 characters are treated
# as strong, despite what they contain, to avoid unnecessarily
# expensive computation.
password when byte_size(password) > 32 ->
%{suggestions: [], warning: "", score: 4}
password ->
existing_phrases =
[]
|> maybe_add_phrase(get_field(changeset, :name))
|> maybe_add_phrase(get_field(changeset, :email))
case ZXCVBN.zxcvbn(password, existing_phrases) do
%{score: score, feedback: feedback} ->
%{suggestions: feedback.suggestions, warning: feedback.warning, score: score}
:error ->
%{suggestions: [], warning: "", score: 3}
end
end
catch
_kind, _value ->
%{suggestions: [], warning: "", score: 3}
Implement better user password validation (#3344) * Add zxcvbn dependency * Change password length range requirement from 6-64 to 12-128 * Reimplement register form in LV * Implement server-side check for password strength * Add rudimentary strength meter * Make password input with strength a separate component and improve it * Fix existing tests to provide strong enough password * Apply formatting * Replace existing registration form with new one * Hide built-in label in `.input` component when none provided * Crop password to first 32 chars for analysis by zxcvbn * Add tests for new form components * Integrate hCaptcha into LV * Fix existing AuthController tests * Add tests for Live.RegisterForm * Hide strength meter when password input is empty * Randomize client IP in headers during tests to avoid hitting rate limit * Apply auxilliary formatting fixes to AuthController * Integrate registration from invitation into LV registration logic * Fix existing password set and reset forms * Make `password_length_hint` component more customizable * Optimize `Auth.User.set_password/2` * Remove unnecessary attribute from registration form * Move password set and reset forms to LV * Add tests for SetPasswordForm LV component * Add tests for password checks in `Auth.User` * Document code a bit * Implement simpler approach to hCaptcha integration * Update CHANGELOG.md * Improve consistency of color scheme * Introduce debounce across all text inputs in registration and password forms * Fix email input background in register form * Ensure only single error is rendered for empty password confirmation case * Remove `/password` form entirely in favor of preferred password reset * Remove unnecessary `router` option from `live_render` calls * Make expensive assigns in LV with `assign_new` (h/t @aerosol) * Accept passwords longer than 32 bytes uniformly as very strong * Avoid displaying blank error side by side with weak password error * Make register actions handle errors gracefully * Render only a single piece of feedback to reduce noise * Make register and password reset forms pw manager friendly (h/t @cnkk) * Move registration forms to live routes * Delete no longer used deadviews * Adjust registration form in accordance to changes in #3290 * Reintroduce dogfood page path for invitation form from #3290 * Use alternative approach to submitting plausible metrics from LV form * Rename metrics events and extend tests to account for them
3 years ago
end
def profile_img_url(%__MODULE__{email: email}) do
hash =
email
|> String.trim()
|> String.downcase()
|> :erlang.md5()
|> Base.encode16(case: :lower)
Path.join(PlausibleWeb.Endpoint.url(), ["avatar/", hash])
end
def trial_accept_traffic_until_offset_days(), do: @trial_accept_traffic_until_offset_days
def subscription_accept_traffic_until_offset_days(),
do: @susbscription_accept_traffic_until_offset_days
defp validate_email_changed(changeset) do
if !get_change(changeset, :email) && !changeset.errors[:email] do
add_error(changeset, :email, "can't be the same", validation: :different_email)
else
changeset
end
end
defp check_password(changeset) do
if password = get_change(changeset, :password) do
if Plausible.Auth.Password.match?(password, changeset.data.password_hash) do
changeset
else
add_error(changeset, :password, "is invalid", validation: :check_password)
end
else
changeset
end
end
Implement better user password validation (#3344) * Add zxcvbn dependency * Change password length range requirement from 6-64 to 12-128 * Reimplement register form in LV * Implement server-side check for password strength * Add rudimentary strength meter * Make password input with strength a separate component and improve it * Fix existing tests to provide strong enough password * Apply formatting * Replace existing registration form with new one * Hide built-in label in `.input` component when none provided * Crop password to first 32 chars for analysis by zxcvbn * Add tests for new form components * Integrate hCaptcha into LV * Fix existing AuthController tests * Add tests for Live.RegisterForm * Hide strength meter when password input is empty * Randomize client IP in headers during tests to avoid hitting rate limit * Apply auxilliary formatting fixes to AuthController * Integrate registration from invitation into LV registration logic * Fix existing password set and reset forms * Make `password_length_hint` component more customizable * Optimize `Auth.User.set_password/2` * Remove unnecessary attribute from registration form * Move password set and reset forms to LV * Add tests for SetPasswordForm LV component * Add tests for password checks in `Auth.User` * Document code a bit * Implement simpler approach to hCaptcha integration * Update CHANGELOG.md * Improve consistency of color scheme * Introduce debounce across all text inputs in registration and password forms * Fix email input background in register form * Ensure only single error is rendered for empty password confirmation case * Remove `/password` form entirely in favor of preferred password reset * Remove unnecessary `router` option from `live_render` calls * Make expensive assigns in LV with `assign_new` (h/t @aerosol) * Accept passwords longer than 32 bytes uniformly as very strong * Avoid displaying blank error side by side with weak password error * Make register actions handle errors gracefully * Render only a single piece of feedback to reduce noise * Make register and password reset forms pw manager friendly (h/t @cnkk) * Move registration forms to live routes * Delete no longer used deadviews * Adjust registration form in accordance to changes in #3290 * Reintroduce dogfood page path for invitation form from #3290 * Use alternative approach to submitting plausible metrics from LV form * Rename metrics events and extend tests to account for them
3 years ago
defp validate_password_strength(changeset) do
if get_change(changeset, :password) != nil and password_strength(changeset).score <= 2 do
add_error(changeset, :password, "is too weak", validation: :strength)
else
changeset
end
end
defp maybe_add_phrase(phrases, nil), do: phrases
defp maybe_add_phrase(phrases, phrase) do
parts = String.split(phrase)
[phrase, parts]
|> List.flatten(phrases)
|> Enum.uniq()
end
defp trial_expiry() do
on_full_build do
Timex.today() |> Timex.shift(days: 30)
else
Timex.today() |> Timex.shift(years: 100)
end
end
defp set_email_verification_status(user) do
on_full_build do
change(user, email_verified: false)
else
selfhosted_config = Application.get_env(:plausible, :selfhost)
must_verify? = Keyword.fetch!(selfhosted_config, :enable_email_verification)
change(user, email_verified: not must_verify?)
end
end
7 years ago
end