Compare commits

...

1 Commits

Author SHA1 Message Date
Flatlogic Bot
2a57c09200 Autosave: 20260217-140709 2026-02-17 14:07:09 +00:00
4 changed files with 329 additions and 202 deletions

View File

@ -0,0 +1,71 @@
module.exports = {
async up(queryInterface, Sequelize) {
const [publicRole] = await queryInterface.sequelize.query(
"SELECT id FROM roles WHERE name = 'Public' LIMIT 1;",
{ type: Sequelize.QueryTypes.SELECT }
);
const [readCoursesPermission] = await queryInterface.sequelize.query(
"SELECT id FROM permissions WHERE name = 'READ_COURSES' LIMIT 1;",
{ type: Sequelize.QueryTypes.SELECT }
);
const [readCourseCategoriesPermission] = await queryInterface.sequelize.query(
"SELECT id FROM permissions WHERE name = 'READ_COURSE_CATEGORIES' LIMIT 1;",
{ type: Sequelize.QueryTypes.SELECT }
);
if (publicRole) {
const permissionIds = [
readCoursesPermission?.id,
readCourseCategoriesPermission?.id,
].filter(Boolean);
for (const permissionId of permissionIds) {
const [existing] = await queryInterface.sequelize.query(
`SELECT * FROM "rolesPermissionsPermissions" WHERE "roles_permissionsId" = '${publicRole.id}' AND "permissionId" = '${permissionId}' LIMIT 1;`,
{ type: Sequelize.QueryTypes.SELECT }
);
if (!existing) {
await queryInterface.bulkInsert('rolesPermissionsPermissions', [
{
createdAt: new Date(),
updatedAt: new Date(),
roles_permissionsId: publicRole.id,
permissionId,
},
]);
}
}
}
},
async down(queryInterface, Sequelize) {
const [publicRole] = await queryInterface.sequelize.query(
"SELECT id FROM roles WHERE name = 'Public' LIMIT 1;",
{ type: Sequelize.QueryTypes.SELECT }
);
const [readCoursesPermission] = await queryInterface.sequelize.query(
"SELECT id FROM permissions WHERE name = 'READ_COURSES' LIMIT 1;",
{ type: Sequelize.QueryTypes.SELECT }
);
const [readCourseCategoriesPermission] = await queryInterface.sequelize.query(
"SELECT id FROM permissions WHERE name = 'READ_COURSE_CATEGORIES' LIMIT 1;",
{ type: Sequelize.QueryTypes.SELECT }
);
if (publicRole) {
const permissionIds = [
readCoursesPermission?.id,
readCourseCategoriesPermission?.id,
].filter(Boolean);
if (permissionIds.length > 0) {
await queryInterface.bulkDelete('rolesPermissionsPermissions', {
roles_permissionsId: publicRole.id,
permissionId: permissionIds,
});
}
}
}
};

View File

