Database migration to support authentication

This commit is contained in:
Paweł Malak
2021-10-18 22:32:00 +02:00
parent 22cbc827c5
commit 4da15ff105
6 changed files with 85 additions and 1 deletions

View File

@@ -1,4 +1,4 @@
import { TagModel, SnippetModel, Snippet_TagModel } from '../models';
import { TagModel, SnippetModel, Snippet_TagModel, UserModel } from '../models';
export const associateModels = async () => {
TagModel.belongsToMany(SnippetModel, {
@@ -12,4 +12,14 @@ export const associateModels = async () => {
foreignKey: 'snippet_id',
as: 'tags'
});
UserModel.hasMany(SnippetModel, {
foreignKey: 'createdBy',
as: 'snippets'
});
SnippetModel.belongsTo(UserModel, {
foreignKey: 'createdBy',
as: 'user'
});
};

View File

@@ -0,0 +1,50 @@
import { DataTypes, QueryInterface } from 'sequelize';
import { createAdmin } from '../../utils';
const { STRING, INTEGER, DATE } = DataTypes;
export const up = async (queryInterface: QueryInterface): Promise<void> => {
await queryInterface.createTable('users', {
id: {
type: INTEGER,
allowNull: false,
primaryKey: true,
autoIncrement: true
},
email: {
type: STRING,
allowNull: false,
unique: true
},
password: {
type: STRING,
allowNull: false
},
role: {
type: STRING,
allowNull: true,
defaultValue: 'user'
},
createdAt: {
type: DATE,
allowNull: false
},
updatedAt: {
type: DATE,
allowNull: false
}
});
await queryInterface.addColumn('snippets', 'createdBy', {
type: INTEGER,
allowNull: false,
defaultValue: 1
});
await createAdmin('admin@local.com', 'snippet-admin');
};
export const down = async (queryInterface: QueryInterface): Promise<void> => {
await queryInterface.dropTable('users');
await queryInterface.removeColumn('snippets', 'createdBy');
};

View File

@@ -43,6 +43,11 @@ export const SnippetModel = sequelize.define<SnippetInstance>(
allowNull: true,
defaultValue: 0
},
createdBy: {
type: INTEGER,
allowNull: false,
defaultValue: 1
},
createdAt: {
type: DATE
},

View File

@@ -9,6 +9,7 @@ export interface Snippet extends Model {
docs: string;
isPinned: number;
tags?: { name: string }[];
createdBy: number;
}
export interface SnippetCreationAttributes

14
src/utils/createAdmin.ts Normal file
View File

@@ -0,0 +1,14 @@
import { UserModel } from '../models';
import { hashPassword } from '.';
export const createAdmin = async (
email: string,
password: string
): Promise<void> => {
const passwordHash = await hashPassword(password);
await UserModel.create({
email,
password: passwordHash,
role: 'admin'
});
};

View File

@@ -3,3 +3,7 @@ export * from './ErrorResponse';
export * from './tagParser';
export * from './getTags';
export * from './createTags';
export * from './createAdmin';
export * from './hashPassword';
export * from './signToken';
export * from './createAdmin';