Проблема при подключении nodejs к MYSQL, который подключен mongodb с аутентификацией JWT
Я использую nodejs mongodb jwt, основанную на редуксе аутентификации. Теперь я преобразую его в 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`
введите описание изображения здесь
Плз см. Экран вывода ниже изображения