feat (server): user scopes
This commit is contained in:
@@ -1,8 +1,11 @@
|
||||
import { Table, Column, Model, CreatedAt, DataType, Scopes} from 'sequelize-typescript';
|
||||
import { Table, Column, Model, CreatedAt, DataType, Scopes, DefaultScope} from 'sequelize-typescript';
|
||||
|
||||
@Scopes(() => ({
|
||||
withoutPassword: {
|
||||
@DefaultScope(() => ({
|
||||
attributes:{ exclude: ['password']}
|
||||
}))
|
||||
@Scopes(() => ({
|
||||
withPassword: {
|
||||
attributes: {include: ['password']}
|
||||
}
|
||||
}))
|
||||
@Table
|
||||
|
||||
@@ -2,6 +2,7 @@ import { compare } from 'bcrypt';
|
||||
import express from 'express';
|
||||
import { logger } from '../util/logging';
|
||||
import User from '../model/user';
|
||||
import { Scope } from '../util/db';
|
||||
import { getJWT, requireAuth } from '../util/auth';
|
||||
import { LoginRequest } from '../messages/Login';
|
||||
import { GenericMessage as Msg } from '../messages/Message';
|
||||
@@ -11,7 +12,7 @@ const router = express.Router();
|
||||
router.post('/login', async (req, res) => {
|
||||
try {
|
||||
const data : LoginRequest = req.body;
|
||||
const user = await User.findOne({where: { userID: data.username}});
|
||||
const user = await User.scope(Scope.withPassword).findOne({where: { userID: data.username}});
|
||||
if (!user) return res.status(401).json(new Msg('Invalid credentials'));
|
||||
const isMatch = await compare(data.password, user.password);
|
||||
if (!isMatch) return res.status(401).json(new Msg('Invalid credentials'));
|
||||
|
||||
@@ -3,6 +3,11 @@ import { logger } from './logging';
|
||||
import User from '../model/user';
|
||||
import Transaction from '../model/transaction';
|
||||
|
||||
enum Scope{
|
||||
// for User
|
||||
withPassword = 'withPassword',
|
||||
}
|
||||
|
||||
// Initialize Sequelize
|
||||
const db = new Sequelize({
|
||||
dialect: 'postgres',
|
||||
@@ -28,4 +33,4 @@ async function testConnection() {
|
||||
}
|
||||
|
||||
// Export Sequelize instance and models
|
||||
export { logger, db, testConnection };
|
||||
export { logger, db, testConnection, Scope };
|
||||
|
||||
Reference in New Issue
Block a user