Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 22 additions & 2 deletions frontend/src/pages/Setup.vue
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
:labels="labels"
:back-button="false"
@finish="finish"
@vue:mounted="sendStartIfLost"
>
<template #brand>
<div
Expand Down Expand Up @@ -116,7 +117,7 @@ import {
TelemetryConsent,
} from '@framework/ui/components/SetupFlow/index'
import { useTelemetry } from '@framework/ui/telemetry/index'
import { computed, inject, reactive } from 'vue'
import { computed, inject, reactive, watch } from 'vue'
import { useRouter } from 'vue-router'
import LMSLogo from '@/components/Icons/LMSLogo.vue'
import PersonaToolIcon from '@/components/PersonaToolIcon.vue'
Expand All @@ -126,7 +127,8 @@ import { setupQuestions } from '@/utils/setupQuestions'

const user = inject('$user')
const router = useRouter()
const { capture } = useTelemetry()
const telemetry = useTelemetry()
const { capture } = telemetry

const answers = reactive({})
let goalRoute = { name: 'Home' }
Expand Down Expand Up @@ -252,5 +254,23 @@ async function finish() {
window.location.href = router.resolve(goalRoute).href
}

// SetupFlow sends setup_started and the first step's view as it opens, and telemetry drops
// events until it has loaded, which on a new site's first page is often later. When it is
// still off as SetupFlow opens, both are sent once it is on. Drop this when the framework's
// SetupFlow waits for telemetry itself.
function sendStartIfLost() {
if (telemetry.isEnabled) return
const firstStep = steps.value[0]?.name
const stop = watch(
() => telemetry.isEnabled,
(on) => {
if (!on) return
stop()
capture('setup_started')
capture('setup_step_viewed', { step: firstStep })
}
)
}

usePageMeta(() => ({ title: __('Set up Frappe Learning') }))
</script>
207 changes: 0 additions & 207 deletions frontend/src/tests/adminBatchDashboardFilters.test.ts

This file was deleted.

