Merge branch 'plausible:master' into master
commit
97c61cecec
@ -0,0 +1,97 @@
|
||||
.filter-list-text:hover ~ .filter-list-edit {
|
||||
display: flex;
|
||||
}
|
||||
|
||||
.filter-list-text:hover ~ .filter-list-remove {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.filter-select__control:focus-within {
|
||||
box-shadow: rgb(255, 255, 255) 0px 0px 0px 0px, rgb(99, 102, 241) 0px 0px 0px 1px, rgba(0, 0, 0, 0) 0px 0px 0px 0px; /* indigo-500 */
|
||||
}
|
||||
|
||||
.filter-select__value-container {
|
||||
padding-left: 1rem !important;
|
||||
}
|
||||
|
||||
.filter-select__control {
|
||||
@apply dark:bg-gray-900 border-gray-300 dark:border-gray-700 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 pr-8;
|
||||
border-radius: 0.375rem !important;
|
||||
background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' fill='none' viewBox='0 0 20 20'%3e%3cpath stroke='%236b7280' stroke-linecap='round' stroke-linejoin='round' stroke-width='1.5' d='M6 8l4 4 4-4'/%3e%3c/svg%3e");
|
||||
background-position: right 0.5rem center;
|
||||
background-repeat: no-repeat;
|
||||
background-size: 1.35rem 1.35rem;
|
||||
}
|
||||
|
||||
.filter-select__control:hover {
|
||||
@apply cursor-pointer;
|
||||
border-color: rgb(156, 163, 175) !important; /* gray-400 */
|
||||
}
|
||||
|
||||
.filter-select__indicator-separator {
|
||||
@apply hidden;
|
||||
}
|
||||
|
||||
.filter-select__dropdown-indicator {
|
||||
display: none !important;
|
||||
}
|
||||
|
||||
.filter-select__input {
|
||||
@apply w-full text-base sm:text-sm;
|
||||
margin: 0 !important;
|
||||
}
|
||||
|
||||
.filter-select__input input {
|
||||
width: 100% !important;
|
||||
box-shadow: none !important;
|
||||
}
|
||||
|
||||
.dark .filter-select__input input {
|
||||
color: rgb(209, 213, 219) !important; /* gray-300 */
|
||||
}
|
||||
|
||||
.filter-select__value-container > :not(.filter-select__single-value) {
|
||||
@apply w-full;
|
||||
padding-top: 0 !important;
|
||||
}
|
||||
|
||||
.filter-select__loading-indicator {
|
||||
color: rgb(79, 70, 229) !important; /* indigo-600 */
|
||||
}
|
||||
|
||||
.filter-select__loading-indicator > span {
|
||||
height: 1.5em;
|
||||
width: 1.5em;
|
||||
}
|
||||
|
||||
.filter-select__single-value {
|
||||
@apply dark:text-gray-400 text-base sm:text-sm;
|
||||
}
|
||||
|
||||
.filter-select__menu-list {
|
||||
@apply dark:bg-gray-900;
|
||||
}
|
||||
|
||||
.filter-select__option {
|
||||
@apply dark:text-gray-300;
|
||||
font-size: 1rem !important;
|
||||
line-height: 1.5rem !important;
|
||||
cursor: pointer !important;
|
||||
}
|
||||
|
||||
@media (min-width: 640px) {
|
||||
.filter-select__option {
|
||||
font-size: 0.875rem !important;
|
||||
line-height: 1.25rem !important;
|
||||
}
|
||||
}
|
||||
|
||||
.filter-select__option--is-focused {
|
||||
background-color: rgb(99, 102, 241) !important; /* indigo-500 */
|
||||
color: white !important;
|
||||
}
|
||||
|
||||
.dark .filter-select__option--is-focused {
|
||||
background-color: rgb(79, 70, 229) !important; /* indigo-600 */
|
||||
}
|
||||
|
||||
@ -0,0 +1,234 @@
|
||||
import React from "react";
|
||||
import { withRouter, Redirect } from 'react-router-dom'
|
||||
|
||||
import Datamap from 'datamaps'
|
||||
import AsyncSelect from 'react-select/async'
|
||||
import debounce from 'lodash.debounce'
|
||||
import Modal from './modal'
|
||||
import { parseQuery, formattedFilters, navigateToQuery } from '../../query'
|
||||
import Transition from "../../../transition";
|
||||
import * as api from '../../api'
|
||||
|
||||
class FilterModal extends React.Component {
|
||||
constructor(props) {
|
||||
super(props)
|
||||
this.state = {
|
||||
query: parseQuery(props.location.search, props.site),
|
||||
selectedFilter: "",
|
||||
negated: false,
|
||||
updatedValue: "",
|
||||
inputValue: "",
|
||||
forceReloadSuggestions: 0,
|
||||
defaultOptions: []
|
||||
}
|
||||
|
||||
this.editableGoals = Object.keys(this.state.query.filters).filter(filter => !['props'].includes(filter))
|
||||
this.renderSelector = this.renderSelector.bind(this)
|
||||
this.fetchSuggestions = this.fetchSuggestions.bind(this)
|
||||
this.handleKeydown = this.handleKeydown.bind(this)
|
||||
this.handleSubmit = this.handleSubmit.bind(this)
|
||||
this.fieldSelectRef = React.createRef()
|
||||
this.debouncedFetchSuggestions = debounce((q, callback) => this.fetchSuggestions(q, callback), 150)
|
||||
}
|
||||
|
||||
componentDidMount() {
|
||||
this.setState({ selectedFilter: this.props.match.params.field })
|
||||
this.fieldSelectRef.current.focus()
|
||||
document.addEventListener("keydown", this.handleKeydown)
|
||||
}
|
||||
|
||||
componentDidUpdate(prevProps, prevState) {
|
||||
const { query, selectedFilter, updatedValue, forceReloadSuggestions } = this.state
|
||||
|
||||
if (prevState.selectedFilter !== selectedFilter) {
|
||||
const negated = !!query.filters[selectedFilter] && query.filters[selectedFilter][0] == '!' && this.negationSupported(selectedFilter)
|
||||
let updatedValue = negated ? query.filters[selectedFilter].slice(1) : (query.filters[selectedFilter] || "")
|
||||
|
||||
if (selectedFilter == 'country') {
|
||||
const allCountries = Datamap.prototype.worldTopo.objects.world.geometries;
|
||||
const selectedCountry = allCountries.find((c) => c.id === updatedValue) || { properties: { name: updatedValue } };
|
||||
updatedValue = selectedCountry.properties.name
|
||||
}
|
||||
|
||||
if (selectedFilter) this.fetchSuggestions('', (defaultOptions) => this.setState({ defaultOptions }))
|
||||
this.setState({ updatedValue, inputValue: updatedValue, negated, forceReloadSuggestions: forceReloadSuggestions + 1 })
|
||||
}
|
||||
}
|
||||
|
||||
componentWillUnmount() {
|
||||
document.removeEventListener("keydown", this.handleKeydown);
|
||||
}
|
||||
|
||||
handleKeydown(e) {
|
||||
if (e.ctrlKey || e.metaKey || e.shiftKey || e.altKey || e.isComposing || e.keyCode === 229) return
|
||||
|
||||
if (e.target.tagName == 'BODY' && e.key == 'Enter') {
|
||||
this.handleSubmit()
|
||||
}
|
||||
}
|
||||
|
||||
negationSupported(filter) {
|
||||
return ['page', 'entry_page', 'exit_page'].includes(filter)
|
||||
}
|
||||
|
||||
fetchSuggestions(searchQuery = "", callback) {
|
||||
const { query, selectedFilter } = this.state
|
||||
const updatedQuery = { ...query, filters: { ...query.filters, [selectedFilter]: null } }
|
||||
|
||||
if (selectedFilter == 'country') {
|
||||
const matchedCountries = Datamap.prototype.worldTopo.objects.world.geometries.filter(c => c.properties.name.includes(searchQuery.trim()))
|
||||
const matches = matchedCountries.map(c => c.id)
|
||||
|
||||
api.get(`/api/stats/${encodeURIComponent(this.props.site.domain)}/suggestions/country`, updatedQuery, { q: matches })
|
||||
.then((res) => {
|
||||
const result = res.map(code => matchedCountries.filter(c => c.id == code)[0].properties.name).map(r => ({ label: r, value: r }))
|
||||
callback(result)
|
||||
})
|
||||
} else {
|
||||
api.get(`/api/stats/${encodeURIComponent(this.props.site.domain)}/suggestions/${selectedFilter}`, updatedQuery, { q: searchQuery.trim() })
|
||||
.then((res) => {
|
||||
const result = res.map(r => ({ label: r, value: r }))
|
||||
callback(result)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
renderSelector(filter) {
|
||||
const { updatedValue, selectedFilter, inputValue, forceReloadSuggestions, defaultOptions } = this.state;
|
||||
|
||||
if (!filter) return null
|
||||
|
||||
return (
|
||||
<AsyncSelect
|
||||
key={`select-${selectedFilter}-${forceReloadSuggestions}`}
|
||||
defaultOptions={inputValue == "" ? defaultOptions : true}
|
||||
cacheOptions
|
||||
loadOptions={(q, callback) => this.debouncedFetchSuggestions(q, callback)}
|
||||
placeholder='Filter value'
|
||||
maxMenuHeight={250}
|
||||
tabSelectsValue={false}
|
||||
classNamePrefix='filter-select'
|
||||
blurInputOnSelect
|
||||
noOptionsMessage={() => (
|
||||
<span className="text-red-500 text-md flex mt-2 px-3">
|
||||
<svg className="w-10 h-10 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"></path></svg>
|
||||
<span className="">No results found in current dashboard, try removing some filters, checking your input and ensuring this {formattedFilters[selectedFilter].toLowerCase()} exists</span>
|
||||
</span>
|
||||
)}
|
||||
loadingMessage={() => (
|
||||
<span>
|
||||
Loading filter suggestions
|
||||
</span>
|
||||
)}
|
||||
value={inputValue == '' ? { label: 'Enter a filter value', value: '' } : { label: updatedValue, value: `${updatedValue } ` }}
|
||||
onChange={({ value }, a) => {
|
||||
this.setState({ updatedValue: value, inputValue: value, forceReloadSuggestions: forceReloadSuggestions + 1 })
|
||||
}}
|
||||
onInputChange={(value, { action }) => {
|
||||
if (action == 'input-change') this.setState({ inputValue: value })
|
||||
if (action == 'menu-close' || action == 'input-blur') this.setState(({inputValue}) => ({ updatedValue: inputValue }))
|
||||
}}
|
||||
inputValue={inputValue}
|
||||
onBlur={() => this.setState({ forceReloadSuggestions: forceReloadSuggestions + 1 })}
|
||||
/>)
|
||||
}
|
||||
|
||||
handleSubmit() {
|
||||
const { selectedFilter, negated, updatedValue } = this.state;
|
||||
const validFilter = this.editableGoals.includes(selectedFilter) && updatedValue.trim()
|
||||
|
||||
let finalFilterValue = (this.negationSupported(selectedFilter) && negated ? '!' : '') + updatedValue.trim()
|
||||
if (selectedFilter == 'country') {
|
||||
const allCountries = Datamap.prototype.worldTopo.objects.world.geometries;
|
||||
const selectedCountry = allCountries.find((c) => c.properties.name === finalFilterValue) || { id: finalFilterValue };
|
||||
finalFilterValue = selectedCountry.id
|
||||
}
|
||||
const finalizedQuery = new URLSearchParams(window.location.search)
|
||||
finalizedQuery.set(selectedFilter, finalFilterValue)
|
||||
|
||||
if (validFilter) {
|
||||
this.setState({ finalizedQuery })
|
||||
}
|
||||
}
|
||||
|
||||
renderBody() {
|
||||
const { selectedFilter, negated, updatedValue, query } = this.state;
|
||||
const validFilter = this.editableGoals.includes(selectedFilter) && updatedValue.trim()
|
||||
|
||||
return (
|
||||
<>
|
||||
<h1 className="text-xl font-bold dark:text-gray-100">{query.filters[selectedFilter] ? 'Edit' : 'Add'} Filter</h1>
|
||||
|
||||
<div className="my-4 border-b border-gray-300"></div>
|
||||
<main className="modal__content">
|
||||
<form className="flex flex-col" id="filter-form" onSubmit={this.handleSubmit}>
|
||||
<select
|
||||
value={selectedFilter || ""}
|
||||
className="my-2 block w-full py-2 pl-3 pr-10 text-base border-gray-300 dark:border-gray-700 hover:border-gray-400 dark:hover:border-gray-200 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm rounded-md dark:bg-gray-900 dark:text-gray-300 cursor-pointer"
|
||||
placeholder="Select a Filter"
|
||||
onChange={(e) => this.setState({ selectedFilter: e.target.value })}
|
||||
ref={this.fieldSelectRef}
|
||||
>
|
||||
<option disabled value="" className="hidden">Select a Filter</option>
|
||||
{this.editableGoals.map(filter => <option key={filter} value={filter}>{formattedFilters[filter]}</option>)}
|
||||
</select>
|
||||
|
||||
{this.negationSupported(selectedFilter) && (
|
||||
<div className="my-4 flex items-center">
|
||||
<label className="text-gray-700 dark:text-gray-300 text-sm cursor-pointer">
|
||||
<input
|
||||
type="checkbox"
|
||||
className="bg-gray-100 dark:bg-gray-900 text-indigo-600 border-gray-300 dark:border-gray-700 hover:border-gray-400 dark:hover:border-gray-200 mr-2 relative inline-flex flex-shrink-0 h-6 w-8 border-1 rounded-full cursor-pointer transition-colors ease-in-out duration-200 focus:outline-none"
|
||||
checked={negated}
|
||||
name="exclude"
|
||||
onChange={(e) => this.setState({ negated: e.target.checked })}
|
||||
/>
|
||||
Exclude pages matching this filter
|
||||
</label>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{this.renderSelector(selectedFilter)}
|
||||
|
||||
<button
|
||||
type="submit"
|
||||
disabled={!validFilter}
|
||||
className="button mt-4 w-2/3 mx-auto"
|
||||
>
|
||||
{query.filters[selectedFilter] ? 'Update' : 'Add'} Filter
|
||||
</button>
|
||||
|
||||
{query.filters[selectedFilter] && (
|
||||
<button
|
||||
className="button mt-8 px-4 mx-auto flex bg-red-500 dark:bg-red-500 hover:bg-red-600 dark:hover:bg-red-700 items-center"
|
||||
onClick={() => {
|
||||
const finalizedQuery = new URLSearchParams(window.location.search)
|
||||
finalizedQuery.delete(selectedFilter)
|
||||
this.setState({ finalizedQuery })
|
||||
}}
|
||||
>
|
||||
<svg className="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"></path></svg>
|
||||
Remove Filter
|
||||
</button>
|
||||
)}
|
||||
</form>
|
||||
</main>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
render() {
|
||||
const { finalizedQuery } = this.state;
|
||||
|
||||
if (finalizedQuery)
|
||||
return <Redirect to={{ pathname: `/${encodeURIComponent(this.props.site.domain)}`, search: finalizedQuery.toString() }} />
|
||||
|
||||
return (
|
||||
<Modal site={this.props.site} maxWidth="460px">
|
||||
{ this.renderBody()}
|
||||
</Modal>
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
export default withRouter(FilterModal)
|
||||
File diff suppressed because it is too large
Load Diff
@ -0,0 +1,23 @@
|
||||
defmodule Plausible.Auth.Invitation do
|
||||
use Ecto.Schema
|
||||
import Ecto.Changeset
|
||||
|
||||
@derive {Jason.Encoder, only: [:invitation_id, :role, :site]}
|
||||
@required [:email, :role, :site_id, :inviter_id]
|
||||
schema "invitations" do
|
||||
field :invitation_id, :string
|
||||
field :email, :string
|
||||
field :role, Ecto.Enum, values: [:owner, :admin, :viewer]
|
||||
|
||||
belongs_to :inviter, Plausible.Auth.User
|
||||
belongs_to :site, Plausible.Site
|
||||
|
||||
timestamps()
|
||||
end
|
||||
|
||||
def new(attrs \\ %{}) do
|
||||
%__MODULE__{invitation_id: Nanoid.generate()}
|
||||
|> cast(attrs, @required)
|
||||
|> validate_required(@required)
|
||||
end
|
||||
end
|
||||
@ -0,0 +1,29 @@
|
||||
defmodule Plausible.Billing.SiteLocker do
|
||||
use Plausible.Repo
|
||||
|
||||
def check_sites_for(user) do
|
||||
if Plausible.Billing.needs_to_upgrade?(user) do
|
||||
set_lock_status_for(user, true)
|
||||
else
|
||||
set_lock_status_for(user, false)
|
||||
end
|
||||
end
|
||||
|
||||
defp set_lock_status_for(user, status) do
|
||||
site_ids =
|
||||
Repo.all(
|
||||
from s in Plausible.Site.Membership,
|
||||
where: s.user_id == ^user.id,
|
||||
where: s.role == :owner,
|
||||
select: s.site_id
|
||||
)
|
||||
|
||||
site_q =
|
||||
from(
|
||||
s in Plausible.Site,
|
||||
where: s.id in ^site_ids
|
||||
)
|
||||
|
||||
Repo.update_all(site_q, set: [locked: status])
|
||||
end
|
||||
end
|
||||
@ -0,0 +1,108 @@
|
||||
defmodule PlausibleWeb.InvitationController do
|
||||
use PlausibleWeb, :controller
|
||||
use Plausible.Repo
|
||||
alias Ecto.Multi
|
||||
alias Plausible.Auth.Invitation
|
||||
alias Plausible.Site.Membership
|
||||
|
||||
plug PlausibleWeb.RequireAccountPlug
|
||||
|
||||
def accept_invitation(conn, %{"invitation_id" => invitation_id}) do
|
||||
invitation =
|
||||
Repo.get_by!(Invitation, invitation_id: invitation_id)
|
||||
|> Repo.preload([:site, :inviter])
|
||||
|
||||
user = conn.assigns[:current_user]
|
||||
existing_membership = Repo.get_by(Membership, user_id: user.id, site_id: invitation.site.id)
|
||||
|
||||
multi =
|
||||
if invitation.role == :owner do
|
||||
downgrade_previous_owner(Multi.new(), invitation.site)
|
||||
else
|
||||
Multi.new()
|
||||
end
|
||||
|
||||
membership_changeset =
|
||||
Membership.changeset(existing_membership || %Membership{}, %{
|
||||
user_id: user.id,
|
||||
site_id: invitation.site.id,
|
||||
role: invitation.role
|
||||
})
|
||||
|
||||
multi =
|
||||
multi
|
||||
|> Multi.insert_or_update(:membership, membership_changeset)
|
||||
|> Multi.delete(:invitation, invitation)
|
||||
|
||||
case Repo.transaction(multi) do
|
||||
{:ok, _} ->
|
||||
notify_invitation_accepted(invitation)
|
||||
Plausible.Billing.SiteLocker.check_sites_for(user)
|
||||
|
||||
conn
|
||||
|> put_flash(:success, "You now have access to #{invitation.site.domain}")
|
||||
|> redirect(to: "/#{URI.encode_www_form(invitation.site.domain)}")
|
||||
|
||||
{:error, _} ->
|
||||
conn
|
||||
|> put_flash(:error, "Something went wrong, please try again")
|
||||
|> redirect(to: "/sites")
|
||||
end
|
||||
end
|
||||
|
||||
defp downgrade_previous_owner(multi, site) do
|
||||
prev_owner =
|
||||
from(
|
||||
sm in Plausible.Site.Membership,
|
||||
where: sm.site_id == ^site.id,
|
||||
where: sm.role == :owner
|
||||
)
|
||||
|
||||
Multi.update_all(multi, :prev_owner, prev_owner, set: [role: :admin])
|
||||
end
|
||||
|
||||
def reject_invitation(conn, %{"invitation_id" => invitation_id}) do
|
||||
invitation =
|
||||
Repo.get_by!(Invitation, invitation_id: invitation_id)
|
||||
|> Repo.preload([:site, :inviter])
|
||||
|
||||
Repo.delete!(invitation)
|
||||
notify_invitation_rejected(invitation)
|
||||
|
||||
conn
|
||||
|> put_flash(:success, "You have rejected the invitation to #{invitation.site.domain}")
|
||||
|> redirect(to: "/sites")
|
||||
end
|
||||
|
||||
defp notify_invitation_accepted(%Invitation{role: :owner} = invitation) do
|
||||
PlausibleWeb.Email.ownership_transfer_accepted(invitation)
|
||||
|> Plausible.Mailer.send_email()
|
||||
end
|
||||
|
||||
defp notify_invitation_accepted(invitation) do
|
||||
PlausibleWeb.Email.invitation_accepted(invitation)
|
||||
|> Plausible.Mailer.send_email()
|
||||
end
|
||||
|
||||
defp notify_invitation_rejected(%Invitation{role: :owner} = invitation) do
|
||||
PlausibleWeb.Email.ownership_transfer_rejected(invitation)
|
||||
|> Plausible.Mailer.send_email()
|
||||
end
|
||||
|
||||
defp notify_invitation_rejected(invitation) do
|
||||
PlausibleWeb.Email.invitation_rejected(invitation)
|
||||
|> Plausible.Mailer.send_email()
|
||||
end
|
||||
|
||||
def remove_invitation(conn, %{"invitation_id" => invitation_id}) do
|
||||
invitation =
|
||||
Repo.get_by!(Invitation, invitation_id: invitation_id)
|
||||
|> Repo.preload(:site)
|
||||
|
||||
Repo.delete!(invitation)
|
||||
|
||||
conn
|
||||
|> put_flash(:success, "You have removed the invitation for #{invitation.email}")
|
||||
|> redirect(to: Routes.site_path(conn, :settings_general, invitation.site.domain))
|
||||
end
|
||||
end
|
||||
@ -0,0 +1,149 @@
|
||||
defmodule PlausibleWeb.Site.MembershipController do
|
||||
use PlausibleWeb, :controller
|
||||
use Plausible.Repo
|
||||
alias Plausible.Sites
|
||||
alias Plausible.Site.Membership
|
||||
alias Plausible.Auth.Invitation
|
||||
|
||||
@only_owner_is_allowed_to [:transfer_ownership_form, :transfer_ownership]
|
||||
|
||||
plug PlausibleWeb.RequireAccountPlug
|
||||
plug PlausibleWeb.AuthorizeSiteAccess, [:owner] when action in @only_owner_is_allowed_to
|
||||
|
||||
plug PlausibleWeb.AuthorizeSiteAccess,
|
||||
[:owner, :admin] when action not in @only_owner_is_allowed_to
|
||||
|
||||
def invite_member_form(conn, %{"website" => site_domain}) do
|
||||
site = Sites.get_for_user!(conn.assigns[:current_user].id, site_domain)
|
||||
|
||||
render(
|
||||
conn,
|
||||
"invite_member_form.html",
|
||||
site: site,
|
||||
layout: {PlausibleWeb.LayoutView, "focus.html"}
|
||||
)
|
||||
end
|
||||
|
||||
def invite_member(conn, %{"website" => site_domain, "email" => email, "role" => role}) do
|
||||
site = Sites.get_for_user!(conn.assigns[:current_user].id, site_domain)
|
||||
user = Plausible.Auth.find_user_by(email: email)
|
||||
|
||||
if user && Sites.is_member?(user.id, site) do
|
||||
msg = "Cannot send invite because #{user.email} is already a member of #{site.domain}"
|
||||
|
||||
render(conn, "invite_member_form.html",
|
||||
error: msg,
|
||||
site: site,
|
||||
layout: {PlausibleWeb.LayoutView, "focus.html"}
|
||||
)
|
||||
else
|
||||
invitation =
|
||||
Invitation.new(%{
|
||||
email: email,
|
||||
role: role,
|
||||
site_id: site.id,
|
||||
inviter_id: conn.assigns[:current_user].id
|
||||
})
|
||||
|> Repo.insert!()
|
||||
|> Repo.preload([:site, :inviter])
|
||||
|
||||
email_template =
|
||||
if user do
|
||||
PlausibleWeb.Email.existing_user_invitation(invitation)
|
||||
else
|
||||
PlausibleWeb.Email.new_user_invitation(invitation)
|
||||
end
|
||||
|
||||
Plausible.Mailer.send_email(email_template)
|
||||
|
||||
conn
|
||||
|> put_flash(
|
||||
:success,
|
||||
"#{email} has been invited to #{site_domain} as #{
|
||||
PlausibleWeb.SiteView.with_indefinite_article(role)
|
||||
}"
|
||||
)
|
||||
|> redirect(to: Routes.site_path(conn, :settings_people, site.domain))
|
||||
end
|
||||
end
|
||||
|
||||
def transfer_ownership_form(conn, %{"website" => site_domain}) do
|
||||
site = Sites.get_for_user!(conn.assigns[:current_user].id, site_domain)
|
||||
|
||||
render(
|
||||
conn,
|
||||
"transfer_ownership_form.html",
|
||||
site: site,
|
||||
layout: {PlausibleWeb.LayoutView, "focus.html"}
|
||||
)
|
||||
end
|
||||
|
||||
def transfer_ownership(conn, %{"website" => site_domain, "email" => email}) do
|
||||
site = Sites.get_for_user!(conn.assigns[:current_user].id, site_domain)
|
||||
user = Plausible.Auth.find_user_by(email: email)
|
||||
|
||||
invitation =
|
||||
Invitation.new(%{
|
||||
email: email,
|
||||
role: :owner,
|
||||
site_id: site.id,
|
||||
inviter_id: conn.assigns[:current_user].id
|
||||
})
|
||||
|> Repo.insert!()
|
||||
|> Repo.preload([:site, :inviter])
|
||||
|
||||
PlausibleWeb.Email.ownership_transfer_request(invitation, user)
|
||||
|> Plausible.Mailer.send_email()
|
||||
|
||||
conn
|
||||
|> put_flash(:success, "Site transfer request has been sent to #{email}")
|
||||
|> redirect(to: Routes.site_path(conn, :settings_people, site.domain))
|
||||
end
|
||||
|
||||
def update_role(conn, %{"id" => id, "new_role" => new_role}) do
|
||||
membership =
|
||||
Repo.get!(Membership, id)
|
||||
|> Repo.preload([:site, :user])
|
||||
|> Membership.changeset(%{role: new_role})
|
||||
|> Repo.update!()
|
||||
|
||||
redirect_target =
|
||||
if membership.user.id == conn.assigns[:current_user].id && new_role == "viewer" do
|
||||
"/#{URI.encode_www_form(membership.site.domain)}"
|
||||
else
|
||||
Routes.site_path(conn, :settings_people, membership.site.domain)
|
||||
end
|
||||
|
||||
conn
|
||||
|> put_flash(
|
||||
:success,
|
||||
"#{membership.user.name} is now #{PlausibleWeb.SiteView.with_indefinite_article(new_role)}"
|
||||
)
|
||||
|> redirect(to: redirect_target)
|
||||
end
|
||||
|
||||
def remove_member(conn, %{"id" => id}) do
|
||||
membership =
|
||||
Repo.get!(Membership, id)
|
||||
|> Repo.preload([:user, :site])
|
||||
|
||||
Repo.delete!(membership)
|
||||
|
||||
PlausibleWeb.Email.site_member_removed(membership)
|
||||
|> Plausible.Mailer.send_email()
|
||||
|
||||
redirect_target =
|
||||
if membership.user.id == conn.assigns[:current_user].id do
|
||||
"/#{URI.encode_www_form(membership.site.domain)}"
|
||||
else
|
||||
Routes.site_path(conn, :settings_people, membership.site.domain)
|
||||
end
|
||||
|
||||
conn
|
||||
|> put_flash(
|
||||
:success,
|
||||
"#{membership.user.name} has been removed from #{membership.site.domain}"
|
||||
)
|
||||
|> redirect(to: redirect_target)
|
||||
end
|
||||
end
|
||||
@ -0,0 +1,50 @@
|
||||
defmodule PlausibleWeb.AuthorizeSiteAccess do
|
||||
import Plug.Conn
|
||||
use Plausible.Repo
|
||||
|
||||
def init([]), do: [:public, :viewer, :admin, :owner]
|
||||
def init(allowed_roles), do: allowed_roles
|
||||
|
||||
def call(conn, allowed_roles) do
|
||||
site = Repo.get_by(Plausible.Site, domain: conn.params["domain"] || conn.params["website"])
|
||||
shared_link_auth = conn.params["auth"]
|
||||
|
||||
shared_link_record =
|
||||
shared_link_auth && Repo.get_by(Plausible.Site.SharedLink, slug: shared_link_auth)
|
||||
|
||||
if !site do
|
||||
PlausibleWeb.ControllerHelpers.render_error(conn, 404) |> halt
|
||||
else
|
||||
user_id = get_session(conn, :current_user_id)
|
||||
membership_role = user_id && Plausible.Sites.role(user_id, site)
|
||||
|
||||
role =
|
||||
cond do
|
||||
user_id && membership_role ->
|
||||
membership_role
|
||||
|
||||
site.public ->
|
||||
:public
|
||||
|
||||
shared_link_record && shared_link_record.site_id == site.id ->
|
||||
:public
|
||||
|
||||
user_id in admin_user_ids() ->
|
||||
:admin
|
||||
|
||||
true ->
|
||||
nil
|
||||
end
|
||||
|
||||
if role in allowed_roles do
|
||||
merge_assigns(conn, site: site, current_user_role: role)
|
||||
else
|
||||
PlausibleWeb.ControllerHelpers.render_error(conn, 404) |> halt
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
defp admin_user_ids() do
|
||||
Application.get_env(:plausible, :admin_user_ids)
|
||||
end
|
||||
end
|
||||
@ -1,33 +0,0 @@
|
||||
defmodule PlausibleWeb.AuthorizeStatsPlug do
|
||||
import Plug.Conn
|
||||
use Plausible.Repo
|
||||
|
||||
def init(options) do
|
||||
options
|
||||
end
|
||||
|
||||
def call(conn, _opts) do
|
||||
site = Repo.get_by(Plausible.Site, domain: conn.params["domain"])
|
||||
shared_link_auth = conn.params["auth"]
|
||||
|
||||
shared_link_record =
|
||||
shared_link_auth && Repo.get_by(Plausible.Site.SharedLink, slug: shared_link_auth)
|
||||
|
||||
if !site do
|
||||
PlausibleWeb.ControllerHelpers.render_error(conn, 404) |> halt
|
||||
else
|
||||
user_id = get_session(conn, :current_user_id)
|
||||
|
||||
can_access =
|
||||
site.public ||
|
||||
(user_id && Plausible.Sites.is_owner?(user_id, site)) ||
|
||||
(shared_link_auth && shared_link_record && shared_link_record.site_id == site.id)
|
||||
|
||||
if !can_access do
|
||||
PlausibleWeb.ControllerHelpers.render_error(conn, 404) |> halt
|
||||
else
|
||||
assign(conn, :site, site)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
@ -1,21 +0,0 @@
|
||||
defmodule PlausibleWeb.UpgradeBillingPlug do
|
||||
import Phoenix.Controller
|
||||
import Plug.Conn
|
||||
use Plausible.Repo
|
||||
|
||||
def init(options) do
|
||||
options
|
||||
end
|
||||
|
||||
def call(conn, _opts) do
|
||||
user = conn.assigns[:current_user]
|
||||
|
||||
if user && Plausible.Billing.needs_to_upgrade?(conn.assigns[:current_user]) do
|
||||
conn
|
||||
|> redirect(to: "/settings")
|
||||
|> halt
|
||||
else
|
||||
conn
|
||||
end
|
||||
end
|
||||
end
|
||||
@ -0,0 +1,12 @@
|
||||
<div class="mx-auto mt-6 text-center dark:text-gray-300">
|
||||
<h1 class="text-3xl font-black">Plausible Analytics</h1>
|
||||
<div class="text-xl font-medium">Lightweight and privacy-friendly web analytics</div>
|
||||
</div>
|
||||
|
||||
<div class="w-full max-w-md mx-auto bg-white dark:bg-gray-800 shadow-md rounded px-8 py-6 mb-4 mt-8">
|
||||
<h2 class="text-xl font-black dark:text-gray-100">Invitation expired</h2>
|
||||
|
||||
<p class="mt-4 text-sm">
|
||||
Your invitation has expired or been revoked. Please request fresh one or you can <%= link("sign up", class: "text-indigo-600 hover:text-indigo-900", to: Routes.auth_path(@conn, :register)) %> for a 30-day unlimited free trial without an invitation.
|
||||
</p>
|
||||
</div>
|
||||
@ -0,0 +1,61 @@
|
||||
<div class="mx-auto mt-6 text-center dark:text-gray-300">
|
||||
<h1 class="text-3xl font-black">Register your Plausible Analytics account</h1>
|
||||
<div class="text-xl font-medium">Set up privacy-friendly analytics with just a few clicks</div>
|
||||
</div>
|
||||
|
||||
<%= form_for @changeset, Routes.auth_path(@conn, :register_from_invitation_form, @invitation.invitation_id), [class: "w-full max-w-md mx-auto bg-white dark:bg-gray-800 shadow-md rounded px-8 py-6 mb-4 mt-8"], fn f -> %>
|
||||
<h2 class="text-xl font-black dark:text-gray-100">Enter your details</h2>
|
||||
<div class="my-4">
|
||||
<div class="flex justify-between">
|
||||
<%= label f, :email, class: "block text-sm font-medium text-gray-700 dark:text-gray-300" %>
|
||||
<p class="text-xs text-gray-500 mt-1">No spam, guaranteed.</p>
|
||||
</div>
|
||||
<div class="mt-1">
|
||||
<%= email_input f, :email, class: "dark:bg-gray-900 shadow-sm focus:ring-indigo-500 focus:border-indigo-500 block w-full sm:text-sm border-gray-300 dark:border-gray-500 rounded-md dark:text-gray-300", placeholder: "example@email.com", value: @invitation.email, readonly: "readonly" %>
|
||||
</div>
|
||||
<%= error_tag f, :email %>
|
||||
</div>
|
||||
|
||||
<div class="my-4">
|
||||
<%= label f, :name, "Full name", class: "block text-sm font-medium text-gray-700 dark:text-gray-300" %>
|
||||
<div class="mt-1">
|
||||
<%= text_input f, :name, class: "dark:bg-gray-900 shadow-sm focus:ring-indigo-500 focus:border-indigo-500 block w-full sm:text-sm border-gray-300 dark:border-gray-500 rounded-md dark:text-gray-300", placeholder: "Jane Doe" %>
|
||||
</div>
|
||||
<%= error_tag f, :name %>
|
||||
</div>
|
||||
|
||||
<div class="my-4">
|
||||
<div class="flex justify-between">
|
||||
<%= label f, :password, class: "block text-sm font-medium text-gray-700 dark:text-gray-300" %>
|
||||
<p class="text-xs text-gray-500 mt-1">Min 6 characters</p>
|
||||
</div>
|
||||
<div class="mt-1">
|
||||
<%= password_input f, :password, class: "dark:bg-gray-900 shadow-sm focus:ring-indigo-500 focus:border-indigo-500 block w-full sm:text-sm border-gray-300 dark:border-gray-500 rounded-md dark:text-gray-300" %>
|
||||
</div>
|
||||
<%= error_tag f, :password %>
|
||||
</div>
|
||||
|
||||
<div class="my-4">
|
||||
<%= label f, :password_confirmation, class: "block text-sm font-medium text-gray-700 dark:text-gray-300" %>
|
||||
<div class="mt-1">
|
||||
<%= password_input f, :password_confirmation, class: "dark:bg-gray-900 shadow-sm focus:ring-indigo-500 focus:border-indigo-500 block w-full sm:text-sm border-gray-300 dark:border-gray-500 rounded-md dark:text-gray-300" %>
|
||||
</div>
|
||||
<%= error_tag f, :password_confirmation %>
|
||||
</div>
|
||||
|
||||
<%= if PlausibleWeb.Captcha.enabled?() do %>
|
||||
<div class="mt-4">
|
||||
<div class="h-captcha" data-sitekey="<%= PlausibleWeb.Captcha.sitekey() %>"></div>
|
||||
<%= if assigns[:captcha_error] do %>
|
||||
<div class="text-red-500 text-xs italic mt-3"><%= @captcha_error %></div>
|
||||
<% end %>
|
||||
<script src="https://hcaptcha.com/1/api.js" async defer></script>
|
||||
</div>
|
||||
<% end %>
|
||||
|
||||
<%= submit "Create my account →", class: "button mt-4 w-full" %>
|
||||
|
||||
<p class="text-center text-gray-600 dark:text-gray-500 text-xs mt-4">
|
||||
Already have an account? <%= link("Log in", to: "/login", class: "underline text-gray-800 dark:text-gray-50") %> instead.
|
||||
</p>
|
||||
<% end %>
|
||||
@ -0,0 +1,10 @@
|
||||
Hey,
|
||||
<br /><br />
|
||||
<%= @invitation.inviter.email %> has invited you to the <%= @invitation.site.domain %> site on Plausible Analytics.
|
||||
<%= link("Click here", to: Routes.site_url(PlausibleWeb.Endpoint, :index)) %> to view and respond to the invitation. The invitation
|
||||
will expire 48 hours after this email is sent.
|
||||
<br /><br />
|
||||
Thanks,<br />
|
||||
Uku and Marko<br />
|
||||
--<br />
|
||||
<%= plausible_url() %><br />
|
||||
@ -0,0 +1,9 @@
|
||||
Hey <%= user_salutation(@invitation.inviter) %>,
|
||||
<br /><br />
|
||||
<%= @invitation.email %> has accepted your invitation to <%= @invitation.site.domain %>.
|
||||
<%= link("Click here", to: Routes.site_url(PlausibleWeb.Endpoint, :settings_general, @invitation.site.domain)) %> to view site settings.
|
||||
<br /><br />
|
||||
Thanks,<br />
|
||||
Uku and Marko<br />
|
||||
--<br />
|
||||
<%= plausible_url() %><br />
|
||||
@ -0,0 +1,9 @@
|
||||
Hey <%= user_salutation(@invitation.inviter) %>,
|
||||
<br /><br />
|
||||
<%= @invitation.email %> has rejected your invitation to <%= @invitation.site.domain %>.
|
||||
<%= link("Click here", to: Routes.site_url(PlausibleWeb.Endpoint, :settings_general, @invitation.site.domain)) %> to view site settings.
|
||||
<br /><br />
|
||||
Thanks,<br />
|
||||
Uku and Marko<br />
|
||||
--<br />
|
||||
<%= plausible_url() %><br />
|
||||
@ -0,0 +1,11 @@
|
||||
Hey,
|
||||
<br /><br />
|
||||
<%= @invitation.inviter.email %> has invited you to join the <%= @invitation.site.domain %> site on Plausible Analytics.
|
||||
<%= link("Click here", to: Routes.auth_url(PlausibleWeb.Endpoint, :register_form), invitation: @invitation.invitation_id) %> to create your account. The link is valid for 48 hours after this email is sent.
|
||||
<br /><br />
|
||||
Plausible is a lightweight and open-source website analytics tool. We hope you like our simple and ethical approach to tracking website visitors.
|
||||
<br /><br />
|
||||
Thanks,<br />
|
||||
Uku and Marko<br />
|
||||
--<br />
|
||||
<%= plausible_url() %><br />
|
||||
@ -0,0 +1,10 @@
|
||||
Hey <%= user_salutation(@invitation.inviter) %>,
|
||||
<br /><br />
|
||||
<%= @invitation.email %> has accepted the ownership transfer of <%= @invitation.site.domain %>. They will be responsible for billing of it going
|
||||
forward and your role has been changed to <b>admin</b>.
|
||||
<%= link("Click here", to: Routes.site_url(PlausibleWeb.Endpoint, :settings_general, @invitation.site.domain)) %> to view site settings.
|
||||
<br /><br />
|
||||
Thanks,<br />
|
||||
Uku and Marko<br />
|
||||
--<br />
|
||||
<%= plausible_url() %><br />
|
||||
@ -0,0 +1,9 @@
|
||||
Hey <%= user_salutation(@invitation.inviter) %>,
|
||||
<br /><br />
|
||||
<%= @invitation.email %> has rejected the ownership transfer of <%= @invitation.site.domain %>.
|
||||
<%= link("Click here", to: Routes.site_url(PlausibleWeb.Endpoint, :settings_general, @invitation.site.domain)) %> to view site settings.
|
||||
<br /><br />
|
||||
Thanks,<br />
|
||||
Uku and Marko<br />
|
||||
--<br />
|
||||
<%= plausible_url() %><br />
|
||||
@ -0,0 +1,15 @@
|
||||
Hey,
|
||||
<br /><br />
|
||||
<%= @invitation.inviter.email %> has request to transfer the ownership of <%= @invitation.site.domain %> site on Plausible Analytics to you.
|
||||
<%= if @new_owner_account do %>
|
||||
<%= link("Click here", to: Routes.site_url(PlausibleWeb.Endpoint, :index)) %> to view and respond to the invitation.
|
||||
<% else %>
|
||||
<%= link("Click here", to: Routes.auth_url(PlausibleWeb.Endpoint, :register_form), invitation: @invitation.invitation_id) %> to create your account.
|
||||
<br /><br />
|
||||
Plausible is a lightweight and open-source website analytics tool. We hope you like our simple and ethical approach to tracking website visitors.
|
||||
<% end %>
|
||||
<br /><br />
|
||||
Thanks,<br />
|
||||
Uku and Marko<br />
|
||||
--<br />
|
||||
<%= plausible_url() %><br />
|
||||
@ -0,0 +1,10 @@
|
||||
Hey <%= user_salutation(@membership.user) %>,
|
||||
<br /><br />
|
||||
An administrator of <%= @membership.site.domain %> has removed you as a member. You won't be able to see the stats anymore.
|
||||
<br /><br />
|
||||
<%= link("Click here", to: Routes.site_url(PlausibleWeb.Endpoint, :index)) %> to view your sites.
|
||||
<br /><br />
|
||||
Thanks,<br />
|
||||
Uku and Marko<br />
|
||||
--<br />
|
||||
<%= plausible_url() %><br />
|
||||
@ -1,5 +1,5 @@
|
||||
<%= if !Application.get_env(:plausible, :is_selfhost) && !@conn.assigns[:skip_plausible_tracking] do %>
|
||||
<script defer src="https://testing-plausible-io-proxy.uku-taht.workers.dev/js/script.js"></script>
|
||||
<script defer src="<%="#{plausible_url()}/js/script.js"%>"></script>
|
||||
<script defer src="<%="#{plausible_url()}/js/plausible.js"%>"></script>
|
||||
<script>window.plausible = window.plausible || function() { (window.plausible.q = window.plausible.q || []).push(arguments) }</script>
|
||||
<% end %>
|
||||
|
||||
@ -0,0 +1,63 @@
|
||||
<%= form_for @conn, Routes.membership_path(@conn, :invite_member, @site.domain), [class: "max-w-lg w-full mx-auto bg-white dark:bg-gray-800 shadow-md rounded px-8 pt-6 pb-8 mb-4 mt-8"], fn f -> %>
|
||||
<h2 class="text-xl font-black dark:text-gray-100">Invite member to <%= @site.domain %></h2>
|
||||
|
||||
<p class="mt-4 max-w-2xl text-sm text-gray-500">
|
||||
Enter the email address and role of the person you want to invite. We will contact them over email to offer them access to
|
||||
<%= @site.domain %> analytics.
|
||||
</p>
|
||||
|
||||
<p class="mt-4 max-w-2xl text-sm text-gray-500">
|
||||
The invitation will expire in 48 hours
|
||||
</p>
|
||||
|
||||
<%= if @conn.assigns[:error] do %>
|
||||
<div class="text-red-500 text-xs italic mt-4"><%= @conn.assigns[:error] %></div>
|
||||
<% end %>
|
||||
|
||||
<div class="my-6">
|
||||
<%= label f, :email, "Email address", class: "block text-sm font-medium text-gray-700 dark:text-gray-300" %>
|
||||
<div class="mt-1 relative rounded-md shadow-sm">
|
||||
<div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
|
||||
<svg class="h-5 w-5 text-gray-400" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor" aria-hidden="true"><path d="M2.003 5.884L10 9.882l7.997-3.998A2 2 0 0016 4H4a2 2 0 00-1.997 1.884z" /><path d="M18 8.118l-8 4-8-4V14a2 2 0 002 2h12a2 2 0 002-2V8.118z" /></svg>
|
||||
</div>
|
||||
<%= email_input(f, :email, class: "focus:ring-indigo-500 focus:border-indigo-500 block w-full rounded-md pl-10 sm:text-sm border-gray-300", placeholder: "john.doe@example.com", required: "true") %>
|
||||
</div>
|
||||
<%= error_tag f, :email %>
|
||||
</div>
|
||||
|
||||
<fieldset x-data="{selectedOption: null}">
|
||||
<%= label f, :role, class: "block text-sm font-medium text-gray-700 dark:text-gray-300" %>
|
||||
<div class="mt-1 bg-white rounded-md -space-y-px">
|
||||
<label class="border-gray-200 rounded-tl-md rounded-tr-md relative border p-4 flex cursor-pointer" :class="{'bg-indigo-50 border-indigo-200 z-10': selectedOption === 'admin', 'border-gray-200': selectedOption !== 'admin'}">
|
||||
<%= radio_button(f, :role, "admin", class: "h-4 w-4 mt-0.5 cursor-pointer text-indigo-600 border-gray-300 focus:ring-indigo-500", "x-model": "selectedOption", required: "true") %>
|
||||
<div class="ml-3 flex flex-col">
|
||||
<span class="text-gray-900 block text-sm font-medium" :class="{'text-indigo-900': selectedOption === 'admin', 'text-gray-900': selectedOption !== 'admin'}">
|
||||
Admin
|
||||
</span>
|
||||
<span class="text-gray-500 block text-sm" :class="{'text-indigo-700': selectedOption === 'admin', 'text-gray-500': selectedOption !== 'admin'}">
|
||||
Can view stats, change site settings and invite other members
|
||||
</span>
|
||||
</div>
|
||||
</label>
|
||||
|
||||
<label class="border-gray-200 relative border p-4 flex cursor-pointer" :class="{'bg-indigo-50 border-indigo-200 z-10': selectedOption === 'viewer', 'border-gray-200': selectedOption !== 'viewer'}">
|
||||
<%= radio_button(f, :role, "viewer", class: "h-4 w-4 mt-0.5 cursor-pointer text-indigo-600 border-gray-300 focus:ring-indigo-500", "x-model": "selectedOption", required: "true") %>
|
||||
<div class="ml-3 flex flex-col">
|
||||
<span class="text-gray-900 block text-sm font-medium" :class="{'text-indigo-900': selectedOption === 'viewer', 'text-gray-900': selectedOption !== 'viewer'}">
|
||||
Viewer
|
||||
</span>
|
||||
<span class="text-gray-500 block text-sm" :class="{'text-indigo-700': selectedOption === 'viewer', 'text-gray-500': selectedOption !== 'viewer'}">
|
||||
Can view stats but cannot access settings or invite members
|
||||
</span>
|
||||
</div>
|
||||
</label>
|
||||
</div>
|
||||
</fieldset>
|
||||
|
||||
<div class="mt-6">
|
||||
<%= submit(class: "button w-full") do %>
|
||||
<svg class="w-5 h-5 mr-1" fill="currentColor" viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg"><path d="M8 9a3 3 0 100-6 3 3 0 000 6zM8 11a6 6 0 016 6H2a6 6 0 016-6zM16 7a1 1 0 10-2 0v1h-1a1 1 0 100 2h1v1a1 1 0 102 0v-1h1a1 1 0 100-2h-1V7z"></path></svg>
|
||||
<span>Invite</span>
|
||||
<% end %>
|
||||
</div>
|
||||
<% end %>
|
||||
@ -0,0 +1,30 @@
|
||||
<%= form_for @conn, Routes.membership_path(@conn, :transfer_ownership, @site.domain), [class: "max-w-lg w-full mx-auto bg-white dark:bg-gray-800 shadow-md rounded px-8 pt-6 pb-8 mb-4 mt-8"], fn f -> %>
|
||||
<h2 class="text-xl font-black dark:text-gray-100">Transfer ownership of <%= @site.domain %></h2>
|
||||
|
||||
<p class="mt-4 max-w-2xl text-sm text-gray-500">
|
||||
Enter the email address of the new owner. We will contact them over email to offer them the ownership of <%= @site.domain %>.
|
||||
</p>
|
||||
<p class="mt-4 max-w-2xl text-sm text-gray-500">
|
||||
If they accept the transfer request, the new owner will be responsible for billing. Your access will be downgraded to <b>admin</b> and
|
||||
any other member roles will stay the same. If they don't respond in 48 hours, the request will expire automatically.
|
||||
</p>
|
||||
|
||||
<%= if @conn.assigns[:error] do %>
|
||||
<div class="text-red-500 text-xs italic mt-4"><%= @conn.assigns[:error] %></div>
|
||||
<% end %>
|
||||
|
||||
<div class="my-6">
|
||||
<%= label f, :email, "Email address", class: "block text-sm font-medium text-gray-700 dark:text-gray-300" %>
|
||||
<div class="mt-1 relative rounded-md shadow-sm">
|
||||
<div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
|
||||
<svg class="h-5 w-5 text-gray-400" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor" aria-hidden="true"><path d="M2.003 5.884L10 9.882l7.997-3.998A2 2 0 0016 4H4a2 2 0 00-1.997 1.884z" /><path d="M18 8.118l-8 4-8-4V14a2 2 0 002 2h12a2 2 0 002-2V8.118z" /></svg>
|
||||
</div>
|
||||
<%= email_input(f, :email, class: "focus:ring-indigo-500 focus:border-indigo-500 block w-full rounded-md pl-10 sm:text-sm border-gray-300", placeholder: "john.doe@example.com", required: "true") %>
|
||||
</div>
|
||||
<%= error_tag f, :email %>
|
||||
</div>
|
||||
|
||||
<div class="mt-6">
|
||||
<%= submit("Request transfer", class: "button w-full") %>
|
||||
</div>
|
||||
<% end %>
|
||||
@ -0,0 +1,149 @@
|
||||
<div class="shadow bg-white dark:bg-gray-800 sm:rounded-md py-6 px-4 sm:p-6">
|
||||
<header class="relative">
|
||||
<h2 class="text-lg leading-6 font-medium text-gray-900 dark:text-gray-100">People</h2>
|
||||
<p class="mt-1 text-sm leading-5 text-gray-500 dark:text-gray-200">Invite your friend or coworkers</p>
|
||||
<%= link(to: "https://plausible.io/docs/users-roles", target: "_blank") do %>
|
||||
<svg class="w-6 h-6 absolute top-0 right-0 text-gray-400" fill="currentColor" viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg"><path fill-rule="evenodd" d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a1 1 0 000 2v3a1 1 0 001 1h1a1 1 0 100-2v-3a1 1 0 00-1-1H9z" clip-rule="evenodd"></path></svg>
|
||||
<% end %>
|
||||
</header>
|
||||
<div class="flow-root mt-6">
|
||||
<ul class="-my-5 divide-y divide-gray-200 dark:divide-gray-50">
|
||||
<%= for membership <- @site.memberships do %>
|
||||
<li class="py-4">
|
||||
<div class="flex items-center space-x-4">
|
||||
<div class="flex-shrink-0">
|
||||
<%= gravatar(membership.user.email, class: "h-8 w-8 rounded-full") %>
|
||||
</div>
|
||||
<div class="flex-1 min-w-0">
|
||||
<p class="text-sm font-medium text-gray-900 dark:text-gray-50 truncate">
|
||||
<%= membership.user.name %>
|
||||
</p>
|
||||
<p class="text-sm text-gray-500 truncate">
|
||||
<%= membership.user.email %>
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div x-data="{open: false}" @click.away="open = false" x-cloak class="relative">
|
||||
<button @click="open = !open" class="inline-flex items-center shadow-sm px-2.5 py-0.5 border border-gray-300 text-sm leading-5 font-medium rounded-full text-gray-700 bg-white hover:bg-gray-50">
|
||||
<%= membership.role |> Atom.to_string() |> String.capitalize() %>
|
||||
<svg class="w-4 h-4 pt-px ml-1" fill="currentColor" viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg"><path fill-rule="evenodd" d="M5.293 7.293a1 1 0 011.414 0L10 10.586l3.293-3.293a1 1 0 111.414 1.414l-4 4a1 1 0 01-1.414 0l-4-4a1 1 0 010-1.414z" clip-rule="evenodd"></path></svg>
|
||||
</button>
|
||||
<ul
|
||||
x-show="open"
|
||||
x-transition:leave="transition ease-in duration-100"
|
||||
x-transition:leave-start="opacity-100"
|
||||
x-transition:leave-end="opacity-0"
|
||||
class="origin-top-right absolute z-10 right-0 mt-2 w-72 rounded-md shadow-lg overflow-hidden bg-white divide-y divide-gray-200 ring-1 ring-black ring-opacity-5 focus:outline-none" tabindex="-1" role="listbox" aria-labelledby="listbox-label" aria-activedescendant="listbox-option-0"
|
||||
>
|
||||
<%= if membership.role == :owner do %>
|
||||
<li class="p-4 text-sm cursor-default group flex justify-between" role="option">
|
||||
<div>
|
||||
<p class="text-base font-medium text-gray-900">Owner</p>
|
||||
<p class="mt-1 text-sm text-gray-500">Site owner cannot be assigned to any other role</p>
|
||||
</div>
|
||||
|
||||
<span class="text-indigo-500">
|
||||
<svg class="h-5 w-5" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor" aria-hidden="true">
|
||||
<path fill-rule="evenodd" d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z" clip-rule="evenodd" />
|
||||
</svg>
|
||||
</span>
|
||||
</li>
|
||||
<%= if @conn.assigns[:current_user_role] == :owner do %>
|
||||
<li class="select-none hover:bg-gray-100 text-red-600" role="option">
|
||||
<%= link("Transfer ownership →", to: Routes.membership_path(@conn, :transfer_ownership_form, @site.domain), class: "inline-block w-full p-4 text-sm text-red-600 font-medium") %>
|
||||
</li>
|
||||
<% end %>
|
||||
<% else %>
|
||||
<%= link(to: Routes.membership_path(@conn, :update_role, @site.domain, membership.id, "admin"), method: :put, class: "p-4 flex justify-between text-sm group hover:bg-indigo-500") do %>
|
||||
<div>
|
||||
<p class="text-base font-medium text-gray-900 group-hover:text-white">Admin</p>
|
||||
<p class="mt-1 text-sm text-gray-500 group-hover:text-gray-100">View stats and edit site settings</p>
|
||||
</div>
|
||||
|
||||
<%= if membership.role == :admin do %>
|
||||
<span class="text-indigo-500 group-hover:text-white">
|
||||
<svg class="h-5 w-5" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor" aria-hidden="true">
|
||||
<path fill-rule="evenodd" d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z" clip-rule="evenodd" />
|
||||
</svg>
|
||||
</span>
|
||||
<% end %>
|
||||
<% end %>
|
||||
<%= link(to: Routes.membership_path(@conn, :update_role, @site.domain, membership.id, "viewer"), method: :put, class: "p-4 flex justify-between text-sm group hover:bg-indigo-500") do %>
|
||||
<div>
|
||||
<p class="text-base font-medium text-gray-900 group-hover:text-white">Viewer</p>
|
||||
<p class="mt-1 text-sm text-gray-500 group-hover:text-white">View stats only</p>
|
||||
</div>
|
||||
|
||||
<%= if membership.role == :viewer do %>
|
||||
<span class="text-indigo-500 group-hover:text-white">
|
||||
<svg class="h-5 w-5" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor" aria-hidden="true">
|
||||
<path fill-rule="evenodd" d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z" clip-rule="evenodd" />
|
||||
</svg>
|
||||
</span>
|
||||
<% end %>
|
||||
<% end %>
|
||||
|
||||
<%= link(to: Routes.membership_path(@conn, :remove_member, @site.domain, membership.id), method: :delete, class: "p-4 flex hover:bg-gray-100 text-red-600") do %>
|
||||
<p class="text-sm text-red-600 font-medium">Remove member</p>
|
||||
<% end %>
|
||||
<% end %>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
</li>
|
||||
<% end %>
|
||||
</ul>
|
||||
|
||||
<%= if Enum.count(@site.invitations) > 0 do %>
|
||||
<header class="mt-12">
|
||||
<h2 class="text-lg leading-6 font-medium text-gray-900 dark:text-gray-100">Pending invitations</h2>
|
||||
</header>
|
||||
<div class="flex flex-col mt-4">
|
||||
<div class="-my-2 overflow-x-auto sm:-mx-6 lg:-mx-8">
|
||||
<div class="py-2 align-middle inline-block min-w-full sm:px-6 lg:px-8">
|
||||
<div class="shadow overflow-hidden border-b border-gray-200 sm:rounded-lg">
|
||||
<table class="min-w-full divide-y divide-gray-200">
|
||||
<thead class="bg-gray-50">
|
||||
<tr>
|
||||
<th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
|
||||
Email
|
||||
</th>
|
||||
<th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
|
||||
Role
|
||||
</th>
|
||||
<th scope="col" class="relative px-6 py-3">
|
||||
<span class="sr-only">Edit</span>
|
||||
</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<%= for invitation <- @site.invitations do %>
|
||||
<tr class="odd:bg-white even:bg-gray-50">
|
||||
<td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">
|
||||
<%= invitation.email %>
|
||||
</td>
|
||||
<td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
|
||||
<%= invitation.role |> Atom.to_string |> String.capitalize %>
|
||||
</td>
|
||||
<td class="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
|
||||
<%= link("Remove", to: "/sites/invitations/#{invitation.invitation_id}", method: :delete, class: "text-red-600 hover:text-red-900") %>
|
||||
</td>
|
||||
</tr>
|
||||
<% end %>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<% end %>
|
||||
</div>
|
||||
|
||||
<div class="mt-8">
|
||||
<%= link(to: Routes.membership_path(@conn, :invite_member_form, @site.domain), class: "button") do %>
|
||||
<svg class="w-5 h-5 mr-1" fill="currentColor" viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg"><path d="M8 9a3 3 0 100-6 3 3 0 000 6zM8 11a6 6 0 016 6H2a6 6 0 016-6zM16 7a1 1 0 10-2 0v1h-1a1 1 0 100 2h1v1a1 1 0 102 0v-1h1a1 1 0 100-2h-1V7z"></path></svg>
|
||||
Invite
|
||||
<% end %>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@ -0,0 +1,32 @@
|
||||
<div class="w-full max-w-lg mx-auto mt-8">
|
||||
<div class="bg-white shadow sm:rounded-lg">
|
||||
<div class="px-4 py-5 sm:px-8 sm:py-6">
|
||||
<div class="mx-auto flex items-center justify-center rounded-full bg-green-100 h-12 w-12">
|
||||
<svg class="w-6 h-6 text-green-600" fill="currentColor" viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg"><path fill-rule="evenodd" d="M5 9V7a5 5 0 0110 0v2a2 2 0 012 2v5a2 2 0 01-2 2H5a2 2 0 01-2-2v-5a2 2 0 012-2zm8-2v2H7V7a3 3 0 016 0z" clip-rule="evenodd"></path></svg>
|
||||
</div>
|
||||
<h3 class="mt-6 text-center text-2xl leading-6 font-medium text-gray-900">
|
||||
Site locked
|
||||
</h3>
|
||||
|
||||
<%= if @conn.assigns[:current_user_role] == :owner do %>
|
||||
<div class="mt-3 text-gray-500 text-center">
|
||||
<p>
|
||||
This site is locked because you don't have an active subscription. We are still counting stats in the background but your access to the dashboard is restricted. Subscribe with the link below to access your stats again.
|
||||
</p>
|
||||
</div>
|
||||
<div class="mt-6 w-full text-center">
|
||||
<%= link("Manage my subscription", to: "/settings", class: "inline-flex items-center px-4 py-2 border border-transparent shadow-sm font-medium rounded-md text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 sm:text-sm") %>
|
||||
</div>
|
||||
<% else %>
|
||||
<div class="mt-3 text-gray-500 text-center">
|
||||
<p>
|
||||
This site is currently locked and cannot be accessed. You can check back later or contact the site owner to unlock it.
|
||||
</p>
|
||||
</div>
|
||||
<div class="mt-6 w-full text-center">
|
||||
<%= link("Back to my sites", to: "/sites", class: "inline-flex items-center px-4 py-2 border border-transparent shadow-sm font-medium rounded-md text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 sm:text-sm") %>
|
||||
</div>
|
||||
<% end %>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@ -0,0 +1,3 @@
|
||||
defmodule PlausibleWeb.Site.MembershipView do
|
||||
use PlausibleWeb, :view
|
||||
end
|
||||
@ -0,0 +1,14 @@
|
||||
defmodule Plausible.Workers.CleanInvitations do
|
||||
use Plausible.Repo
|
||||
use Oban.Worker, queue: :clean_invitations
|
||||
|
||||
@impl Oban.Worker
|
||||
def perform(_job) do
|
||||
Repo.delete_all(
|
||||
from i in Plausible.Auth.Invitation,
|
||||
where: i.inserted_at < fragment("now() - INTERVAL '48 hours'")
|
||||
)
|
||||
|
||||
:ok
|
||||
end
|
||||
end
|
||||
@ -0,0 +1,16 @@
|
||||
defmodule Plausible.Workers.LockSites do
|
||||
use Plausible.Repo
|
||||
use Oban.Worker, queue: :lock_sites
|
||||
|
||||
@impl Oban.Worker
|
||||
def perform(_job) do
|
||||
subscription_q = from(s in Plausible.Billing.Subscription, order_by: [desc: s.inserted_at])
|
||||
users = Repo.all(from u in Plausible.Auth.User, preload: [subscription: ^subscription_q])
|
||||
|
||||
for user <- users do
|
||||
Plausible.Billing.SiteLocker.check_sites_for(user)
|
||||
end
|
||||
|
||||
:ok
|
||||
end
|
||||
end
|
||||
@ -0,0 +1,13 @@
|
||||
defmodule Plausible.Repo.Migrations.AddRoleToSiteMemberships do
|
||||
use Ecto.Migration
|
||||
|
||||
def change do
|
||||
create_query = "CREATE TYPE site_membership_role AS ENUM ('owner', 'admin', 'viewer')"
|
||||
drop_query = "DROP TYPE site_membership_role"
|
||||
execute(create_query, drop_query)
|
||||
|
||||
alter table(:site_memberships) do
|
||||
add :role, :site_membership_role, null: false, default: "owner"
|
||||
end
|
||||
end
|
||||
end
|
||||
@ -0,0 +1,18 @@
|
||||
defmodule Plausible.Repo.Migrations.AddInvitations do
|
||||
use Ecto.Migration
|
||||
|
||||
def change do
|
||||
create table(:invitations) do
|
||||
add :email, :string, null: false
|
||||
add :site_id, references(:sites), null: false
|
||||
add :inviter_id, references(:users), null: false
|
||||
add :role, :site_membership_role, null: false
|
||||
add :invitation_id, :string
|
||||
|
||||
timestamps()
|
||||
end
|
||||
|
||||
create unique_index(:invitations, [:site_id, :email])
|
||||
create unique_index(:invitations, :invitation_id)
|
||||
end
|
||||
end
|
||||
@ -0,0 +1,9 @@
|
||||
defmodule Plausible.Repo.Migrations.AddLockedToSites do
|
||||
use Ecto.Migration
|
||||
|
||||
def change do
|
||||
alter table(:sites) do
|
||||
add :locked, :boolean, null: false, default: false
|
||||
end
|
||||
end
|
||||
end
|
||||
@ -0,0 +1 @@
|
||||
!function(){"use strict";var e,t,i,n,r=window.location,o=window.document,l=o.getElementById("plausible"),s=l.getAttribute("data-api")||(e=l.src.split("/"),t=e[0],i=e[2],t+"//"+i+"/api/event"),w=window.localStorage.plausible_ignore,d=l&&l.getAttribute("data-exclude").split(",");function p(e){console.warn("Ignoring Event: "+e)}function a(e,t){if(/^localhost$|^127(?:\.[0-9]+){0,2}\.[0-9]+$|^(?:0*\:)*?:?0*1$/.test(r.hostname)||"file:"===r.protocol)return p("localhost");if(!(window.phantom||window._phantom||window.__nightmare||window.navigator.webdriver||window.Cypress)){if("true"==w)return p("localStorage flag");if(d)for(var i=0;i<d.length;i++)if("pageview"==e&&r.pathname.match(new RegExp("^"+d[i].trim().replace(/\*\*/g,".*").replace(/([^\.])\*/g,"$1[^\\s/]*")+"/?$")))return p("exclusion rule");var n={};n.n=e,n.u=r.href,n.d=l.getAttribute("data-domain"),n.r=o.referrer||null,n.w=window.innerWidth,t&&t.meta&&(n.m=JSON.stringify(t.meta)),t&&t.props&&(n.p=JSON.stringify(t.props)),n.h=1;var a=new XMLHttpRequest;a.open("POST",s,!0),a.setRequestHeader("Content-Type","text/plain"),a.send(JSON.stringify(n)),a.onreadystatechange=function(){4==a.readyState&&t&&t.callback&&t.callback()}}}function c(){n=r.pathname,a("pageview")}window.addEventListener("hashchange",c);var u=window.plausible&&window.plausible.q||[];window.plausible=a;for(var g=0;g<u.length;g++)a.apply(this,u[g]);"prerender"===o.visibilityState?o.addEventListener("visibilitychange",function(){n||"visible"!==o.visibilityState||c()}):c()}();
|
||||
@ -0,0 +1 @@
|
||||
!function(){"use strict";var e,t,i,a,r=window.location,o=window.document,l=o.getElementById("plausible"),s=l.getAttribute("data-api")||(e=l.src.split("/"),t=e[0],i=e[2],t+"//"+i+"/api/event"),c=window.localStorage.plausible_ignore,p=l&&l.getAttribute("data-exclude").split(",");function d(e){console.warn("Ignoring Event: "+e)}function n(e,t){if(/^localhost$|^127(?:\.[0-9]+){0,2}\.[0-9]+$|^(?:0*\:)*?:?0*1$/.test(r.hostname)||"file:"===r.protocol)return d("localhost");if(!(window.phantom||window._phantom||window.__nightmare||window.navigator.webdriver||window.Cypress)){if("true"==c)return d("localStorage flag");if(p)for(var i=0;i<p.length;i++)if("pageview"==e&&r.pathname.match(new RegExp("^"+p[i].trim().replace(/\*\*/g,".*").replace(/([^\.])\*/g,"$1[^\\s/]*")+"/?$")))return d("exclusion rule");var a={};a.n=e,a.u=r.href,a.d=l.getAttribute("data-domain"),a.r=o.referrer||null,a.w=window.innerWidth,t&&t.meta&&(a.m=JSON.stringify(t.meta)),t&&t.props&&(a.p=JSON.stringify(t.props)),a.h=1;var n=new XMLHttpRequest;n.open("POST",s,!0),n.setRequestHeader("Content-Type","text/plain"),n.send(JSON.stringify(a)),n.onreadystatechange=function(){4==n.readyState&&t&&t.callback&&t.callback()}}}function u(){a=r.pathname,n("pageview")}function w(e){for(var t=e.target,i="auxclick"==e.type&&2==e.which,a="click"==e.type;t&&(void 0===t.tagName||"a"!=t.tagName.toLowerCase()||!t.href);)t=t.parentNode;t&&t.href&&t.host&&t.host!==r.host&&((i||a)&&plausible("Outbound Link: Click",{props:{url:t.href}}),t.target&&!t.target.match(/^_(self|parent|top)$/i)||e.ctrlKey||e.metaKey||e.shiftKey||!a||(setTimeout(function(){r.href=t.href},150),e.preventDefault()))}window.addEventListener("hashchange",u),o.addEventListener("click",w),o.addEventListener("auxclick",w);var h=window.plausible&&window.plausible.q||[];window.plausible=n;for(var f=0;f<h.length;f++)n.apply(this,h[f]);"prerender"===o.visibilityState?o.addEventListener("visibilitychange",function(){a||"visible"!==o.visibilityState||u()}):u()}();
|
||||
@ -0,0 +1 @@
|
||||
!function(){"use strict";var t,e,i,n,r=window.location,o=window.document,l=o.getElementById("plausible"),s=l.getAttribute("data-api")||(t=l.src.split("/"),e=t[0],i=t[2],e+"//"+i+"/api/event"),p=window.localStorage.plausible_ignore,w=l&&l.getAttribute("data-exclude").split(",");function d(t){console.warn("Ignoring Event: "+t)}function a(t,e){if(/^localhost$|^127(?:\.[0-9]+){0,2}\.[0-9]+$|^(?:0*\:)*?:?0*1$/.test(r.hostname)||"file:"===r.protocol)return d("localhost");if(!(window.phantom||window._phantom||window.__nightmare||window.navigator.webdriver||window.Cypress)){if("true"==p)return d("localStorage flag");if(w)for(var i=0;i<w.length;i++)if("pageview"==t&&r.pathname.match(new RegExp("^"+w[i].trim().replace(/\*\*/g,".*").replace(/([^\.])\*/g,"$1[^\\s/]*")+"/?$")))return d("exclusion rule");var n={};n.n=t,n.u=r.href,n.d=l.getAttribute("data-domain"),n.r=o.referrer||null,n.w=window.innerWidth,e&&e.meta&&(n.m=JSON.stringify(e.meta)),e&&e.props&&(n.p=JSON.stringify(e.props));var a=new XMLHttpRequest;a.open("POST",s,!0),a.setRequestHeader("Content-Type","text/plain"),a.send(JSON.stringify(n)),a.onreadystatechange=function(){4==a.readyState&&e&&e.callback&&e.callback()}}}function u(){n!==r.pathname&&(n=r.pathname,a("pageview"))}var c,g=window.history;g.pushState&&(c=g.pushState,g.pushState=function(){c.apply(this,arguments),u()},window.addEventListener("popstate",u));var h=window.plausible&&window.plausible.q||[];window.plausible=a;for(var f=0;f<h.length;f++)a.apply(this,h[f]);"prerender"===o.visibilityState?o.addEventListener("visibilitychange",function(){n||"visible"!==o.visibilityState||u()}):u()}();
|
||||
@ -0,0 +1 @@
|
||||
!function(){"use strict";var e,t,i,a,r=window.location,o=window.document,l=o.getElementById("plausible"),s=l.getAttribute("data-api")||(e=l.src.split("/"),t=e[0],i=e[2],t+"//"+i+"/api/event"),p=window.localStorage.plausible_ignore,c=l&&l.getAttribute("data-exclude").split(",");function u(e){console.warn("Ignoring Event: "+e)}function n(e,t){if(/^localhost$|^127(?:\.[0-9]+){0,2}\.[0-9]+$|^(?:0*\:)*?:?0*1$/.test(r.hostname)||"file:"===r.protocol)return u("localhost");if(!(window.phantom||window._phantom||window.__nightmare||window.navigator.webdriver||window.Cypress)){if("true"==p)return u("localStorage flag");if(c)for(var i=0;i<c.length;i++)if("pageview"==e&&r.pathname.match(new RegExp("^"+c[i].trim().replace(/\*\*/g,".*").replace(/([^\.])\*/g,"$1[^\\s/]*")+"/?$")))return u("exclusion rule");var a={};a.n=e,a.u=r.href,a.d=l.getAttribute("data-domain"),a.r=o.referrer||null,a.w=window.innerWidth,t&&t.meta&&(a.m=JSON.stringify(t.meta)),t&&t.props&&(a.p=JSON.stringify(t.props));var n=new XMLHttpRequest;n.open("POST",s,!0),n.setRequestHeader("Content-Type","text/plain"),n.send(JSON.stringify(a)),n.onreadystatechange=function(){4==n.readyState&&t&&t.callback&&t.callback()}}}function d(){a!==r.pathname&&(a=r.pathname,n("pageview"))}function w(e){for(var t=e.target,i="auxclick"==e.type&&2==e.which,a="click"==e.type;t&&(void 0===t.tagName||"a"!=t.tagName.toLowerCase()||!t.href);)t=t.parentNode;t&&t.href&&t.host&&t.host!==r.host&&((i||a)&&plausible("Outbound Link: Click",{props:{url:t.href}}),t.target&&!t.target.match(/^_(self|parent|top)$/i)||e.ctrlKey||e.metaKey||e.shiftKey||!a||(setTimeout(function(){r.href=t.href},150),e.preventDefault()))}var h,f=window.history;f.pushState&&(h=f.pushState,f.pushState=function(){h.apply(this,arguments),d()},window.addEventListener("popstate",d)),o.addEventListener("click",w),o.addEventListener("auxclick",w);var g=window.plausible&&window.plausible.q||[];window.plausible=n;for(var v=0;v<g.length;v++)n.apply(this,g[v]);"prerender"===o.visibilityState?o.addEventListener("visibilitychange",function(){a||"visible"!==o.visibilityState||d()}):d()}();
|
||||
@ -0,0 +1 @@
|
||||
!function(){"use strict";var e,t,i,n,a=window.location,o=window.document,r=o.getElementById("plausible"),l=r.getAttribute("data-api")||(e=r.src.split("/"),t=e[0],i=e[2],t+"//"+i+"/api/event"),s=window.localStorage.plausible_ignore;function w(e){console.warn("Ignoring Event: "+e)}function d(e,t){if(/^localhost$|^127(?:\.[0-9]+){0,2}\.[0-9]+$|^(?:0*\:)*?:?0*1$/.test(a.hostname)||"file:"===a.protocol)return w("localhost");if(!(window.phantom||window._phantom||window.__nightmare||window.navigator.webdriver||window.Cypress)){if("true"==s)return w("localStorage flag");var i={};i.n=e,i.u=a.href,i.d=r.getAttribute("data-domain"),i.r=o.referrer||null,i.w=window.innerWidth,t&&t.meta&&(i.m=JSON.stringify(t.meta)),t&&t.props&&(i.p=JSON.stringify(t.props)),i.h=1;var n=new XMLHttpRequest;n.open("POST",l,!0),n.setRequestHeader("Content-Type","text/plain"),n.send(JSON.stringify(i)),n.onreadystatechange=function(){4==n.readyState&&t&&t.callback&&t.callback()}}}function p(){n=a.pathname,d("pageview")}window.addEventListener("hashchange",p);var c=window.plausible&&window.plausible.q||[];window.plausible=d;for(var u=0;u<c.length;u++)d.apply(this,c[u]);"prerender"===o.visibilityState?o.addEventListener("visibilitychange",function(){n||"visible"!==o.visibilityState||p()}):p()}();
|
||||
@ -0,0 +1 @@
|
||||
!function(){"use strict";var e,t,i,n,a=window.location,r=window.document,o=r.getElementById("plausible"),l=o.getAttribute("data-api")||(e=o.src.split("/"),t=e[0],i=e[2],t+"//"+i+"/api/event"),s=window.localStorage.plausible_ignore;function c(e){console.warn("Ignoring Event: "+e)}function d(e,t){if(/^localhost$|^127(?:\.[0-9]+){0,2}\.[0-9]+$|^(?:0*\:)*?:?0*1$/.test(a.hostname)||"file:"===a.protocol)return c("localhost");if(!(window.phantom||window._phantom||window.__nightmare||window.navigator.webdriver||window.Cypress)){if("true"==s)return c("localStorage flag");var i={};i.n=e,i.u=a.href,i.d=o.getAttribute("data-domain"),i.r=r.referrer||null,i.w=window.innerWidth,t&&t.meta&&(i.m=JSON.stringify(t.meta)),t&&t.props&&(i.p=JSON.stringify(t.props)),i.h=1;var n=new XMLHttpRequest;n.open("POST",l,!0),n.setRequestHeader("Content-Type","text/plain"),n.send(JSON.stringify(i)),n.onreadystatechange=function(){4==n.readyState&&t&&t.callback&&t.callback()}}}function p(){n=a.pathname,d("pageview")}function w(e){for(var t=e.target,i="auxclick"==e.type&&2==e.which,n="click"==e.type;t&&(void 0===t.tagName||"a"!=t.tagName.toLowerCase()||!t.href);)t=t.parentNode;t&&t.href&&t.host&&t.host!==a.host&&((i||n)&&plausible("Outbound Link: Click",{props:{url:t.href}}),t.target&&!t.target.match(/^_(self|parent|top)$/i)||e.ctrlKey||e.metaKey||e.shiftKey||!n||(setTimeout(function(){a.href=t.href},150),e.preventDefault()))}window.addEventListener("hashchange",p),r.addEventListener("click",w),r.addEventListener("auxclick",w);var u=window.plausible&&window.plausible.q||[];window.plausible=d;for(var h=0;h<u.length;h++)d.apply(this,u[h]);"prerender"===r.visibilityState?r.addEventListener("visibilitychange",function(){n||"visible"!==r.visibilityState||p()}):p()}();
|
||||
@ -0,0 +1 @@
|
||||
!function(){"use strict";var t,e,i,n,a=window.location,o=window.document,r=o.getElementById("plausible"),l=r.getAttribute("data-api")||(t=r.src.split("/"),e=t[0],i=t[2],e+"//"+i+"/api/event"),s=window.localStorage.plausible_ignore;function p(t){console.warn("Ignoring Event: "+t)}function w(t,e){if(/^localhost$|^127(?:\.[0-9]+){0,2}\.[0-9]+$|^(?:0*\:)*?:?0*1$/.test(a.hostname)||"file:"===a.protocol)return p("localhost");if(!(window.phantom||window._phantom||window.__nightmare||window.navigator.webdriver||window.Cypress)){if("true"==s)return p("localStorage flag");var i={};i.n=t,i.u=a.href,i.d=r.getAttribute("data-domain"),i.r=o.referrer||null,i.w=window.innerWidth,e&&e.meta&&(i.m=JSON.stringify(e.meta)),e&&e.props&&(i.p=JSON.stringify(e.props));var n=new XMLHttpRequest;n.open("POST",l,!0),n.setRequestHeader("Content-Type","text/plain"),n.send(JSON.stringify(i)),n.onreadystatechange=function(){4==n.readyState&&e&&e.callback&&e.callback()}}}function d(){n!==a.pathname&&(n=a.pathname,w("pageview"))}var u,c=window.history;c.pushState&&(u=c.pushState,c.pushState=function(){u.apply(this,arguments),d()},window.addEventListener("popstate",d));var h=window.plausible&&window.plausible.q||[];window.plausible=w;for(var f=0;f<h.length;f++)w.apply(this,h[f]);"prerender"===o.visibilityState?o.addEventListener("visibilitychange",function(){n||"visible"!==o.visibilityState||d()}):d()}();
|
||||
@ -0,0 +1 @@
|
||||
!function(){"use strict";var t,e,i,n,a=window.location,r=window.document,o=r.getElementById("plausible"),l=o.getAttribute("data-api")||(t=o.src.split("/"),e=t[0],i=t[2],e+"//"+i+"/api/event"),s=window.localStorage.plausible_ignore;function p(t){console.warn("Ignoring Event: "+t)}function d(t,e){if(/^localhost$|^127(?:\.[0-9]+){0,2}\.[0-9]+$|^(?:0*\:)*?:?0*1$/.test(a.hostname)||"file:"===a.protocol)return p("localhost");if(!(window.phantom||window._phantom||window.__nightmare||window.navigator.webdriver||window.Cypress)){if("true"==s)return p("localStorage flag");var i={};i.n=t,i.u=a.href,i.d=o.getAttribute("data-domain"),i.r=r.referrer||null,i.w=window.innerWidth,e&&e.meta&&(i.m=JSON.stringify(e.meta)),e&&e.props&&(i.p=JSON.stringify(e.props));var n=new XMLHttpRequest;n.open("POST",l,!0),n.setRequestHeader("Content-Type","text/plain"),n.send(JSON.stringify(i)),n.onreadystatechange=function(){4==n.readyState&&e&&e.callback&&e.callback()}}}function c(){n!==a.pathname&&(n=a.pathname,d("pageview"))}function u(t){for(var e=t.target,i="auxclick"==t.type&&2==t.which,n="click"==t.type;e&&(void 0===e.tagName||"a"!=e.tagName.toLowerCase()||!e.href);)e=e.parentNode;e&&e.href&&e.host&&e.host!==a.host&&((i||n)&&plausible("Outbound Link: Click",{props:{url:e.href}}),e.target&&!e.target.match(/^_(self|parent|top)$/i)||t.ctrlKey||t.metaKey||t.shiftKey||!n||(setTimeout(function(){a.href=e.href},150),t.preventDefault()))}var w,h=window.history;h.pushState&&(w=h.pushState,h.pushState=function(){w.apply(this,arguments),c()},window.addEventListener("popstate",c)),r.addEventListener("click",u),r.addEventListener("auxclick",u);var f=window.plausible&&window.plausible.q||[];window.plausible=d;for(var g=0;g<f.length;g++)d.apply(this,f[g]);"prerender"===r.visibilityState?r.addEventListener("visibilitychange",function(){n||"visible"!==r.visibilityState||c()}):c()}();
|
||||
@ -0,0 +1,110 @@
|
||||
defmodule Plausible.Billing.SiteLockerTest do
|
||||
use Plausible.DataCase
|
||||
use Bamboo.Test, shared: true
|
||||
alias Plausible.Billing.SiteLocker
|
||||
|
||||
describe "check_sites_for/1" do
|
||||
test "does not lock sites if user is on trial" do
|
||||
user =
|
||||
insert(:user, trial_expiry_date: Timex.today())
|
||||
|> Repo.preload(:subscription)
|
||||
|
||||
site = insert(:site, locked: true, members: [user])
|
||||
|
||||
SiteLocker.check_sites_for(user)
|
||||
|
||||
refute Repo.reload!(site).locked
|
||||
end
|
||||
|
||||
test "does not lock if user has an active subscription" do
|
||||
user = insert(:user)
|
||||
insert(:subscription, status: "active", user: user)
|
||||
user = Repo.preload(user, :subscription)
|
||||
site = insert(:site, locked: true, members: [user])
|
||||
|
||||
SiteLocker.check_sites_for(user)
|
||||
|
||||
refute Repo.reload!(site).locked
|
||||
end
|
||||
|
||||
test "does not lock user who is past due" do
|
||||
user = insert(:user)
|
||||
insert(:subscription, status: "past_due", user: user)
|
||||
user = Repo.preload(user, :subscription)
|
||||
site = insert(:site, members: [user])
|
||||
|
||||
SiteLocker.check_sites_for(user)
|
||||
|
||||
refute Repo.reload!(site).locked
|
||||
end
|
||||
|
||||
test "does not lock user who cancelled subscription but it hasn't expired yet" do
|
||||
user = insert(:user)
|
||||
insert(:subscription, status: "deleted", user: user)
|
||||
user = Repo.preload(user, :subscription)
|
||||
site = insert(:site, members: [user])
|
||||
|
||||
SiteLocker.check_sites_for(user)
|
||||
|
||||
refute Repo.reload!(site).locked
|
||||
end
|
||||
|
||||
test "locks user who cancelled subscription and the cancelled subscription has expired" do
|
||||
user = insert(:user)
|
||||
|
||||
insert(:subscription,
|
||||
status: "deleted",
|
||||
next_bill_date: Timex.today() |> Timex.shift(days: -1),
|
||||
user: user
|
||||
)
|
||||
|
||||
site = insert(:site, members: [user])
|
||||
|
||||
user = Repo.preload(user, :subscription)
|
||||
|
||||
SiteLocker.check_sites_for(user)
|
||||
|
||||
refute Repo.reload!(site).locked
|
||||
end
|
||||
|
||||
test "locks all sites if user has no trial or active subscription" do
|
||||
user =
|
||||
insert(:user, trial_expiry_date: Timex.today() |> Timex.shift(days: -1))
|
||||
|> Repo.preload(:subscription)
|
||||
|
||||
site = insert(:site, locked: true, members: [user])
|
||||
|
||||
SiteLocker.check_sites_for(user)
|
||||
|
||||
assert Repo.reload!(site).locked
|
||||
end
|
||||
|
||||
test "only locks sites that the user owns" do
|
||||
user =
|
||||
insert(:user, trial_expiry_date: Timex.today() |> Timex.shift(days: -1))
|
||||
|> Repo.preload(:subscription)
|
||||
|
||||
owner_site =
|
||||
insert(:site,
|
||||
memberships: [
|
||||
build(:site_membership, user: user, role: :owner)
|
||||
]
|
||||
)
|
||||
|
||||
viewer_site =
|
||||
insert(:site,
|
||||
memberships: [
|
||||
build(:site_membership, user: user, role: :viewer)
|
||||
]
|
||||
)
|
||||
|
||||
SiteLocker.check_sites_for(user)
|
||||
|
||||
owner_site = Repo.reload!(owner_site)
|
||||
viewer_site = Repo.reload!(viewer_site)
|
||||
|
||||
assert owner_site.locked
|
||||
refute viewer_site.locked
|
||||
end
|
||||
end
|
||||
end
|
||||
@ -0,0 +1,133 @@
|
||||
defmodule PlausibleWeb.Api.StatsController.SuggestionsTest do
|
||||
use PlausibleWeb.ConnCase
|
||||
import Plausible.TestUtils
|
||||
|
||||
describe "GET /api/stats/:domain/suggestions/:filter_name" do
|
||||
setup [:create_user, :log_in, :create_site]
|
||||
|
||||
test "returns suggestions for pages without a query", %{conn: conn, site: site} do
|
||||
conn = get(conn, "/api/stats/#{site.domain}/suggestions/page?period=month&date=2019-01-01")
|
||||
|
||||
assert json_response(conn, 200) == ["/", "/register", "/contact", "/irrelevant"]
|
||||
end
|
||||
|
||||
test "returns suggestions for pages with a query", %{conn: conn, site: site} do
|
||||
conn =
|
||||
get(conn, "/api/stats/#{site.domain}/suggestions/page?period=month&date=2019-01-01&q=re")
|
||||
|
||||
assert json_response(conn, 200) == ["/register", "/irrelevant"]
|
||||
end
|
||||
|
||||
test "returns suggestions for pages without any suggestions", %{conn: conn, site: site} do
|
||||
conn =
|
||||
get(
|
||||
conn,
|
||||
"/api/stats/#{site.domain}/suggestions/page?period=month&date=2019-01-01&q=/123"
|
||||
)
|
||||
|
||||
assert json_response(conn, 200) == []
|
||||
end
|
||||
|
||||
test "returns suggestions for goals", %{conn: conn, site: site} do
|
||||
conn = get(conn, "/api/stats/#{site.domain}/suggestions/goal?period=month&date=2019-01-01")
|
||||
|
||||
assert json_response(conn, 200) == []
|
||||
end
|
||||
|
||||
test "returns suggestions for sources", %{conn: conn, site: site} do
|
||||
conn =
|
||||
get(conn, "/api/stats/#{site.domain}/suggestions/source?period=month&date=2019-01-01")
|
||||
|
||||
assert json_response(conn, 200) == ["10words", "Bing"]
|
||||
end
|
||||
|
||||
test "returns suggestions for countries", %{conn: conn, site: site} do
|
||||
conn =
|
||||
get(
|
||||
conn,
|
||||
"/api/stats/#{site.domain}/suggestions/country?period=month&date=2019-01-01&q=GBR,UKR,URY,USA"
|
||||
)
|
||||
|
||||
assert json_response(conn, 200) == ["USA"]
|
||||
end
|
||||
|
||||
test "returns suggestions for countries without country in search", %{conn: conn, site: site} do
|
||||
conn =
|
||||
get(
|
||||
conn,
|
||||
"/api/stats/#{site.domain}/suggestions/country?period=month&date=2019-01-01&q=GBR,UKR,URY"
|
||||
)
|
||||
|
||||
assert json_response(conn, 200) == []
|
||||
end
|
||||
|
||||
test "returns suggestions for screen sizes", %{conn: conn, site: site} do
|
||||
conn =
|
||||
get(conn, "/api/stats/#{site.domain}/suggestions/screen?period=month&date=2019-01-01")
|
||||
|
||||
assert json_response(conn, 200) == ["Desktop"]
|
||||
end
|
||||
|
||||
test "returns suggestions for browsers", %{conn: conn, site: site} do
|
||||
conn =
|
||||
get(conn, "/api/stats/#{site.domain}/suggestions/browser?period=month&date=2019-01-01")
|
||||
|
||||
assert json_response(conn, 200) == ["Chrome"]
|
||||
end
|
||||
|
||||
test "returns suggestions for browser versions", %{conn: conn, site: site} do
|
||||
filters = Jason.encode!(%{browser: "Chrome"})
|
||||
|
||||
conn =
|
||||
get(
|
||||
conn,
|
||||
"/api/stats/#{site.domain}/suggestions/browser_version?period=month&date=2019-01-01&filters=#{
|
||||
filters
|
||||
}"
|
||||
)
|
||||
|
||||
assert json_response(conn, 200) == ["78.0"]
|
||||
end
|
||||
|
||||
test "returns suggestions for OS", %{conn: conn, site: site} do
|
||||
conn = get(conn, "/api/stats/#{site.domain}/suggestions/os?period=month&date=2019-01-01")
|
||||
|
||||
assert json_response(conn, 200) == ["Mac"]
|
||||
end
|
||||
|
||||
test "returns suggestions for OS versions", %{conn: conn, site: site} do
|
||||
filters = Jason.encode!(%{os: "Mac"})
|
||||
|
||||
conn =
|
||||
get(
|
||||
conn,
|
||||
"/api/stats/#{site.domain}/suggestions/os_version?period=month&date=2019-01-01&filters=#{
|
||||
filters
|
||||
}"
|
||||
)
|
||||
|
||||
assert json_response(conn, 200) == ["10.15"]
|
||||
end
|
||||
|
||||
test "returns suggestions for OS versions with search", %{conn: conn, site: site} do
|
||||
filters = Jason.encode!(%{os: "Mac"})
|
||||
|
||||
conn =
|
||||
get(
|
||||
conn,
|
||||
"/api/stats/#{site.domain}/suggestions/os_version?period=month&date=2019-01-01&filters=#{
|
||||
filters
|
||||
}&q=11"
|
||||
)
|
||||
|
||||
assert json_response(conn, 200) == []
|
||||
end
|
||||
|
||||
test "returns suggestions for referrers", %{conn: conn, site: site} do
|
||||
conn =
|
||||
get(conn, "/api/stats/#{site.domain}/suggestions/referrer?period=month&date=2019-01-01")
|
||||
|
||||
assert json_response(conn, 200) == ["10words.com/page1"]
|
||||
end
|
||||
end
|
||||
end
|
||||
@ -0,0 +1,158 @@
|
||||
defmodule PlausibleWeb.Site.InvitationControllerTest do
|
||||
use PlausibleWeb.ConnCase
|
||||
use Plausible.Repo
|
||||
use Bamboo.Test
|
||||
import Plausible.TestUtils
|
||||
|
||||
setup [:create_user, :log_in]
|
||||
|
||||
describe "POST /sites/invitations/:invitation_id/accept" do
|
||||
test "converts the invitation into a membership", %{conn: conn, user: user} do
|
||||
site = insert(:site)
|
||||
|
||||
invitation =
|
||||
insert(:invitation,
|
||||
site_id: site.id,
|
||||
inviter: build(:user),
|
||||
email: user.email,
|
||||
role: :admin
|
||||
)
|
||||
|
||||
post(conn, "/sites/invitations/#{invitation.invitation_id}/accept")
|
||||
|
||||
refute Repo.exists?(from(i in Plausible.Auth.Invitation, where: i.email == ^user.email))
|
||||
|
||||
membership = Repo.get_by(Plausible.Site.Membership, user_id: user.id, site_id: site.id)
|
||||
assert membership.role == :admin
|
||||
end
|
||||
|
||||
test "notifies the original inviter", %{conn: conn, user: user} do
|
||||
inviter = insert(:user)
|
||||
site = insert(:site)
|
||||
|
||||
invitation =
|
||||
insert(:invitation, site_id: site.id, inviter: inviter, email: user.email, role: :admin)
|
||||
|
||||
post(conn, "/sites/invitations/#{invitation.invitation_id}/accept")
|
||||
|
||||
assert_email_delivered_with(
|
||||
to: [nil: inviter.email],
|
||||
subject: "[Plausible Analytics] #{user.email} accepted your invitation to #{site.domain}"
|
||||
)
|
||||
end
|
||||
|
||||
test "ownership transfer - notifies the original inviter with a different email", %{
|
||||
conn: conn,
|
||||
user: user
|
||||
} do
|
||||
inviter = insert(:user)
|
||||
site = insert(:site)
|
||||
|
||||
invitation =
|
||||
insert(:invitation, site_id: site.id, inviter: inviter, email: user.email, role: :owner)
|
||||
|
||||
post(conn, "/sites/invitations/#{invitation.invitation_id}/accept")
|
||||
|
||||
assert_email_delivered_with(
|
||||
to: [nil: inviter.email],
|
||||
subject:
|
||||
"[Plausible Analytics] #{user.email} accepted the ownership transfer of #{site.domain}"
|
||||
)
|
||||
end
|
||||
|
||||
test "ownership transfer - downgrades previous owner to admin", %{conn: conn, user: user} do
|
||||
old_owner = insert(:user)
|
||||
site = insert(:site, members: [old_owner])
|
||||
|
||||
invitation =
|
||||
insert(:invitation, site_id: site.id, inviter: old_owner, email: user.email, role: :owner)
|
||||
|
||||
post(conn, "/sites/invitations/#{invitation.invitation_id}/accept")
|
||||
|
||||
refute Repo.exists?(from(i in Plausible.Auth.Invitation, where: i.email == ^user.email))
|
||||
|
||||
old_owner_membership =
|
||||
Repo.get_by(Plausible.Site.Membership, user_id: old_owner.id, site_id: site.id)
|
||||
|
||||
assert old_owner_membership.role == :admin
|
||||
|
||||
new_owner_membership =
|
||||
Repo.get_by(Plausible.Site.Membership, user_id: user.id, site_id: site.id)
|
||||
|
||||
assert new_owner_membership.role == :owner
|
||||
end
|
||||
|
||||
test "ownership transfer - will lock the site if new owner does not have an active subscription or trial",
|
||||
%{
|
||||
conn: conn,
|
||||
user: user
|
||||
} do
|
||||
Repo.update_all(from(u in Plausible.Auth.User, where: u.id == ^user.id),
|
||||
set: [trial_expiry_date: Timex.today() |> Timex.shift(days: -1)]
|
||||
)
|
||||
|
||||
inviter = insert(:user)
|
||||
site = insert(:site, locked: false)
|
||||
|
||||
invitation =
|
||||
insert(:invitation, site_id: site.id, inviter: inviter, email: user.email, role: :owner)
|
||||
|
||||
post(conn, "/sites/invitations/#{invitation.invitation_id}/accept")
|
||||
|
||||
assert Repo.reload!(site).locked
|
||||
end
|
||||
end
|
||||
|
||||
describe "POST /sites/invitations/:invitation_id/reject" do
|
||||
test "deletes the invitation", %{conn: conn, user: user} do
|
||||
site = insert(:site)
|
||||
|
||||
invitation =
|
||||
insert(:invitation,
|
||||
site_id: site.id,
|
||||
inviter: build(:user),
|
||||
email: user.email,
|
||||
role: :admin
|
||||
)
|
||||
|
||||
post(conn, "/sites/invitations/#{invitation.invitation_id}/reject")
|
||||
|
||||
refute Repo.exists?(from(i in Plausible.Auth.Invitation, where: i.email == ^user.email))
|
||||
end
|
||||
|
||||
test "notifies the original inviter", %{conn: conn, user: user} do
|
||||
inviter = insert(:user)
|
||||
site = insert(:site)
|
||||
|
||||
invitation =
|
||||
insert(:invitation, site_id: site.id, inviter: inviter, email: user.email, role: :admin)
|
||||
|
||||
post(conn, "/sites/invitations/#{invitation.invitation_id}/reject")
|
||||
|
||||
assert_email_delivered_with(
|
||||
to: [nil: inviter.email],
|
||||
subject: "[Plausible Analytics] #{user.email} rejected your invitation to #{site.domain}"
|
||||
)
|
||||
end
|
||||
end
|
||||
|
||||
describe "DELETE /sites/invitations/:invitation_id" do
|
||||
test "removes the invitation", %{conn: conn} do
|
||||
site = insert(:site)
|
||||
|
||||
invitation =
|
||||
insert(:invitation,
|
||||
site_id: site.id,
|
||||
inviter: build(:user),
|
||||
email: "jane@example.com",
|
||||
role: :admin
|
||||
)
|
||||
|
||||
delete(conn, "/sites/invitations/#{invitation.invitation_id}")
|
||||
|
||||
refute Repo.exists?(
|
||||
from i in Plausible.Auth.Invitation, where: i.email == "jane@example.com"
|
||||
)
|
||||
end
|
||||
end
|
||||
end
|
||||
@ -0,0 +1,204 @@
|
||||
defmodule PlausibleWeb.Site.MembershipControllerTest do
|
||||
use PlausibleWeb.ConnCase
|
||||
use Plausible.Repo
|
||||
use Bamboo.Test
|
||||
import Plausible.TestUtils
|
||||
|
||||
setup [:create_user, :log_in]
|
||||
|
||||
describe "GET /sites/:website/memberships/invite" do
|
||||
test "shows invite form", %{conn: conn, user: user} do
|
||||
site = insert(:site, members: [user])
|
||||
|
||||
conn = get(conn, "/sites/#{site.domain}/memberships/invite")
|
||||
|
||||
assert html_response(conn, 200) =~ "Invite member to"
|
||||
end
|
||||
end
|
||||
|
||||
describe "POST /sites/:website/memberships/invite" do
|
||||
test "creates invitation", %{conn: conn, user: user} do
|
||||
site = insert(:site, members: [user])
|
||||
|
||||
conn =
|
||||
post(conn, "/sites/#{site.domain}/memberships/invite", %{
|
||||
email: "john.doe@example.com",
|
||||
role: "admin"
|
||||
})
|
||||
|
||||
invitation = Repo.get_by(Plausible.Auth.Invitation, email: "john.doe@example.com")
|
||||
|
||||
assert invitation.role == :admin
|
||||
assert redirected_to(conn) == "/#{site.domain}/settings/people"
|
||||
end
|
||||
|
||||
test "sends invitation email for new user", %{conn: conn, user: user} do
|
||||
site = insert(:site, members: [user])
|
||||
|
||||
post(conn, "/sites/#{site.domain}/memberships/invite", %{
|
||||
email: "john.doe@example.com",
|
||||
role: "admin"
|
||||
})
|
||||
|
||||
assert_email_delivered_with(
|
||||
to: [nil: "john.doe@example.com"],
|
||||
subject: "[Plausible Analytics] You've been invited to #{site.domain}"
|
||||
)
|
||||
end
|
||||
|
||||
test "sends invitation email for existing user", %{conn: conn, user: user} do
|
||||
existing_user = insert(:user)
|
||||
site = insert(:site, members: [user])
|
||||
|
||||
post(conn, "/sites/#{site.domain}/memberships/invite", %{
|
||||
email: existing_user.email,
|
||||
role: "admin"
|
||||
})
|
||||
|
||||
assert_email_delivered_with(
|
||||
to: [nil: existing_user.email],
|
||||
subject: "[Plausible Analytics] You've been invited to #{site.domain}"
|
||||
)
|
||||
end
|
||||
|
||||
test "renders form with error if the invitee is already a member", %{conn: conn, user: user} do
|
||||
second_member = insert(:user)
|
||||
site = insert(:site, members: [user, second_member])
|
||||
|
||||
conn =
|
||||
post(conn, "/sites/#{site.domain}/memberships/invite", %{
|
||||
email: second_member.email,
|
||||
role: "admin"
|
||||
})
|
||||
|
||||
assert html_response(conn, 200) =~
|
||||
"#{second_member.email} is already a member of #{site.domain}"
|
||||
end
|
||||
end
|
||||
|
||||
describe "GET /sites/:website/transfer-ownership" do
|
||||
test "shows ownership transfer form", %{conn: conn, user: user} do
|
||||
site = insert(:site, members: [user])
|
||||
|
||||
conn = get(conn, "/sites/#{site.domain}/transfer-ownership")
|
||||
|
||||
assert html_response(conn, 200) =~ "Transfer ownership of"
|
||||
end
|
||||
end
|
||||
|
||||
describe "POST /sites/:website/transfer-ownership" do
|
||||
test "creates invitation with :owner role", %{conn: conn, user: user} do
|
||||
site = insert(:site, members: [user])
|
||||
|
||||
conn =
|
||||
post(conn, "/sites/#{site.domain}/transfer-ownership", %{email: "john.doe@example.com"})
|
||||
|
||||
invitation = Repo.get_by(Plausible.Auth.Invitation, email: "john.doe@example.com")
|
||||
|
||||
assert invitation.role == :owner
|
||||
assert redirected_to(conn) == "/#{site.domain}/settings/people"
|
||||
end
|
||||
|
||||
test "sends ownership transfer email for new user", %{conn: conn, user: user} do
|
||||
site = insert(:site, members: [user])
|
||||
|
||||
post(conn, "/sites/#{site.domain}/transfer-ownership", %{email: "john.doe@example.com"})
|
||||
|
||||
assert_email_delivered_with(
|
||||
to: [nil: "john.doe@example.com"],
|
||||
subject: "[Plausible Analytics] Request to transfer ownership of #{site.domain}"
|
||||
)
|
||||
end
|
||||
|
||||
test "sends invitation email for existing user", %{conn: conn, user: user} do
|
||||
existing_user = insert(:user)
|
||||
site = insert(:site, members: [user])
|
||||
|
||||
post(conn, "/sites/#{site.domain}/transfer-ownership", %{email: existing_user.email})
|
||||
|
||||
assert_email_delivered_with(
|
||||
to: [nil: existing_user.email],
|
||||
subject: "[Plausible Analytics] Request to transfer ownership of #{site.domain}"
|
||||
)
|
||||
end
|
||||
end
|
||||
|
||||
describe "PUT /sites/memberships/:id/role/:new_role" do
|
||||
test "updates a site member's role", %{conn: conn, user: user} do
|
||||
admin = insert(:user)
|
||||
|
||||
site =
|
||||
insert(:site,
|
||||
memberships: [
|
||||
build(:site_membership, user: user, role: :owner),
|
||||
build(:site_membership, user: admin, role: :admin)
|
||||
]
|
||||
)
|
||||
|
||||
membership = Repo.get_by(Plausible.Site.Membership, user_id: admin.id)
|
||||
|
||||
put(conn, "/sites/#{site.domain}/memberships/#{membership.id}/role/viewer")
|
||||
|
||||
membership = Repo.reload!(membership)
|
||||
|
||||
assert membership.role == :viewer
|
||||
end
|
||||
|
||||
test "can downgrade yourself from admin to viewer, redirects to stats instead", %{
|
||||
conn: conn,
|
||||
user: user
|
||||
} do
|
||||
site = insert(:site, memberships: [build(:site_membership, user: user, role: :admin)])
|
||||
|
||||
membership = Repo.get_by(Plausible.Site.Membership, user_id: user.id)
|
||||
|
||||
conn = put(conn, "/sites/#{site.domain}/memberships/#{membership.id}/role/viewer")
|
||||
|
||||
membership = Repo.reload!(membership)
|
||||
|
||||
assert membership.role == :viewer
|
||||
assert redirected_to(conn) == "/#{site.domain}"
|
||||
end
|
||||
end
|
||||
|
||||
describe "DELETE /sites/memberships/:id" do
|
||||
test "removes a member from a site", %{conn: conn, user: user} do
|
||||
admin = insert(:user)
|
||||
|
||||
site =
|
||||
insert(:site,
|
||||
memberships: [
|
||||
build(:site_membership, user: user, role: :owner),
|
||||
build(:site_membership, user: admin, role: :admin)
|
||||
]
|
||||
)
|
||||
|
||||
membership = Enum.find(site.memberships, &(&1.role == :admin))
|
||||
|
||||
delete(conn, "/sites/#{site.domain}/memberships/#{membership.id}")
|
||||
|
||||
refute Repo.exists?(from sm in Plausible.Site.Membership, where: sm.user_id == ^admin.id)
|
||||
end
|
||||
|
||||
test "notifies the user who has been removed via email", %{conn: conn, user: user} do
|
||||
admin = insert(:user)
|
||||
|
||||
site =
|
||||
insert(:site,
|
||||
memberships: [
|
||||
build(:site_membership, user: user, role: :owner),
|
||||
build(:site_membership, user: admin, role: :admin)
|
||||
]
|
||||
)
|
||||
|
||||
membership = Enum.find(site.memberships, &(&1.role == :admin))
|
||||
|
||||
delete(conn, "/sites/#{site.domain}/memberships/#{membership.id}")
|
||||
|
||||
assert_email_delivered_with(
|
||||
to: [nil: admin.email],
|
||||
subject: "[Plausible Analytics] Your access to #{site.domain} has been revoked"
|
||||
)
|
||||
end
|
||||
end
|
||||
end
|
||||
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue