refactor utils

This commit is contained in:
wancat committed 2024-02-19 18:05:00 +08:00
1 parent 9509bbc355
commit d6c95cea4a
13 files changed
+126 -31

No files matched your search

@@ -1,9 +1,22 @@
import { User } from '@linux-odyssey/models'
import type { Profile } from 'passport'
import type { VerifyCallback } from 'passport-oauth2'
export default async function oauthVerify(provider, profile, query, cb) {
export type SocialLogin = {
provider: string
id: string
displayName: string
}
export default async function oauthVerify(
provider: string,
profile: Profile,
query: Record<string, any>,
cb: VerifyCallback
) {
process.nextTick(async () => {
try {
const email = profile.emails[0]?.value
const email = profile.emails ? profile.emails[0]?.value : undefined
if (!email) {
return cb(new Error('No email found'))
}
@@ -26,7 +39,9 @@ export default async function oauthVerify(provider, profile, query, cb) {
return cb(null, user)
} catch (err) {
return cb(err)
return cb(
err instanceof Error ? err : new Error('An unknown error occurred')
)
}
})
}
@@ -5,17 +5,18 @@ import { get } from './utils/env.js'
// Import dotenv and load ../.env
dotenv.config({ path: '../.env' })
function getTrustProxies(key) {
if (!process.env[key]) {
function getTrustProxies(key: string): string[] {
const value = process.env[key]
if (!value) {
return []
}
return process.env[key]
return value
.split(',')
.map((p) => validator.trim(p))
.filter((p) => validator.isIPRange(p) || validator.isIP(p))
}
function getUrl(key) {
function getUrl(key: string): string {
const url = get(key, '')
if (validator.isURL(url)) {
return validator.trim(url)
@@ -50,8 +51,8 @@ function createConfig() {
clientSecret: get('GITHUB_CLIENT_SECRET', ''),
},
trustedProxies: getTrustProxies('TRUSTED_PROXIES'),
surveyUrl: getUrl('SURVEY_URL', ''),
bugReportUrl: getUrl('BUG_REPORT_URL', ''),
surveyUrl: getUrl('SURVEY_URL'),
bugReportUrl: getUrl('BUG_REPORT_URL'),
docker: {
network: get('DOCKER_NETWORK', 'host'),
@@ -74,7 +75,7 @@ function createConfig() {
const config = createConfig()
export function getQuestImage(id) {
export function getQuestImage(id: string): string {
return `${config.docker.imagePrefix}${id}`
}
@@ -1,7 +1,12 @@
import { User, UserProfile } from '@linux-odyssey/models'
import { SocialLogin } from '../auth/oauthVerify.js'
import { hashPassword } from '../utils/auth.js'
export async function createUser(username, email, { password, socialLogin }) {
export async function createUser(
username: string,
email: string,
{ password, socialLogin }: { password?: string; socialLogin?: SocialLogin }
) {
const user = new User({
username,
email,
@@ -2,11 +2,11 @@ import jwt from 'jsonwebtoken'
import bcrypt from 'bcrypt'
import config from '../config.js'
export function hashPassword(password) {
export function hashPassword(password: string): Promise<string> {
return bcrypt.hash(password, 10)
}
export function genJWT(payload) {
export function genJWT(payload: any): Promise<string> {
return new Promise((resolve, reject) => {
jwt.sign(
payload,
@@ -15,6 +15,8 @@ export function genJWT(payload) {
(err, token) => {
if (err) {
reject(err)
} else if (token === undefined) {
reject(new Error('Token is undefined'))
} else {
resolve(token)
}
@@ -23,7 +25,7 @@ export function genJWT(payload) {
})
}
export function verifyJWT(token) {
export function verifyJWT(token: string): Promise<any> {
return new Promise((resolve, reject) => {
jwt.verify(token, config.secret, (err, decoded) => {
if (err) {
-13
View File
@@ -1,13 +0,0 @@
import crypto from 'crypto'
export function get(key, defaultValue) {
const value = process.env[key]
if (value != null) {
return value
}
return defaultValue
}
export function genSecret() {
return crypto.randomUUID()
}
+10
View File
@@ -0,0 +1,10 @@
import crypto from 'crypto'
export function get<T>(key: string, defaultValue: T): T {
const value = process.env[key]
return value !== undefined ? (value as unknown as T) : defaultValue
}
export function genSecret() {
return crypto.randomUUID()
}
File renamed without changes.
@@ -8,7 +8,10 @@ import logger from './logger.js'
const questDirectory = path.join(process.cwd(), '..', 'quests')
class QuestValidationError extends Error {
constructor(message, questId, error) {
questId: string
error: any
constructor(message: string, questId: string, error: any) {
super(message)
this.name = 'QuestValidationError'
this.questId = questId
@@ -16,7 +19,10 @@ class QuestValidationError extends Error {
}
}
async function mapQuests(callback) {
// eslint-disable-next-line no-unused-vars
type QuestCallback = (id: string, questPath: string) => Promise<any>
async function mapQuests(callback: QuestCallback) {
const questNames = await fs.readdir(questDirectory, {
withFileTypes: true,
})
@@ -44,7 +50,7 @@ export async function loadAndUpdateQuests() {
return mapQuests(async (id, questPath) => {
const files = await fs.readdir(questPath)
if (!files.includes('game.yml')) {
throw new QuestValidationError(`Missing game.yml`, id)
throw new QuestValidationError(`Missing game.yml`, id, null)
}
try {
File renamed without changes.