fase(9): auth module with casl rbac and session management
This commit is contained in:
56
dist/modules/auth/application/commands/LoginCommand.js
vendored
Normal file
56
dist/modules/auth/application/commands/LoginCommand.js
vendored
Normal file
@@ -0,0 +1,56 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.LoginCommand = void 0;
|
||||
const Result_1 = require("../../../../shared/domain/Result");
|
||||
const Email_1 = require("../../domain/value-objects/Email");
|
||||
const UserLoggedIn_1 = require("../../domain/events/UserLoggedIn");
|
||||
const crypto_1 = require("crypto");
|
||||
class LoginCommand {
|
||||
constructor(userRepository, sessionRepository, eventBus, verifyPassword, sessionMaxAgeSeconds = 7 * 24 * 60 * 60) {
|
||||
this.userRepository = userRepository;
|
||||
this.sessionRepository = sessionRepository;
|
||||
this.eventBus = eventBus;
|
||||
this.verifyPassword = verifyPassword;
|
||||
this.sessionMaxAgeSeconds = sessionMaxAgeSeconds;
|
||||
}
|
||||
async execute(request) {
|
||||
let email;
|
||||
try {
|
||||
email = Email_1.Email.create(request.email);
|
||||
}
|
||||
catch {
|
||||
return (0, Result_1.Err)('Invalid credentials');
|
||||
}
|
||||
const user = await this.userRepository.findByEmail(email.value);
|
||||
if (!user) {
|
||||
return (0, Result_1.Err)('Invalid credentials');
|
||||
}
|
||||
const valid = await this.verifyPassword(request.password, user.passwordHash);
|
||||
if (!valid) {
|
||||
return (0, Result_1.Err)('Invalid credentials');
|
||||
}
|
||||
const token = (0, crypto_1.randomUUID)();
|
||||
const expiresAt = new Date(Date.now() + this.sessionMaxAgeSeconds * 1000);
|
||||
const session = {
|
||||
id: (0, crypto_1.randomUUID)(),
|
||||
userId: user.id.toString(),
|
||||
token,
|
||||
expiresAt,
|
||||
createdAt: new Date(),
|
||||
};
|
||||
await this.sessionRepository.save(session);
|
||||
const event = new UserLoggedIn_1.UserLoggedIn(user.id.toString(), {
|
||||
email: user.email.value,
|
||||
sessionId: session.id,
|
||||
});
|
||||
await this.eventBus.publish(event);
|
||||
return (0, Result_1.Ok)({
|
||||
userId: user.id.toString(),
|
||||
sessionToken: token,
|
||||
expiresAt,
|
||||
role: user.role.value,
|
||||
name: user.name,
|
||||
});
|
||||
}
|
||||
}
|
||||
exports.LoginCommand = LoginCommand;
|
||||
Reference in New Issue
Block a user