mirror of
https://github.com/sergeyyarkov/educt-server.git
synced 2026-10-12 02:39:09 +03:00
Compare commits
No commits in common. "develop" and "v1.1.0" have entirely different histories.
@ -24,7 +24,12 @@
|
||||
"Database": "database",
|
||||
"Contracts": "contracts"
|
||||
},
|
||||
"preloads": ["./start/routes", "./start/kernel", "./start/event", "./start/bouncer"],
|
||||
"preloads": [
|
||||
"./routes/index",
|
||||
"./start/kernel",
|
||||
"./start/event",
|
||||
"./start/bouncer"
|
||||
],
|
||||
"providers": [
|
||||
"./providers/AppProvider",
|
||||
"@adonisjs/core",
|
||||
@ -37,7 +42,9 @@
|
||||
"@adonisjs/bouncer",
|
||||
"@adonisjs/drive-s3"
|
||||
],
|
||||
"aceProviders": ["@adonisjs/repl"],
|
||||
"aceProviders": [
|
||||
"@adonisjs/repl"
|
||||
],
|
||||
"metaFiles": [
|
||||
{
|
||||
"pattern": "resources/views/**/*.edge",
|
||||
|
||||
@ -1,20 +1,6 @@
|
||||
# Adonis default .gitignore ignores
|
||||
node_modules
|
||||
build
|
||||
coverage
|
||||
.vscode
|
||||
.DS_STORE
|
||||
.env
|
||||
tmp
|
||||
uploads
|
||||
|
||||
# Additional .gitignore ignores (any custom file you wish)
|
||||
.idea
|
||||
|
||||
# Additional good to have ignores for dockerignore
|
||||
Dockerfile*
|
||||
docker-compose*
|
||||
.dockerignore
|
||||
*.md
|
||||
node_modules
|
||||
.git
|
||||
.gitignore
|
||||
*.log
|
||||
.env
|
||||
Dockerfile
|
||||
@ -19,8 +19,8 @@ SMTP_PASSWORD=<password>
|
||||
MAILGUN_API_KEY=<mailgun-api-key>
|
||||
MAILGUN_DOMAIN=<your-domain>
|
||||
CACHE_VIEWS=false
|
||||
DRIVE_DISK=local
|
||||
S3_KEY=dummyKey
|
||||
S3_SECRET=dummySecret
|
||||
S3_BUCKET=dummyBucket
|
||||
S3_REGION=dummyRegion
|
||||
S3_REGION=dummyRegion
|
||||
S3_ENDPOINT=dummyEndpoint
|
||||
|
||||
@ -15,7 +15,7 @@
|
||||
"project": "./tsconfig.json",
|
||||
"include": ["src/**/*.ts", "src/**/*.js", "test/**/*.ts"]
|
||||
},
|
||||
"plugins": ["@typescript-eslint", "import"],
|
||||
"plugins": ["@typescript-eslint"],
|
||||
"rules": {
|
||||
"no-unused-vars": "off",
|
||||
"@typescript-eslint/no-unused-vars": ["error"]
|
||||
|
||||
1
.gitignore
vendored
1
.gitignore
vendored
@ -6,4 +6,3 @@ coverage
|
||||
.env
|
||||
tmp
|
||||
uploads
|
||||
npm-debug.log
|
||||
49
CHANGELOG.md
49
CHANGELOG.md
@ -1,53 +1,8 @@
|
||||
# Changelog
|
||||
|
||||
## [1.4.2] - 2022-12-06
|
||||
## Unreleased
|
||||
|
||||
## Added
|
||||
|
||||
- Uploading video from url source (YouTube, Vimeo, .mp4, etc..)
|
||||
- Added student and teacher to seeders
|
||||
|
||||
## Fix
|
||||
|
||||
- Removing lesson files from drive when deleting course, category or user.
|
||||
- Fixed lesson display ordering when seeding database
|
||||
- Refactored bouncer actions
|
||||
|
||||
## [1.3.2] - 2022-06-06
|
||||
|
||||
## Added
|
||||
|
||||
- Updated npm dependencies
|
||||
- [Added](https://github.com/sergeyyarkov/educt-server/commit/294a4f584dd39d295372802305004365fb01fdb2) `MAILER` env variable
|
||||
|
||||
## Fix
|
||||
|
||||
- Fixed schema validator on saving lesson order
|
||||
- Fixed lesson [duration updating](https://github.com/sergeyyarkov/educt-server/commit/ffdebc4f927abe3b63c62c84268f40f9e6663895#diff-86d18314585862595621b4e90f675b79ac74e7a0a47b2797556902eeff75e14a)
|
||||
- Updated cors config
|
||||
- Deleted `api` from path url
|
||||
|
||||
## [1.3.1] - 2022-04-10
|
||||
|
||||
## Added
|
||||
|
||||
- Docker files for building container
|
||||
|
||||
## [1.2.1] - 2022-03-06
|
||||
|
||||
## Added
|
||||
|
||||
- Saving latest notifications about new messages
|
||||
- Saving recent conversation messages based on constant (now 100)
|
||||
- Simple chat implementation between users
|
||||
- Added `about` and `last_login` columns for user
|
||||
- Updating info api route of authorized user
|
||||
|
||||
### Fix
|
||||
|
||||
- Refactored routes import
|
||||
- Fixed updating user info
|
||||
- Cleaning up session store before starting websocket server
|
||||
- API deployment with Docker and Nginx web server.
|
||||
|
||||
## [1.1.0] - 2022-01-31
|
||||
|
||||
|
||||
25
Dockerfile
25
Dockerfile
@ -1,25 +0,0 @@
|
||||
ARG NODE_IMAGE=node:14.17.3-alpine3.11
|
||||
|
||||
FROM ${NODE_IMAGE} AS base
|
||||
RUN apk --no-cache add dumb-init
|
||||
RUN mkdir -p /home/node/app && chown node:node /home/node/app
|
||||
WORKDIR /home/node/app
|
||||
USER node
|
||||
RUN mkdir uploads
|
||||
|
||||
FROM base as builder
|
||||
COPY --chown=node:node package*.json ./
|
||||
RUN npm ci
|
||||
COPY --chown=node:node . .
|
||||
RUN node ace build --production
|
||||
|
||||
FROM base as production
|
||||
ENV NODE_ENV=production
|
||||
ENV PORT=3333
|
||||
ENV HOST=0.0.0.0
|
||||
WORKDIR /home/node/app
|
||||
COPY --chown=node:node --from=builder /home/node/app/build .
|
||||
RUN npm ci --production
|
||||
|
||||
EXPOSE 3333
|
||||
CMD ["dumb-init", "node", "server.js"]
|
||||
@ -1,8 +1,3 @@
|
||||
# educt-server
|
||||
# About API
|
||||
|
||||
_This service is part of [Educt](https://github.com/sergeyyarkov/educt) which contains API application._
|
||||
|
||||
<!-- ## Requirements
|
||||
|
||||
- NodeJS >= 14.17.3
|
||||
- Docker -->
|
||||
...
|
||||
|
||||
@ -11,66 +11,19 @@
|
||||
},
|
||||
"list:routes": {
|
||||
"settings": {
|
||||
"loadApp": true,
|
||||
"stayAlive": true
|
||||
"loadApp": true
|
||||
},
|
||||
"commandPath": "@adonisjs/core/build/commands/ListRoutes/index",
|
||||
"commandPath": "@adonisjs/core/build/commands/ListRoutes",
|
||||
"commandName": "list:routes",
|
||||
"description": "List application routes",
|
||||
"args": [],
|
||||
"aliases": [],
|
||||
"flags": [
|
||||
{
|
||||
"name": "verbose",
|
||||
"propertyName": "verbose",
|
||||
"type": "boolean",
|
||||
"description": "Display more information"
|
||||
},
|
||||
{
|
||||
"name": "reverse",
|
||||
"propertyName": "reverse",
|
||||
"type": "boolean",
|
||||
"alias": "r",
|
||||
"description": "Reverse routes display"
|
||||
},
|
||||
{
|
||||
"name": "methods",
|
||||
"propertyName": "methodsFilter",
|
||||
"type": "array",
|
||||
"alias": "m",
|
||||
"description": "Filter routes by method"
|
||||
},
|
||||
{
|
||||
"name": "patterns",
|
||||
"propertyName": "patternsFilter",
|
||||
"type": "array",
|
||||
"alias": "p",
|
||||
"description": "Filter routes by the route pattern"
|
||||
},
|
||||
{
|
||||
"name": "names",
|
||||
"propertyName": "namesFilter",
|
||||
"type": "array",
|
||||
"alias": "n",
|
||||
"description": "Filter routes by route name"
|
||||
},
|
||||
{
|
||||
"name": "json",
|
||||
"propertyName": "json",
|
||||
"type": "boolean",
|
||||
"description": "Output as JSON"
|
||||
},
|
||||
{
|
||||
"name": "table",
|
||||
"propertyName": "table",
|
||||
"type": "boolean",
|
||||
"description": "Output as Table"
|
||||
},
|
||||
{
|
||||
"name": "max-width",
|
||||
"propertyName": "maxWidth",
|
||||
"type": "number",
|
||||
"description": "Specify maximum rendering width. Ignored for JSON Output"
|
||||
}
|
||||
]
|
||||
},
|
||||
@ -102,7 +55,7 @@
|
||||
},
|
||||
"commandPath": "@adonisjs/lucid/build/commands/DbSeed",
|
||||
"commandName": "db:seed",
|
||||
"description": "Execute database seeders",
|
||||
"description": "Execute database seeder files",
|
||||
"args": [],
|
||||
"aliases": [],
|
||||
"flags": [
|
||||
@ -126,12 +79,6 @@
|
||||
"type": "array",
|
||||
"description": "Define a custom set of seeders files names to run",
|
||||
"alias": "f"
|
||||
},
|
||||
{
|
||||
"name": "compact-output",
|
||||
"propertyName": "compactOutput",
|
||||
"type": "boolean",
|
||||
"description": "A compact single-line output"
|
||||
}
|
||||
]
|
||||
},
|
||||
@ -166,13 +113,6 @@
|
||||
"type": "boolean",
|
||||
"alias": "c",
|
||||
"description": "Generate the controller for the model"
|
||||
},
|
||||
{
|
||||
"name": "factory",
|
||||
"propertyName": "factory",
|
||||
"type": "boolean",
|
||||
"alias": "f",
|
||||
"description": "Generate a factory for the model"
|
||||
}
|
||||
]
|
||||
},
|
||||
@ -237,81 +177,13 @@
|
||||
"aliases": [],
|
||||
"flags": []
|
||||
},
|
||||
"make:factory": {
|
||||
"settings": {},
|
||||
"commandPath": "@adonisjs/lucid/build/commands/MakeFactory",
|
||||
"commandName": "make:factory",
|
||||
"description": "Make a new factory",
|
||||
"args": [
|
||||
{
|
||||
"type": "string",
|
||||
"propertyName": "model",
|
||||
"name": "model",
|
||||
"required": true,
|
||||
"description": "The name of the model"
|
||||
}
|
||||
],
|
||||
"aliases": [],
|
||||
"flags": [
|
||||
{
|
||||
"name": "model-path",
|
||||
"propertyName": "modelPath",
|
||||
"type": "string",
|
||||
"description": "The path to the model"
|
||||
},
|
||||
{
|
||||
"name": "exact",
|
||||
"propertyName": "exact",
|
||||
"type": "boolean",
|
||||
"description": "Create the factory with the exact name as provided",
|
||||
"alias": "e"
|
||||
}
|
||||
]
|
||||
},
|
||||
"db:wipe": {
|
||||
"settings": {
|
||||
"loadApp": true
|
||||
},
|
||||
"commandPath": "@adonisjs/lucid/build/commands/DbWipe",
|
||||
"commandName": "db:wipe",
|
||||
"description": "Drop all tables, views and types in database",
|
||||
"args": [],
|
||||
"aliases": [],
|
||||
"flags": [
|
||||
{
|
||||
"name": "connection",
|
||||
"propertyName": "connection",
|
||||
"type": "string",
|
||||
"description": "Define a custom database connection",
|
||||
"alias": "c"
|
||||
},
|
||||
{
|
||||
"name": "drop-views",
|
||||
"propertyName": "dropViews",
|
||||
"type": "boolean",
|
||||
"description": "Drop all views"
|
||||
},
|
||||
{
|
||||
"name": "drop-types",
|
||||
"propertyName": "dropTypes",
|
||||
"type": "boolean",
|
||||
"description": "Drop all custom types (Postgres only)"
|
||||
},
|
||||
{
|
||||
"name": "force",
|
||||
"propertyName": "force",
|
||||
"type": "boolean",
|
||||
"description": "Explicitly force command to run in production"
|
||||
}
|
||||
]
|
||||
},
|
||||
"migration:run": {
|
||||
"settings": {
|
||||
"loadApp": true
|
||||
},
|
||||
"commandPath": "@adonisjs/lucid/build/commands/Migration/Run",
|
||||
"commandName": "migration:run",
|
||||
"description": "Migrate database by running pending migrations",
|
||||
"description": "Run pending migrations",
|
||||
"args": [],
|
||||
"aliases": [],
|
||||
"flags": [
|
||||
@ -332,13 +204,7 @@
|
||||
"name": "dry-run",
|
||||
"propertyName": "dryRun",
|
||||
"type": "boolean",
|
||||
"description": "Do not run actual queries. Instead view the SQL output"
|
||||
},
|
||||
{
|
||||
"name": "compact-output",
|
||||
"propertyName": "compactOutput",
|
||||
"type": "boolean",
|
||||
"description": "A compact single-line output"
|
||||
"description": "Print SQL queries, instead of running the migrations"
|
||||
}
|
||||
]
|
||||
},
|
||||
@ -348,7 +214,7 @@
|
||||
},
|
||||
"commandPath": "@adonisjs/lucid/build/commands/Migration/Rollback",
|
||||
"commandName": "migration:rollback",
|
||||
"description": "Rollback migrations to a specific batch number",
|
||||
"description": "Rollback migrations to a given batch number",
|
||||
"args": [],
|
||||
"aliases": [],
|
||||
"flags": [
|
||||
@ -369,19 +235,13 @@
|
||||
"name": "dry-run",
|
||||
"propertyName": "dryRun",
|
||||
"type": "boolean",
|
||||
"description": "Do not run actual queries. Instead view the SQL output"
|
||||
"description": "Print SQL queries, instead of running the migrations"
|
||||
},
|
||||
{
|
||||
"name": "batch",
|
||||
"propertyName": "batch",
|
||||
"type": "number",
|
||||
"description": "Define custom batch number for rollback. Use 0 to rollback to initial state"
|
||||
},
|
||||
{
|
||||
"name": "compact-output",
|
||||
"propertyName": "compactOutput",
|
||||
"type": "boolean",
|
||||
"description": "A compact single-line output"
|
||||
}
|
||||
]
|
||||
},
|
||||
@ -391,7 +251,7 @@
|
||||
},
|
||||
"commandPath": "@adonisjs/lucid/build/commands/Migration/Status",
|
||||
"commandName": "migration:status",
|
||||
"description": "View migrations status",
|
||||
"description": "Check migrations current status.",
|
||||
"args": [],
|
||||
"aliases": [],
|
||||
"flags": [
|
||||
@ -404,117 +264,6 @@
|
||||
}
|
||||
]
|
||||
},
|
||||
"migration:reset": {
|
||||
"settings": {
|
||||
"loadApp": true
|
||||
},
|
||||
"commandPath": "@adonisjs/lucid/build/commands/Migration/Reset",
|
||||
"commandName": "migration:reset",
|
||||
"description": "Rollback all migrations",
|
||||
"args": [],
|
||||
"aliases": [],
|
||||
"flags": [
|
||||
{
|
||||
"name": "connection",
|
||||
"propertyName": "connection",
|
||||
"type": "string",
|
||||
"description": "Define a custom database connection",
|
||||
"alias": "c"
|
||||
},
|
||||
{
|
||||
"name": "force",
|
||||
"propertyName": "force",
|
||||
"type": "boolean",
|
||||
"description": "Explicitly force command to run in production"
|
||||
},
|
||||
{
|
||||
"name": "dry-run",
|
||||
"propertyName": "dryRun",
|
||||
"type": "boolean",
|
||||
"description": "Do not run actual queries. Instead view the SQL output"
|
||||
}
|
||||
]
|
||||
},
|
||||
"migration:refresh": {
|
||||
"settings": {
|
||||
"loadApp": true
|
||||
},
|
||||
"commandPath": "@adonisjs/lucid/build/commands/Migration/Refresh",
|
||||
"commandName": "migration:refresh",
|
||||
"description": "Rollback and migrate database",
|
||||
"args": [],
|
||||
"aliases": [],
|
||||
"flags": [
|
||||
{
|
||||
"name": "connection",
|
||||
"propertyName": "connection",
|
||||
"type": "string",
|
||||
"description": "Define a custom database connection",
|
||||
"alias": "c"
|
||||
},
|
||||
{
|
||||
"name": "force",
|
||||
"propertyName": "force",
|
||||
"type": "boolean",
|
||||
"description": "Explicitly force command to run in production"
|
||||
},
|
||||
{
|
||||
"name": "dry-run",
|
||||
"propertyName": "dryRun",
|
||||
"type": "boolean",
|
||||
"description": "Do not run actual queries. Instead view the SQL output"
|
||||
},
|
||||
{
|
||||
"name": "seed",
|
||||
"propertyName": "seed",
|
||||
"type": "boolean",
|
||||
"description": "Run seeders"
|
||||
}
|
||||
]
|
||||
},
|
||||
"migration:fresh": {
|
||||
"settings": {
|
||||
"loadApp": true
|
||||
},
|
||||
"commandPath": "@adonisjs/lucid/build/commands/Migration/Fresh",
|
||||
"commandName": "migration:fresh",
|
||||
"description": "Drop all tables and re-migrate the database",
|
||||
"args": [],
|
||||
"aliases": [],
|
||||
"flags": [
|
||||
{
|
||||
"name": "connection",
|
||||
"propertyName": "connection",
|
||||
"type": "string",
|
||||
"description": "Define a custom database connection",
|
||||
"alias": "c"
|
||||
},
|
||||
{
|
||||
"name": "force",
|
||||
"propertyName": "force",
|
||||
"type": "boolean",
|
||||
"description": "Explicitly force command to run in production"
|
||||
},
|
||||
{
|
||||
"name": "seed",
|
||||
"propertyName": "seed",
|
||||
"type": "boolean",
|
||||
"description": "Run seeders"
|
||||
},
|
||||
{
|
||||
"name": "drop-views",
|
||||
"propertyName": "dropViews",
|
||||
"type": "boolean",
|
||||
"description": "Drop all views"
|
||||
},
|
||||
{
|
||||
"name": "drop-types",
|
||||
"propertyName": "dropTypes",
|
||||
"type": "boolean",
|
||||
"description": "Drop all custom types (Postgres only)"
|
||||
}
|
||||
]
|
||||
},
|
||||
"make:mailer": {
|
||||
"settings": {},
|
||||
"commandPath": "@adonisjs/mail/build/commands/MakeMailer",
|
||||
|
||||
@ -1,38 +0,0 @@
|
||||
import { inject, Ioc } from '@adonisjs/core/build/standalone';
|
||||
import { HttpContextContract } from '@ioc:Adonis/Core/HttpContext';
|
||||
import { ConversationType } from 'App/Store/MessageStore';
|
||||
import IResponse from 'App/Datatypes/Interfaces/IResponse';
|
||||
|
||||
/**
|
||||
* Enums
|
||||
*/
|
||||
import HttpStatusEnum from 'App/Datatypes/Enums/HttpStatusEnum';
|
||||
|
||||
/**
|
||||
* Services
|
||||
*/
|
||||
import WsService from 'App/Services/WsService';
|
||||
|
||||
import BaseController from '../../BaseController';
|
||||
|
||||
@inject()
|
||||
export default class ChatController extends BaseController {
|
||||
/**
|
||||
* Get list of conversations (users)
|
||||
* GET /chat/conversations
|
||||
*/
|
||||
public async getConversations(ctx: HttpContextContract) {
|
||||
const user = await ctx.auth.authenticate();
|
||||
const data = await WsService.messageStore.getConversations(user.id);
|
||||
const result: IResponse<ConversationType[]> = {
|
||||
success: true,
|
||||
status: HttpStatusEnum.OK,
|
||||
message: 'Fetched conversations.',
|
||||
data,
|
||||
};
|
||||
|
||||
return this.sendResponse(ctx, result.data, result.message, result.status);
|
||||
}
|
||||
}
|
||||
|
||||
new Ioc().make(ChatController);
|
||||
@ -1,6 +1,6 @@
|
||||
import { Exception, inject, Ioc } from '@adonisjs/core/build/standalone';
|
||||
import { HttpContextContract } from '@ioc:Adonis/Core/HttpContext';
|
||||
import { schema, rules } from '@ioc:Adonis/Core/Validator';
|
||||
import { schema } from '@ioc:Adonis/Core/Validator';
|
||||
|
||||
/**
|
||||
* Services
|
||||
@ -141,7 +141,7 @@ export default class LessonsController extends BaseController {
|
||||
// eslint-disable-next-line class-methods-use-this
|
||||
public async saveOrder(ctx: HttpContextContract) {
|
||||
const saveOrderSchema = schema.create({
|
||||
ids: schema.array([rules.minLength(1)]).members(schema.string()),
|
||||
ids: schema.array().members(schema.string()),
|
||||
});
|
||||
const payload = await ctx.request.validate({ schema: saveOrderSchema });
|
||||
const { data, message, status, success, error } = await this.lessonService.updateOrder(payload.ids);
|
||||
|
||||
@ -12,7 +12,6 @@ import MeService from 'App/Services/MeService';
|
||||
*/
|
||||
import ChangePasswordValidator from 'App/Validators/Password/ChangePasswordValidator';
|
||||
import UpdateContactsValidator from 'App/Validators/Contacts/UpdateContactsValidator';
|
||||
import UpdateUserInfoValidator from 'App/Validators/User/UpdateUserInfoValidator';
|
||||
|
||||
import BaseController from '../../BaseController';
|
||||
|
||||
@ -109,35 +108,6 @@ export default class MeController extends BaseController {
|
||||
|
||||
return this.sendResponse(ctx, result.data, result.message, result.status);
|
||||
}
|
||||
|
||||
/**
|
||||
* Update personal info of user
|
||||
* PATCH /me/info
|
||||
*/
|
||||
public async updateInfo(ctx: HttpContextContract) {
|
||||
const payload = await ctx.request.validate(UpdateUserInfoValidator);
|
||||
const result = await this.meService.updateUserInfo(payload, ctx.auth);
|
||||
|
||||
if (!result.success && result.error) {
|
||||
throw new Exception(result.message, result.status, result.error.code);
|
||||
}
|
||||
|
||||
return this.sendResponse(ctx, result.data, result.message, result.status);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get messages of conversation by chat id
|
||||
* GET /me/messages
|
||||
*/
|
||||
public async chatHistory(ctx: HttpContextContract) {
|
||||
const result = await this.meService.fetchChatHistory(ctx.params.chat_id, ctx.auth);
|
||||
|
||||
if (!result.success && result.error) {
|
||||
throw new Exception(result.message, result.status, result.error.code);
|
||||
}
|
||||
|
||||
return this.sendResponse(ctx, result.data, result.message, result.status);
|
||||
}
|
||||
}
|
||||
|
||||
new Ioc().make(MeController);
|
||||
|
||||
@ -93,7 +93,7 @@ export default class UsersController extends BaseController {
|
||||
*/
|
||||
|
||||
public async delete(ctx: HttpContextContract) {
|
||||
const result = await this.userService.deleteUser(ctx.params.id, ctx);
|
||||
const result = await this.userService.deleteUser(ctx.params.id);
|
||||
|
||||
if (!result.success && result.error) {
|
||||
throw new Exception(result.message, result.status, result.error.code);
|
||||
|
||||
@ -17,15 +17,15 @@ export default class OnlineController {
|
||||
this.socket = socket;
|
||||
this.io = io;
|
||||
this.sessionStore = sessionStore;
|
||||
}
|
||||
|
||||
public handle() {
|
||||
this.onConnected(this.socket);
|
||||
this.onConnected(socket);
|
||||
|
||||
this.socket.on('disconnect', reason => this.onDisconnected(reason));
|
||||
}
|
||||
|
||||
public sendOnline(online: [string, { userId: string; userName: string }][]) {
|
||||
this.io.sockets.emit('user:online', online);
|
||||
public sendOnlineCount(online: number) {
|
||||
this.socket.emit('user:online', online);
|
||||
this.socket.broadcast.emit('user:online', online);
|
||||
}
|
||||
|
||||
public setUserOnline() {
|
||||
@ -37,8 +37,8 @@ export default class OnlineController {
|
||||
*/
|
||||
this.sessionStore
|
||||
.saveSession(sessionId, { userId, userName, connected: true })
|
||||
.then(() => this.sessionStore.getOnlineSessions())
|
||||
.then(online => this.sendOnline(online));
|
||||
.then(() => this.sessionStore.getOnlineSessionsCount())
|
||||
.then(online => this.sendOnlineCount(online));
|
||||
}
|
||||
}
|
||||
|
||||
@ -54,7 +54,7 @@ export default class OnlineController {
|
||||
*/
|
||||
this.sessionStore
|
||||
.saveSession(sessionId, { userId, userName, connected: false })
|
||||
.then(() => this.sessionStore.getOnlineSessions())
|
||||
.then(() => this.sessionStore.getOnlineSessionsCount())
|
||||
.then(online => this.socket.broadcast.emit('user:online', online));
|
||||
}
|
||||
}
|
||||
|
||||
@ -1,28 +0,0 @@
|
||||
import Course from 'App/Models/Course';
|
||||
|
||||
export type FileEntry = {
|
||||
path: string;
|
||||
name: string;
|
||||
};
|
||||
|
||||
export default class CourseHelper {
|
||||
public static getVideoFileNames(course: Course): Array<FileEntry | null> {
|
||||
const data = course.lessons.map(l => {
|
||||
if (!l.video) return null;
|
||||
return { path: 'videos/', name: l.video.name };
|
||||
});
|
||||
|
||||
return data;
|
||||
}
|
||||
|
||||
public static getMaterialFileNames(course: Course): FileEntry[] {
|
||||
const data = course.lessons.flatMap(l => l.materials.map(m => ({ path: 'materials/', name: m.name })));
|
||||
return data;
|
||||
}
|
||||
|
||||
public static getImageFileName(course: Course): FileEntry | null {
|
||||
if (!course.image) return null;
|
||||
const data = { path: 'images/courses/', name: course.image.name };
|
||||
return data;
|
||||
}
|
||||
}
|
||||
@ -1,6 +1,5 @@
|
||||
import { Exception } from '@adonisjs/core/build/standalone';
|
||||
import { HttpContextContract } from '@ioc:Adonis/Core/HttpContext';
|
||||
import User from 'App/Models/User';
|
||||
|
||||
export default class Role {
|
||||
error: {
|
||||
@ -24,7 +23,7 @@ export default class Role {
|
||||
* @param {string[]} roles - Array of roles for route
|
||||
* @param {string[]} userRole - Array of roles of current user
|
||||
*/
|
||||
protected check(roles: string[], userRoles: string[]): void {
|
||||
protected checkRoles(roles: string[], userRoles: string[]): void {
|
||||
if (!roles.some(role => userRoles.includes(role))) {
|
||||
/**
|
||||
* Failed to verify user rights
|
||||
@ -34,20 +33,8 @@ export default class Role {
|
||||
}
|
||||
|
||||
public async handle({ auth }: HttpContextContract, next: () => Promise<void>, roles: string[]) {
|
||||
const { userId } = auth.use('api').token?.meta;
|
||||
const user = await User.query().where('id', userId).preload('roles').first();
|
||||
|
||||
if (!user) {
|
||||
/**
|
||||
* User not found
|
||||
*/
|
||||
throw new Exception('Cannot identify current user.', this.error.status, this.error.code);
|
||||
}
|
||||
|
||||
this.check(
|
||||
roles,
|
||||
user.roles.map(role => role.slug)
|
||||
);
|
||||
const { userRoles } = auth.use('api').token?.meta;
|
||||
this.checkRoles(roles, userRoles);
|
||||
await next();
|
||||
}
|
||||
}
|
||||
|
||||
@ -37,9 +37,6 @@ export default class Lesson extends BaseModel {
|
||||
@column()
|
||||
public description: string;
|
||||
|
||||
@column()
|
||||
public linked_video_url: string | null;
|
||||
|
||||
@column()
|
||||
public duration: string;
|
||||
|
||||
|
||||
@ -70,12 +70,6 @@ export default class User extends BaseModel {
|
||||
})
|
||||
public lessons_progress: HasMany<typeof LessonProgress>;
|
||||
|
||||
@column()
|
||||
public about: string | null;
|
||||
|
||||
@column.dateTime()
|
||||
public last_login: DateTime | null;
|
||||
|
||||
@column.dateTime({ autoCreate: true })
|
||||
public createdAt: DateTime;
|
||||
|
||||
|
||||
@ -1,35 +0,0 @@
|
||||
import { BasePolicy } from '@ioc:Adonis/Addons/Bouncer';
|
||||
|
||||
/**
|
||||
* Helpers
|
||||
*/
|
||||
import RoleHelper from 'App/Helpers/RoleHelper';
|
||||
|
||||
/**
|
||||
* Models
|
||||
*/
|
||||
import Lesson from 'App/Models/Lesson';
|
||||
import User from 'App/Models/User';
|
||||
|
||||
/**
|
||||
* Datatypes
|
||||
*/
|
||||
import RoleEnum from 'App/Datatypes/Enums/RoleEnum';
|
||||
|
||||
export default class LessonPolicy extends BasePolicy {
|
||||
public async view(user: User, lesson: Lesson) {
|
||||
/**
|
||||
* Load required data to check permissions
|
||||
*/
|
||||
await user.load(loader => loader.load('roles').load('courses'));
|
||||
await lesson.load('course');
|
||||
|
||||
const isAdminOrTeacher = RoleHelper.userContainRoles(user.roles, [RoleEnum.ADMIN, RoleEnum.TEACHER]);
|
||||
|
||||
if (isAdminOrTeacher) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return !!user.courses.find(course => course.id === lesson.course.id);
|
||||
}
|
||||
}
|
||||
@ -1,36 +0,0 @@
|
||||
import { BasePolicy } from '@ioc:Adonis/Addons/Bouncer';
|
||||
|
||||
/**
|
||||
* Models
|
||||
*/
|
||||
import User from 'App/Models/User';
|
||||
|
||||
/**
|
||||
* Helpers
|
||||
*/
|
||||
import RoleHelper from 'App/Helpers/RoleHelper';
|
||||
|
||||
/**
|
||||
* Datatypes
|
||||
*/
|
||||
import RoleEnum from 'App/Datatypes/Enums/RoleEnum';
|
||||
|
||||
export default class RolePolicy extends BasePolicy {
|
||||
public async manage(user: User, roles: Array<RoleEnum>) {
|
||||
await user.load('roles');
|
||||
|
||||
const isAdmin = RoleHelper.userContainRoles(user.roles, [RoleEnum.ADMIN]);
|
||||
const isTeacher = RoleHelper.userContainRoles(user.roles, [RoleEnum.TEACHER]);
|
||||
|
||||
if (isAdmin) {
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* User with role `TEACHER` can manage only user with `STUDENT` role
|
||||
*/
|
||||
if (!(roles.includes(RoleEnum.TEACHER) || roles.includes(RoleEnum.ADMIN)) && isTeacher) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -32,32 +32,6 @@ export default class CourseRepository {
|
||||
this.Course = Course;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get list of courses by teacher id
|
||||
*
|
||||
* @param id Teacher id
|
||||
* @returns Array of courses
|
||||
*/
|
||||
public async getByTeacherId(id: string | number): Promise<Course[]> {
|
||||
const data = await this.Course.query()
|
||||
.preload('lessons', q => q.preload('video').preload('materials'))
|
||||
.where('teacher_id', id);
|
||||
return data;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get list of courses by category id
|
||||
*
|
||||
* @param id Category id
|
||||
* @returns Array of courses
|
||||
*/
|
||||
public async getByCategoryId(id: string | number): Promise<Course[]> {
|
||||
const data = await this.Course.query()
|
||||
.preload('lessons', q => q.preload('video').preload('materials'))
|
||||
.where('category_id', id);
|
||||
return data;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set status on course
|
||||
*
|
||||
@ -263,7 +237,6 @@ export default class CourseRepository {
|
||||
public async delete(id: string | number): Promise<Course | null> {
|
||||
const course = await this.Course.query()
|
||||
.preload('category')
|
||||
.preload('lessons', q => q.preload('video').preload('materials'))
|
||||
.withCount('students')
|
||||
.withCount('likes')
|
||||
.withCount('lessons')
|
||||
|
||||
@ -106,7 +106,6 @@ export default class LessonRepository {
|
||||
duration: data.duration.toFormat('HH:mm:ss'),
|
||||
display_order: Number.parseInt(course.$extras.lessons_count, 10) + 1,
|
||||
course_id: course.id,
|
||||
linked_video_url: !data.video ? data.linked_video_url : null,
|
||||
});
|
||||
|
||||
/**
|
||||
@ -117,9 +116,7 @@ export default class LessonRepository {
|
||||
/**
|
||||
* Move video file to disk and save to database
|
||||
*/
|
||||
if (data.video) {
|
||||
await this.createVideo(lesson, data.video);
|
||||
}
|
||||
await this.createVideo(lesson, data.video);
|
||||
|
||||
/**
|
||||
* Create materials
|
||||
@ -147,38 +144,31 @@ export default class LessonRepository {
|
||||
|
||||
if (lesson) {
|
||||
/**
|
||||
* Update fields
|
||||
* Update files
|
||||
*/
|
||||
lesson.merge({
|
||||
title: data.title,
|
||||
description: data.description,
|
||||
course_id: data.course_id,
|
||||
...(data.duration && { duration: data.duration.toFormat('HH:mm:ss') }),
|
||||
});
|
||||
|
||||
/**
|
||||
* Update linked video url
|
||||
*/
|
||||
if (data.linked_video_url && !data.video) {
|
||||
if (lesson.video) {
|
||||
await this.Drive.delete(`videos/${lesson.video.name}`);
|
||||
}
|
||||
|
||||
await lesson.related('video').query().delete();
|
||||
lesson.merge({ linked_video_url: data.linked_video_url });
|
||||
}
|
||||
|
||||
/**
|
||||
* Update file video
|
||||
* Update video
|
||||
*/
|
||||
if (data.video) {
|
||||
/**
|
||||
* Delete video from drive and database
|
||||
*/
|
||||
if (lesson.video) {
|
||||
await this.Drive.delete(`videos/${lesson.video.name}`);
|
||||
}
|
||||
|
||||
await lesson.related('video').query().delete();
|
||||
|
||||
/**
|
||||
* Upload new video to drive and save to database
|
||||
*/
|
||||
await this.createVideo(lesson, data.video);
|
||||
lesson.merge({ linked_video_url: null });
|
||||
}
|
||||
|
||||
/**
|
||||
@ -211,10 +201,7 @@ export default class LessonRepository {
|
||||
/**
|
||||
* Delete files from disk
|
||||
*/
|
||||
if (lesson.video) {
|
||||
await this.Drive.delete(`videos/${lesson.video.name}`);
|
||||
}
|
||||
|
||||
await this.Drive.delete(`videos/${lesson.video.name}`);
|
||||
await this.deleteMaterials(lesson);
|
||||
|
||||
/**
|
||||
|
||||
@ -1,5 +1,4 @@
|
||||
import Hash from '@ioc:Adonis/Core/Hash';
|
||||
import { DateTime } from 'luxon';
|
||||
|
||||
/**
|
||||
* Models
|
||||
@ -12,7 +11,6 @@ import Role from 'App/Models/Role';
|
||||
*/
|
||||
import CreateUserValidator from 'App/Validators/User/CreateUserValidator';
|
||||
import UpdateUserValidator from 'App/Validators/User/UpdateUserValidator';
|
||||
import UpdateUserInfoValidator from 'App/Validators/User/UpdateUserInfoValidator';
|
||||
|
||||
export default class UserRepository {
|
||||
private User: typeof User;
|
||||
@ -161,32 +159,6 @@ export default class UserRepository {
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Updates the time of last login column in database for user
|
||||
*
|
||||
* @param id User id
|
||||
*/
|
||||
public async updateLastLogin(id: number | string) {
|
||||
await this.User.query().where('id', id).update({ last_login: DateTime.now() }).first();
|
||||
}
|
||||
|
||||
/**
|
||||
* Update personal info of user
|
||||
*
|
||||
* @param data New fields
|
||||
*/
|
||||
public async updateInfo(id: string | number, data: UpdateUserInfoValidator['schema']['props']) {
|
||||
const user = await this.User.query().preload('contacts').preload('roles').where('id', id).first();
|
||||
const { about } = data;
|
||||
|
||||
if (user) {
|
||||
await user.merge({ about }).save();
|
||||
return { about: user.about };
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Rewrite all user roles
|
||||
*
|
||||
|
||||
@ -66,21 +66,12 @@ export default class AuthService {
|
||||
*/
|
||||
const token = await ctx.auth.use(this.authGuard).generate(user, {
|
||||
expiresIn: '1d',
|
||||
userId: user.id,
|
||||
userRoles: user.roles.map(role => role.slug),
|
||||
userName: user.fullname,
|
||||
});
|
||||
|
||||
/**
|
||||
* Set cookie token to response
|
||||
*/
|
||||
ctx.response.cookie('token', token.token);
|
||||
|
||||
/**
|
||||
* Save last login date
|
||||
*/
|
||||
await this.userRepository.updateLastLogin(user.id);
|
||||
|
||||
return {
|
||||
success: true,
|
||||
status: HttpStatusEnum.OK,
|
||||
|
||||
@ -10,7 +10,6 @@ import HttpStatusEnum from 'App/Datatypes/Enums/HttpStatusEnum';
|
||||
* Repositories
|
||||
*/
|
||||
import CategoryRepository from 'App/Repositories/CategoryRepository';
|
||||
import CourseRepository from 'App/Repositories/CourseRepository';
|
||||
|
||||
/**
|
||||
* Validators
|
||||
@ -18,27 +17,12 @@ import CourseRepository from 'App/Repositories/CourseRepository';
|
||||
import CreateCategoryValidator from 'App/Validators/Category/CreateCategoryValidator';
|
||||
import UpdateCategoryValidator from 'App/Validators/Category/UpdateCategoryValidator';
|
||||
|
||||
/**
|
||||
* Services
|
||||
*/
|
||||
import CourseService from 'App/Services/CourseService';
|
||||
|
||||
@inject()
|
||||
export default class CategoryService {
|
||||
private categoryRepository: CategoryRepository;
|
||||
|
||||
private courseRepository: CourseRepository;
|
||||
|
||||
private courseService: CourseService;
|
||||
|
||||
constructor(
|
||||
categoryRepository: CategoryRepository,
|
||||
courseRepository: CourseRepository,
|
||||
courseService: CourseService
|
||||
) {
|
||||
constructor(categoryRepository: CategoryRepository) {
|
||||
this.categoryRepository = categoryRepository;
|
||||
this.courseRepository = courseRepository;
|
||||
this.courseService = courseService;
|
||||
}
|
||||
|
||||
/**
|
||||
@ -110,7 +94,7 @@ export default class CategoryService {
|
||||
* @returns Deleted category
|
||||
*/
|
||||
public async deleteCategory(id: string | number): Promise<IResponse> {
|
||||
const data = await this.categoryRepository.getById(id);
|
||||
const data = await this.categoryRepository.delete(id);
|
||||
|
||||
if (!data) {
|
||||
return {
|
||||
@ -124,10 +108,6 @@ export default class CategoryService {
|
||||
};
|
||||
}
|
||||
|
||||
const courses = await this.courseRepository.getByCategoryId(id);
|
||||
await this.courseService.deleteAllFiles(courses);
|
||||
await this.categoryRepository.delete(id);
|
||||
|
||||
return {
|
||||
success: true,
|
||||
status: HttpStatusEnum.OK,
|
||||
|
||||
@ -25,8 +25,6 @@ import CreateCourseValidator from 'App/Validators/Course/CreateCourseValidator';
|
||||
import UpdateCourseValidator from 'App/Validators/Course/UpdateCourseValidator';
|
||||
import FetchCoursesValidator from 'App/Validators/Course/FetchCoursesValidator';
|
||||
import Course from 'App/Models/Course';
|
||||
import Drive from '@ioc:Adonis/Core/Drive';
|
||||
import CourseHelper, { FileEntry } from 'App/Helpers/CourseHelper';
|
||||
|
||||
@inject()
|
||||
export default class CourseService {
|
||||
@ -235,9 +233,9 @@ export default class CourseService {
|
||||
/**
|
||||
* Find course teacher
|
||||
*/
|
||||
const user = await this.userRepository.getById(data.teacher_id);
|
||||
const teacher = await this.userRepository.getById(data.teacher_id);
|
||||
|
||||
if (!user) {
|
||||
if (!teacher) {
|
||||
return {
|
||||
success: false,
|
||||
status: HttpStatusEnum.NOT_FOUND,
|
||||
@ -249,13 +247,13 @@ export default class CourseService {
|
||||
};
|
||||
}
|
||||
|
||||
const isHasPermissions = RoleHelper.userContainRoles(user.roles, [RoleEnum.ADMIN, RoleEnum.TEACHER]);
|
||||
const isTeacher = RoleHelper.userHasRoles(teacher.roles, [RoleEnum.TEACHER]);
|
||||
|
||||
if (!isHasPermissions) {
|
||||
if (!isTeacher) {
|
||||
return {
|
||||
success: false,
|
||||
status: HttpStatusEnum.BAD_REQUEST,
|
||||
message: `User with id "${user.id}" does not have sufficient permissions.`,
|
||||
message: `User with id "${teacher.id}" not a teacher.`,
|
||||
data: {},
|
||||
error: {
|
||||
code: 'E_BAD_REQUEST',
|
||||
@ -312,8 +310,6 @@ export default class CourseService {
|
||||
};
|
||||
}
|
||||
|
||||
await this.deleteAllFiles([course]);
|
||||
|
||||
return {
|
||||
success: true,
|
||||
status: HttpStatusEnum.OK,
|
||||
@ -330,7 +326,7 @@ export default class CourseService {
|
||||
* @returns Response
|
||||
*/
|
||||
public async updateCourse(id: string | number, data: UpdateCourseValidator['schema']['props']): Promise<IResponse> {
|
||||
const course = await this.courseRepository.getById(id);
|
||||
const course = await this.courseRepository.update(id, data);
|
||||
|
||||
if (!course) {
|
||||
return {
|
||||
@ -344,45 +340,11 @@ export default class CourseService {
|
||||
};
|
||||
}
|
||||
|
||||
if (data.teacher_id) {
|
||||
const teacher = await this.userRepository.getById(data.teacher_id);
|
||||
|
||||
if (!teacher) {
|
||||
return {
|
||||
success: false,
|
||||
status: HttpStatusEnum.NOT_FOUND,
|
||||
message: 'Teacher not found.',
|
||||
data: {},
|
||||
error: {
|
||||
code: 'E_NOT_FOUND',
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
await teacher.load('roles');
|
||||
|
||||
const isTeacherOrAdmin = RoleHelper.userContainRoles(teacher.roles, [RoleEnum.ADMIN, RoleEnum.TEACHER]);
|
||||
|
||||
if (!isTeacherOrAdmin) {
|
||||
return {
|
||||
success: false,
|
||||
status: HttpStatusEnum.BAD_REQUEST,
|
||||
message: 'Author is not a teacher or admin.',
|
||||
data: {},
|
||||
error: {
|
||||
code: 'E_BAD_REQUEST',
|
||||
},
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
const updated = await this.courseRepository.update(id, data);
|
||||
|
||||
return {
|
||||
success: true,
|
||||
status: HttpStatusEnum.OK,
|
||||
message: 'Course updated.',
|
||||
data: updated || {},
|
||||
data: course,
|
||||
};
|
||||
}
|
||||
|
||||
@ -705,29 +667,6 @@ export default class CourseService {
|
||||
data: { count },
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* This function will delete all associated course files on disk
|
||||
*
|
||||
* @param courses List of courses
|
||||
*/
|
||||
public async deleteAllFiles(courses: Course[]): Promise<void> {
|
||||
/**
|
||||
* Collect file names
|
||||
*/
|
||||
const images = courses.map(course => CourseHelper.getImageFileName(course)).filter(Boolean) as FileEntry[];
|
||||
const videos = courses.flatMap(course => CourseHelper.getVideoFileNames(course)).filter(Boolean) as FileEntry[];
|
||||
const materials = courses.flatMap(course => CourseHelper.getMaterialFileNames(course));
|
||||
|
||||
/**
|
||||
* Remove files from disk
|
||||
*/
|
||||
const promises = videos
|
||||
.concat(images, materials)
|
||||
.map(file => Drive.delete(`${file.path}${file.name.substring(file.name.lastIndexOf('/') + 1)}`));
|
||||
|
||||
await Promise.all(promises);
|
||||
}
|
||||
}
|
||||
|
||||
new Ioc().make(CourseService);
|
||||
|
||||
@ -78,7 +78,20 @@ export default class LessonService {
|
||||
};
|
||||
}
|
||||
|
||||
await ctx.bouncer.with('LessonPolicy').authorize('view', lesson);
|
||||
/**
|
||||
* Allow user to view lesson content
|
||||
*/
|
||||
if (await ctx.bouncer.denies('viewLessonContent', lesson)) {
|
||||
return {
|
||||
success: false,
|
||||
status: HttpStatusEnum.FORBIDDEN,
|
||||
message: 'The user is not a student of this course.',
|
||||
data: {},
|
||||
error: {
|
||||
code: 'E_FORBIDDEN',
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Load lesson with materials
|
||||
@ -96,8 +109,7 @@ export default class LessonService {
|
||||
/**
|
||||
* Fetch lesson material by file name
|
||||
*
|
||||
* @param ctx Http context
|
||||
* @param name Filename
|
||||
* @param fileName Name of file
|
||||
* @returns Response
|
||||
*/
|
||||
public async fetchMaterialFile(ctx: HttpContextContract, name: string): Promise<IResponse<LessonMaterial>> {
|
||||
@ -119,7 +131,18 @@ export default class LessonService {
|
||||
* Allow user to view lesson material
|
||||
*/
|
||||
await material.load('lesson');
|
||||
await ctx.bouncer.with('LessonPolicy').authorize('view', material.lesson);
|
||||
|
||||
if (await ctx.bouncer.denies('viewLessonContent', material.lesson)) {
|
||||
return {
|
||||
success: false,
|
||||
status: HttpStatusEnum.FORBIDDEN,
|
||||
message: 'You are not able to view this file.',
|
||||
data: {},
|
||||
error: {
|
||||
code: 'E_FORBIDDEN',
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
@ -145,7 +168,18 @@ export default class LessonService {
|
||||
}
|
||||
|
||||
await video.load('lesson');
|
||||
await ctx.bouncer.with('LessonPolicy').authorize('view', video.lesson);
|
||||
|
||||
if (await ctx.bouncer.denies('viewLessonContent', video.lesson)) {
|
||||
return {
|
||||
success: false,
|
||||
status: HttpStatusEnum.FORBIDDEN,
|
||||
message: 'You are not able to view this file.',
|
||||
data: {},
|
||||
error: {
|
||||
code: 'E_FORBIDDEN',
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
@ -177,7 +211,17 @@ export default class LessonService {
|
||||
};
|
||||
}
|
||||
|
||||
await ctx.bouncer.with('LessonPolicy').authorize('view', lesson);
|
||||
if (await ctx.bouncer.denies('viewLessonContent', lesson)) {
|
||||
return {
|
||||
success: false,
|
||||
status: HttpStatusEnum.FORBIDDEN,
|
||||
message: 'The user is not a student of this course.',
|
||||
data: {},
|
||||
error: {
|
||||
code: 'E_FORBIDDEN',
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
const progress = await this.lessonProgressRepository.get(user.id, lesson.id);
|
||||
|
||||
@ -310,7 +354,20 @@ export default class LessonService {
|
||||
};
|
||||
}
|
||||
|
||||
await ctx.bouncer.with('LessonPolicy').authorize('view', lesson);
|
||||
/**
|
||||
* Allow user to view lesson content
|
||||
*/
|
||||
if (await ctx.bouncer.denies('viewLessonContent', lesson)) {
|
||||
return {
|
||||
success: false,
|
||||
status: HttpStatusEnum.FORBIDDEN,
|
||||
message: 'The user is not a student of this course.',
|
||||
data: {},
|
||||
error: {
|
||||
code: 'E_FORBIDDEN',
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Load lesson with materials
|
||||
|
||||
@ -5,36 +5,14 @@ import Redis from '@ioc:Adonis/Addons/Redis';
|
||||
import Mail from '@ioc:Adonis/Addons/Mail';
|
||||
import Hash from '@ioc:Adonis/Core/Hash';
|
||||
import Logger from '@ioc:Adonis/Core/Logger';
|
||||
|
||||
/**
|
||||
* Datatypes
|
||||
*/
|
||||
import RoleEnum from 'App/Datatypes/Enums/RoleEnum';
|
||||
import HttpStatusEnum from 'App/Datatypes/Enums/HttpStatusEnum';
|
||||
import IResponse from 'App/Datatypes/Interfaces/IResponse';
|
||||
import CodeErrorEnum from 'App/Datatypes/Enums/CodeErrorEnum';
|
||||
|
||||
/**
|
||||
* Repositories
|
||||
*/
|
||||
import ContactRepository from 'App/Repositories/ContactRepository';
|
||||
import UserRepository from 'App/Repositories/UserRepository';
|
||||
|
||||
/**
|
||||
* Validator
|
||||
*/
|
||||
import UpdateUserInfoValidator from 'App/Validators/User/UpdateUserInfoValidator';
|
||||
import UpdateContactsValidator from 'App/Validators/Contacts/UpdateContactsValidator';
|
||||
|
||||
/**
|
||||
* Helpers
|
||||
*/
|
||||
import CodeErrorEnum from 'App/Datatypes/Enums/CodeErrorEnum';
|
||||
import RoleHelper from 'App/Helpers/RoleHelper';
|
||||
|
||||
/**
|
||||
* Services
|
||||
*/
|
||||
import Ws from './WsService';
|
||||
import RoleEnum from 'App/Datatypes/Enums/RoleEnum';
|
||||
|
||||
@inject()
|
||||
export default class MeService {
|
||||
@ -77,16 +55,11 @@ export default class MeService {
|
||||
});
|
||||
}
|
||||
|
||||
const notifications = await Ws.notificationStore.getNotifications(user.id);
|
||||
|
||||
return {
|
||||
success: true,
|
||||
status: HttpStatusEnum.OK,
|
||||
message: 'Fetched authorized user data.',
|
||||
data: {
|
||||
...user.toJSON(),
|
||||
notifications,
|
||||
},
|
||||
data: user,
|
||||
};
|
||||
}
|
||||
|
||||
@ -274,9 +247,9 @@ export default class MeService {
|
||||
/**
|
||||
* Update user conctact
|
||||
*
|
||||
* @param data Fields to update
|
||||
* @param data Data to update
|
||||
* @param auth AuthContract
|
||||
* @returns IResponse
|
||||
* @returns Updated user contacts
|
||||
*/
|
||||
public async updateUserContacts(
|
||||
data: UpdateContactsValidator['schema']['props'],
|
||||
@ -306,93 +279,6 @@ export default class MeService {
|
||||
data: user.contacts,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Update info about user
|
||||
*
|
||||
* @param data Fields to update
|
||||
* @param auth AuthContract
|
||||
* @returns IResponse
|
||||
*/
|
||||
public async updateUserInfo(
|
||||
data: UpdateUserInfoValidator['schema']['props'],
|
||||
auth: AuthContract
|
||||
): Promise<IResponse> {
|
||||
const user = await auth.use(this.authGuard).authenticate();
|
||||
const { about, ...newContacts } = data;
|
||||
|
||||
if (Object.keys(data).length === 0) {
|
||||
return {
|
||||
success: false,
|
||||
status: HttpStatusEnum.BAD_REQUEST,
|
||||
message: 'You must specify at least one field.',
|
||||
data: {},
|
||||
error: {
|
||||
code: 'E_BAD_REQUEST',
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Personal info updating
|
||||
*/
|
||||
if (about !== undefined) {
|
||||
await this.userRepository.updateInfo(user.id, data);
|
||||
}
|
||||
|
||||
/**
|
||||
* Contacts updating
|
||||
*/
|
||||
if (data.phone_number !== undefined || data.twitter_id !== undefined || data.telegram_id !== undefined) {
|
||||
const contacts = await this.contactRepository.update(user, newContacts);
|
||||
|
||||
if (!contacts) {
|
||||
await this.contactRepository.create(user, newContacts);
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
status: HttpStatusEnum.OK,
|
||||
message: 'User contacts updated.',
|
||||
data: { ...data },
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch history of chat
|
||||
*
|
||||
* @param chatId Id of user
|
||||
* @param auth AuthContract
|
||||
* @returns IResponse
|
||||
*/
|
||||
public async fetchChatHistory(chatId: string, auth: AuthContract): Promise<IResponse> {
|
||||
const firstUser = await auth.use(this.authGuard).authenticate();
|
||||
const secondUser = await this.userRepository.getById(chatId);
|
||||
|
||||
if (!secondUser) {
|
||||
return {
|
||||
success: false,
|
||||
status: HttpStatusEnum.NOT_FOUND,
|
||||
message: 'Chat not found.',
|
||||
data: {},
|
||||
error: {
|
||||
code: 'E_NOT_FOUND',
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
const history = await Ws.messageStore.getHistory(firstUser.id, secondUser.id);
|
||||
|
||||
return {
|
||||
success: true,
|
||||
status: HttpStatusEnum.OK,
|
||||
message: 'Chat history fetched.',
|
||||
data: {
|
||||
history,
|
||||
},
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
new Ioc().make(MeService);
|
||||
|
||||
@ -20,7 +20,7 @@ export default class StatService {
|
||||
`
|
||||
);
|
||||
|
||||
const online = await Ws.sessionStore.getOnlineSessions();
|
||||
const online = await Ws.sessionStore.getOnlineSessionsCount();
|
||||
|
||||
return {
|
||||
success: true,
|
||||
@ -28,7 +28,7 @@ export default class StatService {
|
||||
message: 'Fetched stat.',
|
||||
data: {
|
||||
...count.rows[0],
|
||||
online: online.length,
|
||||
online,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@ -22,48 +22,21 @@ import Role from 'App/Models/Role';
|
||||
import RoleRepository from 'App/Repositories/RoleRepository';
|
||||
import UserRepository from 'App/Repositories/UserRepository';
|
||||
|
||||
/**
|
||||
* Services
|
||||
*/
|
||||
import CourseService from './CourseService';
|
||||
|
||||
/**
|
||||
* Validators
|
||||
*/
|
||||
import CreateUserValidator from 'App/Validators/User/CreateUserValidator';
|
||||
import UpdateUserValidator from 'App/Validators/User/UpdateUserValidator';
|
||||
|
||||
/**
|
||||
* Datatypes
|
||||
*/
|
||||
import RoleEnum from 'App/Datatypes/Enums/RoleEnum';
|
||||
|
||||
/**
|
||||
* Helpers
|
||||
*/
|
||||
import RoleHelper from 'App/Helpers/RoleHelper';
|
||||
import CourseRepository from 'App/Repositories/CourseRepository';
|
||||
|
||||
@inject()
|
||||
export default class UserService {
|
||||
private userRepository: UserRepository;
|
||||
|
||||
private roleRepository: RoleRepository;
|
||||
|
||||
private courseRepository: CourseRepository;
|
||||
|
||||
private courseService: CourseService;
|
||||
|
||||
constructor(
|
||||
userRepository: UserRepository,
|
||||
roleRepository: RoleRepository,
|
||||
courseRepository: CourseRepository,
|
||||
courseService: CourseService
|
||||
) {
|
||||
constructor(userRepository: UserRepository, roleRepository: RoleRepository) {
|
||||
this.userRepository = userRepository;
|
||||
this.roleRepository = roleRepository;
|
||||
this.courseRepository = courseRepository;
|
||||
this.courseService = courseService;
|
||||
}
|
||||
|
||||
/**
|
||||
@ -147,7 +120,20 @@ export default class UserService {
|
||||
};
|
||||
}
|
||||
|
||||
await ctx.bouncer.with('RolePolicy').authorize('manage', [role.slug as RoleEnum]);
|
||||
/**
|
||||
* Check user permissions
|
||||
*/
|
||||
if (await ctx.bouncer.denies('manageUserRole', role)) {
|
||||
return {
|
||||
success: false,
|
||||
status: HttpStatusEnum.FORBIDDEN,
|
||||
message: 'You dont have permissions to permorm that action',
|
||||
data: {},
|
||||
error: {
|
||||
code: 'E_FORBIDDEN',
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Create new user
|
||||
@ -180,7 +166,7 @@ export default class UserService {
|
||||
data: UpdateUserValidator['schema']['props'],
|
||||
ctx: HttpContextContract
|
||||
): Promise<IResponse> {
|
||||
const user = await this.userRepository.getById(id);
|
||||
const user = await this.userRepository.update(id, data);
|
||||
|
||||
if (!user) {
|
||||
return {
|
||||
@ -194,8 +180,6 @@ export default class UserService {
|
||||
};
|
||||
}
|
||||
|
||||
await ctx.bouncer.with('RolePolicy').authorize('manage', user.roles.map(r => r.slug) as [RoleEnum]);
|
||||
|
||||
/**
|
||||
* Update user role
|
||||
*/
|
||||
@ -203,18 +187,27 @@ export default class UserService {
|
||||
const role = await this.roleRepository.getBySlug(data.role);
|
||||
|
||||
if (role) {
|
||||
await ctx.bouncer.with('RolePolicy').authorize('manage', [data.role]);
|
||||
if (await ctx.bouncer.denies('manageUserRole', role)) {
|
||||
return {
|
||||
success: false,
|
||||
status: HttpStatusEnum.FORBIDDEN,
|
||||
message: 'You dont have permissions to permorm that action',
|
||||
data: {},
|
||||
error: {
|
||||
code: 'E_FORBIDDEN',
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
await this.userRepository.updateRoles(user, [role]);
|
||||
}
|
||||
}
|
||||
|
||||
const updated = await this.userRepository.update(id, data);
|
||||
|
||||
return {
|
||||
success: true,
|
||||
status: HttpStatusEnum.OK,
|
||||
message: 'User updated.',
|
||||
data: updated || {},
|
||||
data: user,
|
||||
};
|
||||
}
|
||||
|
||||
@ -224,8 +217,8 @@ export default class UserService {
|
||||
* @param id User id
|
||||
* @returns Response
|
||||
*/
|
||||
public async deleteUser(id: string | number, ctx: HttpContextContract): Promise<IResponse> {
|
||||
const user = await this.userRepository.getById(id);
|
||||
public async deleteUser(id: string | number): Promise<IResponse> {
|
||||
const user = await this.userRepository.delete(id);
|
||||
|
||||
if (!user) {
|
||||
return {
|
||||
@ -239,15 +232,6 @@ export default class UserService {
|
||||
};
|
||||
}
|
||||
|
||||
await ctx.bouncer.with('RolePolicy').authorize('manage', user.roles.map(r => r.slug) as [RoleEnum]);
|
||||
|
||||
if (RoleHelper.userContainRoles(user.roles, [RoleEnum.TEACHER, RoleEnum.ADMIN])) {
|
||||
const courses = await this.courseRepository.getByTeacherId(id);
|
||||
await this.courseService.deleteAllFiles(courses);
|
||||
}
|
||||
|
||||
await this.userRepository.delete(id);
|
||||
|
||||
return {
|
||||
success: true,
|
||||
status: HttpStatusEnum.OK,
|
||||
|
||||
@ -1,7 +1,6 @@
|
||||
import { Server } from 'socket.io';
|
||||
import Redis from '@ioc:Adonis/Addons/Redis';
|
||||
import AdonisServer from '@ioc:Adonis/Core/Server';
|
||||
import { DateTime } from 'luxon';
|
||||
|
||||
/**
|
||||
* Controllers
|
||||
@ -12,13 +11,7 @@ import OnlineController from 'App/Controllers/Ws/OnlineController';
|
||||
* Middlewares
|
||||
*/
|
||||
import AuthMiddleware from 'App/Middleware/Ws/Auth';
|
||||
|
||||
/**
|
||||
* Stores
|
||||
*/
|
||||
import RedisSessionStore from 'App/Store/SessionStore';
|
||||
import RedisMessageStore from 'App/Store/MessageStore';
|
||||
import RedisNotificationStore from 'App/Store/NotificationStore';
|
||||
|
||||
export interface ServerToClientEvents {
|
||||
/**
|
||||
@ -26,18 +19,7 @@ export interface ServerToClientEvents {
|
||||
*/
|
||||
'user:session': (data: { sessionId: string | undefined; userId: string | undefined }) => void;
|
||||
'user:connected': (data: { userId: string; userName: string }) => void;
|
||||
'user:online': (data: [string, { userId: string; userName: string }][]) => void;
|
||||
|
||||
/**
|
||||
* Chat
|
||||
*/
|
||||
'chat:message': (data: {
|
||||
content: string;
|
||||
time: string;
|
||||
from: string;
|
||||
to: string;
|
||||
notificationId?: string | undefined;
|
||||
}) => void;
|
||||
'user:online': (data: number) => void;
|
||||
}
|
||||
|
||||
export interface ClientToServerEvents {
|
||||
@ -46,16 +28,6 @@ export interface ClientToServerEvents {
|
||||
*/
|
||||
'user:logout': () => void;
|
||||
'user:status': () => void;
|
||||
|
||||
/**
|
||||
* Chat
|
||||
*/
|
||||
'chat:message': (data: { content: string; to: string }) => void;
|
||||
|
||||
/**
|
||||
* Notification
|
||||
*/
|
||||
'notification:read': (data: { userId: string; ids: string[] }) => void;
|
||||
}
|
||||
|
||||
export interface InterServerEvents {}
|
||||
@ -71,10 +43,6 @@ class WsService {
|
||||
|
||||
public sessionStore: RedisSessionStore;
|
||||
|
||||
public messageStore: RedisMessageStore;
|
||||
|
||||
public notificationStore: RedisNotificationStore;
|
||||
|
||||
public booted = false;
|
||||
|
||||
public boot() {
|
||||
@ -89,70 +57,25 @@ class WsService {
|
||||
credentials: true,
|
||||
},
|
||||
});
|
||||
|
||||
/**
|
||||
* Stores
|
||||
*/
|
||||
this.sessionStore = new RedisSessionStore(Redis.connection('session'));
|
||||
this.messageStore = new RedisMessageStore(Redis.connection('message'));
|
||||
this.notificationStore = new RedisNotificationStore(Redis.connection('notification'));
|
||||
|
||||
/**
|
||||
* Clean up sessions before start
|
||||
*/
|
||||
this.sessionStore.destroyAllSessions().then(() => {
|
||||
/**
|
||||
* Middlewares
|
||||
*/
|
||||
this.setupMiddlewares();
|
||||
|
||||
/**
|
||||
* On connection socket
|
||||
*/
|
||||
this.listen();
|
||||
});
|
||||
this.setupMiddlewares();
|
||||
this.listen();
|
||||
}
|
||||
|
||||
private listen() {
|
||||
this.io.on('connection', async socket => {
|
||||
this.io.on('connection', socket => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
const onlineController = new OnlineController(socket, this.io, this.sessionStore);
|
||||
|
||||
onlineController.handle();
|
||||
|
||||
const { sessionId, userId, userName } = socket.data;
|
||||
const isExistSocketData = !!(sessionId && userId && userName);
|
||||
|
||||
if (isExistSocketData) {
|
||||
socket.join(userId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Send session to client
|
||||
*/
|
||||
socket.emit('user:session', { sessionId: socket.data.sessionId, userId: socket.data.userId });
|
||||
|
||||
socket.on('chat:message', async ({ content, to }) => {
|
||||
if (isExistSocketData) {
|
||||
const message = {
|
||||
content,
|
||||
from: userId,
|
||||
to,
|
||||
time: DateTime.now().toISO(),
|
||||
};
|
||||
|
||||
await this.messageStore.add(userId, to, message);
|
||||
|
||||
if (userId !== to) {
|
||||
const notification = await this.notificationStore.add(to, `You received a new private message`, 'MESSAGE');
|
||||
this.io.to(to).emit('chat:message', { ...message, notificationId: notification.id });
|
||||
} else {
|
||||
this.io.to(to).emit('chat:message', { ...message });
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
socket.on('notification:read', data => this.notificationStore.del(data.userId, data.ids));
|
||||
|
||||
/**
|
||||
* Destroy session on user logout request
|
||||
*/
|
||||
|
||||
@ -1,118 +0,0 @@
|
||||
import { RedisConnectionContract } from '@ioc:Adonis/Addons/Redis';
|
||||
import Logger from '@ioc:Adonis/Core/Logger';
|
||||
import User from 'App/Models/User';
|
||||
import { DateTime } from 'luxon';
|
||||
import { nanoid } from 'nanoid';
|
||||
|
||||
type MessageDataType = {
|
||||
from: string;
|
||||
to: string;
|
||||
content: string;
|
||||
time: string;
|
||||
};
|
||||
|
||||
export type ConversationType = {
|
||||
userId: string;
|
||||
fullname: string;
|
||||
lastMessage: MessageDataType;
|
||||
};
|
||||
|
||||
const MESSAGE_TTL = 185 * 24 * 60 * 60; // 185 days
|
||||
const MAX_MESSAGES_HISTORY = 100;
|
||||
|
||||
class RedisMessageStore {
|
||||
public redisClient: RedisConnectionContract;
|
||||
|
||||
constructor(redisClient: RedisConnectionContract) {
|
||||
this.redisClient = redisClient;
|
||||
}
|
||||
|
||||
public async add(firstUserId: string, secondUserId: string, data: MessageDataType): Promise<'OK' | 'ERROR'> {
|
||||
try {
|
||||
const msgId = nanoid();
|
||||
const msgKey = `${firstUserId}:${msgId}`;
|
||||
const key = `message:${msgKey}`;
|
||||
|
||||
await this.redisClient
|
||||
.multi()
|
||||
.hmset(key, {
|
||||
from: data.from,
|
||||
to: data.to,
|
||||
content: data.content,
|
||||
time: DateTime.now().toISO(),
|
||||
})
|
||||
.expire(key, MESSAGE_TTL)
|
||||
.exec();
|
||||
|
||||
const convKey = this.createConversationKey(firstUserId, secondUserId);
|
||||
const msgKeys = await this.redisClient.lrange(convKey, 0, -1);
|
||||
|
||||
await this.redisClient.lpush(convKey, msgKey);
|
||||
|
||||
if (msgKeys.length >= MAX_MESSAGES_HISTORY) {
|
||||
const deletedMsgKey = await this.redisClient.rpop(convKey);
|
||||
await this.redisClient.del(`message:${deletedMsgKey}`);
|
||||
}
|
||||
|
||||
return 'OK';
|
||||
} catch (error) {
|
||||
Logger.error(error);
|
||||
return 'ERROR';
|
||||
}
|
||||
}
|
||||
|
||||
public async getHistory(firstUserId: string, secondUserId: string): Promise<MessageDataType[]> {
|
||||
const convKey = this.createConversationKey(firstUserId, secondUserId);
|
||||
const msgKeys = await this.redisClient.lrange(convKey, 0, -1);
|
||||
const messages = await Promise.all(msgKeys.map(key => `message:${key}`).map(key => this.getMessage(key)));
|
||||
|
||||
return messages.sort((m1, m2) => new Date(m1.time).valueOf() - new Date(m2.time).valueOf());
|
||||
}
|
||||
|
||||
public async getConversations(userId: string): Promise<ConversationType[]> {
|
||||
/**
|
||||
* Getting conversations that had some message history
|
||||
*/
|
||||
const conversations = await this.redisClient.keys(`conversation:*${userId}*`);
|
||||
const userIds = conversations
|
||||
.map(id => id.split(':')[1])
|
||||
.map(id => (userId !== id.split('&')[0] ? id.split('&')[0] : id.split('&')[1]));
|
||||
|
||||
/**
|
||||
* Fetch this users
|
||||
*/
|
||||
const users = await User.query().select('id', 'first_name', 'last_name').where('id', 'in', userIds);
|
||||
|
||||
/**
|
||||
* Fetch last message of each conversation
|
||||
*/
|
||||
const result = await Promise.all(
|
||||
users.map(async u => {
|
||||
const convKey = this.createConversationKey(userId, u.id);
|
||||
const msgKey = await this.redisClient.lindex(convKey, 0);
|
||||
const lastMessage = await this.getMessage(`message:${msgKey}`);
|
||||
|
||||
return {
|
||||
userId: u.id,
|
||||
fullname: `${u.first_name} ${u.last_name}`,
|
||||
lastMessage,
|
||||
};
|
||||
})
|
||||
);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
private async getMessage(key: string): Promise<MessageDataType> {
|
||||
const message = (await this.redisClient.hgetall(key)) as MessageDataType;
|
||||
return message;
|
||||
}
|
||||
|
||||
// eslint-disable-next-line class-methods-use-this
|
||||
private createConversationKey(userId1: string, userId2: string): string {
|
||||
const [id1, id2] = [userId1, userId2].sort();
|
||||
return `conversation:${id1}&${id2}`;
|
||||
}
|
||||
}
|
||||
|
||||
export default RedisMessageStore;
|
||||
@ -1,65 +0,0 @@
|
||||
import { RedisConnectionContract } from '@ioc:Adonis/Addons/Redis';
|
||||
import Logger from '@ioc:Adonis/Core/Logger';
|
||||
import { nanoid } from 'nanoid';
|
||||
|
||||
const NOTIFICATION_TTL = 185 * 24 * 60 * 60; // 185 days
|
||||
|
||||
type NotificationType = {
|
||||
id: string;
|
||||
type: 'SYSTEM' | 'MESSAGE';
|
||||
content: string;
|
||||
time: string;
|
||||
};
|
||||
|
||||
class RedisNotificationStore {
|
||||
public redisClient: RedisConnectionContract;
|
||||
|
||||
constructor(redisClient: RedisConnectionContract) {
|
||||
this.redisClient = redisClient;
|
||||
}
|
||||
|
||||
public async add(userId: string, content: string, type: NotificationType['type']): Promise<NotificationType> {
|
||||
try {
|
||||
const id = nanoid();
|
||||
const key = `notification:${id}`;
|
||||
const timestamp = Date.now();
|
||||
const notification = {
|
||||
id,
|
||||
content,
|
||||
time: new Date(timestamp).toISOString(),
|
||||
type,
|
||||
};
|
||||
|
||||
await this.redisClient.zadd(`user:${userId}`, timestamp, key);
|
||||
await this.redisClient.multi().hmset(key, notification).expire(key, NOTIFICATION_TTL).exec();
|
||||
|
||||
return notification;
|
||||
} catch (error) {
|
||||
Logger.error(error);
|
||||
return Promise.reject(error);
|
||||
}
|
||||
}
|
||||
|
||||
public async getNotifications(userId: string) {
|
||||
const keys = await this.redisClient.zrevrangebyscore(`user:${userId}`, '+inf', '-inf');
|
||||
const notifications = await Promise.all(keys.map(key => this.get(key)));
|
||||
return notifications;
|
||||
}
|
||||
|
||||
private async get(key: string): Promise<NotificationType> {
|
||||
const notification = (await this.redisClient.hgetall(key)) as NotificationType;
|
||||
return notification;
|
||||
}
|
||||
|
||||
public async del(userId: string, keys: string[]): Promise<number> {
|
||||
if (keys.length === 0) return 0;
|
||||
|
||||
const k = keys.map(v => `notification:${v}`);
|
||||
const count = await this.redisClient.zrem(`user:${userId}`, k);
|
||||
await this.redisClient.del(k);
|
||||
|
||||
return count;
|
||||
}
|
||||
}
|
||||
|
||||
export default RedisNotificationStore;
|
||||
@ -25,20 +25,6 @@ class RedisSessionStore {
|
||||
};
|
||||
}
|
||||
|
||||
private async scanSessionKeys(): Promise<Set<string>> {
|
||||
const keys = new Set<string>();
|
||||
let nextIndex = 0;
|
||||
|
||||
do {
|
||||
// eslint-disable-next-line no-await-in-loop
|
||||
const [nextIndexAsStr, result] = await this.redisClient.scan(nextIndex, 'MATCH', '*', 'COUNT', 100);
|
||||
nextIndex = parseInt(nextIndexAsStr, 10);
|
||||
result.forEach(s => keys.add(s));
|
||||
} while (nextIndex !== 0);
|
||||
|
||||
return keys;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return session data by session id
|
||||
*
|
||||
@ -54,35 +40,35 @@ class RedisSessionStore {
|
||||
* Returns the all sessions from store
|
||||
*/
|
||||
public async getSessions(): Promise<Array<SessionDataType | undefined>> {
|
||||
const keys = await this.scanSessionKeys();
|
||||
const keys = new Set<string>();
|
||||
let nextIndex = 0;
|
||||
|
||||
do {
|
||||
// eslint-disable-next-line no-await-in-loop
|
||||
const [nextIndexAsStr, result] = await this.redisClient.scan(nextIndex, 'MATCH', '*', 'COUNT', 100);
|
||||
nextIndex = parseInt(nextIndexAsStr, 10);
|
||||
result.forEach(s => keys.add(s));
|
||||
} while (nextIndex !== 0);
|
||||
const commands = Array.from(keys).map(key => {
|
||||
const [, ...id] = key.split('-');
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
const [prefix, ...id] = key.split('-');
|
||||
return ['hmget', id.join('-'), 'userId', 'userName', 'connected'];
|
||||
});
|
||||
|
||||
return this.redisClient
|
||||
.multi(commands)
|
||||
.exec()
|
||||
.then(results => {
|
||||
if (results === null) return [];
|
||||
return results.map(([err, session]: [Error, (string | null)[]]) => (err ? undefined : this.transform(session)));
|
||||
});
|
||||
.then(results => results.map(([err, session]) => (err ? undefined : this.transform(session))));
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the unique sessions with connected flag `true`
|
||||
*/
|
||||
public async getOnlineSessions() {
|
||||
public async getOnlineSessionsCount() {
|
||||
const sessions = await this.getSessions();
|
||||
const online = new Map<string, { userId: string; userName: string }>();
|
||||
const online = new Set(sessions.filter(s => s?.connected === true).map(s => s?.userId));
|
||||
|
||||
sessions.forEach(s => {
|
||||
if (s?.connected === true) {
|
||||
online.set(s.userId, s);
|
||||
}
|
||||
});
|
||||
|
||||
return Array.from(online);
|
||||
return online.size;
|
||||
}
|
||||
|
||||
/**
|
||||
@ -117,27 +103,6 @@ class RedisSessionStore {
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove all sessions from redis store
|
||||
*
|
||||
* @returns Count of deleted sessions
|
||||
*/
|
||||
public async destroyAllSessions() {
|
||||
const keys = await this.scanSessionKeys().then(values =>
|
||||
Array.from(values).map(v => {
|
||||
const [, ...key] = v.split('-');
|
||||
return key.join('-');
|
||||
})
|
||||
);
|
||||
|
||||
if (keys.length > 0) {
|
||||
const deleted = await this.redisClient.del(keys);
|
||||
return deleted;
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
export default RedisSessionStore;
|
||||
|
||||
@ -7,7 +7,7 @@ export default class CreateContactsValidator {
|
||||
public schema = schema.create({
|
||||
phone_number: schema.string.nullableAndOptional({}, [
|
||||
rules.mobile({
|
||||
locale: ['ru-RU', 'en-US'],
|
||||
locales: ['ru-RU', 'en-US'],
|
||||
strict: true,
|
||||
}),
|
||||
]),
|
||||
|
||||
@ -7,29 +7,17 @@ export default class UpdateContactsValidator {
|
||||
public schema = schema.create({
|
||||
phone_number: schema.string.nullableAndOptional({}, [
|
||||
rules.mobile({
|
||||
locale: ['ru-RU', 'en-US'],
|
||||
locales: ['ru-RU', 'en-US'],
|
||||
strict: true,
|
||||
}),
|
||||
rules.unique({ table: 'contacts', column: 'phone_number' }),
|
||||
]),
|
||||
vk_id: schema.string.nullableAndOptional({}, [
|
||||
rules.regex(/^([a-zA-Z0-9_]){1,64}$/),
|
||||
rules.unique({ table: 'contacts', column: 'vk_id' }),
|
||||
]),
|
||||
twitter_id: schema.string.nullableAndOptional({}, [
|
||||
rules.regex(/(^|[^@\w])@(\w{1,15})\b/),
|
||||
rules.unique({ table: 'contacts', column: 'twitter_id' }),
|
||||
]),
|
||||
telegram_id: schema.string.nullableAndOptional({}, [
|
||||
rules.regex(/(^|[^@\w])@(\w{1,64})\b/),
|
||||
rules.unique({ table: 'contacts', column: 'telegram_id' }),
|
||||
]),
|
||||
vk_id: schema.string.nullableAndOptional({}, [rules.regex(/^([a-zA-Z0-9_]){1,64}$/)]),
|
||||
twitter_id: schema.string.nullableAndOptional({}, [rules.regex(/(^|[^@\w])@(\w{1,15})\b/)]),
|
||||
telegram_id: schema.string.nullableAndOptional({}, [rules.regex(/(^|[^@\w])@(\w{1,64})\b/)]),
|
||||
});
|
||||
|
||||
public messages = {
|
||||
'phone_number.unique': 'This phone number is not available.',
|
||||
'vk_id.unique': 'This ID is not available.',
|
||||
'twitter_id.unique': 'Twitter username is not available.',
|
||||
'telegram_id.unique': 'Telegram username is not available.',
|
||||
'phone_number.unique': 'This phone number is not available',
|
||||
};
|
||||
}
|
||||
|
||||
@ -11,7 +11,7 @@ export default class CreateCourseValidator {
|
||||
education_description: schema.string.nullable(),
|
||||
image: schema.file.optional({
|
||||
size: '10mb',
|
||||
extnames: ['jpg', 'jpeg', 'png', 'webp'],
|
||||
extnames: ['jpg', 'jpeg', 'png'],
|
||||
}),
|
||||
teacher_id: schema.string({}, [rules.exists({ table: 'users', column: 'id' })]),
|
||||
category_id: schema.string({}, [rules.exists({ table: 'categories', column: 'id' })]),
|
||||
|
||||
@ -10,7 +10,7 @@ export default class UpdateCourseValidator {
|
||||
education_description: schema.string.nullable(),
|
||||
image: schema.file.optional({
|
||||
size: '10mb',
|
||||
extnames: ['jpg', 'jpeg', 'png', 'webp'],
|
||||
extnames: ['jpg', 'jpeg', 'png'],
|
||||
}),
|
||||
teacher_id: schema.string.optional({}, [rules.exists({ table: 'users', column: 'id' })]),
|
||||
category_id: schema.string.optional({}, [rules.exists({ table: 'categories', column: 'id' })]),
|
||||
|
||||
@ -9,11 +9,10 @@ export default class CreateLessonValidator {
|
||||
title: schema.string({}, [rules.maxLength(255)]),
|
||||
description: schema.string(),
|
||||
duration: schema.date({ format: 'HH:mm:ss' }),
|
||||
video: schema.file.optional({
|
||||
video: schema.file({
|
||||
size: '5000mb',
|
||||
extnames: ['mp4', 'mov', 'avi', 'wmv', 'webm', 'flv'],
|
||||
}),
|
||||
linked_video_url: schema.string.optional([rules.regex(new RegExp('^(http|https|ftp)://'))]),
|
||||
materials: schema.array.optional().members(
|
||||
schema.file({
|
||||
size: '100mb',
|
||||
|
||||
@ -13,7 +13,6 @@ export default class UpdateLessonValidator {
|
||||
size: '5000mb',
|
||||
extnames: ['mp4', 'mov', 'avi', 'wmv', 'webm', 'flv'],
|
||||
}),
|
||||
linked_video_url: schema.string.optional([rules.regex(new RegExp('^(http|https|ftp)://'))]),
|
||||
materials: schema.array.nullableAndOptional().members(
|
||||
schema.file({
|
||||
size: '100mb',
|
||||
|
||||
@ -1,33 +0,0 @@
|
||||
import { schema, rules } from '@ioc:Adonis/Core/Validator';
|
||||
import { HttpContextContract } from '@ioc:Adonis/Core/HttpContext';
|
||||
|
||||
export default class UpdateUserInfoValidator {
|
||||
constructor(protected ctx: HttpContextContract) {}
|
||||
|
||||
public schema = schema.create({
|
||||
about: schema.string.nullableAndOptional(),
|
||||
phone_number: schema.string.nullableAndOptional({}, [
|
||||
rules.mobile({ locale: ['ru-RU', 'en-US'], strict: true }),
|
||||
rules.unique({ table: 'contacts', column: 'phone_number' }),
|
||||
]),
|
||||
vk_id: schema.string.nullableAndOptional({}, [
|
||||
rules.regex(/^([a-zA-Z0-9_]){1,64}$/),
|
||||
rules.unique({ table: 'contacts', column: 'vk_id' }),
|
||||
]),
|
||||
twitter_id: schema.string.nullableAndOptional({}, [
|
||||
rules.regex(/(^|[^@\w])@(\w{1,15})\b/),
|
||||
rules.unique({ table: 'contacts', column: 'twitter_id' }),
|
||||
]),
|
||||
telegram_id: schema.string.nullableAndOptional({}, [
|
||||
rules.regex(/(^|[^@\w])@(\w{1,64})\b/),
|
||||
rules.unique({ table: 'contacts', column: 'telegram_id' }),
|
||||
]),
|
||||
});
|
||||
|
||||
public messages = {
|
||||
'phone_number.unique': 'This phone number is not available.',
|
||||
'vk_id.unique': 'This ID is not available.',
|
||||
'twitter_id.unique': 'Twitter username is not available.',
|
||||
'telegram_id.unique': 'Telegram username is not available.',
|
||||
};
|
||||
}
|
||||
@ -8,7 +8,6 @@ export default class UpdateUserValidator {
|
||||
public schema = schema.create({
|
||||
first_name: schema.string.optional(),
|
||||
last_name: schema.string.optional(),
|
||||
about: schema.string.optional(),
|
||||
login: schema.string.optional({}, [rules.unique({ table: 'users', column: 'login' })]),
|
||||
email: schema.string.optional({}, [rules.email(), rules.unique({ table: 'users', column: 'email' })]),
|
||||
password: schema.string.optional(),
|
||||
|
||||
@ -106,8 +106,8 @@ export const http: ServerConfig = {
|
||||
path: '/',
|
||||
maxAge: '1d',
|
||||
httpOnly: true,
|
||||
secure: true,
|
||||
sameSite: 'none',
|
||||
secure: false,
|
||||
sameSite: false,
|
||||
},
|
||||
|
||||
/*
|
||||
|
||||
11
config/cloudinary.ts
Normal file
11
config/cloudinary.ts
Normal file
@ -0,0 +1,11 @@
|
||||
import Env from '@ioc:Adonis/Core/Env';
|
||||
import { CloudinaryConfig } from '@ioc:Adonis/Addons/Cloudinary';
|
||||
|
||||
const cloudinaryConfig: CloudinaryConfig = {
|
||||
cloudName: Env.get('CLOUDINARY_CLOUD_NAME'),
|
||||
apiKey: Env.get('CLOUDINARY_API_KEY'),
|
||||
apiSecret: Env.get('CLOUDINARY_API_SECRET'),
|
||||
secure: Env.get('CLOUDINARY_SECURE', true),
|
||||
};
|
||||
|
||||
export default cloudinaryConfig;
|
||||
@ -43,7 +43,6 @@ const databaseConfig: DatabaseConfig = {
|
||||
database: Env.get('PG_DB_NAME'),
|
||||
},
|
||||
migrations: {
|
||||
disableRollbacksInProduction: true,
|
||||
naturalSort: true,
|
||||
tableName: 'migrations',
|
||||
},
|
||||
|
||||
@ -6,7 +6,7 @@
|
||||
*/
|
||||
|
||||
import Env from '@ioc:Adonis/Core/Env';
|
||||
import { driveConfig } from '@adonisjs/core/build/config';
|
||||
import { DriveConfig } from '@ioc:Adonis/Core/Drive';
|
||||
import Application from '@ioc:Adonis/Core/Application';
|
||||
|
||||
/*
|
||||
@ -18,7 +18,7 @@ import Application from '@ioc:Adonis/Core/Application';
|
||||
| defined inside the `contracts` directory.
|
||||
|
|
||||
*/
|
||||
export default driveConfig({
|
||||
const driveConfig: DriveConfig = {
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Default disk
|
||||
@ -143,4 +143,6 @@ export default driveConfig({
|
||||
// usingUniformAcl: false
|
||||
// },
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
export default driveConfig;
|
||||
|
||||
@ -6,7 +6,7 @@
|
||||
*/
|
||||
|
||||
import Env from '@ioc:Adonis/Core/Env';
|
||||
import { hashConfig } from '@adonisjs/core/build/config';
|
||||
import { HashConfig } from '@ioc:Adonis/Core/Hash';
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
@ -17,7 +17,7 @@ import { hashConfig } from '@adonisjs/core/build/config';
|
||||
| defined inside `contracts` directory.
|
||||
|
|
||||
*/
|
||||
export default hashConfig({
|
||||
const hashConfig: HashConfig = {
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Default hasher
|
||||
@ -70,4 +70,6 @@ export default hashConfig({
|
||||
rounds: 10,
|
||||
},
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
export default hashConfig;
|
||||
|
||||
@ -6,9 +6,9 @@
|
||||
*/
|
||||
|
||||
import Env from '@ioc:Adonis/Core/Env';
|
||||
import { mailConfig } from '@adonisjs/mail/build/config';
|
||||
import { MailConfig } from '@ioc:Adonis/Addons/Mail';
|
||||
|
||||
export default mailConfig({
|
||||
const mailConfig: MailConfig = {
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Default mailer
|
||||
@ -18,7 +18,7 @@ export default mailConfig({
|
||||
| a mailer
|
||||
|
|
||||
*/
|
||||
mailer: Env.get('MAILER'),
|
||||
mailer: 'mailgun',
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
@ -71,4 +71,6 @@ export default mailConfig({
|
||||
domain: Env.get('MAILGUN_DOMAIN'),
|
||||
},
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
export default mailConfig;
|
||||
|
||||
@ -51,22 +51,6 @@ const redisConfig: RedisConfig = {
|
||||
keyPrefix: 'session-',
|
||||
healthCheck: true,
|
||||
},
|
||||
message: {
|
||||
host: Env.get('REDIS_HOST'),
|
||||
port: Env.get('REDIS_PORT'),
|
||||
password: Env.get('REDIS_PASSWORD', ''),
|
||||
keyPrefix: '',
|
||||
db: 2,
|
||||
healthCheck: true,
|
||||
},
|
||||
notification: {
|
||||
host: Env.get('REDIS_HOST'),
|
||||
port: Env.get('REDIS_PORT'),
|
||||
password: Env.get('REDIS_PASSWORD', ''),
|
||||
keyPrefix: '',
|
||||
db: 3,
|
||||
healthCheck: true,
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
|
||||
@ -1,6 +1,16 @@
|
||||
import { InferDisksFromConfig } from '@adonisjs/core/build/config';
|
||||
import driveConfig from '../config/drive';
|
||||
|
||||
declare module '@ioc:Adonis/Core/Drive' {
|
||||
interface DisksList extends InferDisksFromConfig<typeof driveConfig> {}
|
||||
interface DisksList {
|
||||
local: {
|
||||
config: LocalDriverConfig;
|
||||
implementation: LocalDriverContract;
|
||||
};
|
||||
s3: {
|
||||
config: S3DriverConfig;
|
||||
implementation: S3DriverContract;
|
||||
};
|
||||
// gcs: {
|
||||
// config: GcsDriverConfig
|
||||
// implementation: GcsDriverContract
|
||||
// }
|
||||
}
|
||||
}
|
||||
|
||||
@ -1,6 +1,19 @@
|
||||
import { InferListFromConfig } from '@adonisjs/core/build/config';
|
||||
import hashConfig from '../config/hash';
|
||||
/**
|
||||
* Contract source: https://git.io/Jfefs
|
||||
*
|
||||
* Feel free to let us know via PR, if you find something broken in this contract
|
||||
* file.
|
||||
*/
|
||||
|
||||
declare module '@ioc:Adonis/Core/Hash' {
|
||||
interface HashersList extends InferListFromConfig<typeof hashConfig> {}
|
||||
interface HashersList {
|
||||
bcrypt: {
|
||||
config: BcryptConfig;
|
||||
implementation: BcryptContract;
|
||||
};
|
||||
argon: {
|
||||
config: ArgonConfig;
|
||||
implementation: ArgonContract;
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@ -1,6 +1,15 @@
|
||||
import { InferMailersFromConfig } from '@adonisjs/mail/build/config';
|
||||
import mailConfig from '../config/mail';
|
||||
/**
|
||||
* Contract source: https://git.io/JvgAT
|
||||
*
|
||||
* Feel free to let us know via PR, if you find something broken in this contract
|
||||
* file.
|
||||
*/
|
||||
|
||||
declare module '@ioc:Adonis/Addons/Mail' {
|
||||
interface MailersList extends InferMailersFromConfig<typeof mailConfig> {}
|
||||
import { MailDrivers } from '@ioc:Adonis/Addons/Mail';
|
||||
|
||||
interface MailersList {
|
||||
smtp: MailDrivers['smtp'];
|
||||
mailgun: MailDrivers['mailgun'];
|
||||
}
|
||||
}
|
||||
|
||||
@ -9,7 +9,5 @@ declare module '@ioc:Adonis/Addons/Redis' {
|
||||
interface RedisConnectionsList {
|
||||
local: RedisConnectionConfig;
|
||||
session: RedisConnectionConfig;
|
||||
message: RedisConnectionConfig;
|
||||
notification: RedisConnectionConfig;
|
||||
}
|
||||
}
|
||||
|
||||
@ -1,4 +1,4 @@
|
||||
import Factory, { FactoryContextContract } from '@ioc:Adonis/Lucid/Factory';
|
||||
import Factory from '@ioc:Adonis/Lucid/Factory';
|
||||
import { string } from '@ioc:Adonis/Core/Helpers';
|
||||
|
||||
/**
|
||||
@ -18,7 +18,7 @@ import Role from 'App/Models/Role';
|
||||
import User from 'App/Models/User';
|
||||
import { DateTime } from 'luxon';
|
||||
|
||||
const makeFakeUser = (faker: FactoryContextContract['faker'], loginPrefix?: string) => {
|
||||
const makeFakeUser = (faker: Faker.FakerStatic, loginPrefix?: string) => {
|
||||
return {
|
||||
first_name: faker.name.firstName(),
|
||||
last_name: faker.name.lastName(),
|
||||
|
||||
@ -8,11 +8,9 @@ export default class Users extends BaseSchema {
|
||||
table.string('id', 21).primary();
|
||||
table.string('first_name', 24).notNullable();
|
||||
table.string('last_name', 24).notNullable();
|
||||
table.text('about');
|
||||
table.string('login', 128).notNullable().unique();
|
||||
table.string('email').notNullable().unique();
|
||||
table.string('password').notNullable();
|
||||
table.timestamp('last_login', { useTz: true });
|
||||
table.timestamp('created_at', { useTz: true });
|
||||
table.timestamp('updated_at', { useTz: true });
|
||||
});
|
||||
|
||||
@ -11,7 +11,6 @@ export default class Lessons extends BaseSchema {
|
||||
table.integer('display_order').notNullable();
|
||||
table.integer('color_id').unsigned().references('colors.id');
|
||||
table.string('description');
|
||||
table.text('linked_video_url').nullable();
|
||||
table.time('duration').notNullable();
|
||||
table.timestamp('created_at', { useTz: true });
|
||||
table.timestamp('updated_at', { useTz: true });
|
||||
|
||||
@ -7,13 +7,7 @@ export default class CourseSeeder extends BaseSeeder {
|
||||
public async run() {
|
||||
this.CourseFactory = CourseFactory;
|
||||
|
||||
const LESSONS_COUNT = 10;
|
||||
|
||||
await this.CourseFactory.with('lessons', LESSONS_COUNT, lessonFactory =>
|
||||
lessonFactory
|
||||
.with('content')
|
||||
.merge(new Array(LESSONS_COUNT).fill(LESSONS_COUNT).map((_, i) => ({ display_order: i + 1 })))
|
||||
)
|
||||
await this.CourseFactory.with('lessons', 10, lessonFactory => lessonFactory.with('content'))
|
||||
.with('category')
|
||||
.with('teacher')
|
||||
.createMany(3);
|
||||
|
||||
@ -11,48 +11,23 @@ export default class UserSeeder extends BaseSeeder {
|
||||
*/
|
||||
const roles = {
|
||||
admin: await Role.findByOrFail('slug', 'admin'),
|
||||
teacher: await Role.findByOrFail('slug', 'teacher'),
|
||||
student: await Role.findByOrFail('slug', 'student'),
|
||||
};
|
||||
|
||||
/**
|
||||
* Administrator
|
||||
*/
|
||||
const administrator = await User.create({
|
||||
const userAdmin = await User.create({
|
||||
first_name: 'John',
|
||||
last_name: 'Doe',
|
||||
login: 'admin',
|
||||
password: '123456',
|
||||
email: 'administrator@example.com',
|
||||
});
|
||||
await administrator.related('roles').attach([roles.admin.id]);
|
||||
await userAdmin.related('roles').attach([roles.admin.id]);
|
||||
|
||||
/**
|
||||
* Teacher
|
||||
*/
|
||||
const teacher = await User.create({
|
||||
first_name: 'Hanna',
|
||||
last_name: 'Liv',
|
||||
login: 'teacher',
|
||||
password: '123456',
|
||||
email: 'teacher@example.com',
|
||||
});
|
||||
await teacher.related('roles').attach([roles.teacher.id]);
|
||||
|
||||
/**
|
||||
* Student
|
||||
*/
|
||||
const student = await User.create({
|
||||
first_name: 'Ylfa',
|
||||
last_name: 'Erna',
|
||||
login: 'student',
|
||||
password: '123456',
|
||||
email: 'student@example.com',
|
||||
});
|
||||
await student.related('roles').attach([roles.student.id]);
|
||||
|
||||
/**
|
||||
* Student list
|
||||
* Students
|
||||
*/
|
||||
await StudentFactory.with('contacts').createMany(20);
|
||||
}
|
||||
|
||||
4
env.ts
4
env.ts
@ -15,10 +15,11 @@
|
||||
import Env from '@ioc:Adonis/Core/Env';
|
||||
|
||||
export default Env.rules({
|
||||
HOST: Env.schema.string({ format: 'host' }),
|
||||
PORT: Env.schema.number(),
|
||||
APP_KEY: Env.schema.string(),
|
||||
APP_NAME: Env.schema.string(),
|
||||
NODE_ENV: Env.schema.enum(['development', 'production', 'test'] as const),
|
||||
NODE_ENV: Env.schema.enum(['development', 'production', 'testing'] as const),
|
||||
DRIVE_DISK: Env.schema.enum(['local', 's3'] as const),
|
||||
PG_HOST: Env.schema.string({ format: 'host' }),
|
||||
PG_PORT: Env.schema.number(),
|
||||
@ -29,7 +30,6 @@ export default Env.rules({
|
||||
REDIS_HOST: Env.schema.string({ format: 'host' }),
|
||||
REDIS_PORT: Env.schema.number(),
|
||||
REDIS_PASSWORD: Env.schema.string.optional(),
|
||||
MAILER: Env.schema.enum(['mailgun', 'smtp'] as const),
|
||||
SMTP_HOST: Env.schema.string({ format: 'host' }),
|
||||
SMTP_PORT: Env.schema.number(),
|
||||
SMTP_USERNAME: Env.schema.string(),
|
||||
|
||||
15867
package-lock.json
generated
15867
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
63
package.json
63
package.json
@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "server",
|
||||
"version": "1.4.5",
|
||||
"version": "1.1.0",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"build": "node ace build --production",
|
||||
@ -15,44 +15,43 @@
|
||||
"db:seed:force": "node ace seed --force"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@adonisjs/assembler": "^5.7.0",
|
||||
"@typescript-eslint/eslint-plugin": "^5.27.0",
|
||||
"@typescript-eslint/parser": "^5.27.0",
|
||||
"@adonisjs/assembler": "^5.3.7",
|
||||
"@typescript-eslint/eslint-plugin": "^4.30.0",
|
||||
"@typescript-eslint/parser": "^4.30.0",
|
||||
"adonis-preset-ts": "^2.1.0",
|
||||
"eslint": "^8.17.0",
|
||||
"eslint-config-airbnb-base": "^15.0.0",
|
||||
"eslint-config-airbnb-typescript": "^17.0.0",
|
||||
"eslint-config-prettier": "^8.5.0",
|
||||
"eslint-plugin-import": "^2.26.0",
|
||||
"eslint-plugin-prettier": "^4.0.0",
|
||||
"pino-pretty": "^8.0.0",
|
||||
"prettier": "^2.6.2",
|
||||
"typescript": "^4.7.3",
|
||||
"youch": "^3.2.0",
|
||||
"youch-terminal": "^2.1.4"
|
||||
"eslint": "^7.32.0",
|
||||
"eslint-config-airbnb-base": "^14.2.1",
|
||||
"eslint-config-airbnb-typescript": "^12.3.1",
|
||||
"eslint-config-prettier": "^8.3.0",
|
||||
"eslint-plugin-import": "^2.24.2",
|
||||
"eslint-plugin-prettier": "^3.4.1",
|
||||
"pino-pretty": "^5.1.3",
|
||||
"prettier": "^2.3.2",
|
||||
"typescript": "^4.4.2",
|
||||
"youch": "^2.2.2",
|
||||
"youch-terminal": "^1.1.1"
|
||||
},
|
||||
"dependencies": {
|
||||
"@adonisjs/application": "^5.2.5",
|
||||
"@adonisjs/attachment-lite": "^1.0.7",
|
||||
"@adonisjs/auth": "^8.2.1",
|
||||
"@adonisjs/bouncer": "^2.3.0",
|
||||
"@adonisjs/core": "^5.8.3",
|
||||
"@adonisjs/drive": "^2.2.0",
|
||||
"@adonisjs/drive-s3": "^1.3.1",
|
||||
"@adonisjs/lucid": "^18.0.1",
|
||||
"@adonisjs/mail": "^8.1.2",
|
||||
"@adonisjs/redis": "^7.3.0",
|
||||
"@adonisjs/repl": "^3.1.11",
|
||||
"@adonisjs/view": "^6.1.5",
|
||||
"@adonisjs/attachment-lite": "^1.0.1",
|
||||
"@adonisjs/auth": "^8.0.10",
|
||||
"@adonisjs/bouncer": "^2.2.5",
|
||||
"@adonisjs/core": "^5.4.2",
|
||||
"@adonisjs/drive": "^2.0.7",
|
||||
"@adonisjs/drive-s3": "^1.0.5",
|
||||
"@adonisjs/lucid": "^16.3.2",
|
||||
"@adonisjs/mail": "^7.2.4",
|
||||
"@adonisjs/redis": "^7.0.9",
|
||||
"@adonisjs/repl": "^3.1.7",
|
||||
"@adonisjs/view": "^6.1.1",
|
||||
"@types/socket.io": "^3.0.2",
|
||||
"cloudinary": "^1.26.3",
|
||||
"luxon": "^2.4.0",
|
||||
"nanoid": "^3.3.4",
|
||||
"pg": "^8.7.3",
|
||||
"luxon": "^1.28.0",
|
||||
"nanoid": "^3.1.25",
|
||||
"pg": "^8.7.1",
|
||||
"phc-bcrypt": "^1.0.7",
|
||||
"proxy-addr": "^2.0.7",
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"socket.io": "^4.5.1",
|
||||
"source-map-support": "^0.5.21"
|
||||
"socket.io": "^4.4.1",
|
||||
"source-map-support": "^0.5.19"
|
||||
}
|
||||
}
|
||||
|
||||
11
routes/api.ts
Normal file
11
routes/api.ts
Normal file
@ -0,0 +1,11 @@
|
||||
/* eslint-disable global-require */
|
||||
import Route from '@ioc:Adonis/Core/Route';
|
||||
|
||||
Route.group(() => {
|
||||
/**
|
||||
* v1
|
||||
*/
|
||||
require('./apis/v1/index');
|
||||
})
|
||||
.prefix('api')
|
||||
.as('api');
|
||||
@ -3,4 +3,4 @@ import Route from '@ioc:Adonis/Core/Route';
|
||||
Route.group(() => {
|
||||
Route.post('login', 'Api/v1/AuthController.login').as('auth.login');
|
||||
Route.post('logout', 'Api/v1/AuthController.logout').middleware('auth').as('auth.logout');
|
||||
}).prefix('v1/auth');
|
||||
}).prefix('auth');
|
||||
@ -6,6 +6,4 @@ Route.group(() => {
|
||||
Route.post('/', 'Api/v1/CategoriesController.create').middleware('role:admin,teacher').as('categories.create');
|
||||
Route.delete('/:id', 'Api/v1/CategoriesController.delete').middleware('role:admin,teacher').as('categories.delete');
|
||||
Route.patch('/:id', 'Api/v1/CategoriesController.update').middleware('role:admin,teacher').as('categories.update');
|
||||
})
|
||||
.prefix('v1/categories')
|
||||
.middleware('auth');
|
||||
}).prefix('categories');
|
||||
@ -61,6 +61,4 @@ Route.group(() => {
|
||||
Route.get('/:id/lessons-progress', 'Api/v1/CoursesController.getLessonsProgress')
|
||||
.middleware('role:admin,teacher,student')
|
||||
.as('courses.get-lessons-progress');
|
||||
})
|
||||
.prefix('v1/courses')
|
||||
.middleware('auth');
|
||||
}).prefix('courses');
|
||||
@ -8,6 +8,4 @@ Route.group(() => {
|
||||
|
||||
return report.healthy ? ctx.response.ok(report) : ctx.response.badRequest(report);
|
||||
}).as('health');
|
||||
})
|
||||
.prefix('v1/health')
|
||||
.middleware('auth');
|
||||
}).prefix('health');
|
||||
@ -5,6 +5,4 @@ Route.group(() => {
|
||||
Route.delete('/:id', 'Api/v1/ImagesController.delete').as('images.delete');
|
||||
Route.get('/', 'Api/v1/ImagesController.list').as('images.list');
|
||||
Route.get('/:id', 'Api/v1/ImagesController.show').as('images.show');
|
||||
})
|
||||
.prefix('v1/images')
|
||||
.middleware('auth');
|
||||
}).prefix('images');
|
||||
74
routes/apis/v1/index.ts
Normal file
74
routes/apis/v1/index.ts
Normal file
@ -0,0 +1,74 @@
|
||||
/* eslint-disable global-require */
|
||||
import Route from '@ioc:Adonis/Core/Route';
|
||||
|
||||
Route.group(() => {
|
||||
Route.get('/', () => {
|
||||
return 'Backend API.';
|
||||
}).as('index');
|
||||
|
||||
/**
|
||||
*
|
||||
* Auth module
|
||||
*
|
||||
*/
|
||||
require('./auth');
|
||||
|
||||
Route.group(() => {
|
||||
/**
|
||||
*
|
||||
* Health check
|
||||
*
|
||||
*/
|
||||
require('./health');
|
||||
|
||||
/**
|
||||
*
|
||||
* Users module
|
||||
*
|
||||
*/
|
||||
require('./users');
|
||||
|
||||
/**
|
||||
*
|
||||
* Me module
|
||||
*
|
||||
*/
|
||||
require('./me');
|
||||
|
||||
/**
|
||||
*
|
||||
* Courses module
|
||||
*
|
||||
*/
|
||||
require('./courses');
|
||||
|
||||
/**
|
||||
*
|
||||
* Lessons module
|
||||
*
|
||||
*/
|
||||
require('./lessons');
|
||||
|
||||
/**
|
||||
*
|
||||
* Images module
|
||||
*
|
||||
* This module is not necessary yet
|
||||
*/
|
||||
// require('./images');
|
||||
|
||||
/**
|
||||
*
|
||||
* Categories module
|
||||
*
|
||||
*/
|
||||
require('./categories');
|
||||
|
||||
/**
|
||||
* Stat module
|
||||
*/
|
||||
require('./stat');
|
||||
}).middleware('auth');
|
||||
})
|
||||
.prefix('v1')
|
||||
.as('v1');
|
||||
@ -18,6 +18,4 @@ Route.group(() => {
|
||||
Route.get('/:id/progress', 'Api/v1/LessonsController.getVideoProgress')
|
||||
.middleware('role:admin,teacher,student')
|
||||
.as('lessons.get-video-progress');
|
||||
})
|
||||
.prefix('v1/lessons')
|
||||
.middleware('auth');
|
||||
}).prefix('lessons');
|
||||
@ -2,10 +2,6 @@ import Route from '@ioc:Adonis/Core/Route';
|
||||
|
||||
Route.group(() => {
|
||||
Route.get('/', 'Api/v1/MeController.show').middleware('role:admin,teacher,student').as('me.show');
|
||||
Route.get('/messages/:chat_id', 'Api/v1/MeController.chatHistory')
|
||||
.middleware('role:admin,teacher,student')
|
||||
.as('me.chat-history');
|
||||
Route.patch('/info', 'Api/v1/MeController.updateInfo').middleware('role:admin,teacher,student').as('me.update-info');
|
||||
Route.patch('/email', 'Api/v1/MeController.changeEmail')
|
||||
.middleware('role:admin,teacher,student')
|
||||
.as('me.change-email');
|
||||
@ -18,6 +14,4 @@ Route.group(() => {
|
||||
Route.patch('/contacts', 'Api/v1/MeController.updateContacts')
|
||||
.middleware('role:admin,teacher,student')
|
||||
.as('me.update-contacts');
|
||||
})
|
||||
.prefix('v1/me')
|
||||
.middleware('auth');
|
||||
}).prefix('me');
|
||||
@ -2,6 +2,4 @@ import Route from '@ioc:Adonis/Core/Route';
|
||||
|
||||
Route.group(() => {
|
||||
Route.get('/', 'Api/v1/StatController.index').middleware('role:admin,teacher,student').as('stat.index');
|
||||
})
|
||||
.prefix('v1/stat')
|
||||
.middleware('auth');
|
||||
}).prefix('stat');
|
||||
@ -7,11 +7,9 @@ Route.group(() => {
|
||||
Route.patch('/:id', 'Api/v1/UsersController.update').middleware('role:admin,teacher').as('users.update');
|
||||
Route.delete('/:id', 'Api/v1/UsersController.delete').middleware('role:admin,teacher').as('users.delete');
|
||||
Route.post('/:id/attach-roles', 'Api/v1/UsersController.attachRoles')
|
||||
.middleware('role:admin')
|
||||
.middleware('role:admin,teacher')
|
||||
.as('users.attach-role');
|
||||
Route.delete('/:id/detach-roles', 'Api/v1/UsersController.detachRoles')
|
||||
.middleware('role:admin')
|
||||
.as('users.detach-role');
|
||||
})
|
||||
.prefix('v1/users')
|
||||
.middleware('auth');
|
||||
}).prefix('users');
|
||||
34
routes/index.ts
Normal file
34
routes/index.ts
Normal file
@ -0,0 +1,34 @@
|
||||
/* eslint-disable global-require */
|
||||
import Route from '@ioc:Adonis/Core/Route';
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Routes
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| This file is dedicated for defining HTTP routes. A single file is enough
|
||||
| for majority of projects, however you can define routes in different
|
||||
| files and just make sure to import them inside this file. For example
|
||||
|
|
||||
| Define routes in following two files
|
||||
| ├── start/routes/cart.ts
|
||||
| ├── start/routes/customer.ts
|
||||
|
|
||||
| and then import them inside `start/routes.ts` as follows
|
||||
|
|
||||
| import './routes/cart'
|
||||
| import './routes/customer'
|
||||
|
|
||||
*/
|
||||
|
||||
Route.group(() => {
|
||||
/**
|
||||
* Api routes
|
||||
*/
|
||||
require('./api');
|
||||
|
||||
/**
|
||||
* Other routes
|
||||
*/
|
||||
require('./videos');
|
||||
});
|
||||
@ -21,3 +21,5 @@ const server = new Ignitor(__dirname).httpServer();
|
||||
server.start().catch(error => {
|
||||
throw new Error(error);
|
||||
});
|
||||
|
||||
process.on('SIGINT', () => server.kill(10));
|
||||
|
||||
@ -6,6 +6,11 @@
|
||||
*/
|
||||
|
||||
import Bouncer from '@ioc:Adonis/Addons/Bouncer';
|
||||
import RoleEnum from 'App/Datatypes/Enums/RoleEnum';
|
||||
import RoleHelper from 'App/Helpers/RoleHelper';
|
||||
import Lesson from 'App/Models/Lesson';
|
||||
import Role from 'App/Models/Role';
|
||||
import User from 'App/Models/User';
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
@ -29,7 +34,22 @@ import Bouncer from '@ioc:Adonis/Addons/Bouncer';
|
||||
| NOTE: Always export the "actions" const from this file
|
||||
|****************************************************************
|
||||
*/
|
||||
export const { actions } = Bouncer;
|
||||
export const { actions } = Bouncer.define('manageUserRole', async (user: User, role: Role) => {
|
||||
await user.load('roles');
|
||||
return !(
|
||||
(role.slug === RoleEnum.ADMIN || role.slug === RoleEnum.TEACHER) &&
|
||||
!RoleHelper.userContainRoles(user.roles, [RoleEnum.ADMIN])
|
||||
);
|
||||
}).define('viewLessonContent', async (user: User, lesson: Lesson) => {
|
||||
await user.load(loader => loader.load('roles').load('courses'));
|
||||
await lesson.load('course');
|
||||
|
||||
if (!RoleHelper.userContainRoles(user.roles, [RoleEnum.ADMIN, RoleEnum.TEACHER])) {
|
||||
return !!user.courses.find(course => course.id === lesson.course.id);
|
||||
}
|
||||
|
||||
return true;
|
||||
});
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
@ -54,7 +74,4 @@ export const { actions } = Bouncer;
|
||||
| NOTE: Always export the "policies" const from this file
|
||||
|****************************************************************
|
||||
*/
|
||||
export const { policies } = Bouncer.registerPolicies({
|
||||
LessonPolicy: () => import('App/Policies/LessonPolicy'),
|
||||
RolePolicy: () => import('App/Policies/RolePolicy'),
|
||||
});
|
||||
export const { policies } = Bouncer.registerPolicies({});
|
||||
|
||||
@ -1,19 +0,0 @@
|
||||
import './routes/index';
|
||||
|
||||
/**
|
||||
* API v1
|
||||
*/
|
||||
import './routes/apis/v1/auth';
|
||||
import './routes/apis/v1/categories';
|
||||
import './routes/apis/v1/chat';
|
||||
import './routes/apis/v1/courses';
|
||||
import './routes/apis/v1/health';
|
||||
import './routes/apis/v1/lessons';
|
||||
import './routes/apis/v1/me';
|
||||
import './routes/apis/v1/stat';
|
||||
import './routes/apis/v1/users';
|
||||
|
||||
/**
|
||||
* Other routes
|
||||
*/
|
||||
import './routes/videos';
|
||||
@ -1,9 +0,0 @@
|
||||
import Route from '@ioc:Adonis/Core/Route';
|
||||
|
||||
Route.group(() => {
|
||||
Route.get('/conversations', 'Api/v1/ChatController.getConversations')
|
||||
.middleware('role:admin,teacher,student')
|
||||
.as('chat.get-conversations');
|
||||
})
|
||||
.prefix('v1/chat')
|
||||
.middleware('auth');
|
||||
@ -1,3 +0,0 @@
|
||||
import Route from '@ioc:Adonis/Core/Route';
|
||||
|
||||
Route.get('/', () => 'Educt Backend API');
|
||||
@ -1,17 +1,30 @@
|
||||
{
|
||||
"extends": "./node_modules/adonis-preset-ts/tsconfig",
|
||||
"include": ["**/*"],
|
||||
"exclude": ["node_modules", "build"],
|
||||
"include": [
|
||||
"**/*"
|
||||
],
|
||||
"exclude": [
|
||||
"node_modules",
|
||||
"build"
|
||||
],
|
||||
"compilerOptions": {
|
||||
"outDir": "build",
|
||||
"rootDir": "./",
|
||||
"sourceMap": true,
|
||||
"useDefineForClassFields": true,
|
||||
"paths": {
|
||||
"App/*": ["./app/*"],
|
||||
"Config/*": ["./config/*"],
|
||||
"Contracts/*": ["./contracts/*"],
|
||||
"Database/*": ["./database/*"]
|
||||
"App/*": [
|
||||
"./app/*"
|
||||
],
|
||||
"Config/*": [
|
||||
"./config/*"
|
||||
],
|
||||
"Contracts/*": [
|
||||
"./contracts/*"
|
||||
],
|
||||
"Database/*": [
|
||||
"./database/*"
|
||||
]
|
||||
},
|
||||
"types": [
|
||||
"@adonisjs/core",
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user