Merge branch 'main' into game

This commit is contained in:
Justin Lin committed 2024-08-28 14:52:13 +08:00
commit 2a868ead48
174 files changed
+6820 -3534

No files matched your search

+2
View File
@@ -0,0 +1,2 @@
ADMIN_USERNAME=alex
ADMIN_PASSWORD=Alex1234
+2 -10
View File
@@ -4,8 +4,7 @@ WORKDIR /app
COPY ./package.json yarn.lock tsconfig.json ./
COPY packages/analytics/package.json ./packages/analytics/package.json
COPY packages/models/package.json ./packages/models/package.json
RUN yarn set version berry
RUN yarn install
RUN yarn install --frozen-lockfile
ENV HOST=0.0.0.0
ENV PORT=3001
EXPOSE 3001
@@ -17,11 +16,4 @@ COPY packages/models ./packages/models
ENV NODE_ENV=production
WORKDIR /app/packages/analytics
RUN yarn build
CMD [ "yarn", "start" ]
# Development stage
FROM build as dev
RUN yarn install --frozen-lockfile
WORKDIR /app/packages/analytics
ENV NODE_ENV=development
CMD [ "yarn", "dev" ]
CMD [ "yarn", "start" ]
+4 -1
View File
@@ -1,3 +1,6 @@
{
"ext": "js,handlebars"
"watch": ["src", "views"],
"ext": "ts,handlebars,js",
"ignore": ["src/**/*.spec.ts"],
"exec": "node --loader ts-node/esm src/index.ts"
}
+13 -5
View File
@@ -6,19 +6,27 @@
"type": "module",
"license": "GPL",
"scripts": {
"start": "node src/index.js",
"build": "tsc",
"dev": "nodemon src/index.js"
"start": "node dist/index.js",
"build": "tsc -b -f",
"watch": "tsc -b --watch",
"dev": "nodemon"
},
"dependencies": {
"@linux-odyssey/models": "*",
"express": "^4.18.2",
"dotenv": "^16.4.5",
"express": "^4.19.2",
"express-basic-auth": "^1.2.1",
"express-handlebars": "^7.1.2",
"mongoose": "^8.0.3"
},
"devDependencies": {
"nodemon": "^3.0.1",
"@swc/core": "^1.4.2",
"@swc/helpers": "^0.5.6",
"@types/express": "^4.17.21",
"@types/node": "^20.11.20",
"nodemon": "^3.1.0",
"regenerator-runtime": "^0.14.1",
"ts-node": "^10.9.2",
"typescript": "^5.3.3"
}
}
+115 -1
View File
@@ -9,7 +9,7 @@ th {
border-collapse: collapse;
border-spacing: 0;
width: 100%;
border: 2px solid black;
border: 2px solid #dcdcdd;
}
th,
@@ -17,3 +17,117 @@ td {
width: 1px;
white-space: nowrap;
}
body {
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
background-color: #000000;
color: #333;
margin: 0;
padding: 20px;
box-sizing: border-box;
}
.title h1 {
color: #00ff00;
text-align: center;
font-size: 50px;
margin-top: 50px;
font-family:
ui-monospace,
SFMono-Regular,
Menlo,
Monaco,
Consolas,
Liberation Mono,
Courier New,
monospace;
}
.title img {
width: 135px;
}
.title {
display: flex;
flex-direction: row;
justify-content: center;
gap: 30px;
margin-bottom: 30px;
}
.heading {
color: #ffffff;
}
nav {
display: flex;
flex-direction: row;
justify-content: center;
gap: 30px;
}
.nav a {
color: white;
text-decoration: none;
font-weight: 600;
font-size: 20px;
}
.data-table {
width: 100%;
border-collapse: collapse;
margin-top: 20px;
color: #dcdcdd;
background-color: #24262e;
}
.data-table td {
padding: 10px;
text-align: left;
font-weight: 400;
}
.data-table a {
color: #00dd00;
font-weight: 500;
}
.data-table th {
color: #dcdcdd;
padding: 10px;
border: 1px solid #dcdcdd;
text-align: left;
}
.container {
background-color: #24262e;
padding: 20px;
border-radius: 8px;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}
.sort {
display: flex;
margin-bottom: 25px;
gap: 15px;
}
.sort a {
background-color: #24262e;
height: 50px;
padding: 0 5 0 5;
border-radius: 10px;
text-decoration: none !important;
}
.sort .btn h3 {
margin: 15 3 0 3;
font-weight: 600;
color: #dcdcdd;
font-size: 15px;
}
.pagination {
width: 100%;
justify-content: center;
margin-top: 20px;
}
+9
View File
@@ -0,0 +1,9 @@
<svg width="638" height="732" viewBox="0 0 638 732" fill="none" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<path d="M0 0H638V732H0V0Z" fill="url(#pattern0)"/>
<defs>
<pattern id="pattern0" patternContentUnits="objectBoundingBox" width="1" height="1">
<use xlink:href="#image0_379_14" transform="matrix(0.00126582 0 0 0.00110327 0 -0.000333748)"/>
</pattern>
<image id="image0_379_14" width="790" height="907" xlink:href="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAxYAAAOLCAYAAADNRhU6AAAAAXNSR0IArs4c6QAAAIRlWElmTU0AKgAAAAgABQEGAAMAAAABAAIAAAEaAAUAAAABAAAASgEbAAUAAAABAAAAUgEoAAMAAAABAAIAAIdpAAQAAAABAAAAWgAAAAAAAAEIAAAAAQAAAQgAAAABAAOgAQADAAAAAQABAACgAgAEAAAAAQAAAxagAwAEAAAAAQAAA4sAAAAA8/vYWgAAAAlwSFlzAAAomgAAKJoBFzohsgAAA4JpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IlhNUCBDb3JlIDYuMC4wIj4KICAgPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4KICAgICAgPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIKICAgICAgICAgICAgeG1sbnM6ZGM9Imh0dHA6Ly9wdXJsLm9yZy9kYy9lbGVtZW50cy8xLjEvIgogICAgICAgICAgICB4bWxuczp0aWZmPSJodHRwOi8vbnMuYWRvYmUuY29tL3RpZmYvMS4wLyIKICAgICAgICAgICAgeG1sbnM6SXB0YzR4bXBFeHQ9Imh0dHA6Ly9pcHRjLm9yZy9zdGQvSXB0YzR4bXBFeHQvMjAwOC0wMi0yOS8iPgogICAgICAgICA8ZGM6dGl0bGU+CiAgICAgICAgICAgIDxyZGY6QWx0PgogICAgICAgICAgICAgICA8cmRmOmxpIHhtbDpsYW5nPSJ4LWRlZmF1bHQiPmF0dGF0Y2htZW50LlpjcjBOQTwvcmRmOmxpPgogICAgICAgICAgICA8L3JkZj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UAR2B4Cagq1Pfw0tyKgCCgCHYPA6OjIZQvQVCTinHiJTDzMjnLmTjy3jH2LSK5YHS6CNiedlMjA3oopW0StVqMIKAKKgCKwTQR0lGibAGp2RUARUAQ6AYFdu8935ufnJJmAg7QZMqJQYR2220FhjbKCSRaSgYFhia8/ot+kdnSV1qkIKAKKQIMQUI1Fg4DUYhQBRUARaBcCU9PnOuvr6xAq4p5QQW7dbu2iijJCpY10gUYmwRob8fi6jIyebsQMXtGgCCgCioAi0H0IqPN29/WZUqwIKAKKQA4BTivLGZ8WYQIlxqfCChQe055L2akHkCwCGOMCual0RkZHd48nE/P0u9CgCCgCioAi0GUIcKxIgyKgCCgCikAXIjA9c/DxSCS8010EjyZQZvgfLfGEC2/2pc5smhWASDMFC+yzjON4186YyPeSnUm3UqUIKAKKgCJQDgE1hSqHjMYrAoqAItDBCIyMXDjrOLJzYWFR0uk0ePNufJ1TqMBGeYIB623QoTscmYeUpEERUAQUAUWg2xDoxi9Rt2Gs9CoCioAi0HAEhoazx9fW1iRBZ23y510XPKGCdBv6HUyRCwkDx+l0QkLRXVbc6LqWKcGKgCKgCPQrAipY9GvPa7sVAUWgaxGY3XG+M3dyzhUqTCvIg3czH06Bwt0CQeyDWcmkEjIw/IRublTX3l9KuCKgCCLine truncated
</defs>
</svg>

