Skip to content

Commit 4d7090c

Browse files
authored
Merge pull request #3377 from pateljannat/fix/setup-password-on-frappe-cloud
fix(setup): ask for a password and record the setup start on new Frappe Cloud sites
2 parents d739be4 + dca7dd3 commit 4d7090c

5 files changed

Lines changed: 178 additions & 11 deletions

File tree

‎frontend/src/pages/Setup.vue‎

Lines changed: 22 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
:labels="labels"
66
:back-button="false"
77
@finish="finish"
8+
@vue:mounted="sendStartIfLost"
89
>
910
<template #brand>
1011
<div
@@ -119,7 +120,7 @@ import {
119120
TelemetryConsent,
120121
} from '@framework/ui/components/SetupFlow/index'
121122
import { useTelemetry } from '@framework/ui/telemetry/index'
122-
import { computed, inject, reactive } from 'vue'
123+
import { computed, inject, reactive, watch } from 'vue'
123124
import { useRouter } from 'vue-router'
124125
import LMSLogo from '@/components/Icons/LMSLogo.vue'
125126
import PersonaToolIcon from '@/components/PersonaToolIcon.vue'
@@ -129,7 +130,8 @@ import { setupQuestions } from '@/utils/setupQuestions'
129130
130131
const user = inject('$user')
131132
const router = useRouter()
132-
const { capture } = useTelemetry()
133+
const telemetry = useTelemetry()
134+
const { capture } = telemetry
133135
134136
const answers = reactive({})
135137
let goalRoute = { name: 'Home' }
@@ -255,5 +257,23 @@ async function finish() {
255257
window.location.href = router.resolve(goalRoute).href
256258
}
257259
260+
// SetupFlow sends setup_started and the first step's view as it opens, and telemetry drops
261+
// events until it has loaded, which on a new site's first page is often later. When it is
262+
// still off as SetupFlow opens, both are sent once it is on. Drop this when the framework's
263+
// SetupFlow waits for telemetry itself.
264+
function sendStartIfLost() {
265+
if (telemetry.isEnabled) return
266+
const firstStep = steps.value[0]?.name
267+
const stop = watch(
268+
() => telemetry.isEnabled,
269+
(on) => {
270+
if (!on) return
271+
stop()
272+
capture('setup_started')
273+
capture('setup_step_viewed', { step: firstStep })
274+
}
275+
)
276+
}
277+
258278
usePageMeta(() => ({ title: __('Set up Frappe Learning') }))
259279
</script>

‎frontend/src/tests/setupPage.test.ts‎

