mirror of
https://github.com/linux-odyssey/linux-odyssey.git
synced 2026-11-06 03:20:13 +08:00
feat: enhance checkUser api
* determine whether it's email or username, and if it exists
This commit is contained in:
1 parent
3aa27ae597
commit
f1510df13e
2 files changed
+37
-23
No files matched your search
@@ -1,5 +1,10 @@
|
||||
import User from '../../models/user.js'
|
||||
import { genJWT, hashPassword } from '../../utils/auth.js'
|
||||
import {
|
||||
genJWT,
|
||||
hashPassword,
|
||||
isValidEmail,
|
||||
isValidUsername,
|
||||
} from '../../utils/auth.js'
|
||||
|
||||
export async function issueToken(req, res) {
|
||||
const { user } = req
|
||||
@@ -13,16 +18,37 @@ export async function issueToken(req, res) {
|
||||
|
||||
export async function checkUsername(req, res) {
|
||||
const { username } = req.query
|
||||
const exists = await User.exists({ username })
|
||||
if (exists) {
|
||||
res.status(409).json({
|
||||
message: `"${username}" already exists`,
|
||||
})
|
||||
} else {
|
||||
if (isValidEmail(username)) {
|
||||
if (await User.exists({ email: username })) {
|
||||
res.status(409).json({
|
||||
type: 'email',
|
||||
message: `"${username}" already exists`,
|
||||
})
|
||||
return
|
||||
}
|
||||
res.status(200).json({
|
||||
type: 'email',
|
||||
message: `"${username}" is available`,
|
||||
})
|
||||
return
|
||||
}
|
||||
if (isValidUsername(username)) {
|
||||
if (await User.exists({ username })) {
|
||||
res.status(409).json({
|
||||
type: 'username',
|
||||
message: `"${username}" already exists`,
|
||||
})
|
||||
return
|
||||
}
|
||||
res.status(200).json({
|
||||
type: 'username',
|
||||
message: `"${username}" is available`,
|
||||
})
|
||||
return
|
||||
}
|
||||
res.status(400).json({
|
||||
message: 'invalid username or email',
|
||||
})
|
||||
}
|
||||
|
||||
export async function register(req, res, next) {
|
||||
|
||||
@@ -8,29 +8,17 @@ export function hashPassword(password) {
|
||||
}
|
||||
|
||||
export async function createTestUser() {
|
||||
let user = await User.findOne({ username: 'testUser' })
|
||||
let user = await User.findOne({ username: 'alex' })
|
||||
if (!user) {
|
||||
user = new User({
|
||||
username: 'testUser',
|
||||
email: 'test@example.com',
|
||||
username: 'alex',
|
||||
email: 'alex@example.com',
|
||||
})
|
||||
user.hashedPassword = await hashPassword('testPassword')
|
||||
user.hashedPassword = await hashPassword('123456')
|
||||
await user.save()
|
||||
}
|
||||
}
|
||||
|
||||
export async function defaultUser() {
|
||||
let user = await User.findOne({ username: 'defaultUser' })
|
||||
if (!user) {
|
||||
user = new User({
|
||||
username: 'defaultUser',
|
||||
email: 'jackson@example.com',
|
||||
})
|
||||
await user.save()
|
||||
}
|
||||
return user
|
||||
}
|
||||
|
||||
export function genJWT(payload) {
|
||||
return new Promise((resolve, reject) => {
|
||||
jwt.sign(
|
||||
|
||||
Reference in new issue
Block a user