implement auth routes, add user migration
This commit is contained in:
1 parent
0b646ee64f
commit
11ff99613a
22 files changed
+828
-63
No files matched your search
@@ -1,35 +0,0 @@
|
||||
import mongoose from "mongoose";
|
||||
const InviteTokenSchema = mongoose.Schema(
|
||||
{
|
||||
email: {
|
||||
type: String,
|
||||
required: true,
|
||||
unique: true,
|
||||
},
|
||||
teamId: {
|
||||
type: mongoose.Schema.Types.ObjectId,
|
||||
ref: "Team",
|
||||
immutable: true,
|
||||
required: true,
|
||||
},
|
||||
role: {
|
||||
type: Array,
|
||||
required: true,
|
||||
default: ["user"],
|
||||
},
|
||||
token: {
|
||||
type: String,
|
||||
required: true,
|
||||
},
|
||||
expiry: {
|
||||
type: Date,
|
||||
default: Date.now,
|
||||
expires: 3600,
|
||||
},
|
||||
},
|
||||
{
|
||||
timestamps: true,
|
||||
}
|
||||
);
|
||||
|
||||
export default mongoose.model("InviteToken", InviteTokenSchema);
|
||||
Executable
+68
@@ -0,0 +1,68 @@
|
||||
import mongoose, { Schema, Document, Types } from "mongoose";
|
||||
|
||||
export interface IInvite extends Document {
|
||||
// v1
|
||||
_id: Types.ObjectId;
|
||||
email: string;
|
||||
teamId: Types.ObjectId;
|
||||
role: string[];
|
||||
token: string;
|
||||
expiry: Date;
|
||||
createdAt: Date;
|
||||
updatedAt: Date;
|
||||
|
||||
// v2
|
||||
tokenHash: string;
|
||||
roles: Types.ObjectId[];
|
||||
createdBy: Types.ObjectId;
|
||||
updatedBy: Types.ObjectId;
|
||||
}
|
||||
|
||||
const InviteSchema = new Schema<IInvite>(
|
||||
{
|
||||
email: {
|
||||
type: String,
|
||||
required: true,
|
||||
unique: true,
|
||||
trim: true,
|
||||
lowercase: true,
|
||||
},
|
||||
teamId: {
|
||||
type: mongoose.Schema.Types.ObjectId,
|
||||
ref: "Team",
|
||||
immutable: true,
|
||||
required: true,
|
||||
},
|
||||
role: {
|
||||
type: [String],
|
||||
required: true,
|
||||
default: ["user"],
|
||||
},
|
||||
token: {
|
||||
type: String,
|
||||
required: true,
|
||||
},
|
||||
expiry: {
|
||||
type: Date,
|
||||
default: Date.now,
|
||||
expires: 3600,
|
||||
},
|
||||
|
||||
// v2
|
||||
roles: [
|
||||
{
|
||||
type: Schema.Types.ObjectId,
|
||||
ref: "Role",
|
||||
required: true,
|
||||
},
|
||||
],
|
||||
tokenHash: { type: String, required: true, unique: true },
|
||||
createdBy: { type: Schema.Types.ObjectId, ref: "User", required: true },
|
||||
updatedBy: { type: Schema.Types.ObjectId, ref: "User", required: true },
|
||||
},
|
||||
{
|
||||
timestamps: true,
|
||||
}
|
||||
);
|
||||
|
||||
export const Invite = mongoose.model<IInvite>("Invite", InviteSchema);
|
||||
@@ -0,0 +1,45 @@
|
||||
import mongoose, { Schema, Document, Types } from "mongoose";
|
||||
|
||||
export interface IRole extends Document {
|
||||
_id: Types.ObjectId;
|
||||
name: string;
|
||||
description?: string;
|
||||
permissions: string[];
|
||||
isActive: boolean;
|
||||
createdAt: Date;
|
||||
updatedAt: Date;
|
||||
}
|
||||
|
||||
const roleSchema = new Schema<IRole>(
|
||||
{
|
||||
name: {
|
||||
type: String,
|
||||
required: true,
|
||||
trim: true,
|
||||
maxlength: 50,
|
||||
},
|
||||
description: {
|
||||
type: String,
|
||||
trim: true,
|
||||
maxlength: 200,
|
||||
},
|
||||
|
||||
permissions: [
|
||||
{
|
||||
type: String,
|
||||
required: true,
|
||||
},
|
||||
],
|
||||
isActive: {
|
||||
type: Boolean,
|
||||
default: true,
|
||||
},
|
||||
},
|
||||
{
|
||||
timestamps: true,
|
||||
}
|
||||
);
|
||||
|
||||
roleSchema.index({ name: 1 }, { unique: true });
|
||||
|
||||
export const Role = mongoose.model<IRole>("Role", roleSchema);
|
||||
@@ -1,11 +1,47 @@
|
||||
import mongoose from "mongoose";
|
||||
import bcrypt from "bcryptjs";
|
||||
import logger from "../../utils/logger.js";
|
||||
import Monitor from "./Monitor.js";
|
||||
import Team from "./Team.js";
|
||||
import Notification from "./Notification.js";
|
||||
import mongoose, { Schema, Document, Types } from "mongoose";
|
||||
|
||||
const UserSchema = mongoose.Schema(
|
||||
import bcrypt from "bcryptjs";
|
||||
import logger from "../../../utils/logger.js";
|
||||
import Monitor from "../Monitor.js";
|
||||
import Team from "../Team.js";
|
||||
import Notification from "../Notification.js";
|
||||
import { subscribe } from "diagnostics_channel";
|
||||
|
||||
export const RoleTypes = ["user", "admin", "superadmin", "demo"] as const;
|
||||
export type RoleType = (typeof RoleTypes)[number];
|
||||
|
||||
export interface ITokenizedUser {
|
||||
sub: string;
|
||||
roles: string[];
|
||||
}
|
||||
|
||||
export interface IUser extends Document {
|
||||
// V1
|
||||
_id: Types.ObjectId;
|
||||
firstName: string;
|
||||
lastName: string;
|
||||
email: string;
|
||||
password: string;
|
||||
avatarImage: string;
|
||||
profileImage: {
|
||||
data: Buffer;
|
||||
contentType: string;
|
||||
};
|
||||
isActive: boolean;
|
||||
isVerified: boolean;
|
||||
role?: RoleType[];
|
||||
teamId: Types.ObjectId;
|
||||
checkTTL: number;
|
||||
createdAt: Date;
|
||||
updatedAt: Date;
|
||||
comparePassword: (submittedPassword: string) => Promise<boolean>;
|
||||
// V2
|
||||
roles: Types.ObjectId[];
|
||||
lastLoginAt?: Date;
|
||||
version: number;
|
||||
}
|
||||
|
||||
const UserSchema = new Schema<IUser>(
|
||||
{
|
||||
firstName: {
|
||||
type: String,
|
||||
@@ -22,7 +58,7 @@ const UserSchema = mongoose.Schema(
|
||||
},
|
||||
password: {
|
||||
type: String,
|
||||
required: true,
|
||||
required: false,
|
||||
},
|
||||
avatarImage: {
|
||||
type: String,
|
||||
@@ -41,8 +77,8 @@ const UserSchema = mongoose.Schema(
|
||||
},
|
||||
role: {
|
||||
type: [String],
|
||||
default: "user",
|
||||
enum: ["user", "admin", "superadmin", "demo"],
|
||||
default: ["user"],
|
||||
enum: RoleTypes,
|
||||
},
|
||||
teamId: {
|
||||
type: mongoose.Schema.Types.ObjectId,
|
||||
@@ -52,6 +88,22 @@ const UserSchema = mongoose.Schema(
|
||||
checkTTL: {
|
||||
type: Number,
|
||||
},
|
||||
|
||||
// v2
|
||||
roles: [
|
||||
{
|
||||
type: Schema.Types.ObjectId,
|
||||
ref: "Role",
|
||||
default: [],
|
||||
},
|
||||
],
|
||||
lastLoginAt: {
|
||||
type: Date,
|
||||
},
|
||||
version: {
|
||||
type: Number,
|
||||
default: 1,
|
||||
},
|
||||
},
|
||||
{
|
||||
timestamps: true,
|
||||
@@ -69,7 +121,7 @@ UserSchema.pre("save", function (next) {
|
||||
|
||||
UserSchema.pre("findOneAndUpdate", function (next) {
|
||||
const update = this.getUpdate();
|
||||
if ("password" in update) {
|
||||
if (update && "password" in update) {
|
||||
const salt = bcrypt.genSaltSync(10);
|
||||
update.password = bcrypt.hashSync(update.password, salt);
|
||||
}
|
||||
@@ -92,15 +144,13 @@ UserSchema.pre("findOneAndDelete", async function (next) {
|
||||
}
|
||||
next();
|
||||
} catch (error) {
|
||||
next(error);
|
||||
next(error as Error);
|
||||
}
|
||||
});
|
||||
|
||||
UserSchema.methods.comparePassword = async function (submittedPassword) {
|
||||
UserSchema.methods.comparePassword = async function (submittedPassword: string) {
|
||||
const res = await bcrypt.compare(submittedPassword, this.password);
|
||||
return res;
|
||||
};
|
||||
|
||||
const User = mongoose.model("User", UserSchema);
|
||||
|
||||
export default User;
|
||||
export const User = mongoose.model<IUser>("User", UserSchema);
|
||||
@@ -0,0 +1,7 @@
|
||||
export { User } from "./auth/User.js";
|
||||
export type { IUser } from "./auth/User.js";
|
||||
export type { ITokenizedUser } from "./auth/User.js";
|
||||
export { Role } from "./auth/Role.js";
|
||||
export type { IRole } from "./auth/Role.js";
|
||||
export type { IInvite } from "./auth/Invite.js";
|
||||
export { Invite } from "./auth/Invite.js";
|
||||
@@ -0,0 +1,49 @@
|
||||
import { User, Role } from "../../models/index.js";
|
||||
import { DEFAULT_ROLES } from "../../../service/v2/business/AuthService.js";
|
||||
async function migrateUsers() {
|
||||
try {
|
||||
// Create roles if they don't exist
|
||||
const roleCount = await Role.countDocuments();
|
||||
let roles;
|
||||
if (roleCount === 0) {
|
||||
const rolePromises = DEFAULT_ROLES.map((roleData) =>
|
||||
new Role({
|
||||
...roleData,
|
||||
}).save()
|
||||
);
|
||||
roles = await Promise.all(rolePromises);
|
||||
} else {
|
||||
roles = await Role.find();
|
||||
}
|
||||
|
||||
// Migrate users
|
||||
const users = await User.find({
|
||||
$or: [{ version: { $exists: false } }, { version: { $lt: 2 } }],
|
||||
});
|
||||
for (const user of users) {
|
||||
for (const role of user.role || []) {
|
||||
if (role === "superadmin") {
|
||||
const superAdminRole = roles.find((role) => role.name === "SuperAdmin");
|
||||
user.roles.push(superAdminRole!._id);
|
||||
}
|
||||
if (role === "admin") {
|
||||
const managerRole = roles.find((role) => role.name === "Manager");
|
||||
user.roles.push(managerRole!._id);
|
||||
}
|
||||
if (role === "user") {
|
||||
const memberRole = roles.find((role) => role.name === "Member");
|
||||
user.roles.push(memberRole!._id);
|
||||
}
|
||||
}
|
||||
user.version = 2;
|
||||
await user.save();
|
||||
}
|
||||
|
||||
return true;
|
||||
} catch (err) {
|
||||
console.error("Migration error:", err);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
export { migrateUsers };
|
||||
@@ -1,7 +1,9 @@
|
||||
import { migrateStatusWindowThreshold } from "./0001_migrateStatusWindowThreshold.js";
|
||||
import { migrateUsers } from "./0002_migrateUsers.js";
|
||||
|
||||
const runMigrations = async () => {
|
||||
await migrateStatusWindowThreshold();
|
||||
await migrateUsers();
|
||||
};
|
||||
|
||||
export { runMigrations };
|
||||
@@ -1,17 +1,17 @@
|
||||
const SERVICE_NAME = "inviteModule";
|
||||
|
||||
class InviteModule {
|
||||
constructor({ InviteToken, crypto, stringService }) {
|
||||
this.InviteToken = InviteToken;
|
||||
constructor({ Invite, crypto, stringService }) {
|
||||
this.Invite = Invite;
|
||||
this.crypto = crypto;
|
||||
this.stringService = stringService;
|
||||
}
|
||||
|
||||
requestInviteToken = async (userData) => {
|
||||
try {
|
||||
await this.InviteToken.deleteMany({ email: userData.email });
|
||||
await this.Invite.deleteMany({ email: userData.email });
|
||||
userData.token = this.crypto.randomBytes(32).toString("hex");
|
||||
let inviteToken = new this.InviteToken(userData);
|
||||
let inviteToken = new this.Invite(userData);
|
||||
await inviteToken.save();
|
||||
return inviteToken;
|
||||
} catch (error) {
|
||||
@@ -23,7 +23,7 @@ class InviteModule {
|
||||
|
||||
getInviteToken = async (token) => {
|
||||
try {
|
||||
const invite = await this.InviteToken.findOne({
|
||||
const invite = await this.Invite.findOne({
|
||||
token,
|
||||
});
|
||||
if (invite === null) {
|
||||
@@ -38,7 +38,7 @@ class InviteModule {
|
||||
};
|
||||
getInviteTokenAndDelete = async (token) => {
|
||||
try {
|
||||
const invite = await this.InviteToken.findOneAndDelete({
|
||||
const invite = await this.Invite.findOneAndDelete({
|
||||
token,
|
||||
});
|
||||
if (invite === null) {
|
||||
|
||||
Reference in new issue
Block a user