我一直在使用Validatorjs进行项目研究,以检查用户的电子邮件是否对应于给定的电子邮件格式。如果匹配,我想将属性(角色)设置为admin。以下是一些代码示例
客户端
注册
import React, { Fragment, useState } from 'react'
import { connect } from 'react-redux'
import { setAlert } from '../../actions/alert'
import { register } from '../../actions/auth'
import Alert from './Alert'
import PropTypes from 'prop-types'
import { NavLink, Button, Modal, ModalHeader, ModalBody, ModalFooter, Form, Input } from 'reactstrap'
import { Redirect } from 'react-router-dom'
import contains from 'validator/lib/contains'
const Register = ({ setAlert, register, isAuthenticated }) => {
const [
formData,
setFormData,
] = useState({
name: '',
email: '',
password: '',
password2: '',
phone: '',
address: '',
})
const [
Role,
setRole,
] = useState({
role: 'user',
})
const { role } = Role
const [
modal,
setModal,
] = useState(false)
const toggle = () => setModal(!modal)
const { name, email, password, password2, phone, address } = formData
const handleChange = (e) => {
setFormData({
...formData,
[e.target.name]: e.target.value,
})
}
const onSubmit = (e) => {
e.preventDefault()
if (password !== password2) {
setAlert('Password do not match', 'danger')
}
if (contains(email, 'admin-') && contains(password, 'admin-')) {
setRole({
...Role,
role: 'admin',
})
}
register({ name, email, password, phone, address, role })
if (isAuthenticated) {
setModal(!modal)
setFormData({
name: '',
email: '',
password: '',
password2: '',
phone: '',
address: '',
role: '',
})
return <Redirect to='/cars' />
}
}
return (
<Fragment>
<NavLink color='danger' onClick={toggle}>
Register
</NavLink>
<Modal isOpen={modal} toggle={toggle} centered>
<ModalHeader toggle={toggle}>Register</ModalHeader>
<Alert>
<Alert />
</Alert>
<ModalBody>
<div className=' '>
<Form className=''>
<Input
type='name'
placeholder='Name'
name='name'
onChange={handleChange}
className='mb-4 form-control-lg'
value={name}
/>
<Input
type='email'
placeholder='Email'
name='email'
onChange={handleChange}
className='mb-4 form-control-lg'
value={email}
/>
<Input
type='password'
placeholder='Password'
name='password'
minLength='4'
onChange={handleChange}
className='mb-4 form-control-lg'
value={password}
/>
<Input
type='password'
placeholder='Confirm Password'
name='password2'
minLength='4'
onChange={handleChange}
className='mb-4 form-control-lg'
value={password2}
/>
<Input
type='phone'
placeholder='Phone'
name='phone'
onChange={handleChange}
className='mb-4 form-control-lg'
value={phone}
/>
<Input
type='address'
placeholder='Address'
name='address'
onChange={handleChange}
className='mb-4 form-control-lg'
value={address}
/>
</Form>
</div>
</ModalBody>
<ModalFooter>
<Button color='primary' onClick={onSubmit}>
Submit
</Button>
</ModalFooter>
</Modal>
</Fragment>
)
}
Register.propTypes = {
setAlert: PropTypes.func.isRequired,
register: PropTypes.func.isRequired,
isAuthenticated: PropTypes.bool,
}
const mapStateToProps = (state) => ({
isAuthenticated: state.auth.isAuthenticated,
})
export default connect(mapStateToProps, { setAlert, register })(Register)
以上,我尝试使用Validator-js库来验证电子邮件和密码,然后传递给 register 操作
服务器端代码
const express = require('express');
const router = express.Router();
const {
check,
validationResult
} = require('express-validator');
const User = require('../models/User');
const bcrypt = require('bcrypt');
const jwt = require('jsonwebtoken')
const gravatar = require('gravatar');
const Admin = require('../models/Admin');
//user registration
router.post(
'/register',
[
check('name', 'Name is required').not().isEmpty(),
check('email', 'Enter a valid email address').isEmail(),
check('password', 'password must be more than 4 characters and must be alphanumeric').isLength({
min: 4
}),
check('phone', 'must be a number').isLength({
max: 11
}).isNumeric(),
check('address', 'address is required').not().isEmpty()
],
async (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({
errors: errors.array()
})
}
const {
email,
password,
name,
phone,
address,
role
} = req.body;
try {
if (role === 'admin') {
let admin = await Admin.findOne({
email
})
if (admin) {
return res.status(400).json({
errors: [{
msg: 'Invalid credentials'
}]
});
}
admin = new Admin({
name,
email,
password,
phone,
role
});
const salt = await bcrypt.genSalt(10);
admin.password = await bcrypt.hash(password, salt);
await admin.save();
const payload = {
admin: {
id: admin.id
}
}
//jsonwebtoken hookup
jwt.sign(payload, process.env.JWT_SECRET, {
expiresIn: 360000
}, (err, token) => {
if (err) throw err;
res.json({
token
});
});
} else {
let user = await User.findOne({
email
});
if (user) {
return res.status(400).json({
errors: [{
msg: 'User already exists'
}]
});
}
const avatar = gravatar.url(email, {
s: '200',
r: 'pg',
d: 'mm'
})
user = new User({
name,
email,
password,
phone,
avatar,
address,
role
});
const salt = await bcrypt.genSalt(10);
user.password = await bcrypt.hash(password, salt);
await user.save();
const payload = {
user: {
id: user.id
}
}
//jsonwebtoken hookup
jwt.sign(payload, process.env.JWT_SECRET, {
expiresIn: 360000
}, (err, token) => {
if (err) throw err;
res.json({
token
});
});
}
} catch (error) {
console.error(error.message);
res.status(500).json('Server Error')
}
}
);
现在的问题是,即使满足条件,我也会不断获得“用户”。
我做错了什么?