41 changes: 38 additions & 3 deletions frontend/src/tests/setupPage.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,9 +26,14 @@ vi.mock('frappe-ui', () => ({
toast: { error: toastError },
usePageMeta: vi.fn(),
}))
vi.mock('@framework/ui/telemetry/index', () => ({
useTelemetry: () => ({ capture: captureMock }),
}))
const telemetry = vi.hoisted(() => ({ on: null as unknown as { value: boolean } }))
vi.mock('@framework/ui/telemetry/index', async () => {
const { reactive, ref } = await import('vue')
telemetry.on = ref(true)
return {
useTelemetry: () => reactive({ capture: captureMock, isEnabled: telemetry.on }),
}
})
vi.mock('@/components/Setup/SetupPreview.vue', () => ({
default: defineComponent({ setup: () => () => h('div') }),
}))
Expand Down Expand Up @@ -111,6 +116,7 @@ describe('Setup', () => {
callMock.mockReset()
callMock.mockImplementation(() => Promise.resolve())
replaceMock.mockClear()
captureMock.mockClear()
toastError.mockClear()
setupState.data = { can_send_email: true }
Object.defineProperty(window, 'location', {
Expand Down Expand Up @@ -200,4 +206,33 @@ describe('Setup', () => {
expect(givenSteps[0].name).toBe('password')
expect(givenSteps.at(-1)?.name).toBe('invite_team')
})

describe('the start event, which telemetry drops while it loads', () => {
it('is sent once telemetry is on, when it was still off as setup opened', async () => {
setupState.data = { can_send_email: true, needs_questions: true }
await import('@framework/ui/telemetry/index')
telemetry.on.value = false
try {
await mountPage()
await flushPromises()
expect(captureMock).not.toHaveBeenCalledWith('setup_started')

telemetry.on.value = true
await flushPromises()
expect(captureMock).toHaveBeenCalledWith('setup_started')
expect(captureMock).toHaveBeenCalledWith('setup_step_viewed', {
step: 'usage_context',
})
} finally {
telemetry.on.value = true
}
})

it('is left to SetupFlow when telemetry was already on', async () => {
setupState.data = { can_send_email: true, needs_questions: true }
await mountPage()
await flushPromises()
expect(captureMock).not.toHaveBeenCalledWith('setup_started')
})
})
})
3 changes: 3 additions & 0 deletions lms/hooks.py
Original file line number Diff line number Diff line change
Expand Up @@ -256,6 +256,9 @@ def get_lms_path():
override_whitelisted_methods = {
# Finishes Google Calendar sign-in started from an evaluator's Slots tab.
"frappe.integrations.doctype.google_calendar.google_calendar.google_callback": "lms.lms.api.google_calendar_callback",
# The framework's setup password step saves through this, which also asks on Frappe Cloud v2
# and sites with email login links; drop it once the framework's own check does.
"frappe.core.doctype.user.user.set_first_password": "lms.lms.onboarding.set_first_password",
}
#
# each overriding function accepts a `data` argument;
Expand Down
55 changes: 49 additions & 6 deletions lms/lms/onboarding.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import frappe
from frappe import _
from frappe.rate_limiter import rate_limit
from frappe.utils import today

ONBOARDING_ROLES = ("System Manager", "Moderator")

Expand Down Expand Up @@ -52,14 +54,55 @@ def get_setup_state() -> dict:
}


def needs_password_setup() -> bool:
"""A Frappe Cloud site owner arrives signed in but with no password; on a framework that knows
the case, the setup flow asks for one first."""
def needs_password_setup(user: str | None = None) -> bool:
"""A Frappe Cloud site owner arrives signed in but with no password, and the setup flow asks
for one first. Frappe's own check skips Frappe Cloud v2 and sites with email login links,
which is every trial site, so Learning asks wherever a password can be used to sign in."""
from frappe.utils.password import has_password

user = user or frappe.session.user
if user in ("Administrator", "Guest") or has_password(user):
return False
if frappe.get_system_settings("disable_user_pass_login"):
return False
if frappe.db.get_single_value("LDAP Settings", "enabled"):
return False
return not frappe.db.exists(
"User Social Login",
{"parenttype": "User", "parent": user, "provider": ["!=", "frappe"], "userid": ["is", "set"]},
)


@frappe.whitelist(methods=["POST"])
@rate_limit(limit=5, seconds=60)
def set_first_password(new_password: str) -> None:
"""Frappe's set_first_password with Learning's check, so the framework's password step saves
on the sites Frappe's own check skips. hooks.py points the framework's method here."""
from frappe.core.doctype.user.user import handle_password_test_fail, test_password_strength
from frappe.utils.password import update_password

try:
from frappe.core.doctype.user.user import needs_password_setup as framework_says
from frappe.utils.password import MAX_PASSWORD_SIZE
except ImportError:
return False
return bool(framework_says())
from frappe.auth import MAX_PASSWORD_SIZE

if frappe.request and frappe.get_request_header("Authorization"):
frappe.throw(_("Set your first password from a signed-in browser."), frappe.PermissionError)
if not new_password or not new_password.strip():
frappe.throw(_("Enter a password."), title=_("Invalid Password"))
if len(new_password) > MAX_PASSWORD_SIZE:
frappe.throw(_("{0} size exceeded the maximum allowed size.").format(_("New Password")))
if not needs_password_setup():
frappe.throw(_("You already have a password. Change it from your settings."), frappe.PermissionError)
user = frappe.get_doc("User", frappe.session.user)
feedback = test_password_strength(
new_password,
user_data=(user.first_name, user.middle_name, user.last_name, user.email, user.birth_date),
)
if feedback and not feedback.get("feedback", {}).get("password_policy_validation_passed", False):
handle_password_test_fail(feedback)
update_password(user.name, new_password, logout_all_sessions=False)
frappe.db.set_value("User", user.name, {"last_password_reset_date": today(), "reset_password_key": ""})


def can_send_email() -> bool:
Expand Down
Loading
Loading