Lines changed: 38 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -26,9 +26,14 @@ vi.mock('frappe-ui', () => ({
2626
toast: { error: toastError },
2727
usePageMeta: vi.fn(),
2828
}))
29-
vi.mock('@framework/ui/telemetry/index', () => ({
30-
useTelemetry: () => ({ capture: captureMock }),
31-
}))
29+
const telemetry = vi.hoisted(() => ({ on: null as unknown as { value: boolean } }))
30+
vi.mock('@framework/ui/telemetry/index', async () => {
31+
const { reactive, ref } = await import('vue')
32+
telemetry.on = ref(true)
33+
return {
34+
useTelemetry: () => reactive({ capture: captureMock, isEnabled: telemetry.on }),
35+
}
36+
})
3237
vi.mock('@/components/Setup/SetupPreview.vue', () => ({
3338
default: defineComponent({ setup: () => () => h('div') }),
3439
}))
@@ -111,6 +116,7 @@ describe('Setup', () => {
111116
callMock.mockReset()
112117
callMock.mockImplementation(() => Promise.resolve())
113118
replaceMock.mockClear()
119+
captureMock.mockClear()
114120
toastError.mockClear()
115121
setupState.data = { can_send_email: true }
116122
Object.defineProperty(window, 'location', {
@@ -200,4 +206,33 @@ describe('Setup', () => {
200206
expect(givenSteps[0].name).toBe('password')
201207
expect(givenSteps.at(-1)?.name).toBe('invite_team')
202208
})
209+
210+
describe('the start event, which telemetry drops while it loads', () => {
211+
it('is sent once telemetry is on, when it was still off as setup opened', async () => {
212+
setupState.data = { can_send_email: true, needs_questions: true }
213+
await import('@framework/ui/telemetry/index')
214+
telemetry.on.value = false
215+
try {
216+
await mountPage()
217+
await flushPromises()
218+
expect(captureMock).not.toHaveBeenCalledWith('setup_started')
219+
220+
telemetry.on.value = true
221+
await flushPromises()
222+
expect(captureMock).toHaveBeenCalledWith('setup_started')
223+
expect(captureMock).toHaveBeenCalledWith('setup_step_viewed', {
224+
step: 'usage_context',
225+
})
226+
} finally {
227+
telemetry.on.value = true
228+
}
229+
})
230+
231+
it('is left to SetupFlow when telemetry was already on', async () => {
232+
setupState.data = { can_send_email: true, needs_questions: true }
233+
await mountPage()
234+
await flushPromises()
235+
expect(captureMock).not.toHaveBeenCalledWith('setup_started')
236+
})
237+
})
203238
})

‎lms/hooks.py‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -261,6 +261,9 @@ def get_lms_path():
261261
override_whitelisted_methods = {
262262
# Finishes Google Calendar sign-in started from an evaluator's Slots tab.
263263
"frappe.integrations.doctype.google_calendar.google_calendar.google_callback": "lms.lms.api.google_calendar_callback",
264+
# The framework's setup password step saves through this, which also asks on Frappe Cloud v2
265+
# and sites with email login links; drop it once the framework's own check does.
266+
"frappe.core.doctype.user.user.set_first_password": "lms.lms.onboarding.set_first_password",
264267
}
265268
#
266269
# each overriding function accepts a `data` argument;

‎lms/lms/onboarding.py‎

Lines changed: 49 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
import frappe
22
from frappe import _
3+
from frappe.rate_limiter import rate_limit
4+
from frappe.utils import today
35

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

@@ -52,14 +54,55 @@ def get_setup_state() -> dict:
5254
}
5355

5456

55-
def needs_password_setup() -> bool:
56-
"""A Frappe Cloud site owner arrives signed in but with no password; on a framework that knows
57-
the case, the setup flow asks for one first."""
57+
def needs_password_setup(user: str | None = None) -> bool:
58+
"""A Frappe Cloud site owner arrives signed in but with no password, and the setup flow asks
59+
for one first. Frappe's own check skips Frappe Cloud v2 and sites with email login links,
60+
which is every trial site, so Learning asks wherever a password can be used to sign in."""
61+
from frappe.utils.password import has_password
62+
63+
user = user or frappe.session.user
64+
if user in ("Administrator", "Guest") or has_password(user):
65+
return False
66+
if frappe.get_system_settings("disable_user_pass_login"):
67+
return False
68+
if frappe.db.get_single_value("LDAP Settings", "enabled"):
69+
return False
70+
return not frappe.db.exists(
71+
"User Social Login",
72+
{"parenttype": "User", "parent": user, "provider": ["!=", "frappe"], "userid": ["is", "set"]},
73+
)
74+
75+
76+
@frappe.whitelist(methods=["POST"])
77+
@rate_limit(limit=5, seconds=60)
78+
def set_first_password(new_password: str) -> None:
79+
"""Frappe's set_first_password with Learning's check, so the framework's password step saves
80+
on the sites Frappe's own check skips. hooks.py points the framework's method here."""
81+
from frappe.core.doctype.user.user import handle_password_test_fail, test_password_strength
82+
from frappe.utils.password import update_password
83+
5884
try:
59-
from frappe.core.doctype.user.user import needs_password_setup as framework_says
85+
from frappe.utils.password import MAX_PASSWORD_SIZE
6086
except ImportError:
61-
return False
62-
return bool(framework_says())
87+
from frappe.auth import MAX_PASSWORD_SIZE
88+
89+
if frappe.request and frappe.get_request_header("Authorization"):
90+
frappe.throw(_("Set your first password from a signed-in browser."), frappe.PermissionError)
91+
if not new_password or not new_password.strip():
92+
frappe.throw(_("Enter a password."), title=_("Invalid Password"))
93+
if len(new_password) > MAX_PASSWORD_SIZE:
94+
frappe.throw(_("{0} size exceeded the maximum allowed size.").format(_("New Password")))
95+
if not needs_password_setup():
96+
frappe.throw(_("You already have a password. Change it from your settings."), frappe.PermissionError)
97+
user = frappe.get_doc("User", frappe.session.user)
98+
feedback = test_password_strength(
99+
new_password,
100+
user_data=(user.first_name, user.middle_name, user.last_name, user.email, user.birth_date),
101+
)
102+
if feedback and not feedback.get("feedback", {}).get("password_policy_validation_passed", False):
103+
handle_password_test_fail(feedback)
104+
update_password(user.name, new_password, logout_all_sessions=False)
105+
frappe.db.set_value("User", user.name, {"last_password_reset_date": today(), "reset_password_key": ""})
63106

64107

65108
def can_send_email() -> bool:

‎lms/tests/api/test_onboarding.py‎

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,9 @@
77
FIRST_GOAL,
88
get_first_course,
99
get_setup_state,
10+
needs_password_setup,
1011
save_setup,
12+
set_first_password,
1113
)
1214
from lms.lms.test_helpers import BaseTestUtils
1315

