【发布时间】:2019-10-31 16:54:53
【问题描述】:
nodejs 连接 MYSQL 时出现问题,MYSQL 由 mongodb 通过 JWT 身份验证连接 AM 使用基于 nodejs mongodb jwt redux 的身份验证。现在正在将其转换为 mysql db,它显示电子邮件或密码不正确。我已经评论了 monodb 代码。我已经提到 ******** 用于 mongdb 配置。我想知道为什么它显示 mysql 本身的电子邮件或密码不正确。
loginAdmin.js
// Imports
import bcrypt from 'bcrypt'
// App Imports
import params from '../../../setup/config/params'
import validate from '../../../setup/helpers/validation'
import { logCreate } from '../../log/mutation'
//import User, { collection as user } from '../model' //Mongodb********
import authResponse from './authResponse'
import Sequelize from 'sequelize'
const sequelize = new Sequelize('dusminute', 'root', '', {
host: 'localhost',
//dialect: /* one of 'mysql' | 'mariadb' | 'postgres' | 'mssql' */
dialect: 'mysql'
});
sequelize
.authenticate()
.then(() => {
console.log('SETUP - Database Connected....');
})
.catch(err => {
console.error('Unable to connect to the database:', err);
});
const User = sequelize.define('user', {
// attributes
email: {
type: Sequelize.STRING,
allowNull: false
}
}, {
// options
});
// Login
export default async function loginAdmin({ params: { email, password }, translate }) {
var qry1,data1;
// Validation rules
const rules = [
{
data: { value: email },
check: 'email',
message: translate.t('user.messages.fields.email')
},
{
data: { value: password, length: params.user.rules.passwordMinLength },
check: 'lengthMin',
message: translate.t('user.messages.fields.passwordMinLength', { length: params.user.rules.passwordMinLength })
}
]
// Validate
try {
validate(rules)
} catch(error) {
throw new Error(error.message)
}
// Check if user exists with same email
try {
// Get user
//MongoDB *****************************
// const user = await User.findOne({ email })
// console.log(user)
// if(user) {
// const passwordsMatch = bcrypt.compare(password, user.password)
// if (passwordsMatch) {
// return {
// data: authResponse(user),
// message: translate.t('user.login.messages.success')
// }
// }
// }
User
.findOrCreate({where: {email: email,role:'admin'},attributes: ['role','isVerified','isPublished','isDeleted','id','email','password','name','mobile','image','createdAt','updatedAt']})
.then(([users, created]) => {
const user=users.get({plain: true})
console.log(user);
if(user) {
const passwordsMatch = bcrypt.compare(password, user.password)
if (passwordsMatch) {
data1= authResponse(user)
console.log(data1)
return {
data: authResponse(user),
message: translate.t('user.login.messages.success')
}
}
}
/*
findOrCreate returns an array containing the object that was found or created and a boolean that
will be true if a new object was created and false if not, like so:
[ {
username: 'sdepold',
job: 'Technical Lead JavaScript',
id: 1,
createdAt: Fri Mar 22 2013 21: 28: 34 GMT + 0100(CET),
updatedAt: Fri Mar 22 2013 21: 28: 34 GMT + 0100(CET)
},
true ]
In the example above, the array spread on line 3 divides the array into its 2 parts and passes them
as arguments to the callback function defined beginning at line 39, which treats them as "user" and
"created" in this case. (So "user" will be the object from index 0 of the returned array and
"created" will equal "true".)
*/
})
} catch (error) {
//await logCreate({ params: { payload: { method: 'userLogin', message: error.message } } })
throw new Error(translate.t('common.messages.error.server'))
}
throw new Error(translate.t('user.login.messages.error.wrongCredentials'))
}
authResponse.js
// Imports
import jwt from 'jsonwebtoken'
// App Imports
import { SECURITY_SECRET } from '../../../setup/config/env'
// Auth Response (token and user info)
export default function userAuthResponse(user) {
//user = user.toJSON() //mongodb***********************
//user=user[0];
delete user.password
//console.log(user.id)
return {
token: jwt.sign({ id: user._id }, SECURITY_SECRET),//mongodb********
//token: jwt.sign({ id: user.id }, SECURITY_SECRET),//mysql
user: user
}
}
query.js
export function login({ email, password }, isLoading = true) {
return async dispatch => {
dispatch({
type: LOGIN_REQUEST,
isLoading
})
dispatch({
type: MESSAGE_SHOW,
message: 'Please wait..'
})
try {
const { data } = await axios.post(API_URL, {
operation: 'userLoginAdmin',
params: { email, password }
})
let message = ''
if(data.success) {alert('success')
console.log(data.data.user)
dispatch(setUser(data.data.token, data.data.user))
setUserLocally(data.data.token, data.data.user)
message = `Login successful. Welcome back, ${ data.data.user.name }.`
} else {console.log(data)
message = data.message
}
dispatch({
type: MESSAGE_SHOW,
message
})
} catch(error) {
dispatch({
type: MESSAGE_SHOW,
message: 'Please try again.'
})
} finally {
dispatch({
type: LOGIN_RESPONSE
})
}
}
}`enter code here`
enter image description here 请看下图的输出屏幕
【问题讨论】:
-
邮箱或密码不正确。检查它们。
标签: mysql node.js reactjs mongodb jwt