4 Commits

Author SHA1 Message Date
Saghar Mohammadi 9f86acacb0 feat(batch-1): multi-role sidebar, video display, certificate layout, upload progress, counselor access
- roleMenuItems.js: merged menu builder that unions items from all user roles
  (student + missionary, student + counselor, etc.) additively
- auth store: expose `roles` array in addition to singular `role`; wire in
  WordPress auth-status cookie sync so the public site can show/hide the
  account button
- router guards: use roles.includes() instead of role === for multi-role access
- layouts (Student/Counselor/Missionary): delegate menuItems to
  buildMergedMenuItems so dual-role users see sections from both roles
- StudentSessionDetailsPage: contentKind now returns 'video' (not 'link')
  when session.videoUrl is set; adds embed iframe branch for online sessions
- CertificateItem.vue: fix CSS order/alignment for desktop + mobile layout
- StudentCertificatesPage.vue: map backend payload fields to component props
  with Jalaali date formatting
- SessionFormPage: upload progress bar (%) during video uploads; embed_code
  textarea for online sessions (frontend-only; dormant until batch-2 backend
  migration is deployed)
- wp-sync/auth-status-cookie.js: cookie helper for WordPress login-state sync

[batch-1-low-risk]
2026-09-02 11:17:20 +04:30
sajjadtalkhabi 81332abdb0 fix: bugs
Deploy banu-front / deploy (push) Successful in 1m47s
2026-08-18 09:08:45 +03:30
sajjadtalkhabi e4a0eb463b Merge branch 'master' of ssh://git.madresebanoo.ir:2222/front-end/banu-front
Deploy banu-front / deploy (push) Successful in 2m0s
2026-08-17 16:59:27 +03:30
sajjadtalkhabi 20551fee63 fix: bugs 2026-08-17 16:59:24 +03:30
18 changed files with 381 additions and 111 deletions
+9 -1
View File
@@ -7,7 +7,9 @@
</button>
</div>
<div class="header-block__logo">
<img :src="logo" alt="logo" />
<a :href="MAIN_SITE_URL">
<img :src="logo" alt="logo" />
</a>
</div>
<div class="header-block__title">
<slot>
@@ -52,6 +54,7 @@
import { computed, ref } from 'vue'
import { useRouter } from 'vue-router'
import { useUIStore } from '@/store/ui'
import { MAIN_SITE_URL } from '@/enums'
import { gallery } from '@/utils/gallery'
import useAuth from '@/composables/useAuth'
import SvgIcon from '@/components/icons/SvgIcon.vue'
@@ -149,7 +152,12 @@ const iconList = [
display: none;
}
a {
display: block;
}
img {
display: block;
margin: 0 auto;
height: 3.5rem;
object-fit: contain;
+4 -1
View File
@@ -220,8 +220,11 @@ export const MISSIONARY_REQUEST_STATUS = Object.freeze({
rejected: 'رد شده',
})
export const MAIN_SITE_URL = 'https://madresebanoo.ir/'
// Landing route per role after login / when a logged-in user hits a guest
// page. Roles not listed here fall back to the student dashboard.
// page. Roles not listed here fall back to the student dashboard. Approved
// users of every role except admin bypass this and land on MAIN_SITE_URL.
export const ROLE_HOME_ROUTES = Object.freeze({
admin: 'admin-dashboard',
counselor: 'counselor-dashboard',
@@ -77,6 +77,19 @@
/>
</div>
<!-- row 3b — embed code (online sessions only) -->
<div class="session-form__row" v-if="form.type === 'online'">
<TextareaField
v-model="form.embedCode"
name="embedCode"
label="کد امبد (Embed Code)"
placeholder="در صورت وجود، کد iframe/embed جلسه (مثلاً از آپارات یا سرویس ویدئوکنفرانس) را اینجا وارد کنید تا به‌جای لینک، به‌صورت مستقیم در صفحه نمایش داده شود."
:row="3"
:error="errors.embedCode"
@blur="validateAt('embedCode', form.embedCode)"
/>
</div>
<!-- row 4 — description -->
<div class="session-form__row">
<TextareaField
@@ -101,6 +114,17 @@
@remove="onContentRemove"
@error="onContentError"
/>
<div v-if="contentUploadMutation.isPending.value" class="session-form__upload-progress">
<div class="session-form__upload-progress-track">
<div
class="session-form__upload-progress-bar"
:style="{ width: contentUploadProgress + '%' }"
/>
</div>
<span class="session-form__upload-progress-text">
{{ contentUploadProgress }}% بارگذاری شده
</span>
</div>
</div>
</div>
@@ -200,6 +224,7 @@ const form = ref({
contentType: '',
type: '',
link: '',
embedCode: '',
description: '',
})
@@ -207,6 +232,7 @@ const image = ref(null)
const contentFiles = ref([])
const coverMediaId = ref(null)
const contentMediaId = ref(null)
const contentUploadProgress = ref(0)
const contentAccept = computed(() => COURSE_CONTENT_TYPE_ACCEPT[form.value.contentType] || '*')
const contentMaxSize = computed(
@@ -238,7 +264,10 @@ const onContentTypeChange = () => {
}
const onSessionTypeChange = () => {
if (form.value.type !== 'online') form.value.link = ''
if (form.value.type !== 'online') {
form.value.link = ''
form.value.embedCode = ''
}
}
const { data: existingSession } = useAdminSessionQuery(sessionId, {
@@ -267,6 +296,7 @@ watch(
contentType,
type: session.type ?? '',
link: session.link ?? '',
embedCode: session.embedCode ?? '',
description: session.description ?? '',
}
coverMediaId.value = coverMedia?.id ?? null
@@ -298,13 +328,20 @@ const purposeForContentType = (contentType) => {
const onContentSelect = async (files) => {
const file = files?.[0]
if (!file) return
contentUploadProgress.value = 0
try {
const formData = objectToFormData({
file,
purpose: purposeForContentType(form.value.contentType),
context: 'session',
})
const response = await contentUploadMutation.mutateAsync(formData)
const response = await contentUploadMutation.mutateAsync({
formData,
onUploadProgress: (event) => {
if (!event.total) return
contentUploadProgress.value = Math.round((event.loaded / event.total) * 100)
},
})
const payload = response?.data ?? response
const id = payload?.id ?? payload?.uploadId
contentFiles.value = [{ id, name: file.name, size: file.size, url: payload?.url }]
@@ -342,6 +379,7 @@ const buildPayload = (values) => {
courseId: values.courseId,
type: values.type,
link: values.type === 'online' ? values.link : undefined,
embedCode: values.type === 'online' ? values.embedCode : undefined,
description: values.description,
mediaIds,
}
@@ -477,6 +515,38 @@ const onCancel = () => router.push({ name: 'admin-sessions' })
color: var(--color-prim-gray);
}
&__upload-progress {
display: flex;
align-items: center;
gap: 0.75rem;
margin-top: -0.25rem;
margin-bottom: 0.75rem;
}
&__upload-progress-track {
flex: 1;
height: 0.5rem;
border-radius: 999px;
background: var(--color-thd-gray);
overflow: hidden;
}
&__upload-progress-bar {
height: 100%;
border-radius: 999px;
background: var(--color-primary);
transition: width 0.2s ease;
}
&__upload-progress-text {
flex-shrink: 0;
font-family: var(--font-family-en);
font-size: 0.75rem;
color: var(--color-sec-gray);
min-width: 3.5rem;
text-align: left;
}
&__preview {
place-items: center center;
}
@@ -9,5 +9,6 @@ export const sessionSchema = object().shape({
then: (schema) => schema.required(),
otherwise: (schema) => schema.nullable().notRequired(),
}),
embedCode: string().nullable().notRequired(),
description: string().nullable().notRequired(),
})
@@ -1,6 +1,8 @@
import { ROLE_HOME_ROUTES } from '@/enums'
import { useAuthStore } from '@/store/auth'
import { useRoute, useRouter } from 'vue-router'
import { MAIN_SITE_URL, ROLE_HOME_ROUTES } from '@/enums'
const shouldLandOnMainSite = (auth) => auth.role !== 'admin' && auth.user?.status === 'approved'
export const useRedirectAfterLogin = () => {
const router = useRouter()
@@ -13,6 +15,10 @@ export const useRedirectAfterLogin = () => {
router.push(redirect).catch(() => router.push('/'))
return
}
if (shouldLandOnMainSite(auth)) {
window.location.href = MAIN_SITE_URL
return
}
const target = { name: ROLE_HOME_ROUTES[auth.role] || 'student-dashboard' }
router.push(target).catch(() => router.push('/'))
}
@@ -120,7 +120,7 @@ const downloadItems = computed(() => [
@media (min-width: 1024px) {
flex: 1;
order: 3;
order: 1;
min-width: 12rem;
}
}
@@ -146,8 +146,8 @@ const downloadItems = computed(() => [
&__course-info {
display: flex;
flex-direction: column;
align-items: flex-start;
text-align: end;
align-items: flex-end;
text-align: right;
gap: 0.25rem;
min-width: 0;
}
@@ -186,6 +186,7 @@ const downloadItems = computed(() => [
background: rgba(107, 107, 107, 4%);
font-family: var(--font-family-fa);
white-space: nowrap;
align-self: center;
@media (min-width: 1024px) {
order: 2;
@@ -222,15 +223,20 @@ const downloadItems = computed(() => [
justify-content: center;
@media (min-width: 1024px) {
order: 1;
justify-content: flex-start;
order: 3;
justify-content: flex-end;
}
}
&__download-btn {
min-width: 9rem;
width: 100%;
height: 2rem;
padding: 0 1.25rem;
@media (min-width: 1024px) {
width: auto;
min-width: 9rem;
}
}
}
</style>
@@ -35,6 +35,7 @@ import { computed, ref } from 'vue'
import { toast } from 'vue3-toastify'
import SvgIcon from '@/components/icons/SvgIcon.vue'
import NoItems from '@/components/blocks/NoItems.vue'
import { formatJalaaliDate } from '@/utils/date-utils'
import { usePagination } from '@/composables/usePagination'
import PaginationBlock from '@/components/blocks/PaginationBlock.vue'
import BoxedIconTitleBlock from '@/components/blocks/BoxedIconTitleBlock.vue'
@@ -53,7 +54,17 @@ const { data, isLoading } = useStudentCertificatesQuery(filters, pagination, {
keepPreviousData: true,
})
const certificates = computed(() => data.value?.data ?? [])
// Bridge the backend payload (title/teacherName/startedAt/endedAt) into the
// display shape CertificateItem expects, without touching its template.
const certificates = computed(() =>
(data.value?.data ?? []).map((c) => ({
...c,
courseTitle: c.title ?? '',
teacherName: c.teacherName ?? '',
startDate: formatJalaaliDate(c.startedAt) || '',
endDate: formatJalaaliDate(c.endedAt) || '',
}))
)
const meta = computed(() => ({
page: pagination.value.page,
perPage: pagination.value.perPage,
@@ -37,12 +37,23 @@
<SvgIcon name="warning" :size="22" color="#b8b8b8" class="ssd__text-icon" />
<p class="ssd__text-body">{{ session.text }}</p>
</div>
<div v-else-if="contentKind === 'embed'" class="ssd__embed">
<iframe
class="ssd__embed-frame"
:srcdoc="session.embedCode"
sandbox="allow-scripts allow-popups allow-forms allow-presentation"
allow="autoplay; fullscreen; picture-in-picture"
allowfullscreen
loading="lazy"
referrerpolicy="no-referrer"
/>
</div>
<div v-else-if="contentKind === 'link'" class="ssd__link">
<div class="ssd__link__box">
<span>https://link</span>
<span>{{ session?.link || 'لینکی ثبت نشده است' }}</span>
<SvgIcon name="link" :size="22" class="ssd__link-icon" />
</div>
<BaseButton text="ورود به جلسه " custom-class="ssd__link-btn">
<BaseButton text="ورود به جلسه " custom-class="ssd__link-btn" @click="openSessionLink">
<template #appendIcon>
<SvgIcon name="arrow-left" :size="18" color="#fff" />
</template>
@@ -129,13 +140,17 @@ const homework = computed(() => (homeworksData.value?.data ?? [])[0] ?? null)
const contentKind = computed(() => {
const s = session.value
if (!s) return ''
if (s.type === 'online') return 'link'
if (s.videoUrl) return 'link'
if (s.type === 'online') return s.embedCode?.trim() ? 'embed' : 'link'
if (s.videoUrl) return 'video'
if (s.audioUrl) return 'audio'
if (s.text) return 'text'
return ''
})
const openSessionLink = () => {
if (session.value?.link) window.open(session.value.link, '_blank', 'noopener,noreferrer')
}
const homeworkAudio = ref(null)
const homeworkImage = ref(null)
const errors = reactive({ audio: '', image: '' })
@@ -260,6 +275,18 @@ const onSubmit = async () => {
}
}
&__embed {
width: 100%;
}
&__embed-frame {
width: 100%;
aspect-ratio: 16 / 9;
border: 0;
border-radius: 1rem;
background: #000;
}
&__link {
display: flex;
align-items: center;
+4 -14
View File
@@ -40,13 +40,16 @@
<script setup>
import { useUIStore } from '@/store/ui'
import { useAuthStore } from '@/store/auth'
import { RouterView, useRoute } from 'vue-router'
import Copyright from '@/components/Copyright.vue'
import HeaderBlock from '@/components/HeaderBlock.vue'
import { buildMergedMenuItems } from '@/layouts/roleMenuItems'
import { computed, onBeforeUnmount, onMounted, ref } from 'vue'
import CounselorSidebar from '@/layouts/sidebars/CounselorSidebar.vue'
const ui = useUIStore()
const auth = useAuthStore()
const route = useRoute()
const isMobile = ref(window.innerWidth < 1024)
@@ -59,20 +62,7 @@ onBeforeUnmount(() => window.removeEventListener('resize', onResize))
const pageTitle = computed(() => route.meta?.title || 'مشاوره')
const pageSubtitle = computed(() => route.meta?.subtitle || '')
const menuItems = computed(() => [
{
title: 'پیشخوان',
icon: 'menu',
to: { name: 'counselor-dashboard' },
active: route.name === 'counselor-dashboard',
},
{
title: 'مشاوره',
icon: 'chat',
to: { name: 'counselor-consultations' },
active: route.name === 'counselor-consultations',
},
])
const menuItems = computed(() => buildMergedMenuItems(auth.roles, route))
</script>
<style lang="scss" scoped>
+4 -26
View File
@@ -38,13 +38,16 @@
<script setup>
import { useUIStore } from '@/store/ui'
import { useAuthStore } from '@/store/auth'
import { RouterView, useRoute } from 'vue-router'
import Copyright from '@/components/Copyright.vue'
import HeaderBlock from '@/components/HeaderBlock.vue'
import { buildMergedMenuItems } from '@/layouts/roleMenuItems'
import { computed, onBeforeUnmount, onMounted, ref } from 'vue'
import StudentSidebar from '@/layouts/sidebars/StudentSidebar.vue'
const ui = useUIStore()
const auth = useAuthStore()
const route = useRoute()
const isMobile = ref(window.innerWidth < 1024)
@@ -57,32 +60,7 @@ onBeforeUnmount(() => window.removeEventListener('resize', onResize))
const pageTitle = computed(() => route.meta?.title || 'سیستم مدیریت اعزام')
const pageSubtitle = computed(() => route.meta?.subtitle || '')
const menuItems = computed(() => [
{
title: 'پیشخوان',
icon: 'menu',
to: { name: 'missionary-dashboard' },
active: route.name === 'missionary-dashboard',
},
{
title: 'سامانه اعزام',
icon: 'user-sound',
to: { name: 'missionary-requests' },
active: route.name === 'missionary-requests',
},
{
title: 'آموزش من',
icon: 'graduation-cap',
to: { name: 'missionary-education' },
active: route.name?.startsWith('missionary-education'),
},
{
title: 'تیکت',
icon: 'envelope-open',
to: { name: 'missionary-tickets' },
active: route.name === 'missionary-tickets',
},
])
const menuItems = computed(() => buildMergedMenuItems(auth.roles, route))
</script>
<style lang="scss" scoped>
+4 -46
View File
@@ -38,13 +38,16 @@
<script setup>
import { useUIStore } from '@/store/ui'
import { useAuthStore } from '@/store/auth'
import { RouterView, useRoute } from 'vue-router'
import Copyright from '@/components/Copyright.vue'
import HeaderBlock from '@/components/HeaderBlock.vue'
import { buildMergedMenuItems } from '@/layouts/roleMenuItems'
import { computed, onBeforeUnmount, onMounted, ref } from 'vue'
import StudentSidebar from '@/layouts/sidebars/StudentSidebar.vue'
const ui = useUIStore()
const auth = useAuthStore()
const route = useRoute()
const isMobile = ref(window.innerWidth < 1024)
@@ -57,52 +60,7 @@ onBeforeUnmount(() => window.removeEventListener('resize', onResize))
const pageTitle = computed(() => route.meta?.title || 'پیشخوان')
const pageSubtitle = computed(() => route.meta?.subtitle || '')
const menuItems = computed(() => [
{
title: 'داشبورد',
icon: 'monitor',
to: { name: 'student-dashboard' },
active: route.name === 'student-dashboard',
},
{
title: 'آموزش',
icon: 'graduation-cap',
to: { name: 'student-terms' },
active: [
'student-terms',
'student-term-details',
'student-lesson-details',
'student-session-details',
'student-exam',
'student-courses',
'student-course-details',
].includes(route.name),
},
{
title: 'خدمات',
icon: 'folder-simple-star',
to: { name: 'student-services' },
active: route.name === 'student-services',
},
{
title: 'گواهینامه',
icon: 'certificate',
to: { name: 'student-certificates' },
active: route.name === 'student-certificates',
},
{
title: 'ویرایش پروفایل',
icon: 'user-circle-check',
to: { name: 'student-profile' },
active: route.name === 'student-profile',
},
{
title: 'تیکت',
icon: 'envelope-open',
to: { name: 'student-tickets' },
active: route.name === 'student-tickets',
},
])
const menuItems = computed(() => buildMergedMenuItems(auth.roles, route))
</script>
<style lang="scss" scoped>
+124
View File
@@ -0,0 +1,124 @@
// Per-role sidebar sections, kept as plain builder functions so any layout
// can request the union of sections for every role a user holds — additive
// multi-role access without each layout hardcoding its own single-role list.
// Only roles with a registered builder participate in the merge; a role
// without one (e.g. admin) contributes nothing and keeps its own standalone
// menu untouched.
export const buildStudentMenuItems = (route) => [
{
title: 'داشبورد',
icon: 'monitor',
to: { name: 'student-dashboard' },
active: route.name === 'student-dashboard',
},
{
title: 'آموزش',
icon: 'graduation-cap',
to: { name: 'student-terms' },
active: [
'student-terms',
'student-term-details',
'student-lesson-details',
'student-session-details',
'student-exam',
'student-courses',
'student-course-details',
].includes(route.name),
},
{
title: 'خدمات',
icon: 'folder-simple-star',
to: { name: 'student-services' },
active: route.name === 'student-services',
},
{
title: 'مشاوره',
icon: 'chat-teardrop-text',
to: { name: 'student-consultants' },
active: route.name === 'student-consultants',
},
{
title: 'گواهینامه',
icon: 'certificate',
to: { name: 'student-certificates' },
active: route.name === 'student-certificates',
},
{
title: 'ویرایش پروفایل',
icon: 'user-circle-check',
to: { name: 'student-profile' },
active: route.name === 'student-profile',
},
{
title: 'تیکت',
icon: 'envelope-open',
to: { name: 'student-tickets' },
active: route.name === 'student-tickets',
},
]
export const buildMissionaryMenuItems = (route) => [
{
title: 'پیشخوان',
icon: 'menu',
to: { name: 'missionary-dashboard' },
active: route.name === 'missionary-dashboard',
},
{
title: 'سامانه اعزام',
icon: 'user-sound',
to: { name: 'missionary-requests' },
active: route.name === 'missionary-requests',
},
{
title: 'آموزش من',
icon: 'graduation-cap',
to: { name: 'missionary-education' },
active: route.name?.startsWith('missionary-education'),
},
{
title: 'تیکت',
icon: 'envelope-open',
to: { name: 'missionary-tickets' },
active: route.name === 'missionary-tickets',
},
]
export const buildCounselorMenuItems = (route) => [
{
title: 'پیشخوان',
icon: 'menu',
to: { name: 'counselor-dashboard' },
active: route.name === 'counselor-dashboard',
},
{
title: 'مشاوره',
icon: 'chat',
to: { name: 'counselor-consultations' },
active: route.name === 'counselor-consultations',
},
]
const MENU_BUILDERS = {
student: buildStudentMenuItems,
missionary: buildMissionaryMenuItems,
counselor: buildCounselorMenuItems,
}
/**
* Union of every panel section unlocked by `roles`, in role order (roles
* come back from the API ordered by role id, so a user's base role's
* sections lead and each additional role's sections are appended after).
*/
export const buildMergedMenuItems = (roles, route) => {
const seen = new Set()
const items = []
for (const roleName of roles ?? []) {
const builder = MENU_BUILDERS[roleName]
if (!builder || seen.has(roleName)) continue
seen.add(roleName)
items.push(...builder(route))
}
return items
}
+4 -1
View File
@@ -1,7 +1,9 @@
<template>
<aside class="admin-sidebar">
<div class="admin-sidebar__logo">
<img :src="logo" alt="مدرسه بانو" />
<a :href="MAIN_SITE_URL">
<img :src="logo" alt="مدرسه بانو" />
</a>
</div>
<nav class="admin-sidebar__nav">
<ul>
@@ -56,6 +58,7 @@
<script setup>
import { ref, watch } from 'vue'
import { RouterLink } from 'vue-router'
import { MAIN_SITE_URL } from '@/enums'
import { gallery } from '@/utils/gallery'
import SvgIcon from '@/components/icons/SvgIcon.vue'
import SidebarLogout from '@/layouts/sidebars/SidebarLogout.vue'
+4 -1
View File
@@ -1,7 +1,9 @@
<template>
<aside class="counselor-sidebar">
<div class="counselor-sidebar__logo">
<img :src="logo" alt="مدرسه بانو" />
<a :href="MAIN_SITE_URL">
<img :src="logo" alt="مدرسه بانو" />
</a>
</div>
<nav class="counselor-sidebar__nav">
<ul>
@@ -23,6 +25,7 @@
</template>
<script setup>
import { MAIN_SITE_URL } from '@/enums'
import { gallery } from '@/utils/gallery'
import SvgIcon from '@/components/icons/SvgIcon.vue'
import SidebarLogout from '@/layouts/sidebars/SidebarLogout.vue'
+4 -1
View File
@@ -1,7 +1,9 @@
<template>
<aside class="student-sidebar" :style="{ backgroundImage: `url(${bgPattern})` }">
<div class="student-sidebar__logo">
<img :src="logo" alt="مدرسه بانو" />
<a :href="MAIN_SITE_URL">
<img :src="logo" alt="مدرسه بانو" />
</a>
</div>
<nav class="student-sidebar__nav">
<ul>
@@ -23,6 +25,7 @@
</template>
<script setup>
import { MAIN_SITE_URL } from '@/enums'
import { gallery } from '@/utils/gallery'
import SvgIcon from '@/components/icons/SvgIcon.vue'
import SidebarLogout from '@/layouts/sidebars/SidebarLogout.vue'
+2 -2
View File
@@ -33,7 +33,7 @@ export const statusGuard = (to) => {
if (!tokenService.hasToken()) return
const auth = useAuthStore()
if (!auth.user) return
if (auth.role && auth.role !== 'student') return
if (!auth.roles.includes('student')) return
if (auth.user.status === 'approved') return
return { name: 'student-register' }
}
@@ -41,7 +41,7 @@ export const statusGuard = (to) => {
export const roleGuard = (to) => {
if (!to.meta?.role) return
const auth = useAuthStore()
if (auth.role !== to.meta.role) {
if (!auth.roles.includes(to.meta.role)) {
return { name: 'home' }
}
return
@@ -0,0 +1,61 @@
import { ROLE_HOME_ROUTES } from '@/enums'
// Read by the WordPress site (madresebanoo.ir) to show/hide its "account"
// button and link it to the right dashboard, without ever seeing a real
// auth token. Must stay in sync with whatever the WP/Elementor side expects
// — see the implementation report for the exact contract.
const COOKIE_NAME = 'mb_auth_status'
const ROOT_DOMAIN = 'madresebanoo.ir'
const isOnRootDomain = () => {
const host = window.location.hostname
return host === ROOT_DOMAIN || host.endsWith(`.${ROOT_DOMAIN}`)
}
const cookieAttributes = () => {
const attrs = ['Path=/', 'SameSite=Lax']
// A Domain=.madresebanoo.ir cookie is only accepted by the browser when the
// current page is actually on that domain (prod). On local dev
// (127.0.0.1/localhost) we fall back to a host-only cookie so the sync
// logic is still exercised, instead of silently failing to set anything.
if (isOnRootDomain()) attrs.push(`Domain=.${ROOT_DOMAIN}`)
// Secure cookies are dropped by the browser on plain http, which local dev
// serves over. Only require it where it can actually work (prod, https).
if (window.location.protocol === 'https:') attrs.push('Secure')
return attrs
}
const writeCookie = (value, { expire = false } = {}) => {
const attrs = cookieAttributes()
attrs.push(expire ? 'Max-Age=0' : '') // no Max-Age on set = session cookie
// This cookie must be readable by a separate WordPress site with plain JS
// (no httpOnly), and needs Domain/SameSite attributes the CookieStore API
// doesn't uniformly support yet — document.cookie is the correct tool here.
// eslint-disable-next-line unicorn/no-document-cookie
document.cookie = [`${COOKIE_NAME}=${value}`, ...attrs].filter(Boolean).join('; ')
}
const dashboardPathFor = async (role) => {
try {
const { default: router } = await import('@/router')
const routeName = ROLE_HOME_ROUTES[role] || 'student-dashboard'
return router.resolve({ name: routeName }).path
} catch {
return '/dashboard'
}
}
/**
* Sets mb_auth_status to a non-sensitive JSON blob describing display state
* only: `{ loggedIn: true, dashboardPath }`. Never put the access token,
* password, or any credential in this cookie.
*/
export const syncAuthStatusCookie = async (role) => {
const dashboardPath = await dashboardPathFor(role)
const value = encodeURIComponent(JSON.stringify({ loggedIn: true, dashboardPath }))
writeCookie(value)
}
export const clearAuthStatusCookie = () => {
writeCookie('', { expire: true })
}
+22 -4
View File
@@ -2,31 +2,49 @@ import { computed, ref } from 'vue'
import { defineStore } from 'pinia'
import { tokenService } from '@/services/api/token-service'
import { syncAuthStatusCookie, clearAuthStatusCookie } from '@/services/wp-sync/auth-status-cookie'
export const useAuthStore = defineStore('auth', () => {
const user = ref(tokenService.getUserInfo())
const isAuthenticated = computed(() => !!tokenService.getToken() && !!user.value)
const role = computed(() => {
// Full set of roles this user holds — access should be additive across all
// of them, never just their first/"primary" one.
const roles = computed(() => {
const u = user.value
if (!u) return null
if (Array.isArray(u.roles) && u.roles.length > 0) return u.roles[0]
return u.role || u.roleName || null
if (!u) return []
if (Array.isArray(u.roles) && u.roles.length > 0) return u.roles
if (u.role) return [u.role]
if (u.roleName) return [u.roleName]
return []
})
// Primary role, used only where a single default is needed (e.g. the
// landing route right after login) — never for access control.
const role = computed(() => roles.value[0] || null)
const setUser = (userData) => {
user.value = userData
tokenService.saveUserInfo(userData)
// Only a real, token-backed session should tell WordPress "logged in" —
// setUser is also used to stash a phone number mid-signup, before any
// token exists, so gate the display-state cookie on the actual token.
if (tokenService.hasToken()) {
syncAuthStatusCookie(role.value)
} else {
clearAuthStatusCookie()
}
}
const clearUser = () => {
user.value = null
tokenService.clearAll()
clearAuthStatusCookie()
}
return {
user,
role,
roles,
isAuthenticated,
setUser,
clearUser,