After

Width:  |  Height:  |  Size: 630 KiB

-18
View File
@@ -1,18 +0,0 @@
function getOrFailed(key) {
if (!process.env[key]) {
throw new Error(`Missing required environment variable: ${key}`)
}
return process.env[key]
}
const config = {
host: process.env.HOST || 'localhost',
port: process.env.PORT || 3001,
db: process.env.MONGO_URL || 'mongodb://localhost:27017/odyssey-test',
username: getOrFailed('ADMIN_USERNAME'),
password: getOrFailed('ADMIN_PASSWORD'),
}
config.baseUrl = process.env.BASE_URL || `http://${config.host}:${config.port}`
export default config
+34
View File
@@ -0,0 +1,34 @@
import dotenv from 'dotenv'
if (process.env.NODE_ENV !== 'production') {
dotenv.config({ path: '.env.dev' })
}
function getOrFailed(key: string): string {
if (!process.env[key]) {
throw new Error(`Missing required environment variable: ${key}`)
}
return process.env[key] as string
}
interface Config {
host: string
port: number
db: string
username: string
password: string
baseUrl: string
}
const config: Config = {
host: process.env.HOST || 'localhost',
port: process.env.PORT ? parseInt(process.env.PORT, 10) : 3001,
db: process.env.MONGO_URL || 'mongodb://localhost:27017/odyssey-test',
username: getOrFailed('ADMIN_USERNAME'),
password: getOrFailed('ADMIN_PASSWORD'),
baseUrl:
process.env.BASE_URL ||
`http://${process.env.HOST || 'localhost'}:${process.env.PORT ? parseInt(process.env.PORT, 10) : 3001}`,
}
export default config
File renamed without changes.
@@ -1,10 +1,12 @@
/* eslint-disable object-shorthand */
import type { Request, Response } from 'express'
import Pagination from '../models/pagination.js'
import { errorCommands } from '../models/commands.js'
// eslint-disable-next-line import/prefer-default-export
export async function commandListController(req, res) {
const { nextKey, order } = req.query
export async function commandListController(
req: Request,
res: Response
): Promise<void> {
const { nextKey, order } = req.query as { nextKey?: string; order: string }
const itemsPerPage = 100
try {
@@ -1,8 +1,8 @@
import { Request, Response } from 'express'
import { userCount } from '../models/users.js'
import { questList } from '../models/quests.js'
// eslint-disable-next-line import/prefer-default-export
export async function homeController(req, res) {
export async function homeController(req: Request, res: Response) {
const quests = await questList()
const [totalQuests, totalCompleted] = quests.reduce(
([total, completed], quest) => [
@@ -17,8 +17,7 @@ export async function homeController(req, res) {
userCount: await userCount(),
totalQuests,
totalCompleted,
completedRate: Math.round((totalCompleted / totalQuests) * 10000) / 100,
}
payload.completedRate =
Math.round((payload.totalCompleted / payload.totalQuests) * 10000) / 100
res.render('home', payload)
}
@@ -1,7 +1,7 @@
import { Request, Response } from 'express'
import { questList } from '../models/quests.js'
// eslint-disable-next-line import/prefer-default-export
export async function questListController(req, res) {
export async function questListController(req: Request, res: Response) {
const quests = await questList()
quests.forEach((quest) => {
quest.failed = quest.started - quest.completed
@@ -1,8 +1,9 @@
import { Request, Response } from 'express'
import Pagination from '../models/pagination.js'
import { sessionList, sessionDetail } from '../models/sessions.js'
export async function sessionListController(req, res) {
const { nextKey, order } = req.query
export async function sessionListController(req: Request, res: Response) {
const { nextKey, order } = req.query as { nextKey: string; order: string }
const itemsPerPage = 50
try {
@@ -21,7 +22,7 @@ export async function sessionListController(req, res) {
}
}
export async function sessionDetailController(req, res) {
export async function sessionDetailController(req: Request, res: Response) {
const { id } = req.params
const session = await sessionDetail(id)
res.render('sessionDetail', { session })
@@ -1,22 +0,0 @@
import Pagination from '../models/pagination.js'
import { userList } from '../models/users.js'
export async function userListController(req, res) {
const { nextKey, order } = req.query
const itemsPerPage = 50
try {
const pagination = new Pagination(order, itemsPerPage, nextKey)
const users = await userList(pagination)
const newNextKey = users[users.length - 1]?._id
res.render('users', {
users,
nextKey: newNextKey,
order: pagination.getOrder(),
})
} catch (error) {
console.error(error)
res.status(500).send('Error fetching user data')
}
}
@@ -0,0 +1,36 @@
import { Request, Response } from 'express'
import mongoose from 'mongoose'
import Pagination from '../models/pagination.js'
import { userList, userDetail, idToUser } from '../models/users.js'
export async function userListController(req: Request, res: Response) {
const { nextKey, order } = req.query as { nextKey: string; order: string }
const itemsPerPage = 50
try {
const pagination = new Pagination(order, itemsPerPage, nextKey)
const users = await userList(pagination)
const newNextKey = users[users.length - 1]?._id
res.render('users', {
users,
nextKey: newNextKey,
order: pagination.getOrder(),
})
} catch (error) {
console.error(error)
res.status(500).send('Error fetching user data')
}
}
export async function userDetailController(req: Request, res: Response) {
const id = new mongoose.Types.ObjectId(req.params.id)
const sessions = await userDetail(id)
try {
const user = await idToUser(id)
res.render('usersDetail', { sessions, user })
} catch (error) {
console.error(error)
res.status(500).send('Error fetching user data')
}
}
File renamed without changes.
+61
View File
@@ -0,0 +1,61 @@
import { Types } from 'mongoose'
export interface User {
username: string
}
export interface SessionDocument {
_id: Types.ObjectId
user: User
quest: string
status: string
createdAt: Date
finishedAt: Date
}
export interface CommandObject {
command: string
pwd: string
stage?: string | null
output: string | undefined
error: string | undefined
createdAt: string
}
export interface SessionObject {
_id: Types.ObjectId
user: string
quest: string
status: string
createdAt: string
finishedAt: string
lastActivityAt: string
usedTime: string
commandCount: number
commands: CommandObject[]
}
export interface SessionDetail {
_id: Types.ObjectId
user: string
quest: string
status: string
createdAt: string
finishedAt: string
usedTime: string
commands: CommandObject[]
}
export interface IUser extends Document {
hashedPassword?: string
socialLogins?: Record<
string,
{
id: string
provider: string
displayName?: string | null | undefined
}
>
}
export interface UserSessionDetail {
_id: Types.ObjectId
quest: string
status: string
createdAt: string
usedTime: string
}
@@ -1,7 +1,8 @@
import { Command } from '@linux-odyssey/models'
import Pagination from './pagination.js'
// eslint-disable-next-line import/prefer-default-export
export async function errorCommands(pagination) {
export async function errorCommands(pagination: Pagination) {
const commands = await Command.aggregate([
pagination.match('_id'),
{
@@ -1,74 +0,0 @@
/* eslint-disable lines-between-class-members */
/* eslint-disable class-methods-use-this */
// eslint-disable-next-line max-classes-per-file
import mongoose from 'mongoose'
export const DESC = 'desc'
export const ASC = 'asc'
class Asc {
getOperator() {
return '$gt'
}
getOrder() {
return 1
}
getName() {
return ASC
}
}
class Desc {
getOperator() {
return '$lt'
}
getOrder() {
return -1
}
getName() {
return DESC
}
}
export default class Pagination {
nextKey = null
itemsPerPage = 50
order = null
constructor(order, itemsPerPage = 50, nextKey = null) {
this.itemsPerPage = itemsPerPage
if (!order || order === DESC) {
this.order = new Desc()
} else if (order === ASC) {
this.order = new Asc()
} else {
throw new Error('order must be asc or desc')
}
if (nextKey) {
this.nextKey = new mongoose.Types.ObjectId(nextKey)
}
}
match(field) {
const stage = this.nextKey
? { [field]: { [this.order.getOperator()]: this.nextKey } }
: {}
return { $match: stage }
}
sort(field) {
return { $sort: { [field]: this.order.getOrder() } }
}
limit() {
return { $limit: this.itemsPerPage }
}
getOrder() {
return this.order.getName()
}
}
@@ -0,0 +1,88 @@
/* eslint-disable class-methods-use-this */
// eslint-disable-next-line max-classes-per-file
import mongoose, { Types } from 'mongoose'
export const DESC: string = 'desc'
export const ASC: string = 'asc'
interface Order {
getOperator(): string
getOrder(): number
getName(): string
}
class Asc implements Order {
getOperator(): string {
return '$gt'
}
getOrder(): number {
return 1
}
getName(): string {
return ASC
}
}
class Desc implements Order {
getOperator(): string {
return '$lt'
}
getOrder(): 1 | -1 {
return -1
}
getName(): string {
return DESC
}
}
export default class Pagination {
nextKey: Types.ObjectId | null = null
itemsPerPage: number = 50
order: Order
constructor(
order: string,
itemsPerPage: number = 50,
nextKey: string | null = null
) {
this.itemsPerPage = itemsPerPage
if (!order || order === DESC) {
this.order = new Desc()
} else if (order === ASC) {
this.order = new Asc()
} else {
throw new Error('order must be asc or desc')
}
if (nextKey) {
this.nextKey = new mongoose.Types.ObjectId(nextKey)
}
}
match(field: string) {
const stage: { [key: string]: { [key: string]: Types.ObjectId } } = this
.nextKey
? {
[field]: {
[this.order ? this.order.getOperator() : '$gt']: this.nextKey,
},
}
: {}
return { $match: stage }
}
sort(field: string): { $sort: Record<string, 1 | -1> } {
return { $sort: { [field]: this.order.getOrder() as 1 | -1 } }
}
limit() {
return { $limit: this.itemsPerPage }
}
getOrder() {
return this.order.getName()
}
}
-83
View File
@@ -1,83 +0,0 @@
import { Command, Session } from '@linux-odyssey/models'
function formatTime(time) {
const seconds = Math.floor(time / 1000)
const minutes = Math.floor(seconds / 60)
const hours = Math.floor(minutes / 60)
return `${hours}h ${minutes % 60}m ${seconds % 60}s`
}
export async function sessionList(pagination) {
const sessions = await Session.aggregate([
pagination.match('_id'),
{
$lookup: {
from: 'users',
localField: 'user',
foreignField: '_id',
as: 'user',
},
},
{ $unwind: '$user' },
{
$lookup: {
from: 'commands',
localField: '_id',
foreignField: 'session',
as: 'commands',
},
},
pagination.sort('_id'),
pagination.limit(),
])
return sessions.map(
({
_id,
user,
quest,
status,
createdAt,
finishedAt,
commands,
lastActivityAt,
}) => {
return {
_id,
user: user.username,
quest,
status,
createdAt: createdAt?.toLocaleString(),
finishedAt: finishedAt?.toLocaleString(),
lastActivityAt: lastActivityAt?.toLocaleString(),
usedTime: formatTime(lastActivityAt - createdAt),
commandCount: commands?.length,
}
}
)
}
export async function sessionDetail(id) {
const session = await Session.findById(id).populate('user').exec()
const commands = (await Command.find({ session: id })).map(
({ command, pwd, output, error, createdAt, stage }) => ({
command: command?.slice(0, 20),
pwd,
stage,
output: output?.slice(0, 50),
error: error?.slice(0, 50),
createdAt: createdAt?.toLocaleString(),
})
)
const { _id, user, quest, status, createdAt, finishedAt } = session
return {
_id,
user: user.username,
quest,
status,
createdAt: createdAt?.toLocaleString(),
finishedAt: finishedAt?.toLocaleString(),
usedTime: finishedAt ? formatTime(finishedAt - createdAt) : '',
commands,
}
}
+99
View File
@@ -0,0 +1,99 @@
import { Command, Session } from '@linux-odyssey/models'
import Pagination from './pagination.js'
import {
CommandObject,
SessionDetail,
SessionDocument,
SessionObject,
} from '../interface.js'
function formatTime(time: number) {
const seconds = Math.floor(time / 1000)
const minutes = Math.floor(seconds / 60)
const hours = Math.floor(minutes / 60)
return `${hours}h ${minutes % 60}m ${seconds % 60}s`
}
export async function sessionList(
pagination: Pagination
): Promise<SessionObject[]> {
const sessions = await Session.aggregate([
pagination.match('_id'),
{
$lookup: {
from: 'users',
localField: 'user',
foreignField: '_id',
as: 'user',
},
},
{ $unwind: '$user' },
{
$lookup: {
from: 'commands',
localField: '_id',
foreignField: 'session',
as: 'commands',
},
},
pagination.sort('_id'),
pagination.limit(),
])
return sessions.map((session) => {
const {
_id,
user,
quest,
status,
createdAt,
finishedAt,
commands,
lastActivityAt,
} = session
return {
_id,
user: user.username, // Assuming `user` is always populated.
quest,
status,
createdAt: createdAt?.toLocaleString(),
finishedAt: finishedAt?.toLocaleString(),
lastActivityAt: lastActivityAt?.toLocaleString(),
usedTime:
lastActivityAt && createdAt
? formatTime(lastActivityAt.getTime() - createdAt.getTime())
: 'N/A', // Ensure both dates are present
commandCount: commands?.length || 0,
commands,
}
})
}
export async function sessionDetail(id: string): Promise<SessionDetail> {
const session = (await Session.findById(id)
.populate('user')
.exec()) as unknown as SessionDocument
const commands: CommandObject[] = (await Command.find({ session: id })).map(
({ command, pwd, output, error, createdAt, stage }): CommandObject => ({
command: command?.slice(0, 20),
pwd,
stage,
output: output?.slice(0, 50),
error: error?.slice(0, 50),
createdAt: createdAt?.toLocaleString(),
})
)
const { _id, user, quest, status, createdAt, finishedAt } = session
return {
_id,
user: user.username,
quest,
status,
createdAt: createdAt?.toLocaleString(),
finishedAt: finishedAt?.toLocaleString(),
usedTime: finishedAt
? formatTime(finishedAt.getTime() - createdAt.getTime())
: '',
commands,
}
}
-49
View File
@@ -1,49 +0,0 @@
import { Session, User } from '@linux-odyssey/models'
function loginMethods(user) {
const methods = []
if (user.hashedPassword) methods.push('password')
if (user.socialLogins) methods.push(...Object.keys(user.socialLogins))
return methods
}
export function userCount() {
return User.find().count()
}
export async function userList(pagination) {
const users = await Session.aggregate([
pagination.match('user'),
{
$group: {
_id: '$user',
count: { $sum: 1 },
lastActivityAt: { $max: '$lastActivityAt' },
},
},
{
$lookup: {
from: 'users',
localField: '_id',
foreignField: '_id',
as: 'userData',
},
},
{ $unwind: '$userData' },
pagination.sort('userData._id'),
pagination.limit(),
])
return users.map(({ userData, count, lastActivityAt }) => {
const { _id, username, email, createdAt } = userData
return {
_id,
username,
email,
createdAt: createdAt?.toLocaleString(),
method: loginMethods(userData),
sessionCount: count,
lastActivityAt: lastActivityAt?.toLocaleString(),
}
})
}
+88
View File
@@ -0,0 +1,88 @@
import { Session, User } from '@linux-odyssey/models'
import { Types } from 'mongoose'
import Pagination from './pagination.js'
import { IUser, UserSessionDetail } from '../interface.js'
function loginMethods(user: IUser): string[] {
const methods: string[] = []
if (user.hashedPassword) methods.push('password')
if (user.socialLogins && typeof user.socialLogins === 'object') {
methods.push(...Object.keys(user.socialLogins))
}
return methods
}
function formatTime(time: number) {
const seconds = Math.floor(time / 1000)
const minutes = Math.floor(seconds / 60)
const hours = Math.floor(minutes / 60)
return `${hours}h ${minutes % 60}m ${seconds % 60}s`
}
export function userCount() {
return User.countDocuments({})
}
export async function userList(pagination: Pagination) {
const users = await Session.aggregate([
pagination.match('user'),
{
$group: {
_id: '$user',
count: { $sum: 1 },
lastActivityAt: { $max: '$lastActivityAt' },
},
},
{
$lookup: {
from: 'users',
localField: '_id',
foreignField: '_id',
as: 'userData',
},
},
{ $unwind: '$userData' },
pagination.sort('userData._id'),
pagination.limit(),
])
return users.map(({ userData, count, lastActivityAt }) => {
const { _id, username, email, createdAt } = userData
return {
_id,
username,
email,
createdAt: createdAt?.toLocaleString(),
method: loginMethods(userData),
sessionCount: count,
lastActivityAt: lastActivityAt?.toLocaleString(),
}
})
}
export async function userDetail(
id: Types.ObjectId
): Promise<UserSessionDetail[]> {
const sessions = await Session.find({
user: id,
})
return sessions.map((session): UserSessionDetail => {
const { _id, quest, status, createdAt, lastActivityAt } = session
return {
_id,
quest,
status,
createdAt: createdAt?.toLocaleString(),
usedTime:
lastActivityAt && createdAt
? formatTime(lastActivityAt.getTime() - createdAt.getTime())
: 'N/A', // Ensure both dates are present
}
})
}
export async function idToUser(id: Types.ObjectId): Promise<String> {
const user = await User.findOne({
_id: id,
})
return user?.username || 'User not found'
}
@@ -1,7 +1,10 @@
import { Router } from 'express'
import { homeController } from './controllers/index.js'
import { userListController } from './controllers/users.js'
import {
userListController,
userDetailController,
} from './controllers/users.js'
import { questListController } from './controllers/quests.js'
import { commandListController } from './controllers/commands.js'
import {
@@ -13,6 +16,7 @@ const router = Router()
router.get('/', homeController)
router.get('/users', userListController)
router.get('/users/:id', userDetailController)
router.get('/quests', questListController)
router.get('/commands', commandListController)
router.get('/sessions', sessionListController)
+4 -2
View File
@@ -1,10 +1,12 @@
{
"extends": "../../tsconfig.json",
"compilerOptions": {
"allowJs": true,
"rootDir": "src",
"outDir": "./dist"
},
"include": ["src"],
"exclude": ["node_modules", "dist"]
"references": [{ "path": "../models" }],
"ts-node": {
"swc": true
}
}
+14 -8
View File
@@ -1,11 +1,15 @@
<h1>Commands</h1>
<h1 class='heading'>Commands</h1>
<div>
<h2>Error commands</h2>
<div class='pagination'>
<a href='/commands?order=asc'>Ascending</a>
<a href='/commands?order=desc'>Descending</a>
<h2 class='heading'>Error commands</h2>
<div class='sort'>
<a href='/commands?order=asc'><div class='btn'>
<h3>Ascending</h3>
</div></a>
<a href='/commands?order=desc'><div class='btn'>
<h3>Descending</h3>
</div></a>
</div>
<table>
<table class='data-table'>
<tr>
<th>Command</th>
<th>User</th>
@@ -25,7 +29,9 @@
</tr>
{{/each}}
</table>
<div class='pagination'>
<a href='/commands?nextKey={{nextKey}}&order={{order}}'>Next</a>
<div class='pagination sort'>
<a href='/commands?nextKey={{nextKey}}&order={{order}}'><div class='btn'>
<h3>Next</h3>
</div></a>
</div>
</div>
+27 -22
View File
@@ -1,22 +1,27 @@
<h1>Welcome to {{title}}</h1>
<div>
<h2>Overview</h2>
<table>
<tr>
<th>Registered Users</th>
<td>{{userCount}}</td>
</tr>
<tr>
<th>Total Started Quests</th>
<td>{{totalQuests}}</td>
</tr>
<tr>
<th>Completed Quests</th>
<td>{{totalCompleted}}</td>
</tr>
<tr>
<th>Completed Rate</th>
<td>{{completedRate}}%</td>
</tr>
</table>
</div>
<body>
<div class='title'>
<img src='icon_totem.svg' class='styled-image' />
<h1>Welcome to {{title}}</h1>
</div>
<div class='container'>
<h2 class='heading'>Overview</h2>
<table class='data-table'>
<tr>
<th>Registered Users</th>
<td>{{userCount}}</td>
</tr>
<tr>
<th>Total Started Quests</th>
<td>{{totalQuests}}</td>
</tr>
<tr>
<th>Completed Quests</th>
<td>{{totalCompleted}}</td>
</tr>
<tr>
<th>Completed Rate</th>
<td>{{completedRate}}%</td>
</tr>
</table>
</div>
</body>
@@ -4,14 +4,12 @@
<link rel='stylesheet' href='/css/style.css' />
</head>
<body>
<nav>
<ul>
<li><a href='/'>Home</a></li>
<li><a href='/users'>Users</a></li>
<li><a href='/quests'>Quests</a></li>
<li><a href='/commands'>Commands</a></li>
<li><a href='/sessions'>Sessions</a></li>
</ul>
<nav class='nav'>
<div><a href='/'>Home</a></div>
<div><a href='/users'>Users</a></div>
<div><a href='/quests'>Quests</a></div>
<div><a href='/commands'>Commands</a></div>
<div><a href='/sessions'>Sessions</a></div>
</nav>
{{{body}}}
</body>
+2 -2
View File
@@ -1,6 +1,6 @@
<h1>Quests</h1>
<h1 class='heading'>Quests</h1>
<div>
<table>
<table class='data-table'>
<tr>
<th>Id</th>
<th>Started</th>
@@ -1,7 +1,7 @@
<h1>{{title}}</h1>
<div>
{{#with session}}
<table>
{{#with session}}<h1 class='heading'>Session {{_id}}</h1>
<div>
<table class='data-table'>
<tr>
<th>Quest</th>
<td>{{quest}}</td>
@@ -32,9 +32,9 @@
</tr>
</table>
<h2>Commands</h2>
<h2 class='heading'>Commands</h2>
<table>
<table class='data-table'>
<tr>
<th>Stage</th>
<th>PWD</th>
@@ -54,5 +54,5 @@
</tr>
{{/each}}
</table>
{{/with}}
</div>
</div>{{/with}}
+13 -7
View File
@@ -1,10 +1,14 @@
<h1>Sessions</h1>
<div class='pagination'>
<a href='/sessions?order=asc'>Ascending</a>
<a href='/sessions?order=desc'>Descending</a>
<h1 class='heading'>Sessions</h1>
<div class='sort'>
<a href='/sessions?order=asc'><div class='btn'>
<h3>Ascending</h3>
</div></a>
<a href='/sessions?order=desc'><div class='btn'>
<h3>Descending</h3>
</div></a>
</div>
<div>
<table>
<table class='data-table'>
<tr>
<th>User</th>
<th>Quest</th>
@@ -29,6 +33,8 @@
{{/each}}
</table>
</div>
<div class='pagination'>
<a href='/sessions?nextKey={{nextKey}}&order={{order}}'>Next</a>
<div class='pagination sort'>
<a href='/sessions?nextKey={{nextKey}}&order={{order}}'><div class='btn'>
<h3>Next</h3>
</div></a>
</div>
+14 -8
View File
@@ -1,10 +1,14 @@
<h1>Users List</h1>
<div class='pagination'>
<a href='/users?order=asc'>Ascending</a>
<a href='/users?order=desc'>Descending</a>
<h1 class='heading'>Users List</h1>
<div class='sort'>
<a href='/users?order=asc'><div class='btn'>
<h3>Ascending</h3>
</div></a>
<a href='/users?order=desc'><div class='btn'>
<h3>Descending</h3>
</div></a>
</div>
<div>
<table>
<table class='data-table'>
<tr>
<th>Username</th>
<th>Last Activity</th>
@@ -15,7 +19,7 @@
</tr>
{{#each users}}
<tr>
<td href='/users/{{_id}}'>{{username}}</td>
<td><a href='/users/{{_id}}'>{{username}}</a></td>
<td>{{lastActivityAt}}</td>
<td>{{sessionCount}}</td>
<td>{{email}}</td>
@@ -25,6 +29,8 @@
{{/each}}
</table>
</div>
<div class='pagination'>
<a href='/users?nextKey={{nextKey}}&order={{order}}'>Next</a>
<div class='pagination sort'>
<a href='/users?nextKey={{nextKey}}&order={{order}}'><div class='btn'>
<h3>Next</h3>
</div></a>
</div>
@@ -0,0 +1,21 @@
<h1 class='heading'>{{user}}'s Sessions History</h1>
<div>
<table class='data-table'>
<tr>
<th>Quest</th>
<th>Status</th>
<th>Created At</th>
<th>Used Time</th>
<th>Session</th>
</tr>
{{#each sessions}}
<tr>
<td>{{quest}}</td>
<td>{{status}}</td>
<td>{{createdAt}}</td>
<td>{{usedTime}}</td>
<td><a href='/sessions/{{_id}}'>Detail</a></td>
</tr>
{{/each}}
</table>
</div>
+10 -3
View File
@@ -1,3 +1,5 @@
import { z } from 'zod'
export const passwordPolicy = {
minLength: 8,
minNumbers: 1,
@@ -6,6 +8,11 @@ export const passwordPolicy = {
minSymbols: 0,
}
export default {
passwordPolicy,
}
export const getSessionsRequestSchema = z.object({
questId: z.string().optional(),
status: z.enum(['active', 'inactive', 'finished']).optional(),
limit: z.coerce.number().optional(),
order: z.enum(['asc', 'desc']).optional(),
})
export type GetSessionsRequest = z.infer<typeof getSessionsRequestSchema>
+3
View File
@@ -10,5 +10,8 @@
"scripts": {
"build": "tsc",
"dev": "tsc -w"
},
"dependencies": {
"zod": "^3.23.8"
}
}
+1 -1
View File
@@ -26,7 +26,7 @@ const api = axios.create({
async function readOrNone(file) {
try {
return await fs.readFile(file, 'utf8')
} catch (err) {
} catch (_) {
return ''
}
}
+2 -2
View File
@@ -25,7 +25,7 @@ async function collectFilesInfo(inputPath, level = 0, hiddenFiles = false) {
)
)
files.push(...result.flat())
} catch (err) {
} catch (_) {
// ignore
}
}
@@ -41,7 +41,7 @@ async function discoverFiles(argv) {
.map((p) => collectFilesInfo(p, 0, argv.a || argv.all))
)
return { discover: result.flat() }
} catch (err) {
} catch (_) {
return {}
}
}
+6
View File
@@ -28,6 +28,7 @@ export interface IUser {
socialLogins: Map<string, ISocialLogin>
createdAt: Date
updatedAt: Date
isGuest: boolean
}
export const User = model<IUser>(
@@ -51,6 +52,11 @@ export const User = model<IUser>(
default: {},
required: true,
},
isGuest: {
type: Boolean,
default: false,
required: true,
},
},
{
timestamps: true,
+3 -3
View File
@@ -5,12 +5,12 @@ interface Node {
export default class DAG {
private nodes = new Map()
private edges = new Set()
private edges = new Set<[string, string]>()
private layers: number[] = []
constructor(nodes: Node[]) {
this.nodes = new Map(nodes.map((node) => [node._id, node]))
this.edges = new Set()
this.edges = new Set<[string, string]>()
this.nodes.forEach((_, id) => {
this.setLayer(id)
this.addEdges(id)
@@ -42,7 +42,7 @@ export default class DAG {
if (!node) {
throw new Error(`Node ${id} not found`)
}
return this.layers[node.layer - 1]
return this.layers[node.layer - 1] || 0
}
private setLayer(id: string) {