Last active
November 14, 2019 00:12
-
-
Save chewtoys/64bb9e74d99dfbcd025cfd816b700483 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // ############################### | |
| import Sequelize from 'sequelize'; | |
| import User from '../models/User'; | |
| import Test from '../models/Test'; | |
| import databaseConfig from '../database'; | |
| const models = [User, Test]; | |
| class Database { | |
| constructor() { | |
| this.init(); | |
| } | |
| init() { | |
| this.connection = new Sequelize(databaseConfig); | |
| models.map(model => model.init(this.connection)); | |
| } | |
| } | |
| export default new Database(); | |
| // ############################### | |
| import Sequelize, { Model } from 'sequelize'; | |
| import bcrypt from 'bcryptjs'; | |
| class User extends Model { | |
| static init(sequelize) { | |
| super.init( | |
| { | |
| name: Sequelize.STRING, | |
| email: Sequelize.STRING, | |
| password_hash: Sequelize.STRING, | |
| }, | |
| { | |
| sequelize, | |
| } | |
| ); | |
| return this; | |
| } | |
| // password_hash: bcrypt.hashSync('123456', 8), | |
| checkPassword(password) { | |
| return bcrypt.compare(password, this.password_hash); | |
| } | |
| } | |
| export default User; | |
| // ############################### | |
| module.exports = { | |
| dialect: 'postgres', | |
| host: 'localhost', | |
| username: 'postgres', | |
| password: 'docker', | |
| database: 'test', | |
| define: { | |
| timestamps: true, | |
| underscored: true, | |
| underscoredAll: true, | |
| }, | |
| }; | |
| // ############################### | |
| const { email, password } = req.body; | |
| const user = await User.findOne({ where: { email } }); | |
| if (!user) { | |
| return res.status(401).json({ error: 'User not found' }); | |
| } | |
| if (!(await user.checkPassword(password))) { | |
| return res.status(401).json({ error: 'Password does not match' }); | |
| } | |
| const { id, name } = user; | |
| return res.json({ | |
| user: { | |
| id, | |
| name, | |
| email, | |
| }, | |
| }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment