99 lines
2.3 KiB
TypeScript
99 lines
2.3 KiB
TypeScript
import {
|
|
DataTypes,
|
|
InferAttributes,
|
|
InferCreationAttributes,
|
|
Model,
|
|
NonAttribute,
|
|
Sequelize,
|
|
} from "sequelize";
|
|
import { TabContextCreationAttributes, TabContextModel } from "./tab-context.model";
|
|
|
|
export type AuthUserCreationAttributes = InferCreationAttributes<
|
|
AuthUserModel,
|
|
{ omit: "contexts" }
|
|
> & {
|
|
contexts: TabContextCreationAttributes[];
|
|
};
|
|
|
|
export class AuthUserModel extends Model<
|
|
InferAttributes<AuthUserModel>,
|
|
InferCreationAttributes<AuthUserModel>
|
|
> {
|
|
// To avoid table creation
|
|
/*static async sync(): Promise<any> {
|
|
return Promise.resolve();
|
|
}*/
|
|
|
|
static associate(connection: Sequelize) {
|
|
const { TabContextModel } = connection.models;
|
|
|
|
AuthUserModel.hasMany(TabContextModel, {
|
|
as: "contexts",
|
|
foreignKey: "user_id",
|
|
onDelete: "CASCADE",
|
|
});
|
|
}
|
|
declare id: string;
|
|
declare username: string;
|
|
declare email: string;
|
|
declare hash_password: string;
|
|
declare roles: string[];
|
|
|
|
declare contexts: NonAttribute<TabContextModel[]>;
|
|
}
|
|
|
|
export default (sequelize: Sequelize) => {
|
|
AuthUserModel.init(
|
|
{
|
|
id: {
|
|
type: DataTypes.UUID,
|
|
primaryKey: true,
|
|
},
|
|
username: {
|
|
type: DataTypes.STRING,
|
|
allowNull: false,
|
|
},
|
|
email: {
|
|
type: DataTypes.STRING,
|
|
allowNull: false,
|
|
},
|
|
hash_password: {
|
|
type: DataTypes.STRING,
|
|
allowNull: false,
|
|
},
|
|
roles: {
|
|
type: DataTypes.STRING,
|
|
allowNull: false,
|
|
defaultValue: "USER",
|
|
get(this: AuthUserModel): string[] {
|
|
const rawValue = this.getDataValue("roles") as any;
|
|
return String(rawValue).split(";");
|
|
},
|
|
set(this: AuthUserModel, value: string[]) {
|
|
const rawValue = value.join(";") as any;
|
|
this.setDataValue("roles", rawValue);
|
|
},
|
|
},
|
|
},
|
|
{
|
|
sequelize,
|
|
tableName: "users",
|
|
paranoid: true, // softs deletes
|
|
timestamps: true,
|
|
|
|
createdAt: "created_at",
|
|
updatedAt: "updated_at",
|
|
deletedAt: "deleted_at",
|
|
|
|
indexes: [{ name: "email_idx", fields: ["email"], unique: true }],
|
|
|
|
whereMergeStrategy: "and", // <- cómo tratar el merge de un scope
|
|
|
|
defaultScope: {},
|
|
|
|
scopes: {},
|
|
}
|
|
);
|
|
return AuthUserModel;
|
|
};
|