Skip to content

Commit

Permalink
feat: log excessive logins (#8774)
Browse files Browse the repository at this point in the history
  • Loading branch information
kwasniew authored Nov 18, 2024
1 parent 6d4e2e9 commit 56db988
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 3 deletions.
6 changes: 5 additions & 1 deletion src/lib/routes/auth/simple-password-provider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,8 +60,12 @@ export class SimplePasswordProvider extends Controller {
res: Response<UserSchema>,
): Promise<void> {
const { username, password } = req.body;
const userAgent = req.get('user-agent');

const user = await this.userService.loginUser(username, password);
const user = await this.userService.loginUser(username, password, {
userAgent,
ip: req.ip,
});
req.session.user = user;
this.openApiService.respondWithValidation(
200,
Expand Down
19 changes: 17 additions & 2 deletions src/lib/services/user-service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -393,7 +393,11 @@ class UserService {
);
}

async loginUser(usernameOrEmail: string, password: string): Promise<IUser> {
async loginUser(
usernameOrEmail: string,
password: string,
device?: { userAgent: string; ip: string },
): Promise<IUser> {
const settings = await this.settingService.get<SimpleAuthSettings>(
simpleAuthSettingsKey,
);
Expand All @@ -417,12 +421,22 @@ class UserService {
const match = await bcrypt.compare(password, passwordHash);
if (match) {
const loginOrder = await this.store.successfullyLogin(user);

const sessions = await this.sessionService.getSessionsForUser(
user.id,
);
if (sessions.length >= 5 && device) {
this.logger.info(
`Excessive login (user id: ${user.id}, user agent: ${device.userAgent}, IP: ${device.ip})`,
);
}

const deleteStaleUserSessions = this.flagResolver.getVariant(
'deleteStaleUserSessions',
);
if (deleteStaleUserSessions.feature_enabled) {
const allowedSessions = Number(
deleteStaleUserSessions.payload?.value || 30,
deleteStaleUserSessions.payload?.value || 5,
);
// subtract current user session that will be created
const deletedSessionsCount =
Expand All @@ -433,6 +447,7 @@ class UserService {
user.deletedSessions = deletedSessionsCount;
user.activeSessions = allowedSessions;
}

this.eventBus.emit(USER_LOGIN, { loginOrder });
return user;
}
Expand Down

0 comments on commit 56db988

Please sign in to comment.