@ -123,9 +123,15 @@ app.use('/api/roles', passport.authenticate('jwt', {session: false}), rolesRoute
app.use('/api/permissions', passport.authenticate('jwt', {session: false}), permissionsRoutes);
app.use('/api/courses', passport.authenticate('jwt', {session: false}), coursesRoutes);
app.use('/api/courses', (req, res, next) => {
if (req.method === 'GET') return next();
return passport.authenticate('jwt', { session: false })(req, res, next);
}, coursesRoutes);
app.use('/api/course_categories', passport.authenticate('jwt', {session: false}), course_categoriesRoutes);
app.use('/api/course_categories', (req, res, next) => {
if (req.method === 'GET') return next();
return passport.authenticate('jwt', { session: false })(req, res, next);
}, course_categoriesRoutes);
app.use('/api/lessons', passport.authenticate('jwt', {session: false}), lessonsRoutes);

View File

@ -1,37 +1,5 @@
const ValidationError = require('../services/notifications/errors/validation');
const RolesDBApi = require('../db/api/roles');
// Cache for the 'Public' role object
let publicRoleCache = null;
// Function to asynchronously fetch and cache the 'Public' role
async function fetchAndCachePublicRole() {
try {
// Use RolesDBApi to find the role by name 'Public'
publicRoleCache = await RolesDBApi.findBy({ name: 'Public' });
if (!publicRoleCache) {
console.error("WARNING: Role 'Public' not found in database during middleware startup. Check your migrations.");
// The system might not function correctly without this role. May need to throw an error or use a fallback stub.
} else {
console.log("'Public' role successfully loaded and cached.");
}
} catch (error) {
console.error("Error fetching 'Public' role during middleware startup:", error);
// Handle the error during startup fetch
throw error; // Important to know if the app can proceed without the Public role
}
}
// Trigger the role fetching when the check-permissions.js module is imported/loaded
// This should happen during application startup when routes are being configured.
fetchAndCachePublicRole().catch(error => {
// Handle the case where the fetchAndCachePublicRole promise is rejected
console.error("Critical error during permissions middleware initialization:", error);
// Decide here if the process should exit if the Public role is essential.
// process.exit(1);
});
/**
* Middleware creator to check if the current user (or Public role) has a specific permission.
@ -61,34 +29,13 @@ function checkPermissions(permission) {
}
}
// 3. Determine the "effective" role for permission check
let effectiveRole = null;
try {
if (currentUser && currentUser.app_role) {
// User is authenticated and has an assigned role
effectiveRole = currentUser.app_role;
} else {
// User is NOT authenticated OR is authenticated but has no role
// Use the cached 'Public' role
if (!publicRoleCache) {
// If the cache is unexpectedly empty (e.g., startup error caught),
// we can try fetching the role again synchronously (less ideal) or just deny access.
console.error("Public role cache is empty. Attempting synchronous fetch...");
// Less efficient fallback option:
effectiveRole = await RolesDBApi.findBy({ name: 'Public' }); // Could be slow
if (!effectiveRole) {
// If even the synchronous attempt failed
return next(new Error("Internal Server Error: Public role missing and cannot be fetched."));
}
} else {
effectiveRole = publicRoleCache; // Use the cached object
}
}
// 3. Determine the authenticated role for permission check
const effectiveRole = currentUser && currentUser.app_role ? currentUser.app_role : null;
if (!effectiveRole) {
return next(new ValidationError('auth.forbidden', 'Role missing for permission check.'));
}
// Check if we got a valid role object
if (!effectiveRole) {
return next(new Error("Internal Server Error: Could not determine effective role."));
}
try {
// 4. Check Permissions on the "effective" role
// Assume the effectiveRole object (from app_role or RolesDBApi) has a getPermissions() method
@ -146,4 +93,3 @@ module.exports = {
checkPermissions,
checkCrudPermissions,
};

View File

@ -3,164 +3,268 @@ import React, { useEffect, useState } from 'react';
import type { ReactElement } from 'react';
import Head from 'next/head';
import Link from 'next/link';
import axios from 'axios';
import { mdiBookOpenVariant, mdiAccountGroup, mdiStar, mdiChevronRight } from '@mdi/js';
import BaseButton from '../components/BaseButton';
import CardBox from '../components/CardBox';
import SectionFullScreen from '../components/SectionFullScreen';
import BaseIcon from '../components/BaseIcon';
import LayoutGuest from '../layouts/Guest';
import BaseDivider from '../components/BaseDivider';
import BaseButtons from '../components/BaseButtons';
import { getPageTitle } from '../config';
import { useAppSelector } from '../stores/hooks';
import CardBoxComponentTitle from "../components/CardBoxComponentTitle";
import { getPexelsImage, getPexelsVideo } from '../helpers/pexels';
import { getMultiplePexelsImages } from '../helpers/pexels';
export default function LandingPage() {
const [courses, setCourses] = useState([]);
const [loading, setLoading] = useState(true);
const [images, setImages] = useState([]);
const textColor = useAppSelector((state) => state.style.linkColor);
const { currentUser } = useAppSelector((state) => state.auth);
export default function Starter() {
const [illustrationImage, setIllustrationImage] = useState({
src: undefined,
photographer: undefined,
photographer_url: undefined,
})
const [illustrationVideo, setIllustrationVideo] = useState({video_files: []})
const [contentType, setContentType] = useState('image');
const [contentPosition, setContentPosition] = useState('left');
const textColor = useAppSelector((state) => state.style.linkColor);
const title = 'Course LMS'
// Fetch Pexels image/video
useEffect(() => {
async function fetchData() {
const image = await getPexelsImage();
const video = await getPexelsVideo();
setIllustrationImage(image);
setIllustrationVideo(video);
}
fetchData();
}, []);
const imageBlock = (image) => (
<div
className='hidden md:flex flex-col justify-end relative flex-grow-0 flex-shrink-0 w-1/3'
style={{
backgroundImage: `${
image
? `url(${image?.src?.original})`
: 'linear-gradient(rgba(255, 255, 255, 0.5), rgba(255, 255, 255, 0.5))'
}`,
backgroundSize: 'cover',
backgroundPosition: 'left center',
backgroundRepeat: 'no-repeat',
}}
>
<div className='flex justify-center w-full bg-blue-300/20'>
<a
className='text-[8px]'
href={image?.photographer_url}
target='_blank'
rel='noreferrer'
>
Photo by {image?.photographer} on Pexels
</a>
</div>
</div>
);
const videoBlock = (video) => {
if (video?.video_files?.length > 0) {
return (
<div className='hidden md:flex flex-col justify-end relative flex-grow-0 flex-shrink-0 w-1/3'>
<video
className='absolute top-0 left-0 w-full h-full object-cover'
autoPlay
loop
muted
>
<source src={video?.video_files[0]?.link} type='video/mp4'/>
Your browser does not support the video tag.
</video>
<div className='flex justify-center w-full bg-blue-300/20 z-10'>
<a
className='text-[8px]'
href={video?.user?.url}
target='_blank'
rel='noreferrer'
>
Video by {video.user.name} on Pexels
</a>
</div>
</div>)
}
};
useEffect(() => {
async function fetchData() {
try {
const [coursesRes, imagesRes] = await Promise.all([
axios.get('/courses?limit=6'),
getMultiplePexelsImages(['education', 'coding', 'business', 'art', 'science', 'math'])
]);
setCourses(coursesRes.data.rows || []);
setImages(imagesRes);
} catch (error) {
console.error('Error fetching landing data:', error);
} finally {
setLoading(false);
}
}
fetchData();
}, []);
return (
<div
style={
contentPosition === 'background'
? {
backgroundImage: `${
illustrationImage
? `url(${illustrationImage.src?.original})`
: 'linear-gradient(rgba(255, 255, 255, 0.5), rgba(255, 255, 255, 0.5))'
}`,
backgroundSize: 'cover',
backgroundPosition: 'left center',
backgroundRepeat: 'no-repeat',
}
: {}
}
>
<div className="min-h-screen bg-white">
<Head>
<title>{getPageTitle('Starter Page')}</title>
<title>{getPageTitle('Learn Online')}</title>
</Head>
<SectionFullScreen bg='violet'>
<div
className={`flex ${
contentPosition === 'right' ? 'flex-row-reverse' : 'flex-row'
} min-h-screen w-full`}
>
{contentType === 'image' && contentPosition !== 'background'
? imageBlock(illustrationImage)
: null}
{contentType === 'video' && contentPosition !== 'background'
? videoBlock(illustrationVideo)
: null}
<div className='flex items-center justify-center flex-col space-y-4 w-full lg:w-full'>
<CardBox className='w-full md:w-3/5 lg:w-2/3'>
<CardBoxComponentTitle title="Welcome to your Course LMS app!"/>
<div className="space-y-3">
<p className='text-center text-gray-500'>This is a React.js/Node.js app generated by the <a className={`${textColor}`} href="https://flatlogic.com/generator">Flatlogic Web App Generator</a></p>
<p className='text-center text-gray-500'>For guides and documentation please check
your local README.md and the <a className={`${textColor}`} href="https://flatlogic.com/documentation">Flatlogic documentation</a></p>
</div>
<BaseButtons>
{/* Hero Section */}
<section className="relative py-20 overflow-hidden bg-slate-900 text-white">
<div className="container mx-auto px-6 relative z-10">
<div className="flex flex-wrap items-center">
<div className="w-full lg:w-1/2 mb-12 lg:mb-0">
<span className="inline-block py-1 px-3 mb-4 text-xs font-semibold tracking-widest text-indigo-400 uppercase bg-indigo-900/30 rounded-full">
New Learning Era
</span>
<h1 className="mb-6 text-5xl lg:text-6xl font-bold leading-tight">
Learn Without <span className="text-indigo-400">Limits</span>
</h1>
<p className="mb-8 text-xl text-slate-400 max-w-lg">
Master new skills with our professional courses led by industry experts. Join thousands of students already learning today.
</p>
<div className="flex flex-wrap gap-4">
<BaseButton
href='/login'
label='Login'
color='info'
className='w-full'
href={currentUser ? '/dashboard' : '/register'}
label="Start Learning Now"
color="info"
className="px-8 py-4 rounded-xl text-lg font-bold shadow-lg shadow-indigo-500/30"
/>
</BaseButtons>
</CardBox>
<BaseButton
href="#featured-courses"
label="Browse Courses"
outline
className="px-8 py-4 rounded-xl text-lg font-bold border-slate-700 text-white hover:bg-slate-800"
/>
</div>
</div>
<div className="w-full lg:w-1/2">
<div className="relative">
<div className="absolute top-0 right-0 -mr-20 -mt-20 w-64 h-64 bg-indigo-500 rounded-full blur-3xl opacity-20"></div>
<div className="absolute bottom-0 left-0 -ml-20 -mb-20 w-64 h-64 bg-purple-500 rounded-full blur-3xl opacity-20"></div>
<img
src={images[0]?.src?.large || "https://images.pexels.com/photos/3184291/pexels-photo-3184291.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=2"}
alt="Learning"
className="relative z-10 w-full rounded-2xl shadow-2xl transform rotate-1 hover:rotate-0 transition-transform duration-500"
/>
</div>
</div>
</div>
</div>
</div>
</SectionFullScreen>
<div className='bg-black text-white flex flex-col text-center justify-center md:flex-row'>
<p className='py-6 text-sm'>© 2026 <span>{title}</span>. All rights reserved</p>
<Link className='py-6 ml-4 text-sm' href='/privacy-policy/'>
Privacy Policy
</Link>
</div>
</section>
{/* Stats Section */}
<section className="py-12 bg-indigo-600">
<div className="container mx-auto px-6">
<div className="flex flex-wrap -mx-4 text-center">
<div className="w-full sm:w-1/3 px-4 mb-8 sm:mb-0">
<h3 className="text-3xl font-bold text-white">100+</h3>
<p className="text-indigo-100 uppercase tracking-widest text-sm">Courses</p>
</div>
<div className="w-full sm:w-1/3 px-4 mb-8 sm:mb-0">
<h3 className="text-3xl font-bold text-white">5k+</h3>
<p className="text-indigo-100 uppercase tracking-widest text-sm">Students</p>
</div>
<div className="w-full sm:w-1/3 px-4">
<h3 className="text-3xl font-bold text-white">4.9/5</h3>
<p className="text-indigo-100 uppercase tracking-widest text-sm">Rating</p>
</div>
</div>
</div>
</section>
{/* Featured Courses */}
<section id="featured-courses" className="py-24 bg-slate-50">
<div className="container mx-auto px-6">
<div className="flex items-end justify-between mb-12">
<div>
<h2 className="text-4xl font-bold text-slate-900 mb-4">Featured Courses</h2>
<p className="text-slate-500 max-w-md">Discover our most popular courses and start your journey today.</p>
</div>
<Link href="/courses/courses-list" className="hidden md:flex items-center text-indigo-600 font-bold hover:text-indigo-700">
View All Courses <BaseIcon path={mdiChevronRight} size={20} />
</Link>
</div>
{loading ? (
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-8">
{[1, 2, 3].map((n) => (
<div key={n} className="h-96 bg-slate-200 animate-pulse rounded-2xl"></div>
))}
</div>
) : (
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-8">
{courses.length > 0 ? courses.map((course, idx) => (
<div key={course.id} className="group bg-white rounded-2xl shadow-sm hover:shadow-xl transition-all duration-300 border border-slate-100 overflow-hidden">
<div className="relative h-48 overflow-hidden">
<img
src={images[idx + 1]?.src?.medium || "https://images.pexels.com/photos/5905709/pexels-photo-5905709.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=2"}
alt={course.title}
className="w-full h-full object-cover group-hover:scale-110 transition-transform duration-500"
/>
{course.is_free && (
<span className="absolute top-4 right-4 bg-green-500 text-white text-xs font-bold px-3 py-1 rounded-full uppercase tracking-tighter">
Free
</span>
)}
</div>
<div className="p-6">
<div className="flex items-center gap-2 mb-3">
<span className="text-indigo-600 bg-indigo-50 text-[10px] font-bold px-2 py-0.5 rounded uppercase leading-none">
{course.level || 'All Levels'}
</span>
</div>
<h3 className="text-xl font-bold text-slate-900 mb-2 line-clamp-1">{course.title}</h3>
<p className="text-slate-500 text-sm mb-6 line-clamp-2">{course.description || course.subtitle}</p>
<div className="flex items-center justify-between border-t border-slate-100 pt-4">
<div className="flex items-center gap-2">
<div className="flex items-center text-amber-500">
<BaseIcon path={mdiStar} size={14} />
<span className="text-slate-900 font-bold text-sm ml-1">4.8</span>
</div>
<span className="text-slate-400 text-xs">(124)</span>
</div>
<div className="text-indigo-600 font-black text-xl">
{course.is_free ? 'Free' : `$${course.price || '49.99'}`}
</div>
</div>
<div className="mt-6">
<BaseButton
href={`/courses/courses-view/?id=${course.id}`}
label="View Details"
className="w-full rounded-xl font-bold"
color="info"
outline
/>
</div>
</div>
</div>
)) : (
<div className="col-span-full py-20 text-center">
<BaseIcon path={mdiBookOpenVariant} size={64} className="mx-auto text-slate-300 mb-4" />
<h3 className="text-xl font-bold text-slate-900 mb-2">No courses found</h3>
<p className="text-slate-500 mb-6">We&apos;re working on adding new content. Check back soon!</p>
{currentUser && currentUser.app_role?.name === 'Instructor' && (
<BaseButton href="/courses/courses-new" label="Add First Course" color="info" />
)}
</div>
)}
</div>
)}
</div>
</section>
{/* Why Choose Us */}
<section className="py-24 bg-white">
<div className="container mx-auto px-6">
<div className="text-center mb-16">
<h2 className="text-4xl font-bold text-slate-900 mb-4">Why Choose Our Platform?</h2>
<div className="w-20 h-1 bg-indigo-600 mx-auto"></div>
</div>
<div className="grid grid-cols-1 md:grid-cols-3 gap-12">
<div className="text-center p-8 rounded-2xl hover:bg-slate-50 transition-colors">
<div className="w-16 h-16 bg-indigo-100 rounded-2xl flex items-center justify-center mx-auto mb-6">
<BaseIcon path={mdiBookOpenVariant} size={32} className="text-indigo-600" />
</div>
<h3 className="text-xl font-bold mb-4">Expert Instruction</h3>
<p className="text-slate-500">Learn from professionals who are active in their fields and passionate about teaching.</p>
</div>
<div className="text-center p-8 rounded-2xl hover:bg-slate-50 transition-colors">
<div className="w-16 h-16 bg-indigo-100 rounded-2xl flex items-center justify-center mx-auto mb-6">
<BaseIcon path={mdiAccountGroup} size={32} className="text-indigo-600" />
</div>
<h3 className="text-xl font-bold mb-4">Flexible Learning</h3>
<p className="text-slate-500">Access your courses anytime, anywhere. Learn at your own pace on any device.</p>
</div>
<div className="text-center p-8 rounded-2xl hover:bg-slate-50 transition-colors">
<div className="w-16 h-16 bg-indigo-100 rounded-2xl flex items-center justify-center mx-auto mb-6">
<BaseIcon path={mdiStar} size={32} className="text-indigo-600" />
</div>
<h3 className="text-xl font-bold mb-4">Lifetime Access</h3>
<p className="text-slate-500">Once you enroll, the content is yours forever. Stay updated with free course updates.</p>
</div>
</div>
</div>
</section>
{/* CTA Section */}
<section className="py-20 bg-indigo-900">
<div className="container mx-auto px-6 text-center">
<h2 className="text-4xl font-bold text-white mb-8">Ready to Start Your Learning Journey?</h2>
<p className="text-indigo-200 mb-10 max-w-2xl mx-auto">Join thousands of students and transform your career today with our expert-led courses.</p>
<div className="flex flex-wrap justify-center gap-4">
<BaseButton
href={currentUser ? '/dashboard' : '/register'}
label="Join for Free"
color="info"
className="px-10 py-4 rounded-xl text-lg font-bold"
/>
<BaseButton
href="/login"
label="Student Login"
outline
className="px-10 py-4 rounded-xl text-lg font-bold border-indigo-400 text-white hover:bg-indigo-800"
/>
</div>
</div>
</section>
{/* Footer */}
<footer className="py-12 bg-slate-900 text-slate-500 border-t border-slate-800">
<div className="container mx-auto px-6">
<div className="flex flex-wrap justify-between items-center">
<div className="w-full md:w-auto mb-6 md:mb-0">
<span className="text-2xl font-black text-white italic tracking-tighter">COURSE<span className="text-indigo-500 underline">LMS</span></span>
</div>
<div className="flex gap-8 text-sm font-medium">
<Link href="/courses/courses-list" className="hover:text-white transition-colors">Courses</Link>
<Link href="/terms-of-use" className="hover:text-white transition-colors">Terms</Link>
<Link href="/privacy-policy" className="hover:text-white transition-colors">Privacy</Link>
</div>
</div>
<div className="mt-12 pt-8 border-t border-slate-800 text-center text-xs tracking-widest uppercase">
&copy; 2026 Course LMS. Built with Flatlogic.
</div>
</div>
</footer>
</div>
);
}
Starter.getLayout = function getLayout(page: ReactElement) {
LandingPage.getLayout = function getLayout(page: ReactElement) {
return <LayoutGuest>{page}</LayoutGuest>;
};