Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion lib/Command/ETL.php
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ class ETL extends Command {
private $etlService;

public function __construct(ETLService $etlService) {
parent::__construct("suspiciouslogin:etl");
parent::__construct('suspiciouslogin:etl');

$this->etlService = $etlService;

Expand Down
8 changes: 4 additions & 4 deletions lib/Command/ModelStatistics.php
Original file line number Diff line number Diff line change
Expand Up @@ -28,9 +28,9 @@ private function printModelStatistics(Model $model, InputInterface $input, Outpu
if (!$input->hasOption('stats') && !$input->getOption('stats')) {
return;
}
$output->writeln("Prescision(y): " . $model->getPrecisionY());
$output->writeln("Prescision(n): " . $model->getPrecisionN());
$output->writeln("Recall(y): " . $model->getRecallY());
$output->writeln("Recall(n): " . $model->getRecallN());
$output->writeln('Prescision(y): ' . $model->getPrecisionY());
$output->writeln('Prescision(n): ' . $model->getPrecisionN());
$output->writeln('Recall(y): ' . $model->getRecallY());
$output->writeln('Recall(n): ' . $model->getRecallN());
}
}
10 changes: 5 additions & 5 deletions lib/Command/Optimize.php
Original file line number Diff line number Diff line change
Expand Up @@ -26,27 +26,27 @@ class Optimize extends Command {
private $optimizerService;

public function __construct(OptimizerService $optimizer) {
parent::__construct("suspiciouslogin:optimize");
parent::__construct('suspiciouslogin:optimize');
$this->optimizerService = $optimizer;

$this->addOption(
'max-epochs',
null,
InputOption::VALUE_OPTIONAL,
"maximum number of epochs of optimization",
'maximum number of epochs of optimization',
100
);
$this->addOption(
'v6',
null,
InputOption::VALUE_NONE,
"train with IPv6 data"
'train with IPv6 data'
);
$this->addOption(
'now',
null,
InputOption::VALUE_OPTIONAL,
"the current time as timestamp",
'the current time as timestamp',
time()
);
$this->registerStatsOption();
Expand All @@ -65,7 +65,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int
$this->optimizerService->optimize(
(int)$input->getOption('max-epochs'),
$input->getOption('v6') ? new IpV6Strategy() : new Ipv4Strategy(),
(int) $input->getOption('now'),
(int)$input->getOption('now'),
$output
);

Expand Down
10 changes: 5 additions & 5 deletions lib/Command/Predict.php
Original file line number Diff line number Diff line change
Expand Up @@ -26,30 +26,30 @@ class Predict extends Command {
private $estimatorService;

public function __construct(EstimatorService $estimatorService) {
parent::__construct("suspiciouslogin:predict");
parent::__construct('suspiciouslogin:predict');

$this->estimatorService = $estimatorService;

$this->addArgument(
'uid',
InputArgument::REQUIRED,
"the UID of the user to run a prediction for"
'the UID of the user to run a prediction for'
);
$this->addArgument(
'ip',
InputArgument::REQUIRED,
"the IP to predict suspiciousness"
'the IP to predict suspiciousness'
);
$this->addArgument(
'model',
InputArgument::OPTIONAL,
"persisted model id (latest if omited)"
'persisted model id (latest if omited)'
);
$this->addOption(
'v6',
null,
InputOption::VALUE_NONE,
"train with IPv6 data"
'train with IPv6 data'
);
}

Expand Down
8 changes: 4 additions & 4 deletions lib/Command/Seed.php
Original file line number Diff line number Diff line change
Expand Up @@ -29,22 +29,22 @@ class Seed extends Command {

public function __construct(IConfig $config,
LoginAddressAggregatedSeeder $seeder) {
parent::__construct("suspiciouslogin:seed");
parent::__construct('suspiciouslogin:seed');
$this->seeder = $seeder;

$this->addOption(
'v6',
null,
InputOption::VALUE_NONE,
"train with IPv6 data"
'train with IPv6 data'
);
$this->setDescription("Fills the database with random IPs for development and testing purposes");
$this->setDescription('Fills the database with random IPs for development and testing purposes');
$this->config = $config;
}

protected function execute(InputInterface $input, OutputInterface $output): int {
if ($this->config->getSystemValueBool('debug', false) === false) {
$output->writeln("<error>This command is meant for development purposes.</error> Enable debug mode and try again if you know what you are doing.");
$output->writeln('<error>This command is meant for development purposes.</error> Enable debug mode and try again if you know what you are doing.');
return 1;
}

Expand Down
30 changes: 15 additions & 15 deletions lib/Command/Train.php
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ class Train extends Command {
public function __construct(DataLoader $loader,
Trainer $optimizer,
ModelStore $store) {
parent::__construct("suspiciouslogin:train");
parent::__construct('suspiciouslogin:train');
$this->trainer = $optimizer;
$this->loader = $loader;
$this->store = $store;
Expand All @@ -48,56 +48,56 @@ public function __construct(DataLoader $loader,
'epochs',
'e',
InputOption::VALUE_OPTIONAL,
"number of epochs to train"
'number of epochs to train'
);
$this->addOption(
'layers',
'l',
InputOption::VALUE_OPTIONAL,
"number of hidden layers"
'number of hidden layers'
);
$this->addOption(
'shuffled',
null,
InputOption::VALUE_OPTIONAL,
"ratio of shuffled negative samples"
'ratio of shuffled negative samples'
);
$this->addOption(
'random',
null,
InputOption::VALUE_OPTIONAL,
"ratio of random negative samples"
'ratio of random negative samples'
);
$this->addOption(
'learn-rate',
null,
InputOption::VALUE_OPTIONAL,
"learning rate"
'learning rate'
);
$this->addOption(
'validation-threshold',
null,
InputOption::VALUE_OPTIONAL,
"determines how much of the most recent data is used for validation. the default is one week"
'determines how much of the most recent data is used for validation. the default is one week'
);
$this->addOption(
'max-age',
null,
InputOption::VALUE_OPTIONAL,
"determines the maximum age of test data"
'determines the maximum age of test data'
);
$this->addOption(
'now',
null,
InputOption::VALUE_OPTIONAL,
"overwrite the current time",
'overwrite the current time',
time()
);
$this->addOption(
'v6',
null,
InputOption::VALUE_NONE,
"train with IPv6 data"
'train with IPv6 data'
);
$this->addOption(
'dry-run',
Expand All @@ -109,7 +109,7 @@ public function __construct(DataLoader $loader,
'now',
null,
InputOption::VALUE_OPTIONAL,
"the current time as timestamp",
'the current time as timestamp',
time()
);
$this->registerStatsOption();
Expand All @@ -134,7 +134,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int
$config = $config->setLearningRate((float)$input->getOption('learn-rate'));
}

$trainingDataConfig = TrainingDataConfig::default((int) $input->getOption('now'));
$trainingDataConfig = TrainingDataConfig::default((int)$input->getOption('now'));
if ($input->getOption('validation-threshold') !== null) {
$trainingDataConfig = $trainingDataConfig->setThreshold((int)$input->getOption('validation-threshold'));
}
Expand Down Expand Up @@ -171,13 +171,13 @@ protected function execute(InputInterface $input, OutputInterface $output): int
$result->getClassifier(),
$result->getModel()
);
$output->writeln("<info>Model and estimator persisted.</info>");
$output->writeln('<info>Model and estimator persisted.</info>');
}
} catch (InsufficientDataException $ex) {
$output->writeln("<info>Not enough data, try again later (<error>" . $ex->getMessage() . "</error>)</info>");
$output->writeln('<info>Not enough data, try again later (<error>' . $ex->getMessage() . '</error>)</info>');
return 1;
} catch (ServiceException $ex) {
$output->writeln("<error>Could not train a model: " . $ex->getMessage() . "</error>");
$output->writeln('<error>Could not train a model: ' . $ex->getMessage() . '</error>');
return 1;
}
return 0;
Expand Down
2 changes: 1 addition & 1 deletion lib/Db/LoginAddressAggregatedSeeder.php
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ public function seed(AClassificationStrategy $strategy): int {
$maxRowsPerUser = 10;
$total = 0;
for ($i = 0; $i <= $numberOfUsers; $i++) {
$numberOfRows = random_int((int) ($maxRowsPerUser * 0.3), (int) ($maxRowsPerUser * 1.3));
$numberOfRows = random_int((int)($maxRowsPerUser * 0.3), (int)($maxRowsPerUser * 1.3));
for ($j = 0; $j <= $numberOfRows; $j++) {
$this->insertRow($now, $i, $strategy);
$total++;
Expand Down
4 changes: 2 additions & 2 deletions lib/Exception/InsufficientDataException.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,9 @@
namespace OCA\SuspiciousLogin\Exception;

class InsufficientDataException extends ServiceException {
public function __construct(string $message = "") {
public function __construct(string $message = '') {
parent::__construct(
$message === "" ? "Insufficient data" : "Insufficient data: $message"
$message === '' ? 'Insufficient data' : "Insufficient data: $message"
);
}
}
4 changes: 2 additions & 2 deletions lib/Listener/LoginMailListener.php
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ public function handle(Event $event): void {

private function getMail(SuspiciousLoginEvent $event, IUser $user): IMessage {
$suspiciousIp = $event->getIp();
$addButton = $this->config->getAppValue('suspicious_login', 'show_more_info_button', '1') === "1";
$addButton = $this->config->getAppValue('suspicious_login', 'show_more_info_button', '1') === '1';

$message = $this->mailer->createMessage();
$emailTemplate = $this->mailer->createEMailTemplate('suspiciousLogin.suspiciousLoginDetected');
Expand All @@ -71,7 +71,7 @@ private function getMail(SuspiciousLoginEvent $event, IUser $user): IMessage {
$emailTemplate->addHeading(
$this->l->t('New login location detected')
);

$additionalText = '';
// Add explanation for more information about the IP-address (if enabled)
if ($addButton) {
Expand Down
8 changes: 4 additions & 4 deletions lib/Migration/Version4002Date20220922094803.php
Original file line number Diff line number Diff line change
Expand Up @@ -109,13 +109,13 @@ protected function chunkedCopying(IQueryBuilder $insert, IQueryBuilder $select,
$insert
->setParameter('uid', $row['uid'])
->setParameter('ip', $row['ip'])
->setParameter('seen', (int) $row['seen'], IQueryBuilder::PARAM_INT)
->setParameter('first_seen', (int) $row['first_seen'], IQueryBuilder::PARAM_INT)
->setParameter('last_seen', (int) $row['last_seen'], IQueryBuilder::PARAM_INT)
->setParameter('seen', (int)$row['seen'], IQueryBuilder::PARAM_INT)
->setParameter('first_seen', (int)$row['first_seen'], IQueryBuilder::PARAM_INT)
->setParameter('last_seen', (int)$row['last_seen'], IQueryBuilder::PARAM_INT)
;
$insert->executeStatement();

$newOffset = (int) $row['id'];
$newOffset = (int)$row['id'];
}
$result->closeCursor();
$this->connection->commit();
Expand Down
4 changes: 3 additions & 1 deletion lib/Migration/Version9000Date20250114095826.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,9 @@

class Version9000Date20250114095826 extends SimpleMigrationStep {

public function __construct(private IJobList $jobList) {
public function __construct(
private IJobList $jobList,
) {
}

public function postSchemaChange(IOutput $output, Closure $schemaClosure, array $options): void {
Expand Down
2 changes: 1 addition & 1 deletion lib/Notifications/Notifier.php
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ public function prepare(INotification $notification, string $languageCode): INot

$additionalText = '';
// Add button for more information about the IP-address
if ($this->config->getAppValue('suspicious_login', 'show_more_info_button', '1') === "1") {
if ($this->config->getAppValue('suspicious_login', 'show_more_info_button', '1') === '1') {
$action = $notification->createAction();
$label = $l->t('Open %s ↗', ['iplookup.flagfox.net']);
$link = 'https://iplookup.flagfox.net/?ip=' . $suspiciousIp;
Expand Down
6 changes: 3 additions & 3 deletions lib/Service/DataLoader.php
Original file line number Diff line number Diff line change
Expand Up @@ -52,18 +52,18 @@ public function loadTrainingAndValidationData(TrainingDataConfig $dataConfig,
$maxAge = $dataConfig->getMaxAge() === -1 ? 0 : $dataConfig->getNow() - $dataConfig->getMaxAge() * 60 * 60 * 24;

if (!$strategy->hasSufficientData($this->loginAddressMapper, $maxAge)) {
throw new InsufficientDataException("Not enough data for the specified maximum age");
throw new InsufficientDataException('Not enough data for the specified maximum age');
}
[$historyRaw, $recentRaw] = $strategy->findHistoricAndRecent(
$this->loginAddressMapper,
$validationThreshold,
$maxAge
);
if (empty($historyRaw)) {
throw new InsufficientDataException("No historic data available");
throw new InsufficientDataException('No historic data available');
}
if (empty($recentRaw)) {
throw new InsufficientDataException("No recent data available");
throw new InsufficientDataException('No recent data available');
}

$positives = $this->addressesToDataSet($historyRaw, $strategy);
Expand Down
2 changes: 1 addition & 1 deletion lib/Service/EstimatorService.php
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ public function __construct(
public function predict(string $uid, string $ip, AClassificationStrategy $strategy, ?int $modelId = null): bool {
try {
if ($modelId === null) {
$this->logger->debug("loading latest model");
$this->logger->debug('loading latest model');

$estimator = $this->modelStore->loadLatest($strategy);
} else {
Expand Down
6 changes: 3 additions & 3 deletions lib/Service/LoginClassifier.php
Original file line number Diff line number Diff line change
Expand Up @@ -58,15 +58,15 @@ private function isAuthenticatedWithAppPassword(IRequest $request): bool {
}

return preg_match(
"/^([0-9A-Za-z]{5})-([0-9A-Za-z]{5})-([0-9A-Za-z]{5})-([0-9A-Za-z]{5})-([0-9A-Za-z]{5})$/",
'/^([0-9A-Za-z]{5})-([0-9A-Za-z]{5})-([0-9A-Za-z]{5})-([0-9A-Za-z]{5})-([0-9A-Za-z]{5})$/',
$pwd[1]
) === 1;
}

public function process(string $uid, string $ip) {
if ($this->isAuthenticatedWithAppPassword($this->request)) {
// We don't care about those logins
$this->logger->debug("App password detected. No address classification is performed");
$this->logger->debug('App password detected. No address classification is performed');
return;
}
try {
Expand All @@ -81,7 +81,7 @@ public function process(string $uid, string $ip) {
// This most likely means there is no trained model yet, so we return early here
return;
} catch (ServiceException $ex) {
$this->logger->warning("Could not predict suspiciousness: " . $ex->getMessage());
$this->logger->warning('Could not predict suspiciousness: ' . $ex->getMessage());
// There was an error loading the model, so we return early here
return;
}
Expand Down
Loading
Loading