@@ -99,3 +101,67 @@ def test_only_a_known_goal_is_saved(self):
99101
frappe.set_user(manager.name)
100102
self.assertRaises(frappe.ValidationError, save_setup, "<script>alert(1)</script>")
101103
self.assertIsNone(frappe.db.get_default(FIRST_GOAL))
104+
105+
106+
class TestFirstPassword(BaseTestUtils):
107+
"""A Frappe Cloud trial owner arrives signed in without a password, on a v2 site with email
108+
login links on, which Frappe's own check skips; Learning's setup still asks for one."""
109+
110+
def setUp(self):
111+
super().setUp()
112+
self.owner = self._create_user(
113+
"cloud.owner@example.com", "Cloud", "Owner", roles=["System Manager"], user_type="System User"
114+
)
115+
frappe.db.delete("__Auth", {"doctype": "User", "name": self.owner.name})
116+
117+
def tearDown(self):
118+
frappe.set_user("Administrator")
119+
super().tearDown()
120+
121+
def system_settings(self, **values):
122+
"""System Settings read as these values, without saving them: saving needs a language and
123+
time zone, which a CI site that never ran the setup wizard does not have."""
124+
read = frappe.get_system_settings
125+
return patch(
126+
"frappe.get_system_settings",
127+
side_effect=lambda key: values[key] if key in values else read(key),
128+
)
129+
130+
def as_trial_site(self):
131+
return patch.dict(
132+
frappe.conf, {"pilot_endpoint": "https://pilot.example.com", "pilot_auth_token": "t"}
133+
)
134+
135+
def test_a_trial_owner_without_a_password_is_asked_for_one(self):
136+
with self.as_trial_site(), self.system_settings(login_with_email_link=1):
137+
self.assertTrue(needs_password_setup(self.owner.name))
138+
139+
def test_the_password_step_saves_on_a_trial_site(self):
140+
from frappe.utils.password import check_password
141+
142+
with self.as_trial_site(), self.system_settings(login_with_email_link=1):
143+
frappe.set_user(self.owner.name)
144+
set_first_password("Eastern_43A1W")
145+
frappe.set_user("Administrator")
146+
self.assertFalse(needs_password_setup(self.owner.name))
147+
self.assertEqual(check_password(self.owner.name, "Eastern_43A1W"), self.owner.name)
148+
149+
def test_the_framework_password_step_reaches_learnings_check(self):
150+
overrides = frappe.get_hooks("override_whitelisted_methods")
151+
self.assertEqual(
152+
overrides.get("frappe.core.doctype.user.user.set_first_password"),
153+
["lms.lms.onboarding.set_first_password"],
154+
)
155+
156+
def test_a_user_with_a_password_cannot_use_it(self):
157+
update_password(self.owner.name, "Eastern_43A1W")
158+
frappe.set_user(self.owner.name)
159+
self.assertRaises(frappe.PermissionError, set_first_password, "Another_43A1W")
160+
161+
def test_not_asked_where_a_password_cannot_sign_in(self):
162+
self.assertFalse(needs_password_setup("Administrator"))
163+
with self.system_settings(disable_user_pass_login=1):
164+
self.assertFalse(needs_password_setup(self.owner.name))
165+
self.owner.append("social_logins", {"provider": "google", "userid": "1234"})
166+
self.owner.save()
167+
self.assertFalse(needs_password_setup(self.owner.name))

0 commit comments

Comments
 (0)