initial Commit

This commit is contained in:
Mark Gregory
2026-11-11 09:57:07 +00:00
commit d3bf9a5779
206 changed files with 13694 additions and 0 deletions
+33
View File
@@ -0,0 +1,33 @@
<?php
namespace App\Actions\Fortify;
use App\Concerns\PasswordValidationRules;
use App\Concerns\ProfileValidationRules;
use App\Models\User;
use Illuminate\Support\Facades\Validator;
use Laravel\Fortify\Contracts\CreatesNewUsers;
class CreateNewUser implements CreatesNewUsers
{
use PasswordValidationRules, ProfileValidationRules;
/**
* Validate and create a newly registered user.
*
* @param array<string, string> $input
*/
public function create(array $input): User
{
Validator::make($input, [
...$this->profileRules(),
'password' => $this->passwordRules(),
])->validate();
return User::create([
'name' => $input['name'],
'email' => $input['email'],
'password' => $input['password'],
]);
}
}
+29
View File
@@ -0,0 +1,29 @@
<?php
namespace App\Actions\Fortify;
use App\Concerns\PasswordValidationRules;
use App\Models\User;
use Illuminate\Support\Facades\Validator;
use Laravel\Fortify\Contracts\ResetsUserPasswords;
class ResetUserPassword implements ResetsUserPasswords
{
use PasswordValidationRules;
/**
* Validate and reset the user's forgotten password.
*
* @param array<string, string> $input
*/
public function reset(User $user, array $input): void
{
Validator::make($input, [
'password' => $this->passwordRules(),
])->validate();
$user->forceFill([
'password' => $input['password'],
])->save();
}
}
+29
View File
@@ -0,0 +1,29 @@
<?php
namespace App\Concerns;
use Illuminate\Contracts\Validation\ValidationRule;
use Illuminate\Validation\Rules\Password;
trait PasswordValidationRules
{
/**
* Get the validation rules used to validate passwords.
*
* @return array<int, Password|ValidationRule|array<mixed>|string>
*/
protected function passwordRules(): array
{
return ['required', 'string', Password::default(), 'confirmed'];
}
/**
* Get the validation rules used to validate the current password.
*
* @return array<int, Password|ValidationRule|array<mixed>|string>
*/
protected function currentPasswordRules(): array
{
return ['required', 'string', 'current_password'];
}
}
+51
View File
@@ -0,0 +1,51 @@
<?php
namespace App\Concerns;
use App\Models\User;
use Illuminate\Contracts\Validation\ValidationRule;
use Illuminate\Validation\Rule;
trait ProfileValidationRules
{
/**
* Get the validation rules used to validate user profiles.
*
* @return array<string, array<int, ValidationRule|array<mixed>|string>>
*/
protected function profileRules(?int $userId = null): array
{
return [
'name' => $this->nameRules(),
'email' => $this->emailRules($userId),
];
}
/**
* Get the validation rules used to validate user names.
*
* @return array<int, ValidationRule|array<mixed>|string>
*/
protected function nameRules(): array
{
return ['required', 'string', 'max:255'];
}
/**
* Get the validation rules used to validate user emails.
*
* @return array<int, ValidationRule|array<mixed>|string>
*/
protected function emailRules(?int $userId = null): array
{
return [
'required',
'string',
'email',
'max:255',
$userId === null
? Rule::unique(User::class)
: Rule::unique(User::class)->ignore($userId),
];
}
}
+79
View File
@@ -0,0 +1,79 @@
<?php
namespace App\Database\Db2;
use Illuminate\Database\Connection;
use Illuminate\Database\Query\Grammars\Grammar as QueryGrammar;
use App\Database\Db2\Db2Processor;
class Db2Connection extends Connection
{
/**
* Restore SQL NULL values from Db2 workaround expressions
* before Eloquent processes the results.
*/
public function select(
$query,
$bindings = [],
$useReadPdo = true,
array $fetchUsing = []
) {
$rows = parent::select(
$query,
$bindings,
$useReadPdo,
$fetchUsing
);
foreach ($rows as $row) {
if (! is_object($row)) {
continue;
}
foreach ($row as $key => $value) {
if ($value === Db2QueryGrammar::NULL_TIMESTAMP_SENTINEL) {
$row->{$key} = null;
continue;
}
if (
in_array($key, [
'two_factor_secret',
'two_factor_recovery_codes',
], true)
&& $value === Db2QueryGrammar::NULL_STRING_SENTINEL
) {
$row->{$key} = null;
}
}
}
return $rows;
}
protected function getDefaultQueryGrammar()
{
return new Db2QueryGrammar($this);
}
protected function getDefaultSchemaGrammar()
{
return new Db2SchemaGrammar($this);
}
public function getSchemaBuilder()
{
if (is_null($this->schemaGrammar)) {
$this->useDefaultSchemaGrammar();
}
return new Db2SchemaBuilder($this);
}
protected function getDefaultPostProcessor()
{
return new Db2Processor;
}
}
@@ -0,0 +1,79 @@
<?php
namespace App\Database\Db2;
use Illuminate\Database\Connection;
use Illuminate\Database\Query\Grammars\Grammar as QueryGrammar;
use App\Database\Db2\Db2Processor;
class Db2Connection extends Connection
{
/**
* Restore SQL NULL values from Db2 workaround expressions
* before Eloquent processes the results.
*/
public function select(
$query,
$bindings = [],
$useReadPdo = true,
array $fetchUsing = []
) {
$rows = parent::select(
$query,
$bindings,
$useReadPdo,
$fetchUsing
);
foreach ($rows as $row) {
if (! is_object($row)) {
continue;
}
foreach ($row as $key => $value) {
if ($value === Db2QueryGrammar::NULL_TIMESTAMP_SENTINEL) {
$row->{$key} = null;
continue;
}
if (
in_array($key, [
'two_factor_secret',
'two_factor_recovery_codes',
], true)
&& $value === Db2QueryGrammar::NULL_STRING_SENTINEL
) {
$row->{$key} = null;
}
}
}
return $rows;
}
protected function getDefaultQueryGrammar()
{
return new Db2QueryGrammar($this);
}
protected function getDefaultSchemaGrammar()
{
return new Db2SchemaGrammar($this);
}
public function getSchemaBuilder()
{
if (is_null($this->schemaGrammar)) {
$this->useDefaultSchemaGrammar();
}
return new Db2SchemaBuilder($this);
}
protected function getDefaultPostProcessor()
{
return new Db2Processor;
}
}
+35
View File
@@ -0,0 +1,35 @@
<?php
namespace App\Database\Db2;
use Illuminate\Database\Query\Processors\Processor;
class Db2Processor extends Processor
{
public function processInsertGetId($query, $sql, $values, $sequence = null)
{
$query->getConnection()->insert($sql, $values);
$result = $query->getConnection()->selectOne(
'SELECT IDENTITY_VAL_LOCAL() AS ID FROM SYSIBM.SYSDUMMY1',
[],
false
);
if ($result === null) {
throw new \RuntimeException(
'Db2 did not return a generated identity value.'
);
}
$id = $result->ID ?? $result->id ?? null;
if ($id === null) {
throw new \RuntimeException(
'Db2 identity value was NULL.'
);
}
return is_numeric($id) ? (int) $id : $id;
}
}
+179
View File
@@ -0,0 +1,179 @@
<?php
namespace App\Database\Db2;
use Illuminate\Database\Query\Grammars\Grammar;
use Illuminate\Database\Query\Builder;
use Illuminate\Database\Query\Expression;
class Db2QueryGrammar extends Grammar
{
private array $db2ColumnCache = [];
public const NULL_STRING_SENTINEL = '__DB2_NULL_STRING__';
protected function compileAggregate($query, $aggregate)
{
$column = $this->columnize($aggregate['columns']);
if (is_array($query->distinct)) {
$column = 'distinct '.$this->columnize($query->distinct);
} elseif ($query->distinct && $column !== '*') {
$column = 'distinct '.$column;
}
$function = strtolower($aggregate['function']);
$expression = "{$function}({$column})";
// PDO_ODBC may return Db2 integer aggregates as binary data.
// Cast only the migration batch aggregate to VARCHAR.
if (
$function === 'max' &&
count($aggregate['columns']) === 1 &&
$aggregate['columns'][0] === 'batch' &&
$query->from === 'migrations'
) {
$expression = "CAST(COALESCE({$expression}, 0) AS VARCHAR(20))";
}
return 'select '.$expression.' as aggregate';
}
protected function compileLimit($query, $limit)
{
return 'fetch first '.(int) $limit.' rows only';
}
public function compileExists(
\Illuminate\Database\Query\Builder $query
) {
$select = $this->compileSelect($query);
return sprintf(
'SELECT CASE WHEN EXISTS (%s) THEN 1 ELSE 0 END AS "exists" FROM SYSIBM.SYSDUMMY1',
$select
);
}
/** A non-NULL value used only for nullable TIMESTAMP result columns. */
public const NULL_TIMESTAMP_SENTINEL = '__DB2_NULL_TIMESTAMP__';
public function compileSelect(\Illuminate\Database\Query\Builder $query)
{
if (
! is_string($query->from) ||
! preg_match('/^(?:"[^"]+"|[A-Za-z_][A-Za-z0-9_]*)(?:\.(?:"[^"]+"|[A-Za-z_][A-Za-z0-9_]*))?$/', $query->from) ||
! empty($query->joins) || ! empty($query->unions) ||
! empty($query->groups) || ! empty($query->havings) ||
$query->aggregate !== null || $query->distinct
) {
return parent::compileSelect($query);
}
$table = $query->from;
if (! isset($this->db2ColumnCache[$table])) {
$this->db2ColumnCache[$table] = $this->connection
->getSchemaBuilder()->getColumns($table);
}
$metadata = [];
foreach ($this->db2ColumnCache[$table] as $column) {
$metadata[strtolower($column['name'])] = $column;
}
$columns = $query->columns ?? ['*'];
if ($columns === ['*']) {
$columns = array_column($this->db2ColumnCache[$table], 'name');
}
$ordinary = [];
$lobs = [];
$changed = false;
foreach ($columns as $column) {
// Expressions and partial wildcards cannot be safely rearranged.
if (! is_string($column) || ! preg_match(
'/^((?:"[^"]+"|[A-Za-z_][A-Za-z0-9_]*)(?:\.(?:"[^"]+"|[A-Za-z_][A-Za-z0-9_]*))?)(?:\s+as\s+("[^"]+"|[A-Za-z_][A-Za-z0-9_]*))?$/i',
$column, $matches
)) {
return parent::compileSelect($query);
}
$identifier = $matches[1];
$parts = explode('.', $identifier);
$name = trim(end($parts), '"');
$info = $metadata[strtolower($name)] ?? null;
if ($info === null) {
return parent::compileSelect($query);
}
$type = strtoupper($info['type_name']);
$selected = $column;
// Work around PDO_ODBC attempting a 4 GiB allocation
// when fetching NULL Fortify VARCHAR(4096) columns.
if (
($info['nullable'] ?? false)
&& $type === 'VARCHAR'
&& in_array($name, [
'two_factor_secret',
'two_factor_recovery_codes',
], true)
) {
$alias = isset($matches[2])
? trim($matches[2], '"')
: $name;
$wrapped = $this->wrap($identifier);
$selected = new Expression(
'COALESCE('
. $wrapped
. ", CAST('__DB2_NULL_STRING__' AS VARCHAR(4096))) AS "
. $this->wrap($alias)
);
$changed = true;
}
if (($info['nullable'] ?? false) && in_array($type, ['TIMESTAMP', 'DATE', 'TIME'], true)) {
// Never return a SQL NULL date/time to the broken PDO_ODBC
// retrieval path. Use a non-NULL character expression instead.
$format = match ($type) {
'DATE' => 'YYYY-MM-DD',
'TIME' => 'HH24:MI:SS',
default => 'YYYY-MM-DD HH24:MI:SS.FF6',
};
$alias = isset($matches[2]) ? trim($matches[2], '"') : $name;
$wrapped = $this->wrap($identifier);
$selected = new Expression(
'CASE WHEN '.$wrapped.' IS NULL THEN '.
"'".self::NULL_TIMESTAMP_SENTINEL."'".
' ELSE VARCHAR_FORMAT('.$wrapped.", '".$format."') END AS ".
$this->wrap($alias)
);
$changed = true;
}
if (in_array($type, ['CLOB', 'BLOB', 'DBCLOB'], true)) {
$lobs[] = $selected;
} else {
$ordinary[] = $selected;
}
}
if ($lobs !== [] && $ordinary !== [] && $columns !== array_merge(
array_filter($ordinary, 'is_string'),
array_filter($lobs, 'is_string')
)) {
$changed = true;
}
if (! $changed && $lobs === []) {
return parent::compileSelect($query);
}
$modified = clone $query;
$modified->columns = array_merge($ordinary, $lobs);
return parent::compileSelect($modified);
}
}
@@ -0,0 +1,179 @@
<?php
namespace App\Database\Db2;
use Illuminate\Database\Query\Grammars\Grammar;
use Illuminate\Database\Query\Builder;
use Illuminate\Database\Query\Expression;
class Db2QueryGrammar extends Grammar
{
private array $db2ColumnCache = [];
public const NULL_STRING_SENTINEL = '__DB2_NULL_STRING__';
protected function compileAggregate($query, $aggregate)
{
$column = $this->columnize($aggregate['columns']);
if (is_array($query->distinct)) {
$column = 'distinct '.$this->columnize($query->distinct);
} elseif ($query->distinct && $column !== '*') {
$column = 'distinct '.$column;
}
$function = strtolower($aggregate['function']);
$expression = "{$function}({$column})";
// PDO_ODBC may return Db2 integer aggregates as binary data.
// Cast only the migration batch aggregate to VARCHAR.
if (
$function === 'max' &&
count($aggregate['columns']) === 1 &&
$aggregate['columns'][0] === 'batch' &&
$query->from === 'migrations'
) {
$expression = "CAST(COALESCE({$expression}, 0) AS VARCHAR(20))";
}
return 'select '.$expression.' as aggregate';
}
protected function compileLimit($query, $limit)
{
return 'fetch first '.(int) $limit.' rows only';
}
public function compileExists(
\Illuminate\Database\Query\Builder $query
) {
$select = $this->compileSelect($query);
return sprintf(
'SELECT CASE WHEN EXISTS (%s) THEN 1 ELSE 0 END AS "exists" FROM SYSIBM.SYSDUMMY1',
$select
);
}
/** A non-NULL value used only for nullable TIMESTAMP result columns. */
public const NULL_TIMESTAMP_SENTINEL = '__DB2_NULL_TIMESTAMP__';
public function compileSelect(\Illuminate\Database\Query\Builder $query)
{
if (
! is_string($query->from) ||
! preg_match('/^(?:"[^"]+"|[A-Za-z_][A-Za-z0-9_]*)(?:\.(?:"[^"]+"|[A-Za-z_][A-Za-z0-9_]*))?$/', $query->from) ||
! empty($query->joins) || ! empty($query->unions) ||
! empty($query->groups) || ! empty($query->havings) ||
$query->aggregate !== null || $query->distinct
) {
return parent::compileSelect($query);
}
$table = $query->from;
if (! isset($this->db2ColumnCache[$table])) {
$this->db2ColumnCache[$table] = $this->connection
->getSchemaBuilder()->getColumns($table);
}
$metadata = [];
foreach ($this->db2ColumnCache[$table] as $column) {
$metadata[strtolower($column['name'])] = $column;
}
$columns = $query->columns ?? ['*'];
if ($columns === ['*']) {
$columns = array_column($this->db2ColumnCache[$table], 'name');
}
$ordinary = [];
$lobs = [];
$changed = false;
foreach ($columns as $column) {
// Expressions and partial wildcards cannot be safely rearranged.
if (! is_string($column) || ! preg_match(
'/^((?:"[^"]+"|[A-Za-z_][A-Za-z0-9_]*)(?:\.(?:"[^"]+"|[A-Za-z_][A-Za-z0-9_]*))?)(?:\s+as\s+("[^"]+"|[A-Za-z_][A-Za-z0-9_]*))?$/i',
$column, $matches
)) {
return parent::compileSelect($query);
}
$identifier = $matches[1];
$parts = explode('.', $identifier);
$name = trim(end($parts), '"');
$info = $metadata[strtolower($name)] ?? null;
if ($info === null) {
return parent::compileSelect($query);
}
$type = strtoupper($info['type_name']);
$selected = $column;
// Work around PDO_ODBC attempting a 4 GiB allocation
// when fetching NULL Fortify VARCHAR(4096) columns.
if (
($info['nullable'] ?? false)
&& $type === 'VARCHAR'
&& in_array($name, [
'two_factor_secret',
'two_factor_recovery_codes',
], true)
) {
$alias = isset($matches[2])
? trim($matches[2], '"')
: $name;
$wrapped = $this->wrap($identifier);
$selected = new Expression(
'COALESCE('
. $wrapped
. ", CAST('__DB2_NULL_STRING__' AS VARCHAR(4096))) AS "
. $this->wrap($alias)
);
$changed = true;
}
if (($info['nullable'] ?? false) && in_array($type, ['TIMESTAMP', 'DATE', 'TIME'], true)) {
// Never return a SQL NULL date/time to the broken PDO_ODBC
// retrieval path. Use a non-NULL character expression instead.
$format = match ($type) {
'DATE' => 'YYYY-MM-DD',
'TIME' => 'HH24:MI:SS',
default => 'YYYY-MM-DD HH24:MI:SS.FF6',
};
$alias = isset($matches[2]) ? trim($matches[2], '"') : $name;
$wrapped = $this->wrap($identifier);
$selected = new Expression(
'CASE WHEN '.$wrapped.' IS NULL THEN '.
"'".self::NULL_TIMESTAMP_SENTINEL."'".
' ELSE VARCHAR_FORMAT('.$wrapped.", '".$format."') END AS ".
$this->wrap($alias)
);
$changed = true;
}
if (in_array($type, ['CLOB', 'BLOB', 'DBCLOB'], true)) {
$lobs[] = $selected;
} else {
$ordinary[] = $selected;
}
}
if ($lobs !== [] && $ordinary !== [] && $columns !== array_merge(
array_filter($ordinary, 'is_string'),
array_filter($lobs, 'is_string')
)) {
$changed = true;
}
if (! $changed && $lobs === []) {
return parent::compileSelect($query);
}
$modified = clone $query;
$modified->columns = array_merge($ordinary, $lobs);
return parent::compileSelect($modified);
}
}
+277
View File
@@ -0,0 +1,277 @@
<?php
namespace App\Database\Db2;
use Illuminate\Database\Schema\Builder;
class Db2SchemaBuilder extends Builder
{
public function hasTable($table)
{
[$schema, $table] = $this->parseDb2TableName($table);
$schema ??= $this->connection->getConfig('schema');
$result = $this->connection->selectOne(
'SELECT COUNT(*) AS CNT
FROM SYSCAT.TABLES
WHERE TABSCHEMA = ?
AND TABNAME = ?',
[strtoupper($schema), $table]
);
return (int) $result->CNT > 0;
}
public function dropAllTables()
{
$schema = $this->connection->getConfig('schema');
if (!$schema || !preg_match('/^[A-Za-z_][A-Za-z0-9_]*$/', $schema)) {
throw new \RuntimeException('A valid Db2 schema is required for db:wipe.');
}
$schema = strtoupper($schema);
$tables = $this->connection->select(
"SELECT TABNAME
FROM SYSCAT.TABLES
WHERE TABSCHEMA = ?
AND TYPE = 'T'
ORDER BY TABNAME",
[$schema]
);
foreach ($tables as $table) {
$name = $table->TABNAME ?? $table->tabname ?? null;
if ($name === null) {
throw new \RuntimeException('Unable to read Db2 table name.');
}
$qualified = '"' . str_replace('"', '""', $schema) . '"."' .
str_replace('"', '""', trim($name)) . '"';
$this->connection->statement(
"DROP TABLE {$qualified}"
);
}
}
// BEGIN DB2 SCHEMA INSPECTION
private function db2Schema($schema = null)
{
$schema = $schema ?? $this->connection->getConfig('schema');
if (!is_string($schema) || $schema === '') {
throw new \RuntimeException('Invalid Db2 schema.');
}
$schema = trim($schema);
if (str_starts_with($schema, '"') && str_ends_with($schema, '"')) {
$schema = substr($schema, 1, -1);
$schema = str_replace('""', '"', $schema);
}
if (!preg_match('/^[A-Za-z_][A-Za-z0-9_]*$/', $schema)) {
throw new \RuntimeException('Invalid Db2 schema.');
}
return strtoupper($schema);
}
public function getTables($schema = null)
{
$schema = $this->db2Schema($schema);
$rows = $this->connection->select(
"SELECT TABSCHEMA, TABNAME, TYPE
FROM SYSCAT.TABLES
WHERE TABSCHEMA = ?
AND TYPE IN ('T', 'V')
ORDER BY TABNAME",
[$schema]
);
return array_map(static function ($row) {
$name = trim($row->TABNAME);
$schema = trim($row->TABSCHEMA);
return [
'name' => $name,
'schema' => $schema,
'schema_qualified_name' =>
'"' . str_replace('"', '""', $schema) .
'"."' . str_replace('"', '""', $name) . '"',
'type' => $row->TYPE === 'V' ? 'view' : 'table',
'size' => null,
'engine' => null,
'collation' => null,
'comment' => null,
];
}, $rows);
}
public function getColumns($table)
{
[$schema, $table] = $this->parseSchemaAndTable($table);
$schema = $this->db2Schema($schema);
// Remove identifier quotes while preserving lowercase names.
$table = trim($table, '"');
$table = str_replace('""', '"', $table);
$rows = $this->connection->select(
"SELECT COLNAME, TYPENAME, LENGTH, SCALE,
NULLS, IDENTITY, COLNO
FROM SYSCAT.COLUMNS
WHERE TABSCHEMA = ?
AND TABNAME = ?
ORDER BY COLNO",
[$schema, $table]
);
return array_map(static function ($row) {
$type = trim($row->TYPENAME);
if (in_array(strtoupper($type), ['VARCHAR', 'CHAR', 'VARGRAPHIC', 'GRAPHIC'])) {
$type .= '(' . (int) $row->LENGTH . ')';
} elseif (in_array(strtoupper($type), ['DECIMAL', 'NUMERIC'])) {
$type .= '(' . (int) $row->LENGTH . ',' . (int) $row->SCALE . ')';
}
return [
'name' => trim($row->COLNAME),
'type_name' => trim($row->TYPENAME),
'type' => $type,
'collation' => null,
'nullable' => trim($row->NULLS) === 'Y',
'default' => null,
'auto_increment' => trim($row->IDENTITY) === 'Y',
'comment' => null,
'generation' => null,
];
}, $rows);
}
public function getIndexes($table)
{
[$schema, $table] = $this->parseSchemaAndTable($table);
$schema = $this->db2Schema($schema);
$rows = $this->connection->select(
"SELECT I.INDNAME, I.UNIQUERULE,
C.COLNAME, C.COLSEQ
FROM SYSCAT.INDEXES I
JOIN SYSCAT.INDEXCOLUSE C
ON I.INDSCHEMA = C.INDSCHEMA
AND I.INDNAME = C.INDNAME
WHERE I.TABSCHEMA = ?
AND I.TABNAME = ?
ORDER BY I.INDNAME, C.COLSEQ",
[$schema, $table]
);
$indexes = [];
foreach ($rows as $row) {
$name = trim($row->INDNAME);
if (!isset($indexes[$name])) {
$indexes[$name] = [
'name' => $name,
'columns' => [],
'type' => 'btree',
'unique' => in_array(
$row->UNIQUERULE, ['P', 'U'], true
),
'primary' => $row->UNIQUERULE === 'P',
];
}
$indexes[$name]['columns'][] = trim($row->COLNAME);
}
return array_values($indexes);
}
public function getForeignKeys($table)
{
[$schema, $table] = $this->parseSchemaAndTable($table);
$schema = $this->db2Schema($schema);
$rows = $this->connection->select(
"SELECT R.CONSTNAME,
R.REFTABSCHEMA,
R.REFTABNAME,
R.DELETERULE,
R.UPDATERULE,
K.COLNAME,
K.COLSEQ,
RK.COLNAME AS REFCOLNAME
FROM SYSCAT.REFERENCES R
JOIN SYSCAT.KEYCOLUSE K
ON R.TABSCHEMA = K.TABSCHEMA
AND R.TABNAME = K.TABNAME
AND R.CONSTNAME = K.CONSTNAME
JOIN SYSCAT.TABCONST TC
ON TC.TABSCHEMA = R.REFTABSCHEMA
AND TC.TABNAME = R.REFTABNAME
AND TC.TYPE = 'P'
JOIN SYSCAT.KEYCOLUSE RK
ON RK.TABSCHEMA = TC.TABSCHEMA
AND RK.TABNAME = TC.TABNAME
AND RK.CONSTNAME = TC.CONSTNAME
AND RK.COLSEQ = K.COLSEQ
WHERE R.TABSCHEMA = ?
AND R.TABNAME = ?
ORDER BY R.CONSTNAME, K.COLSEQ",
[$schema, $table]
);
$foreignKeys = [];
foreach ($rows as $row) {
$name = trim($row->CONSTNAME);
if (!isset($foreignKeys[$name])) {
$foreignKeys[$name] = [
'name' => $name,
'columns' => [],
'foreign_schema' => trim($row->REFTABSCHEMA),
'foreign_table' => trim($row->REFTABNAME),
'foreign_columns' => [],
'on_update' => trim($row->UPDATERULE),
'on_delete' => trim($row->DELETERULE),
];
}
$foreignKeys[$name]['columns'][] = trim($row->COLNAME);
$foreignKeys[$name]['foreign_columns'][] =
trim($row->REFCOLNAME);
}
return array_values($foreignKeys);
}
private function parseDb2TableName(string $table): array
{
if (preg_match('/^"((?:[^"]|"")*)"\."((?:[^"]|"")*)"$/', $table, $matches)) {
return [
str_replace('""', '"', $matches[1]),
str_replace('""', '"', $matches[2]),
];
}
[$schema, $name] = $this->parseSchemaAndTable($table);
return [
$schema === null ? null : trim($schema, '"'),
trim($name, '"'),
];
}
}
+227
View File
@@ -0,0 +1,227 @@
<?php
namespace App\Database\Db2;
use Illuminate\Database\Schema\Grammars\Grammar;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Fluent;
class Db2SchemaGrammar extends Grammar
{
protected $modifiers = ['Nullable', 'Default'];
public function compileCreate(Blueprint $blueprint, Fluent $command)
{
$columns = [];
$primaryKeys = [];
foreach ($blueprint->getAddedColumns() as $column) {
$sql = $this->wrap($column) . ' ' . $this->getType($column);
if ($column->autoIncrement) {
$sql .= ' GENERATED BY DEFAULT AS IDENTITY';
// Laravel's $table->id() does not explicitly
// set the primary attribute.
$primaryKeys[] = $column->name;
}
$sql .= $column->nullable ? '' : ' NOT NULL';
if (!is_null($column->default)) {
$sql .= ' DEFAULT ' . $this->getDefaultValue($column->default);
}
$columns[] = $sql;
}
// Db2 identity columns are not automatically primary keys.
if (!empty($primaryKeys)) {
$columns[] = sprintf(
'PRIMARY KEY (%s)',
$this->columnize($primaryKeys)
);
}
return sprintf(
'CREATE TABLE %s (%s)',
$this->wrapTable($blueprint),
implode(', ', $columns)
);
}
protected function typeBigInteger(Fluent $column)
{
return 'BIGINT';
}
protected function typeInteger(Fluent $column)
{
return 'INTEGER';
}
protected function typeSmallInteger(Fluent $column)
{
return 'SMALLINT';
}
protected function typeString(Fluent $column)
{
return 'VARCHAR(' . ($column->length ?: 255) . ')';
}
protected function typeText(Fluent $column)
{
return 'CLOB(1M)';
}
protected function typeLongText(Fluent $column)
{
return 'CLOB(2M)';
}
protected function typeBoolean(Fluent $column)
{
return 'SMALLINT';
}
protected function typeTimestamp(Fluent $column)
{
return 'TIMESTAMP';
}
protected function typeDateTime(Fluent $column)
{
return 'TIMESTAMP';
}
protected function typeDate(Fluent $column)
{
return 'DATE';
}
protected function typeBinary(Fluent $column)
{
return 'BLOB(1M)';
}
protected function typeDecimal(Fluent $column)
{
return sprintf(
'DECIMAL(%d,%d)',
$column->total ?? 8,
$column->places ?? 2
);
}
public function compilePrimary(Blueprint $blueprint, Fluent $command)
{
return sprintf(
'ALTER TABLE %s ADD PRIMARY KEY (%s)',
$this->wrapTable($blueprint),
$this->columnize($command->columns)
);
}
protected function typeMediumText(Fluent $column)
{
return 'CLOB(16M)';
}
public function compileUnique(Blueprint $blueprint, Fluent $command)
{
return sprintf(
'CREATE UNIQUE INDEX %s ON %s (%s)',
$this->wrap($command->index),
$this->wrapTable($blueprint),
$this->columnize($command->columns)
);
}
public function compileIndex(Blueprint $blueprint, Fluent $command)
{
return sprintf(
'CREATE INDEX %s ON %s (%s)',
$this->wrap($command->index),
$this->wrapTable($blueprint),
$this->columnize($command->columns)
);
}
protected function typeJson(\Illuminate\Database\Schema\ColumnDefinition $column)
{
return 'CLOB(1M)';
}
protected function typeJsonb(\Illuminate\Database\Schema\ColumnDefinition $column)
{
return 'CLOB(1M)';
}
protected function typeTinyText(\Illuminate\Database\Schema\ColumnDefinition $column)
{
return 'VARCHAR(255)';
}
public function compileInsertOrIgnore(
\Illuminate\Database\Query\Builder $query,
array $values
) {
if (empty($values)) {
return '';
}
if (!is_array(reset($values))) {
$values = [$values];
}
$columns = array_keys(reset($values));
$table = $this->wrapTable($query->from);
$sourceColumns = implode(
', ',
array_map(fn ($column) => $this->wrap($column), $columns)
);
$rows = [];
foreach ($values as $row) {
$rows[] = '(' . implode(
', ',
array_fill(0, count($columns), '?')
) . ')';
}
$source = implode(', ', $rows);
$conditions = [];
foreach ($columns as $column) {
$wrapped = $this->wrap($column);
$conditions[] = "target.$wrapped = source.$wrapped";
}
return sprintf(
'MERGE INTO %s AS target
USING (VALUES %s) AS source (%s)
ON %s
WHEN NOT MATCHED THEN
INSERT (%s)
VALUES (%s)',
$table,
$source,
$sourceColumns,
implode(' AND ', $conditions),
$sourceColumns,
implode(
', ',
array_map(
fn ($column) => 'source.' . $this->wrap($column),
$columns
)
)
);
}
}
+8
View File
@@ -0,0 +1,8 @@
<?php
namespace App\Http\Controllers;
abstract class Controller
{
//
}
+24
View File
@@ -0,0 +1,24 @@
<?php
namespace App\Livewire\Actions;
use Illuminate\Http\RedirectResponse;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Session;
use Livewire\Features\SupportRedirects\Redirector;
class Logout
{
/**
* Log the current user out of the application.
*/
public function __invoke(): Redirector|RedirectResponse
{
Auth::guard('web')->logout();
Session::invalidate();
Session::regenerateToken();
return redirect('/');
}
}
+12
View File
@@ -0,0 +1,12 @@
<?php
namespace App\Livewire\Settings;
use Livewire\Attributes\Title;
use Livewire\Component;
#[Title('Appearance settings')]
class Appearance extends Component
{
//
}
+29
View File
@@ -0,0 +1,29 @@
<?php
namespace App\Livewire\Settings;
use App\Concerns\PasswordValidationRules;
use App\Livewire\Actions\Logout;
use Illuminate\Support\Facades\Auth;
use Livewire\Component;
class DeleteUserForm extends Component
{
use PasswordValidationRules;
public string $password = '';
/**
* Delete the currently authenticated user.
*/
public function deleteUser(Logout $logout): void
{
$this->validate([
'password' => $this->currentPasswordRules(),
]);
tap(Auth::user(), $logout(...))->delete();
$this->redirect('/', navigate: true);
}
}
+84
View File
@@ -0,0 +1,84 @@
<?php
namespace App\Livewire\Settings;
use App\Concerns\ProfileValidationRules;
use Flux\Flux;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Support\Facades\Auth;
use Livewire\Attributes\Computed;
use Livewire\Attributes\Title;
use Livewire\Component;
#[Title('Profile settings')]
class Profile extends Component
{
use ProfileValidationRules;
public string $name = '';
public string $email = '';
/**
* Mount the component.
*/
public function mount(): void
{
$this->name = Auth::user()->name;
$this->email = Auth::user()->email;
}
/**
* Update the profile information for the currently authenticated user.
*/
public function updateProfileInformation(): void
{
$user = Auth::user();
$validated = $this->validate($this->profileRules($user->id));
$user->fill($validated);
if ($user->isDirty('email')) {
$user->email_verified_at = null;
}
$user->save();
Flux::toast(variant: 'success', text: __('Profile updated.'));
}
/**
* Send an email verification notification to the current user.
*/
public function resendVerificationNotification(): void
{
$user = Auth::user();
if ($user->hasVerifiedEmail()) {
$this->redirectIntended(default: route('dashboard', absolute: false));
return;
}
$user->sendEmailVerificationNotification();
Flux::toast(text: __('A new verification link has been sent to your email address.'));
}
#[Computed]
public function hasUnverifiedEmail(): bool
{
$user = Auth::user();
return $user instanceof MustVerifyEmail && ! $user->hasVerifiedEmail();
}
#[Computed]
public function showDeleteUser(): bool
{
$user = Auth::user();
return ! $user instanceof MustVerifyEmail || $user->hasVerifiedEmail();
}
}
+312
View File
@@ -0,0 +1,312 @@
<?php
namespace App\Livewire\Settings;
use App\Concerns\PasswordValidationRules;
use Exception;
use Flux\Flux;
use Illuminate\Support\Facades\Auth;
use Illuminate\Validation\ValidationException;
use Laravel\Fortify\Actions\ConfirmTwoFactorAuthentication;
use Laravel\Fortify\Actions\DisableTwoFactorAuthentication;
use Laravel\Fortify\Actions\EnableTwoFactorAuthentication;
use Laravel\Fortify\Features;
use Laravel\Fortify\Fortify;
use Laravel\Passkeys\Actions\DeletePasskey;
use Livewire\Attributes\Computed;
use Livewire\Attributes\Locked;
use Livewire\Attributes\Title;
use Livewire\Attributes\Validate;
use Livewire\Component;
#[Title('Security settings')]
class Security extends Component
{
use PasswordValidationRules;
public string $current_password = '';
public string $password = '';
public string $password_confirmation = '';
#[Locked]
public bool $canManageTwoFactor;
#[Locked]
public bool $twoFactorEnabled;
#[Locked]
public bool $requiresConfirmation;
#[Locked]
public string $qrCodeSvg = '';
#[Locked]
public string $manualSetupKey = '';
public bool $showModal = false;
public bool $showVerificationStep = false;
#[Validate('required|string|size:6', onUpdate: false)]
public string $code = '';
#[Locked]
public bool $canManagePasskeys;
/**
* @var array<int, array{id: int, name: string, authenticator: string|null, created_at_diff: string, last_used_at_diff: string|null}>
*/
#[Locked]
public array $passkeys = [];
public bool $showDeleteModal = false;
#[Locked]
public ?int $deletingPasskeyId = null;
#[Locked]
public string $deletingPasskeyName = '';
/**
* Mount the component.
*/
public function mount(DisableTwoFactorAuthentication $disableTwoFactorAuthentication): void
{
$this->canManageTwoFactor = Features::canManageTwoFactorAuthentication();
if ($this->canManageTwoFactor) {
if (Fortify::confirmsTwoFactorAuthentication() && is_null(auth()->user()->two_factor_confirmed_at)) {
$disableTwoFactorAuthentication(auth()->user());
}
$this->twoFactorEnabled = auth()->user()->hasEnabledTwoFactorAuthentication();
$this->requiresConfirmation = Features::optionEnabled(Features::twoFactorAuthentication(), 'confirm');
}
$this->canManagePasskeys = Features::canManagePasskeys();
if ($this->canManagePasskeys) {
$this->loadPasskeys();
}
}
/**
* Update the password for the currently authenticated user.
*/
public function updatePassword(): void
{
try {
$validated = $this->validate([
'current_password' => $this->currentPasswordRules(),
'password' => $this->passwordRules(),
]);
} catch (ValidationException $e) {
$this->reset('current_password', 'password', 'password_confirmation');
throw $e;
}
Auth::user()->update([
'password' => $validated['password'],
]);
$this->reset('current_password', 'password', 'password_confirmation');
Flux::toast(variant: 'success', text: __('Password updated.'));
}
/**
* Load the user's passkeys.
*/
public function loadPasskeys(): void
{
$this->passkeys = Auth::user()->passkeys()
->select(['id', 'name', 'credential', 'created_at', 'last_used_at'])
->latest()
->get()
->map(fn ($passkey) => [
'id' => $passkey->id,
'name' => $passkey->name,
'authenticator' => $passkey->authenticator,
'created_at_diff' => $passkey->created_at->diffForHumans(),
'last_used_at_diff' => $passkey->last_used_at?->diffForHumans(),
])
->all();
}
/**
* Show the delete confirmation modal.
*/
public function confirmDelete(int $passkeyId): void
{
$passkey = Auth::user()->passkeys()->findOrFail($passkeyId);
$this->deletingPasskeyId = $passkey->id;
$this->deletingPasskeyName = $passkey->name;
$this->showDeleteModal = true;
}
/**
* Delete the passkey.
*/
public function deletePasskey(DeletePasskey $deletePasskey): void
{
if (! $this->deletingPasskeyId) {
return;
}
$user = Auth::user();
$passkey = $user->passkeys()->findOrFail($this->deletingPasskeyId);
$deletePasskey($user, $passkey);
$this->closeDeleteModal();
$this->loadPasskeys();
}
/**
* Close the delete confirmation modal.
*/
public function closeDeleteModal(): void
{
$this->showDeleteModal = false;
$this->deletingPasskeyId = null;
$this->deletingPasskeyName = '';
}
/**
* Enable two-factor authentication for the user.
*/
public function enable(EnableTwoFactorAuthentication $enableTwoFactorAuthentication): void
{
$enableTwoFactorAuthentication(auth()->user());
if (! $this->requiresConfirmation) {
$this->twoFactorEnabled = auth()->user()->hasEnabledTwoFactorAuthentication();
}
$this->loadSetupData();
$this->showModal = true;
}
/**
* Load the two-factor authentication setup data for the user.
*/
private function loadSetupData(): void
{
$user = auth()->user();
try {
$this->qrCodeSvg = $user?->twoFactorQrCodeSvg();
$this->manualSetupKey = decrypt($user->two_factor_secret);
} catch (Exception) {
$this->addError('setupData', 'Failed to fetch setup data.');
$this->reset('qrCodeSvg', 'manualSetupKey');
}
}
/**
* Show the two-factor verification step if necessary.
*/
public function showVerificationIfNecessary(): void
{
if ($this->requiresConfirmation) {
$this->showVerificationStep = true;
$this->resetErrorBag();
return;
}
$this->closeModal();
}
/**
* Confirm two-factor authentication for the user.
*/
public function confirmTwoFactor(ConfirmTwoFactorAuthentication $confirmTwoFactorAuthentication): void
{
$this->validate();
$confirmTwoFactorAuthentication(auth()->user(), $this->code);
$this->closeModal();
$this->twoFactorEnabled = true;
}
/**
* Reset two-factor verification state.
*/
public function resetVerification(): void
{
$this->reset('code', 'showVerificationStep');
$this->resetErrorBag();
}
/**
* Disable two-factor authentication for the user.
*/
public function disable(DisableTwoFactorAuthentication $disableTwoFactorAuthentication): void
{
$disableTwoFactorAuthentication(auth()->user());
$this->twoFactorEnabled = false;
}
/**
* Close the two-factor authentication modal.
*/
public function closeModal(): void
{
$this->reset(
'code',
'manualSetupKey',
'qrCodeSvg',
'showModal',
'showVerificationStep',
);
$this->resetErrorBag();
if (! $this->requiresConfirmation) {
$this->twoFactorEnabled = auth()->user()->hasEnabledTwoFactorAuthentication();
}
}
/**
* Get the current modal configuration state.
*
* @return array{title: string, description: string, buttonText: string}
*/
#[Computed]
public function modalConfig(): array
{
if ($this->twoFactorEnabled) {
return [
'title' => __('Two-factor authentication enabled'),
'description' => __('Two-factor authentication is now enabled. Scan the QR code or enter the setup key in your authenticator app.'),
'buttonText' => __('Close'),
];
}
if ($this->showVerificationStep) {
return [
'title' => __('Verify authentication code'),
'description' => __('Enter the 6-digit code from your authenticator app.'),
'buttonText' => __('Continue'),
];
}
return [
'title' => __('Enable two-factor authentication'),
'description' => __('To finish enabling two-factor authentication, scan the QR code or enter the setup key in your authenticator app.'),
'buttonText' => __('Continue'),
];
}
}
+51
View File
@@ -0,0 +1,51 @@
<?php
namespace App\Livewire\Settings\TwoFactor;
use Exception;
use Laravel\Fortify\Actions\GenerateNewRecoveryCodes;
use Livewire\Attributes\Locked;
use Livewire\Component;
class RecoveryCodes extends Component
{
/** @var list<string> */
#[Locked]
public array $recoveryCodes = [];
/**
* Mount the component.
*/
public function mount(): void
{
$this->loadRecoveryCodes();
}
/**
* Generate new recovery codes for the user.
*/
public function regenerateRecoveryCodes(GenerateNewRecoveryCodes $generateNewRecoveryCodes): void
{
$generateNewRecoveryCodes(auth()->user());
$this->loadRecoveryCodes();
}
/**
* Load the recovery codes for the user.
*/
private function loadRecoveryCodes(): void
{
$user = auth()->user();
if ($user->hasEnabledTwoFactorAuthentication() && $user->two_factor_recovery_codes) {
try {
$this->recoveryCodes = json_decode(decrypt($user->two_factor_recovery_codes), true);
} catch (Exception) {
$this->addError('recoveryCodes', 'Failed to load recovery codes');
$this->recoveryCodes = [];
}
}
}
}
+62
View File
@@ -0,0 +1,62 @@
<?php
namespace App\Models;
// use Illuminate\Contracts\Auth\MustVerifyEmail;
use Database\Factories\UserFactory;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Attributes\Hidden;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Illuminate\Support\Carbon;
use Illuminate\Support\Str;
use Laravel\Fortify\Contracts\PasskeyUser;
use Laravel\Fortify\PasskeyAuthenticatable;
use Laravel\Fortify\TwoFactorAuthenticatable;
/**
* @property int $id
* @property string $name
* @property string $email
* @property Carbon|null $email_verified_at
* @property string $password
* @property string|null $two_factor_secret
* @property string|null $two_factor_recovery_codes
* @property Carbon|null $two_factor_confirmed_at
* @property string|null $remember_token
* @property Carbon|null $created_at
* @property Carbon|null $updated_at
*/
#[Fillable(['name', 'email', 'password'])]
#[Hidden(['password', 'two_factor_secret', 'two_factor_recovery_codes', 'remember_token'])]
class User extends Authenticatable implements PasskeyUser
{
/** @use HasFactory<UserFactory> */
use HasFactory, Notifiable, PasskeyAuthenticatable, TwoFactorAuthenticatable;
/**
* Get the attributes that should be cast.
*
* @return array<string, string>
*/
protected function casts(): array
{
return [
'email_verified_at' => 'datetime',
'password' => 'hashed',
];
}
/**
* Get the user's initials
*/
public function initials(): string
{
$initials = Str::initials($this->name, true);
return Str::length($initials) > 1
? Str::substr($initials, 0, 1).Str::substr($initials, -1)
: $initials;
}
}
+57
View File
@@ -0,0 +1,57 @@
<?php
namespace App\Providers;
use App\Database\Db2\Db2Connection;
use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\DB;
use PDO;
class AppServiceProvider extends ServiceProvider
{
public function register(): void
{
DB::extend('odbc', function (array $config, string $name) {
$pdo = new PDO(
'odbc:' . ($config['dsn'] ?? 'MEDIUK'),
$config['username'] ?? '',
$config['password'] ?? '',
[
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_OBJ,
]
);
$schema = $config['schema'] ?? null;
if ($schema) {
if (!preg_match('/^[A-Za-z_][A-Za-z0-9_]*$/', $schema)) {
throw new \InvalidArgumentException('Invalid Db2 schema');
}
$pdo->exec('SET CURRENT SCHEMA ' . $schema);
}
$config['name'] = $name;
return new Db2Connection(
$pdo,
$config['database'] ?? '',
$config['prefix'] ?? '',
$config
);
});
}
public function boot(): void
{
\DB::connection('db2_local')->beforeExecuting(
function ($sql, $bindings, $connection) {
logger()->debug('DB2 BEFORE EXECUTE', [
'sql' => $sql,
'bindings_count' => count($bindings),
]);
}
);
}
}
+80
View File
@@ -0,0 +1,80 @@
<?php
namespace App\Providers;
use App\Actions\Fortify\CreateNewUser;
use App\Actions\Fortify\ResetUserPassword;
use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Str;
use Laravel\Fortify\Fortify;
class FortifyServiceProvider extends ServiceProvider
{
/**
* Register any application services.
*/
public function register(): void
{
//
}
/**
* Bootstrap any application services.
*/
public function boot(): void
{
$this->configureActions();
$this->configureViews();
$this->configureRateLimiting();
}
/**
* Configure Fortify actions.
*/
private function configureActions(): void
{
Fortify::resetUserPasswordsUsing(ResetUserPassword::class);
Fortify::createUsersUsing(CreateNewUser::class);
}
/**
* Configure Fortify views.
*/
private function configureViews(): void
{
Fortify::loginView(fn () => view('livewire.auth.login'));
Fortify::verifyEmailView(fn () => view('livewire.auth.verify-email'));
Fortify::twoFactorChallengeView(fn () => view('livewire.auth.two-factor-challenge'));
Fortify::confirmPasswordView(fn () => view('livewire.auth.confirm-password'));
Fortify::registerView(fn () => view('livewire.auth.register'));
Fortify::resetPasswordView(fn () => view('livewire.auth.reset-password'));
Fortify::requestPasswordResetLinkView(fn () => view('livewire.auth.forgot-password'));
}
/**
* Configure rate limiting.
*/
private function configureRateLimiting(): void
{
RateLimiter::for('two-factor', function (Request $request) {
return Limit::perMinute(5)->by($request->session()->get('login.id'));
});
RateLimiter::for('login', function (Request $request) {
$throttleKey = Str::transliterate(Str::lower($request->input(Fortify::username())).'|'.$request->ip());
return Limit::perMinute(5)->by($throttleKey);
});
RateLimiter::for('passkeys', function (Request $request) {
$credentialId = $request->input('credential.id');
return Limit::perMinute(10)->by(
($credentialId ?: $request->session()->getId()).'|'.$request->ip(),
);
});
}
}