feat: add register-guest api

This commit is contained in:
wancat authored and Chen, Tai-Lin committed 2024-07-03 00:34:32 +08:00
1 parent 715352f77c
commit 9d1bed7543
4 files changed
+63 -3

No files matched your search

+25 -1
View File
@@ -1,7 +1,7 @@
import type { Request, Response, NextFunction, Express } from 'express'
import { matchedData } from 'express-validator'
import { genJWT } from '../../utils/auth.js'
import { createUser } from '../../models/userManager.js'
import { createUser, createGuestUser } from '../../models/userManager.js'
import { asyncHandler } from '../../middleware/error.js'
import logger from '../../utils/logger.js'
@@ -39,6 +39,30 @@ export const register = asyncHandler(
}
)
export const registerGuest = asyncHandler(
async (req: Request, res: Response) => {
const user = await createGuestUser()
req.login(
{
id: user.id,
username: user.username,
email: user.email,
},
(err) => {
if (err) {
res.status(500).json({
message: 'error logging in',
})
return
}
res.status(201).json({
message: 'user created',
})
}
)
}
)
export function logout(req: Request, res: Response) {
req.logout((err) => {
if (err) {
+3
View File
@@ -9,6 +9,7 @@ import {
logout,
registerFromSession,
socialLoginHandler,
registerGuest,
} from '../controllers/authController.js'
import {
checkUsernameValidators,
@@ -32,6 +33,8 @@ router.post(
router.post('/register', authenticateRateLimit, registerValidators, register)
router.post('/register-guest', authenticateRateLimit, registerGuest)
router.post('/logout', logout)
router.get(
+17
View File
@@ -1,4 +1,5 @@
import { Express } from 'express'
import { format } from 'date-fns'
import { User, UserProfile } from '@linux-odyssey/models'
import { hashPassword } from '../utils/auth.js'
@@ -31,6 +32,22 @@ export async function createUser(
return user
}
export async function createGuestUser() {
const username = `guest_${format(new Date(), 'yyyyMMddHHmmss')}`
const user = new User({
username,
email: `${username}@example.com`,
})
await user.save()
const profile = new UserProfile({
user,
})
await profile.save()
return user
}
export function leaderboard() {
return UserProfile.aggregate([
{
+18 -2
View File
@@ -1,14 +1,14 @@
openapi: 3.0.0
servers:
- url: /api/v1
- url: https://odyssey.wancat.cc/api/v1
- url: https://linuxodyssey.xyz/api/v1
- url: http://localhost:3000/api/v1
info:
description: Linux Odyssey API
version: '1.0.0'
title: Session API
contact:
email: wancat@wancat.cc
email: contact@linuxodyssey.xyz
license:
name: Apache 2.0
url: 'http://www.apache.org/licenses/LICENSE-2.0.html'
@@ -233,6 +233,22 @@ paths:
type: string
example: connect.sid=s%3Aq1Z; Path=/; HttpOnly; SameSite=Strict; Secure
/auth/register-guest:
post:
summary: Register a new guest user
responses:
201:
description: User created
headers:
Set-Cookie:
schema:
type: string
example: connect.sid=s%3Aq1Z; Path=/; HttpOnly; SameSite=Strict; Secure
content:
application/json:
schema:
$ref: '#/components/schemas/User'
/auth/login:
post:
summary: Log in a user