diff --git a/.env.example b/.env.example index 8c22ddf..977de14 100644 --- a/.env.example +++ b/.env.example @@ -56,6 +56,13 @@ SSO_AUTO_PROVISION=false # true: hide the password form; only administrators can still sign in with a password, at /Login?local=1. SSO_DISABLE_LOCAL_LOGIN=false +# ---- Two-factor sign-in ---- +# Anyone with a password can turn on authenticator-app codes under My profile -> Security. +# true: administrators who sign in with a password must set it up before using Taskist. +TWO_FACTOR_REQUIRE_FOR_ADMINS=false +# "Don't ask again on this device" lasts this many days; 0 turns the option off. +TWO_FACTOR_REMEMBER_DEVICE_DAYS=30 + # ---- Seeding ---- # Reference data (roles, permissions, menus, translations, admin account). Leave true for a usable install. SEED_DATA=true diff --git a/CHANGELOG.md b/CHANGELOG.md index 1073bfe..abb6bef 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -16,6 +16,7 @@ Each release lists **Upgrade notes** when an install needs action beyond the ste - **Appearance**: light, dark or system theme and an accent colour per user. - **Per-user export column layouts** on top of the administrator's default. - **Tags** for the backlog, with inline create and merge. +- **Two-factor sign-in** with any authenticator app (TOTP), turned on per user under My profile → Security: QR-code setup, ten one-time recovery codes, an optional "don't ask again on this device" (`Authentication:TwoFactor:RememberDeviceDays`, default 30), and administrator reset on the user's page. `Authentication:TwoFactor:RequireForAdministrators` (off by default) makes it mandatory for administrators who sign in with a password. Single sign-on users are not asked, since their identity provider handles it. See [docs/two-factor.md](docs/two-factor.md). ([#12](https://github.com/Taskist/taskist/issues/12)) - **Single sign-on with OpenID Connect** (`Authentication:Oidc`, off by default): Keycloak, Authentik, Entra ID, Google, Okta and other providers. Existing users are linked by verified e-mail; optional account creation on first sign-in (*Registered* role only), optional group → role mapping (adds roles only), and an SSO-only mode that keeps password sign-in for administrators at `/Login?local=1`. Linked sign-ins are listed under My profile → Security and on the user's admin page. See [docs/sso.md](docs/sso.md). ([#11](https://github.com/Taskist/taskist/issues/11)) - **Optional Sentry error tracking** (`Sentry:Enabled` + `Sentry:Dsn`, off by default): unhandled exceptions and logged errors, with request bodies, cookies, query strings, auth headers and personal data filtered out. - `Security:RequireHttpsCookies` and `Security:ForwardedHeaders:*` settings for plain-HTTP and reverse-proxy deployments. diff --git a/README.md b/README.md index d0a3ee1..044a551 100644 --- a/README.md +++ b/README.md @@ -80,7 +80,7 @@ Taskist is a self-hosted **task, change request and bug tracker** built with ASP **⚙️ Administration** -- Users, roles and fine-grained permissions; optional single sign-on with any OpenID Connect provider +- Users, roles and fine-grained permissions; two-factor sign-in with an authenticator app; optional single sign-on with any OpenID Connect provider - Masters for clients, projects, modules, statuses, task types, severities, tags and reporters — shared or per project - Database-driven translations, e-mail templates and settings - Light, dark and system themes with an accent colour per user; activity log; background-jobs dashboard @@ -177,10 +177,12 @@ Taskist reads `appsettings.json`, `appsettings.{Environment}.json`, user-secrets | `Authentication:Oidc:AutoProvision` | `false` | Create a Taskist account (*Registered* role only) on first sign-in. Off = only existing users can sign in | | `Authentication:Oidc:RoleClaim` / `RoleMappings` | — | Optional: add Taskist roles from provider groups, e.g. `{"taskist-leads": "TeamLead"}`. Only adds roles, never removes them | | `Authentication:Oidc:DisableLocalLogin` | `false` | Hide the password form. Administrators can still sign in with a password at `/Login?local=1` | +| `Authentication:TwoFactor:RequireForAdministrators` | `false` | Administrators who sign in with a password must turn on two-factor sign-in before using Taskist; see [docs/two-factor.md](docs/two-factor.md) | +| `Authentication:TwoFactor:RememberDeviceDays` | `30` | How long "Don't ask again on this device" lasts after a two-factor sign-in; `0` turns the option off | Everything else — password policy, lockout, session length, e-mail, Git, notifications, report layouts — lives in the app under **Configuration → Settings**. -**Behind a reverse proxy** (nginx, Traefik, IIS, a cloud load balancer): keep `RequireHttpsCookies=true`, set `ForwardedHeaders:Enabled=true` and list the proxy in `KnownProxies` or `KnownNetworks`, and set `App:BaseUrl` to the public `https://` address. In Docker these are `TASKIST_REQUIRE_HTTPS_COOKIES`, `TASKIST_FORWARDED_HEADERS`, `TASKIST_PROXY_NETWORK` and `APP_BASE_URL` in `.env`; Sentry uses `SENTRY_ENABLED`, `SENTRY_DSN`, `SENTRY_ENVIRONMENT` and `SENTRY_TRACES_SAMPLE_RATE`; single sign-on uses the `SSO_*` variables. +**Behind a reverse proxy** (nginx, Traefik, IIS, a cloud load balancer): keep `RequireHttpsCookies=true`, set `ForwardedHeaders:Enabled=true` and list the proxy in `KnownProxies` or `KnownNetworks`, and set `App:BaseUrl` to the public `https://` address. In Docker these are `TASKIST_REQUIRE_HTTPS_COOKIES`, `TASKIST_FORWARDED_HEADERS`, `TASKIST_PROXY_NETWORK` and `APP_BASE_URL` in `.env`; Sentry uses `SENTRY_ENABLED`, `SENTRY_DSN`, `SENTRY_ENVIRONMENT` and `SENTRY_TRACES_SAMPLE_RATE`; single sign-on uses the `SSO_*` variables and two-factor sign-in the `TWO_FACTOR_*` ones. diff --git a/SECURITY.md b/SECURITY.md index edb7d73..a5b56b0 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -82,6 +82,19 @@ Secrets are write-only in the UI and are never written to the activity log. - The forgot-password endpoint is rate limited per IP address. - Change the seeded `admin@taskist.org` password immediately after installation. +### Two-factor sign-in + +Users with a password can turn on authenticator-app codes (TOTP, RFC 6238: 6 digits, 30-second steps) under **My profile → Security**. Setup in [docs/two-factor.md](docs/two-factor.md). + +- **Secrets** are 160-bit random keys, stored encrypted with Data Protection (like other stored secrets) and never written to the audit log. The QR code is generated on the server; nothing is sent to an outside service. +- **Codes** are accepted for the current 30-second step ±1 and **only once**: a code, or any older one, can't be replayed after a successful sign-in. +- **Recovery codes:** ten single-use codes, about 50 bits each, stored as SHA-256 hashes and shown only once. Turning two-factor off or creating new codes requires a current code. +- **Wrong codes** count towards the same failed-attempt lock-out as wrong passwords, and the counter is only reset after the **second** step succeeds. Each sign-in attempt also allows at most five codes before the user has to start again with their password. The half-finished sign-in lives in a separate, encrypted five-minute cookie, so a correct password alone never creates a session. +- **"Don't ask again on this device"** (`Authentication:TwoFactor:RememberDeviceDays`, default 30, `0` turns it off) sets an encrypted, HttpOnly, always-*Secure* cookie (so it only works over HTTPS) tied to the user and to when two-factor was last turned on, so it stops working as soon as two-factor is reset or turned off and on again. +- **Administrators can be required** to use it (`Authentication:TwoFactor:RequireForAdministrators`): until they set it up, administrators who signed in with only a password are limited to their profile page. +- **Resetting:** an administrator can reset a user's two-factor sign-in from the user's page (recorded in the activity log for both accounts). Keep this in mind for your support process: anyone who can convince an administrator to reset it is back to password-only. +- Single sign-on users are not asked for a Taskist code; enforce MFA at your identity provider. + ### Single sign-on (optional) Taskist can sign users in through an OpenID Connect provider (`Authentication:Oidc`, off by default; setup in [docs/sso.md](docs/sso.md)). diff --git a/THIRD-PARTY-NOTICES.md b/THIRD-PARTY-NOTICES.md index cdb0e5c..c26003b 100644 --- a/THIRD-PARTY-NOTICES.md +++ b/THIRD-PARTY-NOTICES.md @@ -70,6 +70,7 @@ Restored at build time; not stored in this repository. | [Microsoft.EntityFrameworkCore.DynamicLinq](https://dynamic-linq.net) | Apache-2.0 | | [MiniProfiler](https://miniprofiler.com) | MIT | | [Newtonsoft.Json](https://www.newtonsoft.com/json) | MIT | +| [QRCoder](https://github.com/Shane32/QRCoder) (two-factor setup QR code) | MIT | | [RestSharp](https://restsharp.dev) | Apache-2.0 | | [ReverseMarkdown](https://github.com/mysticmind/reversemarkdown-net) | MIT | | [Riok.Mapperly](https://mapperly.riok.app) | Apache-2.0 | diff --git a/docker-compose.yml b/docker-compose.yml index c7a16ab..39f4b5d 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -65,6 +65,9 @@ services: Authentication__Oidc__ClientSecret: ${SSO_CLIENT_SECRET:-} Authentication__Oidc__AutoProvision: ${SSO_AUTO_PROVISION:-false} Authentication__Oidc__DisableLocalLogin: ${SSO_DISABLE_LOCAL_LOGIN:-false} + # two-factor sign-in; see TWO_FACTOR_* in .env.example and docs/two-factor.md + Authentication__TwoFactor__RequireForAdministrators: ${TWO_FACTOR_REQUIRE_FOR_ADMINS:-false} + Authentication__TwoFactor__RememberDeviceDays: ${TWO_FACTOR_REMEMBER_DEVICE_DAYS:-30} ports: - "${TASKIST_PORT:-8080}:8080" volumes: diff --git a/docs/two-factor.md b/docs/two-factor.md new file mode 100644 index 0000000..14f63ef --- /dev/null +++ b/docs/two-factor.md @@ -0,0 +1,53 @@ +# Two-factor sign-in + +Two-factor sign-in asks for a code from an authenticator app after the password, so a stolen password alone isn't enough to get into Taskist. It works with any app that supports standard time-based codes (TOTP), such as Microsoft Authenticator, Google Authenticator, 1Password, Bitwarden, Authy or Aegis. + +- [For users: turn it on](#for-users-turn-it-on) +- [Signing in](#signing-in) +- [Lost your phone?](#lost-your-phone) +- [For administrators](#for-administrators) + +## For users: turn it on + +1. Open **My profile → Security** and click **Turn on** under *Two-factor sign-in*. +2. Scan the QR code with your authenticator app. If you can't scan it, type the key shown under the code into the app instead. +3. Enter the 6-digit code the app shows and click **Turn on**. +4. Taskist shows ten **recovery codes**. Save them somewhere safe, for example in your password manager. Each one signs you in once if you lose your phone. They aren't shown again. + +The option is only shown for accounts with a Taskist password. If you sign in with single sign-on, your organisation's identity provider handles extra verification instead. + +## Signing in + +After your password, Taskist asks for the current code from your app. If you tick **Don't ask again on this device**, that browser skips the code step for the next 30 days (your administrator can change or turn off this period). + +If a code is rejected, check that your phone's clock is set automatically, and use the newest code. A code can only be used once. + +## Lost your phone? + +- On the code step, click **Can't use your app? Use a recovery code** and enter one of your saved recovery codes. +- Once you're in, go to **My profile → Security** and either turn two-factor sign-in off and on again with your new phone, or click **New recovery codes** if you've used several. +- No phone and no recovery codes? Ask an administrator to **reset** your two-factor sign-in. You can then sign in with your password and set it up again. + +## For administrators + +### Settings + +| Setting | Default | Description | +| --- | --- | --- | +| `Authentication:TwoFactor:RequireForAdministrators` | `false` | Administrators who sign in with a password must set up two-factor sign-in. Until they do, they can only use their profile page. | +| `Authentication:TwoFactor:RememberDeviceDays` | `30` | How long "Don't ask again on this device" lasts. `0` removes the option, so a code is asked at every sign-in. The remembered-device cookie is always marked *Secure*, so the option only works when people reach Taskist over HTTPS; on a plain-HTTP install (such as the Docker sample) a code is asked every time. | + +In Docker these are `TWO_FACTOR_REQUIRE_FOR_ADMINS` and `TWO_FACTOR_REMEMBER_DEVICE_DAYS` in `.env`. + +### Resetting a user + +Open **Users & Access → Users**, edit the user, and click **Reset two-factor**. This removes their authenticator key, recovery codes and remembered devices; they can sign in with just their password until they set it up again. Both your account and theirs get an entry in the activity log. + +Before resetting, make sure the request really comes from that person: a reset by mistake puts the account back to password-only. + +### Good to know + +- Wrong codes count towards the normal failed-attempt lock-out (**Configuration → Settings → Security**), just like wrong passwords. A locked account is unlocked from the user list as usual. +- Turning two-factor sign-in off, or creating new recovery codes, needs a current code, so someone who briefly gets hold of an open session can't quietly remove it. +- Single sign-on users are never asked for a Taskist code. If you require MFA, enforce it at your identity provider. +- Keep the Data Protection key folder backed up (see [SECURITY.md](../SECURITY.md)). The authenticator keys are encrypted with it; if it's lost, every user with two-factor sign-in needs a reset. diff --git a/sql-scripts/01_schema.sql b/sql-scripts/01_schema.sql index 9796240..ae64a1a 100644 --- a/sql-scripts/01_schema.sql +++ b/sql-scripts/01_schema.sql @@ -2032,3 +2032,64 @@ END; COMMIT; GO +BEGIN TRANSACTION; +IF NOT EXISTS ( + SELECT * FROM [__EFMigrationsHistory] + WHERE [MigrationId] = N'20261112183742_AddUserTwoFactor' +) +BEGIN + CREATE TABLE [UserRecoveryCode] ( + [Id] int NOT NULL IDENTITY, + [UserId] int NOT NULL, + [CodeHash] nvarchar(64) NOT NULL, + [CreatedOn] datetime2 NOT NULL, + [UsedOn] datetime2 NULL, + CONSTRAINT [PK_UserRecoveryCode] PRIMARY KEY ([Id]), + CONSTRAINT [FK_UserRecoveryCode_User_UserId] FOREIGN KEY ([UserId]) REFERENCES [User] ([Id]) + ); +END; + +IF NOT EXISTS ( + SELECT * FROM [__EFMigrationsHistory] + WHERE [MigrationId] = N'20261112183742_AddUserTwoFactor' +) +BEGIN + CREATE TABLE [UserTwoFactor] ( + [Id] int NOT NULL IDENTITY, + [UserId] int NOT NULL, + [Secret] nvarchar(max) NOT NULL, + [EnabledOn] datetime2 NOT NULL, + [LastUsedTimeStep] bigint NOT NULL, + CONSTRAINT [PK_UserTwoFactor] PRIMARY KEY ([Id]), + CONSTRAINT [FK_UserTwoFactor_User_UserId] FOREIGN KEY ([UserId]) REFERENCES [User] ([Id]) + ); +END; + +IF NOT EXISTS ( + SELECT * FROM [__EFMigrationsHistory] + WHERE [MigrationId] = N'20261112183742_AddUserTwoFactor' +) +BEGIN + CREATE INDEX [IX_UserRecoveryCode_UserId] ON [UserRecoveryCode] ([UserId]); +END; + +IF NOT EXISTS ( + SELECT * FROM [__EFMigrationsHistory] + WHERE [MigrationId] = N'20261112183742_AddUserTwoFactor' +) +BEGIN + CREATE UNIQUE INDEX [IX_UserTwoFactor_UserId] ON [UserTwoFactor] ([UserId]); +END; + +IF NOT EXISTS ( + SELECT * FROM [__EFMigrationsHistory] + WHERE [MigrationId] = N'20261112183742_AddUserTwoFactor' +) +BEGIN + INSERT INTO [__EFMigrationsHistory] ([MigrationId], [ProductVersion]) + VALUES (N'20261112183742_AddUserTwoFactor', N'10.0.13'); +END; + +COMMIT; +GO + diff --git a/sql-scripts/03_locale.sql b/sql-scripts/03_locale.sql index 4a3ff2e..87633ec 100644 --- a/sql-scripts/03_locale.sql +++ b/sql-scripts/03_locale.sql @@ -623,6 +623,19 @@ FROM (VALUES (N'Login.Sso.Or', N'or'), (N'Login.Sso.PasswordSignInDisabled', N'Password sign-in is turned off. Use single sign-on instead.'), (N'Login.Sso.SignInWith', N'Sign in with'), + (N'Login.TwoFactor.Cancel', N'Cancel and sign in again'), + (N'Login.TwoFactor.Code', N'Authentication code'), + (N'Login.TwoFactor.Expired', N'Your sign-in timed out or had too many wrong codes. Sign in again.'), + (N'Login.TwoFactor.Intro', N'Enter the 6-digit code from your authenticator app.'), + (N'Login.TwoFactor.RecoveryCode', N'Recovery code'), + (N'Login.TwoFactor.RecoveryIntro', N'Enter one of the recovery codes you saved when you set up two-factor sign-in. Each code works once.'), + (N'Login.TwoFactor.RememberDevice', N'Don’t ask again on this device for {0} days'), + (N'Login.TwoFactor.Title', N'Two-factor sign-in'), + (N'Login.TwoFactor.UseApp', N'Use your authenticator app instead'), + (N'Login.TwoFactor.UseRecovery', N'Can’t use your app? Use a recovery code'), + (N'Login.TwoFactor.Verify', N'Verify'), + (N'Login.TwoFactor.WrongCode', N'That code isn’t right. Check your authenticator app and try again.'), + (N'Login.TwoFactor.WrongRecoveryCode', N'That recovery code isn’t valid or has already been used.'), (N'Message.DeleteSuccess', N'Deleted successfully'), (N'Message.SaveSuccess', N'Saved successfully'), (N'Message.UpdateSuccess', N'Updated successfully'), @@ -760,6 +773,35 @@ FROM (VALUES (N'Profile.SignIns.Unlink', N'Unlink'), (N'Profile.SignIns.UnlinkConfirm', N'Unlink this sign-in? You can link it again by signing in with single sign-on.'), (N'Profile.SignIns.Unlinked', N'Sign-in unlinked.'), + (N'Profile.TwoFactor.CodePrompt', N'Enter the current code from your authenticator app.'), + (N'Profile.TwoFactor.CodesIntro', N'Save these codes somewhere safe, such as a password manager. Each one signs you in once if you lose your phone. They won’t be shown again.'), + (N'Profile.TwoFactor.CodesLeft', N'{0} recovery codes left'), + (N'Profile.TwoFactor.CodesRegenerated', N'New recovery codes created. The old ones no longer work.'), + (N'Profile.TwoFactor.CodesTitle', N'Your recovery codes'), + (N'Profile.TwoFactor.Copied', N'Copied to the clipboard.'), + (N'Profile.TwoFactor.Copy', N'Copy'), + (N'Profile.TwoFactor.Disabled', N'Two-factor sign-in is off.'), + (N'Profile.TwoFactor.DisablePrompt', N'To turn off two-factor sign-in, enter a code from your authenticator app or a recovery code.'), + (N'Profile.TwoFactor.Enable', N'Turn on'), + (N'Profile.TwoFactor.Enabled', N'Two-factor sign-in is on.'), + (N'Profile.TwoFactor.Hint', N'Ask for a code from an authenticator app after your password.'), + (N'Profile.TwoFactor.ManualKey', N'Can’t scan it? Enter this key in the app instead:'), + (N'Profile.TwoFactor.NewCodes', N'New recovery codes'), + (N'Profile.TwoFactor.Off', N'Off'), + (N'Profile.TwoFactor.On', N'On'), + (N'Profile.TwoFactor.QrAlt', N'QR code for your authenticator app'), + (N'Profile.TwoFactor.RequiredHeading', N'Set up two-factor sign-in to continue'), + (N'Profile.TwoFactor.RequiredText', N'Administrators must use two-factor sign-in. Turn it on below; the rest of Taskist is available once it’s set up.'), + (N'Profile.TwoFactor.SavedThem', N'I’ve saved them'), + (N'Profile.TwoFactor.SetupExpired', N'The setup timed out. Close this window and start again.'), + (N'Profile.TwoFactor.SetupTitle', N'Set up two-factor sign-in'), + (N'Profile.TwoFactor.Step1', N'Scan this QR code with an authenticator app'), + (N'Profile.TwoFactor.Step1Hint', N'For example Microsoft Authenticator, Google Authenticator, 1Password, Bitwarden or Aegis.'), + (N'Profile.TwoFactor.Step2', N'Enter the 6-digit code the app shows'), + (N'Profile.TwoFactor.Title', N'Two-factor sign-in'), + (N'Profile.TwoFactor.TurnOff', N'Turn off'), + (N'Profile.TwoFactor.TurnOn', N'Turn on'), + (N'Profile.TwoFactor.WrongCode', N'That code isn’t right. Check the time on your phone and try the newest code.'), (N'Profile.ZoomIn', N'Zoom in'), (N'Profile.ZoomOut', N'Zoom out'), (N'ProfilePage.Title', N'My Profile'), @@ -1312,6 +1354,10 @@ FROM (VALUES (N'UserPage.SignIns.Intro', N'Accounts at the identity provider that can sign this user in. Removing one doesn’t delete the user; if their e-mail still matches, it’s linked again on their next single sign-on.'), (N'UserPage.SignIns.RemoveConfirm', N'Remove this sign-in from the user?'), (N'UserPage.Title', N'User Registration'), + (N'UserPage.TwoFactor.Reset', N'Reset two-factor'), + (N'UserPage.TwoFactor.ResetConfirm', N'Reset two-factor sign-in for this user? Their authenticator app, recovery codes and remembered devices stop working, and they can sign in with just their password until they set it up again.'), + (N'UserPage.TwoFactor.ResetDone', N'Two-factor sign-in was reset.'), + (N'UserPage.TwoFactor.ResetHint', N'Reset it if the user has lost both their authenticator app and their recovery codes.'), (N'UserProjectModel.CanAddWiki', N'Can Add Wiki'), (N'UserProjectModel.CanChangeProject', N'Can Change Project'), (N'UserProjectModel.CanClose', N'Can Close'), diff --git a/src/Libraries/Taskist.Core/Common/ActivityType.cs b/src/Libraries/Taskist.Core/Common/ActivityType.cs index 830eb6a..d16a042 100644 --- a/src/Libraries/Taskist.Core/Common/ActivityType.cs +++ b/src/Libraries/Taskist.Core/Common/ActivityType.cs @@ -9,6 +9,10 @@ public static class ActivityType public const string Logout = "Logout"; + public const string TwoFactorEnabled = "TwoFactorEnabled"; + + public const string TwoFactorDisabled = "TwoFactorDisabled"; + public const string AccessDenied = "AccessDenied"; public const string Export = "Export"; diff --git a/src/Libraries/Taskist.Core/Domain/Users/UserRecoveryCode.cs b/src/Libraries/Taskist.Core/Domain/Users/UserRecoveryCode.cs new file mode 100644 index 0000000..38d7ce1 --- /dev/null +++ b/src/Libraries/Taskist.Core/Domain/Users/UserRecoveryCode.cs @@ -0,0 +1,14 @@ +using Taskist.Core.Domain.Common; + +namespace Taskist.Core.Domain.Users; + +public class UserRecoveryCode : BaseEntity +{ + public int UserId { get; set; } + + public string CodeHash { get; set; } + + public DateTime CreatedOn { get; set; } + + public DateTime? UsedOn { get; set; } +} diff --git a/src/Libraries/Taskist.Core/Domain/Users/UserTwoFactor.cs b/src/Libraries/Taskist.Core/Domain/Users/UserTwoFactor.cs new file mode 100644 index 0000000..6751c0e --- /dev/null +++ b/src/Libraries/Taskist.Core/Domain/Users/UserTwoFactor.cs @@ -0,0 +1,15 @@ +using Taskist.Core.Domain.Common; + +namespace Taskist.Core.Domain.Users; + +public class UserTwoFactor : BaseEntity +{ + public int UserId { get; set; } + + [Encrypted] + public string Secret { get; set; } + + public DateTime EnabledOn { get; set; } + + public long LastUsedTimeStep { get; set; } +} diff --git a/src/Libraries/Taskist.Core/Security/Base32.cs b/src/Libraries/Taskist.Core/Security/Base32.cs new file mode 100644 index 0000000..f5aed95 --- /dev/null +++ b/src/Libraries/Taskist.Core/Security/Base32.cs @@ -0,0 +1,73 @@ +using System.Text; + +namespace Taskist.Core.Security; + +public static class Base32 +{ + #region Fields + + private const string Alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"; + + #endregion + + #region Methods + + public static string Encode(byte[] data) + { + ArgumentNullException.ThrowIfNull(data); + + var output = new StringBuilder((data.Length * 8 + 4) / 5); + int buffer = 0, bits = 0; + + foreach (var b in data) + { + buffer = (buffer << 8) | b; + bits += 8; + while (bits >= 5) + { + output.Append(Alphabet[(buffer >> (bits - 5)) & 31]); + bits -= 5; + } + } + + if (bits > 0) + output.Append(Alphabet[(buffer << (5 - bits)) & 31]); + + return output.ToString(); + } + + public static byte[]? Decode(string? text) + { + if (string.IsNullOrWhiteSpace(text)) + return null; + + var output = new List(text.Length * 5 / 8); + int buffer = 0, bits = 0; + + foreach (var raw in text) + { + if (raw == ' ' || raw == '-' || raw == '=') + continue; + + var index = Alphabet.IndexOf(char.ToUpperInvariant(raw)); + if (index < 0) + return null; + + buffer = (buffer << 5) | index; + bits += 5; + if (bits >= 8) + { + output.Add((byte)((buffer >> (bits - 8)) & 0xFF)); + bits -= 8; + } + } + + return output.Count == 0 ? null : output.ToArray(); + } + + public static string Group(string value, int size = 4) => + string.Join(' ', Enumerable.Range(0, (value.Length + size - 1) / size) + .Select(i => value.Substring(i * size, Math.Min(size, value.Length - i * size)))); + + #endregion +} diff --git a/src/Libraries/Taskist.Core/Security/OtpAuthUri.cs b/src/Libraries/Taskist.Core/Security/OtpAuthUri.cs new file mode 100644 index 0000000..3eea9bb --- /dev/null +++ b/src/Libraries/Taskist.Core/Security/OtpAuthUri.cs @@ -0,0 +1,20 @@ +namespace Taskist.Core.Security; + +public static class OtpAuthUri +{ + #region Methods + + public static string Build(string issuer, string account, string base32Secret) + { + ArgumentException.ThrowIfNullOrWhiteSpace(issuer); + ArgumentException.ThrowIfNullOrWhiteSpace(account); + ArgumentException.ThrowIfNullOrWhiteSpace(base32Secret); + + var label = $"{Uri.EscapeDataString(issuer.Trim())}:{Uri.EscapeDataString(account.Trim())}"; + + return $"otpauth://totp/{label}?secret={base32Secret}&issuer={Uri.EscapeDataString(issuer.Trim())}" + + $"&algorithm=SHA1&digits={Totp.Digits}&period={Totp.PeriodSeconds}"; + } + + #endregion +} diff --git a/src/Libraries/Taskist.Core/Security/RecoveryCodes.cs b/src/Libraries/Taskist.Core/Security/RecoveryCodes.cs new file mode 100644 index 0000000..ce1be32 --- /dev/null +++ b/src/Libraries/Taskist.Core/Security/RecoveryCodes.cs @@ -0,0 +1,54 @@ +using System.Security.Cryptography; +using System.Text; + +namespace Taskist.Core.Security; + +public static class RecoveryCodes +{ + #region Fields + + public const int DefaultCount = 10; + + private const string Alphabet = "23456789abcdefghjkmnpqrstuvwxyz"; + + private const int GroupLength = 5; + + #endregion + + #region Methods + + public static IReadOnlyList Generate(int count = DefaultCount) + { + var codes = new HashSet(StringComparer.Ordinal); + while (codes.Count < count) + { + var chars = new char[GroupLength * 2]; + for (var i = 0; i < chars.Length; i++) + chars[i] = Alphabet[RandomNumberGenerator.GetInt32(Alphabet.Length)]; + + codes.Add($"{new string(chars, 0, GroupLength)}-{new string(chars, GroupLength, GroupLength)}"); + } + + return codes.ToList(); + } + + public static string? Normalize(string? code) + { + if (string.IsNullOrWhiteSpace(code)) + return null; + + var normalized = new string(code.Where(c => !char.IsWhiteSpace(c) && c != '-').ToArray()).ToLowerInvariant(); + return normalized.Length == GroupLength * 2 && normalized.All(c => Alphabet.Contains(c)) ? normalized : null; + } + + public static string? Hash(string? code) + { + var normalized = Normalize(code); + if (normalized == null) + return null; + + return Convert.ToHexStringLower(SHA256.HashData(Encoding.ASCII.GetBytes(normalized))); + } + + #endregion +} diff --git a/src/Libraries/Taskist.Core/Security/Totp.cs b/src/Libraries/Taskist.Core/Security/Totp.cs new file mode 100644 index 0000000..2fe3674 --- /dev/null +++ b/src/Libraries/Taskist.Core/Security/Totp.cs @@ -0,0 +1,75 @@ +using System.Buffers.Binary; +using System.Security.Cryptography; +using System.Text; + +namespace Taskist.Core.Security; + +public static class Totp +{ + #region Fields + + public const int Digits = 6; + + public const int PeriodSeconds = 30; + + public const int SecretBytes = 20; + + public const int DefaultWindow = 1; + + #endregion + + #region Methods + + public static string GenerateSecret() => Base32.Encode(RandomNumberGenerator.GetBytes(SecretBytes)); + + public static long TimeStep(DateTimeOffset time) => time.ToUnixTimeSeconds() / PeriodSeconds; + + public static string ComputeCode(byte[] key, long timeStep) + { + ArgumentNullException.ThrowIfNull(key); + + Span counter = stackalloc byte[8]; + BinaryPrimitives.WriteInt64BigEndian(counter, timeStep); + + var hash = HMACSHA1.HashData(key, counter); + var offset = hash[^1] & 0x0F; + var binary = ((hash[offset] & 0x7F) << 24) + | (hash[offset + 1] << 16) + | (hash[offset + 2] << 8) + | hash[offset + 3]; + + return (binary % 1_000_000).ToString("D6"); + } + + public static string? NormalizeCode(string? code) + { + if (string.IsNullOrWhiteSpace(code)) + return null; + + var digits = new string(code.Where(c => !char.IsWhiteSpace(c) && c != '-').ToArray()); + return digits.Length == Digits && digits.All(char.IsAsciiDigit) ? digits : null; + } + + public static long? Verify(string? base32Secret, string? code, DateTimeOffset now, long lastUsedTimeStep, int window = DefaultWindow) + { + var key = Base32.Decode(base32Secret); + var normalized = NormalizeCode(code); + if (key == null || normalized == null) + return null; + + var expected = Encoding.ASCII.GetBytes(normalized); + var current = TimeStep(now); + long? matched = null; + + for (var step = current - window; step <= current + window; step++) + { + var candidate = Encoding.ASCII.GetBytes(ComputeCode(key, step)); + if (CryptographicOperations.FixedTimeEquals(candidate, expected) && step > lastUsedTimeStep) + matched ??= step; + } + + return matched; + } + + #endregion +} diff --git a/src/Libraries/Taskist.Data/Configuration/Users/UserRecoveryCodeConfig.cs b/src/Libraries/Taskist.Data/Configuration/Users/UserRecoveryCodeConfig.cs new file mode 100644 index 0000000..a093f1b --- /dev/null +++ b/src/Libraries/Taskist.Data/Configuration/Users/UserRecoveryCodeConfig.cs @@ -0,0 +1,28 @@ +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Metadata.Builders; +using Taskist.Core.Domain.Users; + +namespace Taskist.Data.Configuration.Users; + +public class UserRecoveryCodeConfig : EntityTypeConfiguration +{ + public override void Configure(EntityTypeBuilder builder) + { + builder.ToTable(nameof(UserRecoveryCode)); + + builder.HasKey(x => x.Id); + + builder.Property(x => x.CodeHash) + .HasMaxLength(64) + .IsRequired(); + + builder.HasIndex(x => x.UserId); + + builder.HasOne() + .WithMany() + .HasForeignKey(x => x.UserId) + .OnDelete(DeleteBehavior.NoAction); + + base.Configure(builder); + } +} diff --git a/src/Libraries/Taskist.Data/Configuration/Users/UserTwoFactorConfig.cs b/src/Libraries/Taskist.Data/Configuration/Users/UserTwoFactorConfig.cs new file mode 100644 index 0000000..04c4860 --- /dev/null +++ b/src/Libraries/Taskist.Data/Configuration/Users/UserTwoFactorConfig.cs @@ -0,0 +1,28 @@ +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Metadata.Builders; +using Taskist.Core.Domain.Users; + +namespace Taskist.Data.Configuration.Users; + +public class UserTwoFactorConfig : EntityTypeConfiguration +{ + public override void Configure(EntityTypeBuilder builder) + { + builder.ToTable(nameof(UserTwoFactor)); + + builder.HasKey(x => x.Id); + + builder.Property(x => x.Secret) + .IsRequired(); + + builder.HasIndex(x => x.UserId) + .IsUnique(); + + builder.HasOne() + .WithMany() + .HasForeignKey(x => x.UserId) + .OnDelete(DeleteBehavior.NoAction); + + base.Configure(builder); + } +} diff --git a/src/Libraries/Taskist.Data/Migrations/20261112183742_AddUserTwoFactor.Designer.cs b/src/Libraries/Taskist.Data/Migrations/20261112183742_AddUserTwoFactor.Designer.cs new file mode 100644 index 0000000..ffe28bc --- /dev/null +++ b/src/Libraries/Taskist.Data/Migrations/20261112183742_AddUserTwoFactor.Designer.cs @@ -0,0 +1,3497 @@ +// +using System; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using Taskist.Data; + +#nullable disable + +namespace Taskist.Data.Migrations +{ + [DbContext(typeof(ApplicationContext))] + [Migration("20261112183742_AddUserTwoFactor")] + partial class AddUserTwoFactor + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "10.0.13") + .HasAnnotation("Relational:MaxIdentifierLength", 128); + + SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder); + + modelBuilder.Entity("Taskist.Core.Domain.Announcements.Announcement", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("Active") + .HasColumnType("bit"); + + b.Property("Audience") + .HasColumnType("int"); + + b.Property("Body") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Deleted") + .HasColumnType("bit"); + + b.Property("DisplayOrder") + .HasColumnType("int"); + + b.Property("RequiresAcknowledgement") + .HasColumnType("bit"); + + b.Property("Severity") + .HasColumnType("int"); + + b.Property("Title") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("nvarchar(200)"); + + b.Property("Type") + .HasColumnType("int"); + + b.Property("ValidFrom") + .HasColumnType("date"); + + b.Property("ValidTo") + .HasColumnType("date"); + + b.HasKey("Id"); + + b.HasIndex("Active", "Deleted"); + + b.ToTable("Announcement", (string)null); + }); + + modelBuilder.Entity("Taskist.Core.Domain.Announcements.AnnouncementAcknowledgement", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("AcknowledgedOnUtc") + .HasColumnType("datetime2"); + + b.Property("AnnouncementId") + .HasColumnType("int"); + + b.Property("UserId") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.HasIndex("AnnouncementId", "UserId") + .IsUnique(); + + b.ToTable("AnnouncementAcknowledgement", (string)null); + }); + + modelBuilder.Entity("Taskist.Core.Domain.Announcements.AnnouncementRole", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("AnnouncementId") + .HasColumnType("int"); + + b.Property("UserRoleId") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex("UserRoleId"); + + b.HasIndex("AnnouncementId", "UserRoleId"); + + b.ToTable("AnnouncementRole", (string)null); + }); + + modelBuilder.Entity("Taskist.Core.Domain.Git.ExternalCommentLink", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("BacklogCommentId") + .HasColumnType("int"); + + b.Property("ContentHash") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("ExternalCommentId") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("ExternalIssueLinkId") + .HasColumnType("int"); + + b.Property("Inbound") + .HasColumnType("bit"); + + b.Property("LastSyncedOn") + .HasColumnType("datetime2"); + + b.HasKey("Id"); + + b.HasIndex("BacklogCommentId"); + + b.HasIndex("ExternalIssueLinkId", "ExternalCommentId") + .IsUnique(); + + b.ToTable("ExternalCommentLink", (string)null); + }); + + modelBuilder.Entity("Taskist.Core.Domain.Git.ExternalIssueLink", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("BacklogId") + .HasColumnType("int"); + + b.Property("CreatedOn") + .HasColumnType("datetime2"); + + b.Property("ExternalId") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("LastError") + .HasMaxLength(1000) + .HasColumnType("nvarchar(1000)"); + + b.Property("LastSyncedOn") + .HasColumnType("datetime2"); + + b.Property("Number") + .HasColumnType("int"); + + b.Property("ProjectRepositoryId") + .HasColumnType("int"); + + b.Property("RemoteState") + .HasMaxLength(20) + .HasColumnType("nvarchar(20)"); + + b.Property("RemoteUpdatedOn") + .HasColumnType("datetime2"); + + b.Property("Snapshot") + .HasColumnType("nvarchar(max)"); + + b.Property("SyncEnabled") + .HasColumnType("bit"); + + b.Property("Url") + .HasMaxLength(500) + .HasColumnType("nvarchar(500)"); + + b.HasKey("Id"); + + b.HasIndex("BacklogId"); + + b.HasIndex("ProjectRepositoryId", "Number") + .IsUnique(); + + b.ToTable("ExternalIssueLink", (string)null); + }); + + modelBuilder.Entity("Taskist.Core.Domain.Git.GitConnection", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("Active") + .HasColumnType("bit"); + + b.Property("AllowInsecureHttp") + .HasColumnType("bit"); + + b.Property("ApiUrl") + .HasMaxLength(500) + .HasColumnType("nvarchar(500)"); + + b.Property("AppId") + .HasMaxLength(50) + .HasColumnType("nvarchar(50)"); + + b.Property("AppPrivateKey") + .HasColumnType("nvarchar(max)"); + + b.Property("AuthMode") + .HasColumnType("int"); + + b.Property("BaseUrl") + .IsRequired() + .HasMaxLength(500) + .HasColumnType("nvarchar(500)"); + + b.Property("CreatedOn") + .HasColumnType("datetime2"); + + b.Property("Deleted") + .HasColumnType("bit"); + + b.Property("IsDefault") + .HasColumnType("bit"); + + b.Property("ModifiedOn") + .HasColumnType("datetime2"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("nvarchar(100)"); + + b.Property("OAuthClientId") + .HasMaxLength(200) + .HasColumnType("nvarchar(200)"); + + b.Property("OAuthClientSecret") + .HasColumnType("nvarchar(max)"); + + b.Property("ProviderType") + .HasColumnType("int"); + + b.Property("ServiceAccountExternalId") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("ServiceAccountUserName") + .HasMaxLength(255) + .HasColumnType("nvarchar(255)"); + + b.Property("ServiceToken") + .HasColumnType("nvarchar(max)"); + + b.HasKey("Id"); + + b.ToTable("GitConnection", (string)null); + }); + + modelBuilder.Entity("Taskist.Core.Domain.Git.GitWebhookDelivery", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("Attempts") + .HasColumnType("int"); + + b.Property("DeliveryId") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("nvarchar(100)"); + + b.Property("Error") + .HasMaxLength(1000) + .HasColumnType("nvarchar(1000)"); + + b.Property("EventName") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("nvarchar(100)"); + + b.Property("Payload") + .HasColumnType("nvarchar(max)"); + + b.Property("ProcessedOn") + .HasColumnType("datetime2"); + + b.Property("ProjectRepositoryId") + .HasColumnType("int"); + + b.Property("ReceivedOn") + .HasColumnType("datetime2"); + + b.Property("Status") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex("ReceivedOn"); + + b.HasIndex("ProjectRepositoryId", "DeliveryId") + .IsUnique(); + + b.ToTable("GitWebhookDelivery", (string)null); + }); + + modelBuilder.Entity("Taskist.Core.Domain.Git.ProjectRepository", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("Active") + .HasColumnType("bit"); + + b.Property("CreatedOn") + .HasColumnType("datetime2"); + + b.Property("DefaultBranch") + .HasMaxLength(255) + .HasColumnType("nvarchar(255)"); + + b.Property("Deleted") + .HasColumnType("bit"); + + b.Property("DisplayName") + .HasMaxLength(255) + .HasColumnType("nvarchar(255)"); + + b.Property("ExternalRepoId") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("GitConnectionId") + .HasColumnType("int"); + + b.Property("IsPrimary") + .HasColumnType("bit"); + + b.Property("IsPrivate") + .HasColumnType("bit"); + + b.Property("IssueClosedStatusId") + .HasColumnType("int"); + + b.Property("IssueImportLabel") + .HasMaxLength(100) + .HasColumnType("nvarchar(100)"); + + b.Property("IssueImportLimitPerHour") + .HasColumnType("int"); + + b.Property("IssueLastPolledOn") + .HasColumnType("datetime2"); + + b.Property("IssueOpenStatusId") + .HasColumnType("int"); + + b.Property("IssueSeverityId") + .HasColumnType("int"); + + b.Property("IssueSyncComments") + .HasColumnType("bit"); + + b.Property("IssueSyncEnabledOn") + .HasColumnType("datetime2"); + + b.Property("IssueSyncMode") + .HasColumnType("int"); + + b.Property("IssueSyncTaskTypeIds") + .HasMaxLength(200) + .HasColumnType("nvarchar(200)"); + + b.Property("IssueSyncUserId") + .HasColumnType("int"); + + b.Property("IssueTaskTypeId") + .HasColumnType("int"); + + b.Property("ModifiedOn") + .HasColumnType("datetime2"); + + b.Property("ProjectId") + .HasColumnType("int"); + + b.Property("RepoRef") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("nvarchar(255)"); + + b.Property("WebUrl") + .HasMaxLength(500) + .HasColumnType("nvarchar(500)"); + + b.Property("WebhookKey") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("WebhookLastDeliveryOn") + .HasColumnType("datetime2"); + + b.Property("WebhookSecret") + .HasColumnType("nvarchar(max)"); + + b.Property("WebhookSecretCreatedOn") + .HasColumnType("datetime2"); + + b.HasKey("Id"); + + b.HasIndex("GitConnectionId"); + + b.HasIndex("IssueClosedStatusId"); + + b.HasIndex("IssueOpenStatusId"); + + b.HasIndex("IssueSeverityId"); + + b.HasIndex("IssueSyncUserId"); + + b.HasIndex("IssueTaskTypeId"); + + b.HasIndex("WebhookKey") + .IsUnique(); + + b.HasIndex("ProjectId", "GitConnectionId", "RepoRef"); + + b.ToTable("ProjectRepository", (string)null); + }); + + modelBuilder.Entity("Taskist.Core.Domain.Git.UserGitAccount", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("AccessToken") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("ConnectedOn") + .HasColumnType("datetime2"); + + b.Property("DisplayName") + .HasMaxLength(255) + .HasColumnType("nvarchar(255)"); + + b.Property("ExpiresOn") + .HasColumnType("datetime2"); + + b.Property("ExternalUserId") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("GitConnectionId") + .HasColumnType("int"); + + b.Property("LastUsedOn") + .HasColumnType("datetime2"); + + b.Property("RefreshExpiresOn") + .HasColumnType("datetime2"); + + b.Property("RefreshToken") + .HasColumnType("nvarchar(max)"); + + b.Property("Scopes") + .HasMaxLength(500) + .HasColumnType("nvarchar(500)"); + + b.Property("TokenType") + .HasColumnType("int"); + + b.Property("UserId") + .HasColumnType("int"); + + b.Property("UserName") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("nvarchar(255)"); + + b.HasKey("Id"); + + b.HasIndex("GitConnectionId", "ExternalUserId") + .IsUnique(); + + b.HasIndex("UserId", "GitConnectionId") + .IsUnique(); + + b.ToTable("UserGitAccount", (string)null); + }); + + modelBuilder.Entity("Taskist.Core.Domain.Localization.Language", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("Active") + .HasColumnType("bit"); + + b.Property("DisplayName") + .IsRequired() + .HasMaxLength(750) + .HasColumnType("nvarchar(750)"); + + b.Property("DisplayOrder") + .HasColumnType("int"); + + b.Property("LanguageCulture") + .IsRequired() + .HasMaxLength(10) + .HasColumnType("nvarchar(10)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(750) + .HasColumnType("nvarchar(750)"); + + b.Property("Rtl") + .HasColumnType("bit"); + + b.HasKey("Id"); + + b.ToTable("Language", (string)null); + }); + + modelBuilder.Entity("Taskist.Core.Domain.Localization.LocaleResource", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("LanguageId") + .HasColumnType("int"); + + b.Property("ResourceKey") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("nvarchar(100)"); + + b.Property("ResourceValue") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.HasKey("Id"); + + b.HasIndex("LanguageId"); + + b.ToTable("LocaleResource", (string)null); + }); + + modelBuilder.Entity("Taskist.Core.Domain.Logging.ActivityLog", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("Comment") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("CreatedOnUtc") + .HasColumnType("datetime2"); + + b.Property("EntityId") + .HasColumnType("int"); + + b.Property("EntityName") + .IsRequired() + .HasMaxLength(500) + .HasColumnType("nvarchar(500)"); + + b.Property("IpAddress") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("SystemName") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("nvarchar(100)"); + + b.Property("UserId") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.ToTable("ActivityLog", (string)null); + }); + + modelBuilder.Entity("Taskist.Core.Domain.Logging.AuditLog", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("Action") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("nvarchar(20)"); + + b.Property("CreatedOnUtc") + .HasColumnType("datetime2"); + + b.Property("EntityId") + .HasColumnType("int"); + + b.Property("EntityName") + .IsRequired() + .HasMaxLength(500) + .HasColumnType("nvarchar(500)"); + + b.Property("IpAddress") + .HasMaxLength(100) + .HasColumnType("nvarchar(100)"); + + b.Property("NewValues") + .HasColumnType("nvarchar(max)"); + + b.Property("OldValues") + .HasColumnType("nvarchar(max)"); + + b.Property("UserId") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex("EntityName", "EntityId"); + + b.ToTable("AuditLog", (string)null); + }); + + modelBuilder.Entity("Taskist.Core.Domain.Logging.Log", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("CreatedOnUtc") + .HasColumnType("datetime2"); + + b.Property("FullMessage") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("IpAddress") + .HasColumnType("nvarchar(max)"); + + b.Property("LogLevel") + .HasColumnType("int"); + + b.Property("LogLevelId") + .HasColumnType("int"); + + b.Property("PageUrl") + .HasColumnType("nvarchar(max)"); + + b.Property("ReferrerUrl") + .HasColumnType("nvarchar(max)"); + + b.Property("ShortMessage") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("UserId") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.ToTable("Log", (string)null); + }); + + modelBuilder.Entity("Taskist.Core.Domain.Masters.Address", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("Address1") + .IsRequired() + .HasMaxLength(750) + .HasColumnType("nvarchar(750)"); + + b.Property("Address2") + .HasMaxLength(750) + .HasColumnType("nvarchar(750)"); + + b.Property("City") + .HasMaxLength(100) + .HasColumnType("nvarchar(100)"); + + b.Property("ZipPostalCode") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("nvarchar(20)"); + + b.HasKey("Id"); + + b.ToTable("Address", (string)null); + }); + + modelBuilder.Entity("Taskist.Core.Domain.Masters.Client", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("Active") + .HasColumnType("bit"); + + b.Property("ContactPerson") + .HasMaxLength(100) + .HasColumnType("nvarchar(100)"); + + b.Property("Deleted") + .HasColumnType("bit"); + + b.Property("Description") + .HasMaxLength(250) + .HasColumnType("nvarchar(250)"); + + b.Property("Email") + .HasMaxLength(250) + .HasColumnType("nvarchar(250)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("nvarchar(100)"); + + b.Property("PhoneNumber") + .HasMaxLength(100) + .HasColumnType("nvarchar(100)"); + + b.Property("Website") + .HasMaxLength(750) + .HasColumnType("nvarchar(750)"); + + b.HasKey("Id"); + + b.ToTable("Client", (string)null); + }); + + modelBuilder.Entity("Taskist.Core.Domain.Masters.CustomField", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ColumnClass") + .HasMaxLength(20) + .HasColumnType("int"); + + b.Property("FieldType") + .HasColumnType("int"); + + b.Property("Label") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Mandatory") + .HasColumnType("bit"); + + b.Property("Options") + .HasColumnType("nvarchar(max)"); + + b.Property("Placement") + .HasColumnType("int"); + + b.Property("ProjectId") + .HasColumnType("int"); + + b.Property("ResourceKey") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("nvarchar(100)"); + + b.HasKey("Id"); + + b.HasIndex("ProjectId"); + + b.ToTable("CustomField", (string)null); + }); + + modelBuilder.Entity("Taskist.Core.Domain.Masters.Document", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ContentType") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("nvarchar(50)"); + + b.Property("Extension") + .IsRequired() + .HasMaxLength(10) + .HasColumnType("nvarchar(10)"); + + b.Property("FileData") + .IsRequired() + .HasColumnType("varbinary(max)"); + + b.Property("FileName") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("nvarchar(255)"); + + b.Property("FileSize") + .HasColumnType("bigint"); + + b.HasKey("Id"); + + b.ToTable("Document", (string)null); + }); + + modelBuilder.Entity("Taskist.Core.Domain.Masters.EmailAccount", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("Active") + .HasColumnType("bit"); + + b.Property("Description") + .HasMaxLength(250) + .HasColumnType("nvarchar(250)"); + + b.Property("EnableSsl") + .HasColumnType("bit"); + + b.Property("FromEmail") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("FromName") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Host") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("nvarchar(100)"); + + b.Property("Password") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Port") + .HasColumnType("int"); + + b.Property("UserName") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.HasKey("Id"); + + b.ToTable("EmailAccount", (string)null); + }); + + modelBuilder.Entity("Taskist.Core.Domain.Masters.EmailTemplate", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("Active") + .HasColumnType("bit"); + + b.Property("EmailAccountId") + .HasColumnType("int"); + + b.Property("EmailBody") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("EmailSubject") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("nvarchar(100)"); + + b.HasKey("Id"); + + b.HasIndex("EmailAccountId"); + + b.ToTable("EmailTemplate", (string)null); + }); + + modelBuilder.Entity("Taskist.Core.Domain.Masters.GenericAttribute", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("CreatedOrUpdatedDate") + .HasColumnType("datetime2"); + + b.Property("EntityId") + .HasColumnType("int"); + + b.Property("Key") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("nvarchar(200)"); + + b.Property("KeyGroup") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("nvarchar(200)"); + + b.Property("Value") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.HasKey("Id"); + + b.ToTable("GenericAttribute", (string)null); + }); + + modelBuilder.Entity("Taskist.Core.Domain.Masters.Menu", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ActionName") + .HasMaxLength(100) + .HasColumnType("nvarchar(100)"); + + b.Property("Active") + .HasColumnType("bit"); + + b.Property("Code") + .HasColumnType("int"); + + b.Property("ControllerName") + .HasMaxLength(100) + .HasColumnType("nvarchar(100)"); + + b.Property("DisplayOrder") + .HasColumnType("int"); + + b.Property("Icon") + .HasMaxLength(100) + .HasColumnType("nvarchar(100)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("nvarchar(50)"); + + b.Property("ParentCode") + .HasColumnType("int"); + + b.Property("Permission") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("nvarchar(100)"); + + b.Property("SystemName") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("nvarchar(100)"); + + b.HasKey("Id"); + + b.ToTable("Menu", (string)null); + }); + + modelBuilder.Entity("Taskist.Core.Domain.Masters.Module", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("Active") + .HasColumnType("bit"); + + b.Property("Deleted") + .HasColumnType("bit"); + + b.Property("Description") + .HasColumnType("nvarchar(max)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("nvarchar(100)"); + + b.Property("ProjectId") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex("ProjectId"); + + b.ToTable("Module", (string)null); + }); + + modelBuilder.Entity("Taskist.Core.Domain.Masters.NotificationChannel", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("Active") + .HasColumnType("bit"); + + b.Property("ChannelType") + .HasColumnType("int"); + + b.Property("CreatedOn") + .HasColumnType("datetime2"); + + b.Property("Deleted") + .HasColumnType("bit"); + + b.Property("EndpointUrl") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("LastError") + .HasMaxLength(1000) + .HasColumnType("nvarchar(1000)"); + + b.Property("LastSentOn") + .HasColumnType("datetime2"); + + b.Property("ModifiedOn") + .HasColumnType("datetime2"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("nvarchar(100)"); + + b.Property("SigningSecret") + .HasColumnType("nvarchar(max)"); + + b.HasKey("Id"); + + b.ToTable("NotificationChannel", (string)null); + }); + + modelBuilder.Entity("Taskist.Core.Domain.Masters.Project", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("Active") + .HasColumnType("bit"); + + b.Property("ClientId") + .HasColumnType("int"); + + b.Property("CodeReviewerId") + .HasColumnType("int"); + + b.Property("Deleted") + .HasColumnType("bit"); + + b.Property("Description") + .HasMaxLength(250) + .HasColumnType("nvarchar(250)"); + + b.Property("EndDate") + .HasColumnType("date"); + + b.Property("GitProjectReference") + .HasMaxLength(50) + .HasColumnType("nvarchar(50)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("nvarchar(100)"); + + b.Property("ProjectManagerId") + .HasColumnType("int"); + + b.Property("ReleaseFullIncrement") + .HasColumnType("int"); + + b.Property("ReleaseVersionFormat") + .HasMaxLength(50) + .HasColumnType("nvarchar(50)"); + + b.Property("StartDate") + .HasColumnType("date"); + + b.Property("TeamLeadId") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex("ClientId"); + + b.HasIndex("CodeReviewerId"); + + b.HasIndex("ProjectManagerId"); + + b.HasIndex("TeamLeadId"); + + b.ToTable("Project", (string)null); + }); + + modelBuilder.Entity("Taskist.Core.Domain.Masters.ProjectNotificationChannel", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("Active") + .HasColumnType("bit"); + + b.Property("Events") + .HasColumnType("int"); + + b.Property("NotificationChannelId") + .HasColumnType("int"); + + b.Property("ProjectId") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex("NotificationChannelId"); + + b.HasIndex("ProjectId", "NotificationChannelId") + .IsUnique(); + + b.ToTable("ProjectNotificationChannel", (string)null); + }); + + modelBuilder.Entity("Taskist.Core.Domain.Masters.Reporter", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("Active") + .HasColumnType("bit"); + + b.Property("Deleted") + .HasColumnType("bit"); + + b.Property("Description") + .HasMaxLength(250) + .HasColumnType("nvarchar(250)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("nvarchar(100)"); + + b.Property("ProjectId") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex("ProjectId"); + + b.ToTable("Reporter", (string)null); + }); + + modelBuilder.Entity("Taskist.Core.Domain.Masters.Setting", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("Name") + .IsRequired() + .HasMaxLength(250) + .HasColumnType("nvarchar(250)"); + + b.Property("Value") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.HasKey("Id"); + + b.ToTable("Setting", (string)null); + }); + + modelBuilder.Entity("Taskist.Core.Domain.Masters.Severity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("Active") + .HasColumnType("bit"); + + b.Property("BackgroundColor") + .HasMaxLength(20) + .HasColumnType("nvarchar(20)"); + + b.Property("Deleted") + .HasColumnType("bit"); + + b.Property("Description") + .HasMaxLength(250) + .HasColumnType("nvarchar(250)"); + + b.Property("GroupId") + .HasColumnType("int"); + + b.Property("IconClass") + .HasMaxLength(50) + .HasColumnType("nvarchar(50)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("nvarchar(100)"); + + b.Property("TextColor") + .HasMaxLength(20) + .HasColumnType("nvarchar(20)"); + + b.HasKey("Id"); + + b.ToTable("Severity", (string)null); + }); + + modelBuilder.Entity("Taskist.Core.Domain.Masters.Status", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("Active") + .HasColumnType("bit"); + + b.Property("BackgroundColor") + .HasMaxLength(20) + .HasColumnType("nvarchar(20)"); + + b.Property("Deleted") + .HasColumnType("bit"); + + b.Property("Description") + .HasMaxLength(250) + .HasColumnType("nvarchar(250)"); + + b.Property("ExternalUse") + .HasColumnType("bit"); + + b.Property("GroupId") + .HasColumnType("int"); + + b.Property("IconClass") + .HasMaxLength(50) + .HasColumnType("nvarchar(50)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("nvarchar(100)"); + + b.Property("ProjectId") + .HasColumnType("int"); + + b.Property("RequiredMrNumberForBug") + .HasColumnType("bit"); + + b.Property("RequiredMrNumberForCr") + .HasColumnType("bit"); + + b.Property("RequiredResolutionForBug") + .HasColumnType("bit"); + + b.Property("RequiredResolutionForCr") + .HasColumnType("bit"); + + b.Property("RequiredRootCauseForBug") + .HasColumnType("bit"); + + b.Property("RequiredRootCauseForCr") + .HasColumnType("bit"); + + b.Property("SystemDefined") + .HasColumnType("bit"); + + b.Property("TextColor") + .HasMaxLength(20) + .HasColumnType("nvarchar(20)"); + + b.HasKey("Id"); + + b.HasIndex("ProjectId"); + + b.ToTable("Status", (string)null); + }); + + modelBuilder.Entity("Taskist.Core.Domain.Masters.SubModule", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("Active") + .HasColumnType("bit"); + + b.Property("Deleted") + .HasColumnType("bit"); + + b.Property("Description") + .HasMaxLength(250) + .HasColumnType("nvarchar(250)"); + + b.Property("ModuleId") + .HasColumnType("int"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("nvarchar(100)"); + + b.Property("OwnerId") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex("ModuleId"); + + b.HasIndex("OwnerId"); + + b.ToTable("SubModule", (string)null); + }); + + modelBuilder.Entity("Taskist.Core.Domain.Masters.Tag", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("Active") + .HasColumnType("bit"); + + b.Property("Deleted") + .HasColumnType("bit"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("nvarchar(100)"); + + b.HasKey("Id"); + + b.ToTable("Tag", (string)null); + }); + + modelBuilder.Entity("Taskist.Core.Domain.Masters.TaskType", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("Active") + .HasColumnType("bit"); + + b.Property("BackgroundColor") + .HasMaxLength(20) + .HasColumnType("nvarchar(20)"); + + b.Property("Deleted") + .HasColumnType("bit"); + + b.Property("Description") + .HasMaxLength(250) + .HasColumnType("nvarchar(250)"); + + b.Property("GroupId") + .HasColumnType("int"); + + b.Property("IconClass") + .HasMaxLength(50) + .HasColumnType("nvarchar(50)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("nvarchar(100)"); + + b.Property("TextColor") + .HasMaxLength(20) + .HasColumnType("nvarchar(20)"); + + b.HasKey("Id"); + + b.ToTable("TaskType", (string)null); + }); + + modelBuilder.Entity("Taskist.Core.Domain.Users.User", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("AddressId") + .HasColumnType("int"); + + b.Property("Code") + .HasColumnType("uniqueidentifier"); + + b.Property("DateOfBirth") + .HasColumnType("date"); + + b.Property("DateOfJoin") + .HasColumnType("date"); + + b.Property("Deleted") + .HasColumnType("bit"); + + b.Property("Email") + .IsRequired() + .HasMaxLength(150) + .HasColumnType("nvarchar(150)"); + + b.Property("FailedLoginAttempts") + .HasColumnType("int"); + + b.Property("FirstName") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("nvarchar(50)"); + + b.Property("FriendlyName") + .HasMaxLength(100) + .HasColumnType("nvarchar(100)"); + + b.Property("GenderId") + .HasColumnType("int"); + + b.Property("GitUserName") + .HasMaxLength(100) + .HasColumnType("nvarchar(100)"); + + b.Property("LanguageId") + .HasColumnType("int"); + + b.Property("LastActivityDate") + .HasColumnType("datetime2"); + + b.Property("LastIPAddress") + .HasMaxLength(100) + .HasColumnType("nvarchar(100)"); + + b.Property("LastLoginDate") + .HasColumnType("datetime2"); + + b.Property("LastName") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("nvarchar(50)"); + + b.Property("Locked") + .HasColumnType("bit"); + + b.Property("MaritalStatus") + .HasColumnType("int"); + + b.Property("MobileNumber") + .IsRequired() + .HasMaxLength(10) + .HasColumnType("nvarchar(10)"); + + b.Property("PhotoDocumentId") + .HasColumnType("int"); + + b.Property("Status") + .HasColumnType("int"); + + b.Property("SystemAccount") + .HasColumnType("bit"); + + b.HasKey("Id"); + + b.HasIndex("AddressId"); + + b.HasIndex("LanguageId"); + + b.ToTable("User", (string)null); + }); + + modelBuilder.Entity("Taskist.Core.Domain.Users.UserExternalLogin", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("CreatedOn") + .HasColumnType("datetime2"); + + b.Property("Email") + .HasMaxLength(150) + .HasColumnType("nvarchar(150)"); + + b.Property("LastUsedOn") + .HasColumnType("datetime2"); + + b.Property("Provider") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("nvarchar(255)"); + + b.Property("Subject") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("nvarchar(255)"); + + b.Property("UserId") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.HasIndex("Provider", "Subject") + .IsUnique(); + + b.ToTable("UserExternalLogin", (string)null); + }); + + modelBuilder.Entity("Taskist.Core.Domain.Users.UserNotification", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("CreatedOnUtc") + .HasColumnType("datetime2"); + + b.Property("DedupeKey") + .HasMaxLength(200) + .HasColumnType("nvarchar(200)"); + + b.Property("IsRead") + .HasColumnType("bit"); + + b.Property("Message") + .HasMaxLength(1000) + .HasColumnType("nvarchar(1000)"); + + b.Property("ReadOnUtc") + .HasColumnType("datetime2"); + + b.Property("Title") + .IsRequired() + .HasMaxLength(300) + .HasColumnType("nvarchar(300)"); + + b.Property("Type") + .HasColumnType("int"); + + b.Property("Url") + .HasMaxLength(500) + .HasColumnType("nvarchar(500)"); + + b.Property("UserId") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex("UserId", "DedupeKey"); + + b.HasIndex("UserId", "IsRead", "CreatedOnUtc"); + + b.ToTable("UserNotification", (string)null); + }); + + modelBuilder.Entity("Taskist.Core.Domain.Users.UserPassword", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("CreatedOn") + .HasColumnType("datetime2"); + + b.Property("Password") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("PasswordSalt") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("UserId") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("UserPassword", (string)null); + }); + + modelBuilder.Entity("Taskist.Core.Domain.Users.UserProjectMap", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("CanAddWiki") + .HasColumnType("bit"); + + b.Property("CanChangeProject") + .HasColumnType("bit"); + + b.Property("CanClose") + .HasColumnType("bit"); + + b.Property("CanComment") + .HasColumnType("bit"); + + b.Property("CanDeleteTask") + .HasColumnType("bit"); + + b.Property("CanEdit") + .HasColumnType("bit"); + + b.Property("CanEditOthersTask") + .HasColumnType("bit"); + + b.Property("CanMergeMergeRequests") + .HasColumnType("bit"); + + b.Property("CanReOpen") + .HasColumnType("bit"); + + b.Property("CanReportBug") + .HasColumnType("bit"); + + b.Property("CanReportCR") + .HasColumnType("bit"); + + b.Property("CanReportToDo") + .HasColumnType("bit"); + + b.Property("CanReviewMergeRequests") + .HasColumnType("bit"); + + b.Property("CanViewOthersTask") + .HasColumnType("bit"); + + b.Property("ProjectId") + .HasColumnType("int"); + + b.Property("UserId") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex("ProjectId"); + + b.HasIndex("UserId"); + + b.ToTable("UserProjectMap", (string)null); + }); + + modelBuilder.Entity("Taskist.Core.Domain.Users.UserRecoveryCode", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("CodeHash") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("CreatedOn") + .HasColumnType("datetime2"); + + b.Property("UsedOn") + .HasColumnType("datetime2"); + + b.Property("UserId") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("UserRecoveryCode", (string)null); + }); + + modelBuilder.Entity("Taskist.Core.Domain.Users.UserRole", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("Active") + .HasColumnType("bit"); + + b.Property("Description") + .HasMaxLength(250) + .HasColumnType("nvarchar(250)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("nvarchar(50)"); + + b.Property("SystemDefined") + .HasColumnType("bit"); + + b.Property("SystemName") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("nvarchar(50)"); + + b.HasKey("Id"); + + b.ToTable("UserRole", (string)null); + }); + + modelBuilder.Entity("Taskist.Core.Domain.Users.UserRoleMap", b => + { + b.Property("UserId") + .HasColumnType("int"); + + b.Property("UserRoleId") + .HasColumnType("int"); + + b.HasKey("UserId", "UserRoleId"); + + b.HasIndex("UserRoleId"); + + b.ToTable("UserRoleMap", (string)null); + }); + + modelBuilder.Entity("Taskist.Core.Domain.Users.UserRolePermission", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("Name") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("nvarchar(100)"); + + b.Property("RoleGroup") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("nvarchar(255)"); + + b.Property("SystemDefined") + .HasColumnType("bit"); + + b.Property("SystemName") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("nvarchar(255)"); + + b.HasKey("Id"); + + b.ToTable("UserRolePermission", (string)null); + }); + + modelBuilder.Entity("Taskist.Core.Domain.Users.UserRolePermissionMap", b => + { + b.Property("PermissionId") + .HasColumnType("int"); + + b.Property("UserRoleId") + .HasColumnType("int"); + + b.HasKey("PermissionId", "UserRoleId"); + + b.HasIndex("UserRoleId"); + + b.ToTable("UserRolePermissionMap", (string)null); + }); + + modelBuilder.Entity("Taskist.Core.Domain.Users.UserTwoFactor", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("EnabledOn") + .HasColumnType("datetime2"); + + b.Property("LastUsedTimeStep") + .HasColumnType("bigint"); + + b.Property("Secret") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("UserId") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex("UserId") + .IsUnique(); + + b.ToTable("UserTwoFactor", (string)null); + }); + + modelBuilder.Entity("Taskist.Core.Domain.Wiki.WikiCategory", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("Active") + .HasColumnType("bit"); + + b.Property("Deleted") + .HasColumnType("bit"); + + b.Property("Description") + .HasMaxLength(250) + .HasColumnType("nvarchar(250)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("nvarchar(100)"); + + b.Property("ParentCategoryId") + .HasColumnType("int"); + + b.Property("ProjectId") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex("ParentCategoryId"); + + b.HasIndex("ProjectId"); + + b.ToTable("WikiCategory", (string)null); + }); + + modelBuilder.Entity("Taskist.Core.Domain.Wiki.WikiDocument", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("CategoryId") + .HasColumnType("int"); + + b.Property("ContentHtml") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("CreatedById") + .HasColumnType("int"); + + b.Property("CreatedOn") + .HasColumnType("datetime2"); + + b.Property("Deleted") + .HasColumnType("bit"); + + b.Property("ModifiedById") + .HasColumnType("int"); + + b.Property("ModifiedOn") + .HasColumnType("datetime2"); + + b.Property("ModuleId") + .HasColumnType("int"); + + b.Property("SubModuleId") + .HasColumnType("int"); + + b.Property("Title") + .IsRequired() + .HasMaxLength(250) + .HasColumnType("nvarchar(250)"); + + b.HasKey("Id"); + + b.HasIndex("CategoryId"); + + b.HasIndex("CreatedById"); + + b.HasIndex("ModifiedById"); + + b.HasIndex("ModuleId"); + + b.HasIndex("SubModuleId"); + + b.ToTable("WikiDocument", (string)null); + }); + + modelBuilder.Entity("Taskist.Core.Domain.Wiki.WikiDocumentVersion", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ContentHtml") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("CreatedOn") + .HasColumnType("datetime2"); + + b.Property("ModifiedById") + .HasColumnType("int"); + + b.Property("Note") + .HasColumnType("nvarchar(max)"); + + b.Property("Title") + .IsRequired() + .HasMaxLength(250) + .HasColumnType("nvarchar(250)"); + + b.Property("WikiDocumentId") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex("ModifiedById"); + + b.HasIndex("WikiDocumentId"); + + b.ToTable("WikiDocumentVersion", (string)null); + }); + + modelBuilder.Entity("Taskist.Core.Domain.Wiki.WikiImage", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("CreatedOn") + .HasColumnType("datetime2"); + + b.Property("DocumentId") + .HasColumnType("int"); + + b.Property("ProjectId") + .HasColumnType("int"); + + b.Property("UploadedById") + .HasColumnType("int"); + + b.Property("WikiDocumentId") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex("DocumentId") + .IsUnique(); + + b.HasIndex("ProjectId"); + + b.HasIndex("UploadedById"); + + b.HasIndex("WikiDocumentId"); + + b.ToTable("WikiImage", (string)null); + }); + + modelBuilder.Entity("Taskist.Core.Domain.WorkItems.Backlog", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("AssigneeId") + .HasColumnType("int"); + + b.Property("AttachmentCount") + .HasColumnType("int"); + + b.Property("Code") + .HasColumnType("uniqueidentifier"); + + b.Property("CommentCount") + .HasColumnType("int"); + + b.Property("CreatedById") + .HasColumnType("int"); + + b.Property("CreatedOn") + .HasColumnType("datetime2"); + + b.Property("Deleted") + .HasColumnType("bit"); + + b.Property("Description") + .HasColumnType("nvarchar(max)"); + + b.Property("DueDate") + .HasColumnType("date"); + + b.Property("EnvironmentJson") + .HasColumnType("nvarchar(max)"); + + b.Property("ExternalNotes") + .HasColumnType("nvarchar(max)"); + + b.Property("MergeRequestId") + .HasColumnType("int"); + + b.Property("MergeRequestRepositoryId") + .HasColumnType("int"); + + b.Property("ModifiedById") + .HasColumnType("int"); + + b.Property("ModifiedOn") + .HasColumnType("datetime2"); + + b.Property("ModuleId") + .HasColumnType("int"); + + b.Property("ParentId") + .HasColumnType("int"); + + b.Property("PlannedStartDate") + .HasColumnType("date"); + + b.Property("ProjectId") + .HasColumnType("int"); + + b.Property("ReOpenCount") + .HasColumnType("int"); + + b.Property("ReleaseId") + .HasColumnType("int"); + + b.Property("ReporterId") + .HasColumnType("int"); + + b.Property("ResolutionDetails") + .HasColumnType("nvarchar(max)"); + + b.Property("RootCauseAnalysis") + .HasColumnType("nvarchar(max)"); + + b.Property("SeverityId") + .HasColumnType("int"); + + b.Property("SourceId") + .HasColumnType("int"); + + b.Property("SourceWikiDocumentId") + .HasColumnType("int"); + + b.Property("StatusId") + .HasColumnType("int"); + + b.Property("SubModuleId") + .HasColumnType("int"); + + b.Property("SubTaskCount") + .HasColumnType("int"); + + b.Property("TaskTypeId") + .HasColumnType("int"); + + b.Property("TesterId") + .HasColumnType("int"); + + b.Property("Title") + .IsRequired() + .HasMaxLength(500) + .HasColumnType("nvarchar(500)"); + + b.HasKey("Id"); + + b.HasIndex("AssigneeId"); + + b.HasIndex("CreatedById"); + + b.HasIndex("MergeRequestRepositoryId"); + + b.HasIndex("ModifiedById"); + + b.HasIndex("ModuleId"); + + b.HasIndex("ParentId"); + + b.HasIndex("ProjectId"); + + b.HasIndex("ReleaseId"); + + b.HasIndex("ReporterId"); + + b.HasIndex("SeverityId"); + + b.HasIndex("SourceWikiDocumentId"); + + b.HasIndex("StatusId"); + + b.HasIndex("SubModuleId"); + + b.HasIndex("TaskTypeId"); + + b.HasIndex("TesterId"); + + b.ToTable("Backlog", (string)null); + }); + + modelBuilder.Entity("Taskist.Core.Domain.WorkItems.BacklogComment", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("BacklogId") + .HasColumnType("int"); + + b.Property("Comment") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("CreatedById") + .HasColumnType("int"); + + b.Property("CreatedOn") + .HasColumnType("datetime2"); + + b.Property("FieldName") + .HasMaxLength(100) + .HasColumnType("nvarchar(100)"); + + b.Property("ModifiedById") + .HasColumnType("int"); + + b.Property("ModifiedOn") + .HasColumnType("datetime2"); + + b.Property("NewValue") + .HasColumnType("nvarchar(max)"); + + b.Property("OldValue") + .HasColumnType("nvarchar(max)"); + + b.Property("PostToIssue") + .HasColumnType("bit"); + + b.Property("SystemComment") + .HasColumnType("bit"); + + b.HasKey("Id"); + + b.HasIndex("BacklogId"); + + b.HasIndex("CreatedById"); + + b.HasIndex("ModifiedById"); + + b.ToTable("BacklogComment", (string)null); + }); + + modelBuilder.Entity("Taskist.Core.Domain.WorkItems.BacklogCustomFieldValue", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("BacklogId") + .HasColumnType("int"); + + b.Property("CustomFieldId") + .HasColumnType("int"); + + b.Property("Value") + .HasColumnType("nvarchar(max)"); + + b.HasKey("Id"); + + b.HasIndex("BacklogId"); + + b.HasIndex("CustomFieldId"); + + b.ToTable("BacklogCustomFieldValue", (string)null); + }); + + modelBuilder.Entity("Taskist.Core.Domain.WorkItems.BacklogDocument", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("BacklogId") + .HasColumnType("int"); + + b.Property("CreatedById") + .HasColumnType("int"); + + b.Property("CreatedOn") + .HasColumnType("datetime2"); + + b.Property("DocumentId") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex("BacklogId"); + + b.HasIndex("CreatedById"); + + b.HasIndex("DocumentId"); + + b.ToTable("BacklogDocument", (string)null); + }); + + modelBuilder.Entity("Taskist.Core.Domain.WorkItems.BacklogStatusLog", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("BacklogId") + .HasColumnType("int"); + + b.Property("CreatedById") + .HasColumnType("int"); + + b.Property("CreatedOn") + .HasColumnType("datetime2"); + + b.Property("StatusId") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex("BacklogId"); + + b.HasIndex("CreatedById"); + + b.HasIndex("StatusId"); + + b.ToTable("BacklogStatusLog", (string)null); + }); + + modelBuilder.Entity("Taskist.Core.Domain.WorkItems.BacklogTag", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("BacklogId") + .HasColumnType("int"); + + b.Property("TagId") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex("TagId"); + + b.HasIndex("BacklogId", "TagId"); + + b.ToTable("BacklogTag", (string)null); + }); + + modelBuilder.Entity("Taskist.Core.Domain.WorkItems.GitBranch", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("BaseBranch") + .HasMaxLength(255) + .HasColumnType("nvarchar(255)"); + + b.Property("CreatedById") + .HasColumnType("int"); + + b.Property("CreatedOn") + .HasColumnType("datetime2"); + + b.Property("Deleted") + .HasColumnType("bit"); + + b.Property("GitProjectReference") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("nvarchar(255)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("nvarchar(255)"); + + b.Property("Origin") + .HasColumnType("int"); + + b.Property("ProjectId") + .HasColumnType("int"); + + b.Property("ProjectRepositoryId") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex("CreatedById"); + + b.HasIndex("ProjectId"); + + b.HasIndex("ProjectRepositoryId"); + + b.HasIndex("GitProjectReference", "Name"); + + b.ToTable("GitBranch", (string)null); + }); + + modelBuilder.Entity("Taskist.Core.Domain.WorkItems.GitBranchTask", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("BacklogId") + .HasColumnType("int"); + + b.Property("GitBranchId") + .HasColumnType("int"); + + b.Property("LinkedById") + .HasColumnType("int"); + + b.Property("LinkedOn") + .HasColumnType("datetime2"); + + b.HasKey("Id"); + + b.HasIndex("BacklogId"); + + b.HasIndex("LinkedById"); + + b.HasIndex("GitBranchId", "BacklogId") + .IsUnique(); + + b.ToTable("GitBranchTask", (string)null); + }); + + modelBuilder.Entity("Taskist.Core.Domain.WorkItems.Release", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("Deleted") + .HasColumnType("bit"); + + b.Property("Description") + .HasMaxLength(500) + .HasColumnType("nvarchar(500)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("nvarchar(50)"); + + b.Property("ProjectId") + .HasColumnType("int"); + + b.Property("ReleaseDate") + .HasColumnType("date"); + + b.Property("ReleaseType") + .HasColumnType("int"); + + b.Property("Status") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex("ProjectId"); + + b.ToTable("Release", (string)null); + }); + + modelBuilder.Entity("Taskist.Core.Domain.WorkItems.ReleaseProject", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ProjectId") + .HasColumnType("int"); + + b.Property("ReleaseId") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex("ProjectId"); + + b.HasIndex("ReleaseId", "ProjectId") + .IsUnique(); + + b.ToTable("ReleaseProject", (string)null); + }); + + modelBuilder.Entity("Taskist.Core.Domain.WorkItems.StatusDurationMetric", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("Active") + .HasColumnType("bit"); + + b.Property("Deleted") + .HasColumnType("bit"); + + b.Property("DisplayOrder") + .HasColumnType("int"); + + b.Property("FromStatusId") + .HasColumnType("int"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("nvarchar(100)"); + + b.Property("ProjectId") + .HasColumnType("int"); + + b.Property("ShowOnTask") + .HasColumnType("bit"); + + b.Property("ToStatusId") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex("FromStatusId"); + + b.HasIndex("ProjectId"); + + b.HasIndex("ToStatusId"); + + b.ToTable("StatusDurationMetric", (string)null); + }); + + modelBuilder.Entity("Taskist.Core.Domain.Announcements.AnnouncementAcknowledgement", b => + { + b.HasOne("Taskist.Core.Domain.Announcements.Announcement", "Announcement") + .WithMany() + .HasForeignKey("AnnouncementId") + .OnDelete(DeleteBehavior.NoAction) + .IsRequired(); + + b.HasOne("Taskist.Core.Domain.Users.User", "User") + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.NoAction) + .IsRequired(); + + b.Navigation("Announcement"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Taskist.Core.Domain.Announcements.AnnouncementRole", b => + { + b.HasOne("Taskist.Core.Domain.Announcements.Announcement", "Announcement") + .WithMany("Roles") + .HasForeignKey("AnnouncementId") + .OnDelete(DeleteBehavior.NoAction) + .IsRequired(); + + b.HasOne("Taskist.Core.Domain.Users.UserRole", "UserRole") + .WithMany() + .HasForeignKey("UserRoleId") + .OnDelete(DeleteBehavior.NoAction) + .IsRequired(); + + b.Navigation("Announcement"); + + b.Navigation("UserRole"); + }); + + modelBuilder.Entity("Taskist.Core.Domain.Git.ExternalCommentLink", b => + { + b.HasOne("Taskist.Core.Domain.WorkItems.BacklogComment", "BacklogComment") + .WithMany() + .HasForeignKey("BacklogCommentId") + .OnDelete(DeleteBehavior.NoAction) + .IsRequired(); + + b.HasOne("Taskist.Core.Domain.Git.ExternalIssueLink", "ExternalIssueLink") + .WithMany() + .HasForeignKey("ExternalIssueLinkId") + .OnDelete(DeleteBehavior.NoAction) + .IsRequired(); + + b.Navigation("BacklogComment"); + + b.Navigation("ExternalIssueLink"); + }); + + modelBuilder.Entity("Taskist.Core.Domain.Git.ExternalIssueLink", b => + { + b.HasOne("Taskist.Core.Domain.WorkItems.Backlog", "Backlog") + .WithMany() + .HasForeignKey("BacklogId") + .OnDelete(DeleteBehavior.NoAction) + .IsRequired(); + + b.HasOne("Taskist.Core.Domain.Git.ProjectRepository", "ProjectRepository") + .WithMany() + .HasForeignKey("ProjectRepositoryId") + .OnDelete(DeleteBehavior.NoAction) + .IsRequired(); + + b.Navigation("Backlog"); + + b.Navigation("ProjectRepository"); + }); + + modelBuilder.Entity("Taskist.Core.Domain.Git.GitWebhookDelivery", b => + { + b.HasOne("Taskist.Core.Domain.Git.ProjectRepository", "ProjectRepository") + .WithMany() + .HasForeignKey("ProjectRepositoryId") + .OnDelete(DeleteBehavior.NoAction) + .IsRequired(); + + b.Navigation("ProjectRepository"); + }); + + modelBuilder.Entity("Taskist.Core.Domain.Git.ProjectRepository", b => + { + b.HasOne("Taskist.Core.Domain.Git.GitConnection", "GitConnection") + .WithMany() + .HasForeignKey("GitConnectionId") + .OnDelete(DeleteBehavior.NoAction) + .IsRequired(); + + b.HasOne("Taskist.Core.Domain.Masters.Status", "IssueClosedStatus") + .WithMany() + .HasForeignKey("IssueClosedStatusId") + .OnDelete(DeleteBehavior.NoAction); + + b.HasOne("Taskist.Core.Domain.Masters.Status", "IssueOpenStatus") + .WithMany() + .HasForeignKey("IssueOpenStatusId") + .OnDelete(DeleteBehavior.NoAction); + + b.HasOne("Taskist.Core.Domain.Masters.Severity", "IssueSeverity") + .WithMany() + .HasForeignKey("IssueSeverityId") + .OnDelete(DeleteBehavior.NoAction); + + b.HasOne("Taskist.Core.Domain.Users.User", "IssueSyncUser") + .WithMany() + .HasForeignKey("IssueSyncUserId") + .OnDelete(DeleteBehavior.NoAction); + + b.HasOne("Taskist.Core.Domain.Masters.TaskType", "IssueTaskType") + .WithMany() + .HasForeignKey("IssueTaskTypeId") + .OnDelete(DeleteBehavior.NoAction); + + b.HasOne("Taskist.Core.Domain.Masters.Project", "Project") + .WithMany() + .HasForeignKey("ProjectId") + .OnDelete(DeleteBehavior.NoAction) + .IsRequired(); + + b.Navigation("GitConnection"); + + b.Navigation("IssueClosedStatus"); + + b.Navigation("IssueOpenStatus"); + + b.Navigation("IssueSeverity"); + + b.Navigation("IssueSyncUser"); + + b.Navigation("IssueTaskType"); + + b.Navigation("Project"); + }); + + modelBuilder.Entity("Taskist.Core.Domain.Git.UserGitAccount", b => + { + b.HasOne("Taskist.Core.Domain.Git.GitConnection", "GitConnection") + .WithMany() + .HasForeignKey("GitConnectionId") + .OnDelete(DeleteBehavior.NoAction) + .IsRequired(); + + b.HasOne("Taskist.Core.Domain.Users.User", "User") + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.NoAction) + .IsRequired(); + + b.Navigation("GitConnection"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Taskist.Core.Domain.Localization.LocaleResource", b => + { + b.HasOne("Taskist.Core.Domain.Localization.Language", "Language") + .WithMany() + .HasForeignKey("LanguageId") + .OnDelete(DeleteBehavior.NoAction) + .IsRequired(); + + b.Navigation("Language"); + }); + + modelBuilder.Entity("Taskist.Core.Domain.Masters.CustomField", b => + { + b.HasOne("Taskist.Core.Domain.Masters.Project", "Project") + .WithMany() + .HasForeignKey("ProjectId") + .OnDelete(DeleteBehavior.NoAction) + .IsRequired(); + + b.Navigation("Project"); + }); + + modelBuilder.Entity("Taskist.Core.Domain.Masters.EmailTemplate", b => + { + b.HasOne("Taskist.Core.Domain.Masters.EmailAccount", "EmailAccount") + .WithMany() + .HasForeignKey("EmailAccountId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("EmailAccount"); + }); + + modelBuilder.Entity("Taskist.Core.Domain.Masters.Module", b => + { + b.HasOne("Taskist.Core.Domain.Masters.Project", "Project") + .WithMany() + .HasForeignKey("ProjectId") + .OnDelete(DeleteBehavior.NoAction); + + b.Navigation("Project"); + }); + + modelBuilder.Entity("Taskist.Core.Domain.Masters.Project", b => + { + b.HasOne("Taskist.Core.Domain.Masters.Client", "Client") + .WithMany() + .HasForeignKey("ClientId") + .OnDelete(DeleteBehavior.NoAction) + .IsRequired(); + + b.HasOne("Taskist.Core.Domain.Users.User", "CodeReviewer") + .WithMany() + .HasForeignKey("CodeReviewerId") + .OnDelete(DeleteBehavior.NoAction); + + b.HasOne("Taskist.Core.Domain.Users.User", "ProjectManager") + .WithMany() + .HasForeignKey("ProjectManagerId") + .OnDelete(DeleteBehavior.NoAction); + + b.HasOne("Taskist.Core.Domain.Users.User", "TeamLead") + .WithMany() + .HasForeignKey("TeamLeadId") + .OnDelete(DeleteBehavior.NoAction); + + b.Navigation("Client"); + + b.Navigation("CodeReviewer"); + + b.Navigation("ProjectManager"); + + b.Navigation("TeamLead"); + }); + + modelBuilder.Entity("Taskist.Core.Domain.Masters.ProjectNotificationChannel", b => + { + b.HasOne("Taskist.Core.Domain.Masters.NotificationChannel", "NotificationChannel") + .WithMany() + .HasForeignKey("NotificationChannelId") + .OnDelete(DeleteBehavior.NoAction) + .IsRequired(); + + b.HasOne("Taskist.Core.Domain.Masters.Project", "Project") + .WithMany() + .HasForeignKey("ProjectId") + .OnDelete(DeleteBehavior.NoAction) + .IsRequired(); + + b.Navigation("NotificationChannel"); + + b.Navigation("Project"); + }); + + modelBuilder.Entity("Taskist.Core.Domain.Masters.Reporter", b => + { + b.HasOne("Taskist.Core.Domain.Masters.Project", "Project") + .WithMany() + .HasForeignKey("ProjectId") + .OnDelete(DeleteBehavior.NoAction); + + b.Navigation("Project"); + }); + + modelBuilder.Entity("Taskist.Core.Domain.Masters.Status", b => + { + b.HasOne("Taskist.Core.Domain.Masters.Project", "Project") + .WithMany() + .HasForeignKey("ProjectId") + .OnDelete(DeleteBehavior.NoAction); + + b.Navigation("Project"); + }); + + modelBuilder.Entity("Taskist.Core.Domain.Masters.SubModule", b => + { + b.HasOne("Taskist.Core.Domain.Masters.Module", "Module") + .WithMany() + .HasForeignKey("ModuleId") + .OnDelete(DeleteBehavior.NoAction) + .IsRequired(); + + b.HasOne("Taskist.Core.Domain.Users.User", "Owner") + .WithMany() + .HasForeignKey("OwnerId") + .OnDelete(DeleteBehavior.NoAction); + + b.Navigation("Module"); + + b.Navigation("Owner"); + }); + + modelBuilder.Entity("Taskist.Core.Domain.Users.User", b => + { + b.HasOne("Taskist.Core.Domain.Masters.Address", "Address") + .WithMany() + .HasForeignKey("AddressId") + .OnDelete(DeleteBehavior.NoAction) + .IsRequired(); + + b.HasOne("Taskist.Core.Domain.Localization.Language", "Language") + .WithMany() + .HasForeignKey("LanguageId") + .OnDelete(DeleteBehavior.NoAction) + .IsRequired(); + + b.Navigation("Address"); + + b.Navigation("Language"); + }); + + modelBuilder.Entity("Taskist.Core.Domain.Users.UserExternalLogin", b => + { + b.HasOne("Taskist.Core.Domain.Users.User", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.NoAction) + .IsRequired(); + }); + + modelBuilder.Entity("Taskist.Core.Domain.Users.UserNotification", b => + { + b.HasOne("Taskist.Core.Domain.Users.User", "User") + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.NoAction) + .IsRequired(); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Taskist.Core.Domain.Users.UserPassword", b => + { + b.HasOne("Taskist.Core.Domain.Users.User", "User") + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.NoAction) + .IsRequired(); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Taskist.Core.Domain.Users.UserProjectMap", b => + { + b.HasOne("Taskist.Core.Domain.Masters.Project", "Project") + .WithMany() + .HasForeignKey("ProjectId") + .OnDelete(DeleteBehavior.NoAction) + .IsRequired(); + + b.HasOne("Taskist.Core.Domain.Users.User", "User") + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.NoAction) + .IsRequired(); + + b.Navigation("Project"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Taskist.Core.Domain.Users.UserRecoveryCode", b => + { + b.HasOne("Taskist.Core.Domain.Users.User", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.NoAction) + .IsRequired(); + }); + + modelBuilder.Entity("Taskist.Core.Domain.Users.UserRoleMap", b => + { + b.HasOne("Taskist.Core.Domain.Users.User", "User") + .WithMany("UserUserRoleMaps") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Taskist.Core.Domain.Users.UserRole", "UserRole") + .WithMany() + .HasForeignKey("UserRoleId") + .OnDelete(DeleteBehavior.NoAction) + .IsRequired(); + + b.Navigation("User"); + + b.Navigation("UserRole"); + }); + + modelBuilder.Entity("Taskist.Core.Domain.Users.UserRolePermissionMap", b => + { + b.HasOne("Taskist.Core.Domain.Users.UserRolePermission", "Permission") + .WithMany("UserRolePermissionMaps") + .HasForeignKey("PermissionId") + .OnDelete(DeleteBehavior.NoAction) + .IsRequired(); + + b.HasOne("Taskist.Core.Domain.Users.UserRole", "UserRole") + .WithMany("UserRolePermissionMaps") + .HasForeignKey("UserRoleId") + .OnDelete(DeleteBehavior.NoAction) + .IsRequired(); + + b.Navigation("Permission"); + + b.Navigation("UserRole"); + }); + + modelBuilder.Entity("Taskist.Core.Domain.Users.UserTwoFactor", b => + { + b.HasOne("Taskist.Core.Domain.Users.User", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.NoAction) + .IsRequired(); + }); + + modelBuilder.Entity("Taskist.Core.Domain.Wiki.WikiCategory", b => + { + b.HasOne("Taskist.Core.Domain.Wiki.WikiCategory", "ParentCategory") + .WithMany() + .HasForeignKey("ParentCategoryId") + .OnDelete(DeleteBehavior.NoAction); + + b.HasOne("Taskist.Core.Domain.Masters.Project", "Project") + .WithMany() + .HasForeignKey("ProjectId") + .OnDelete(DeleteBehavior.NoAction); + + b.Navigation("ParentCategory"); + + b.Navigation("Project"); + }); + + modelBuilder.Entity("Taskist.Core.Domain.Wiki.WikiDocument", b => + { + b.HasOne("Taskist.Core.Domain.Wiki.WikiCategory", "Category") + .WithMany() + .HasForeignKey("CategoryId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Taskist.Core.Domain.Users.User", "CreatedBy") + .WithMany() + .HasForeignKey("CreatedById") + .OnDelete(DeleteBehavior.NoAction) + .IsRequired(); + + b.HasOne("Taskist.Core.Domain.Users.User", "ModifiedBy") + .WithMany() + .HasForeignKey("ModifiedById") + .OnDelete(DeleteBehavior.NoAction) + .IsRequired(); + + b.HasOne("Taskist.Core.Domain.Masters.Module", "Module") + .WithMany() + .HasForeignKey("ModuleId") + .OnDelete(DeleteBehavior.NoAction); + + b.HasOne("Taskist.Core.Domain.Masters.SubModule", "SubModule") + .WithMany() + .HasForeignKey("SubModuleId") + .OnDelete(DeleteBehavior.NoAction); + + b.Navigation("Category"); + + b.Navigation("CreatedBy"); + + b.Navigation("ModifiedBy"); + + b.Navigation("Module"); + + b.Navigation("SubModule"); + }); + + modelBuilder.Entity("Taskist.Core.Domain.Wiki.WikiDocumentVersion", b => + { + b.HasOne("Taskist.Core.Domain.Users.User", "ModifiedBy") + .WithMany() + .HasForeignKey("ModifiedById") + .OnDelete(DeleteBehavior.NoAction) + .IsRequired(); + + b.HasOne("Taskist.Core.Domain.Wiki.WikiDocument", "WikiDocument") + .WithMany() + .HasForeignKey("WikiDocumentId") + .OnDelete(DeleteBehavior.NoAction) + .IsRequired(); + + b.Navigation("ModifiedBy"); + + b.Navigation("WikiDocument"); + }); + + modelBuilder.Entity("Taskist.Core.Domain.Wiki.WikiImage", b => + { + b.HasOne("Taskist.Core.Domain.Masters.Document", null) + .WithMany() + .HasForeignKey("DocumentId") + .OnDelete(DeleteBehavior.NoAction) + .IsRequired(); + + b.HasOne("Taskist.Core.Domain.Masters.Project", null) + .WithMany() + .HasForeignKey("ProjectId") + .OnDelete(DeleteBehavior.NoAction) + .IsRequired(); + + b.HasOne("Taskist.Core.Domain.Users.User", null) + .WithMany() + .HasForeignKey("UploadedById") + .OnDelete(DeleteBehavior.NoAction) + .IsRequired(); + + b.HasOne("Taskist.Core.Domain.Wiki.WikiDocument", null) + .WithMany() + .HasForeignKey("WikiDocumentId") + .OnDelete(DeleteBehavior.NoAction) + .IsRequired(); + }); + + modelBuilder.Entity("Taskist.Core.Domain.WorkItems.Backlog", b => + { + b.HasOne("Taskist.Core.Domain.Users.User", "Assignee") + .WithMany() + .HasForeignKey("AssigneeId") + .OnDelete(DeleteBehavior.NoAction); + + b.HasOne("Taskist.Core.Domain.Users.User", "CreatedBy") + .WithMany() + .HasForeignKey("CreatedById") + .OnDelete(DeleteBehavior.NoAction) + .IsRequired(); + + b.HasOne("Taskist.Core.Domain.Git.ProjectRepository", null) + .WithMany() + .HasForeignKey("MergeRequestRepositoryId") + .OnDelete(DeleteBehavior.NoAction); + + b.HasOne("Taskist.Core.Domain.Users.User", "ModifiedBy") + .WithMany() + .HasForeignKey("ModifiedById") + .OnDelete(DeleteBehavior.NoAction); + + b.HasOne("Taskist.Core.Domain.Masters.Module", "Module") + .WithMany() + .HasForeignKey("ModuleId") + .OnDelete(DeleteBehavior.NoAction); + + b.HasOne("Taskist.Core.Domain.WorkItems.Backlog", "Parent") + .WithMany() + .HasForeignKey("ParentId") + .OnDelete(DeleteBehavior.NoAction); + + b.HasOne("Taskist.Core.Domain.Masters.Project", "Project") + .WithMany() + .HasForeignKey("ProjectId") + .OnDelete(DeleteBehavior.NoAction) + .IsRequired(); + + b.HasOne("Taskist.Core.Domain.WorkItems.Release", "Release") + .WithMany() + .HasForeignKey("ReleaseId") + .OnDelete(DeleteBehavior.NoAction); + + b.HasOne("Taskist.Core.Domain.Masters.Reporter", "Reporter") + .WithMany() + .HasForeignKey("ReporterId") + .OnDelete(DeleteBehavior.NoAction); + + b.HasOne("Taskist.Core.Domain.Masters.Severity", "Severity") + .WithMany() + .HasForeignKey("SeverityId") + .OnDelete(DeleteBehavior.NoAction) + .IsRequired(); + + b.HasOne("Taskist.Core.Domain.Wiki.WikiDocument", "SourceWikiDocument") + .WithMany() + .HasForeignKey("SourceWikiDocumentId") + .OnDelete(DeleteBehavior.NoAction); + + b.HasOne("Taskist.Core.Domain.Masters.Status", "Status") + .WithMany() + .HasForeignKey("StatusId") + .OnDelete(DeleteBehavior.NoAction) + .IsRequired(); + + b.HasOne("Taskist.Core.Domain.Masters.SubModule", "SubModule") + .WithMany() + .HasForeignKey("SubModuleId") + .OnDelete(DeleteBehavior.NoAction); + + b.HasOne("Taskist.Core.Domain.Masters.TaskType", "TaskType") + .WithMany() + .HasForeignKey("TaskTypeId") + .OnDelete(DeleteBehavior.NoAction) + .IsRequired(); + + b.HasOne("Taskist.Core.Domain.Users.User", "Tester") + .WithMany() + .HasForeignKey("TesterId") + .OnDelete(DeleteBehavior.NoAction); + + b.Navigation("Assignee"); + + b.Navigation("CreatedBy"); + + b.Navigation("ModifiedBy"); + + b.Navigation("Module"); + + b.Navigation("Parent"); + + b.Navigation("Project"); + + b.Navigation("Release"); + + b.Navigation("Reporter"); + + b.Navigation("Severity"); + + b.Navigation("SourceWikiDocument"); + + b.Navigation("Status"); + + b.Navigation("SubModule"); + + b.Navigation("TaskType"); + + b.Navigation("Tester"); + }); + + modelBuilder.Entity("Taskist.Core.Domain.WorkItems.BacklogComment", b => + { + b.HasOne("Taskist.Core.Domain.WorkItems.Backlog", "Backlog") + .WithMany() + .HasForeignKey("BacklogId") + .OnDelete(DeleteBehavior.NoAction) + .IsRequired(); + + b.HasOne("Taskist.Core.Domain.Users.User", "CreatedBy") + .WithMany() + .HasForeignKey("CreatedById") + .OnDelete(DeleteBehavior.NoAction) + .IsRequired(); + + b.HasOne("Taskist.Core.Domain.Users.User", "ModifiedBy") + .WithMany() + .HasForeignKey("ModifiedById") + .OnDelete(DeleteBehavior.NoAction); + + b.Navigation("Backlog"); + + b.Navigation("CreatedBy"); + + b.Navigation("ModifiedBy"); + }); + + modelBuilder.Entity("Taskist.Core.Domain.WorkItems.BacklogCustomFieldValue", b => + { + b.HasOne("Taskist.Core.Domain.WorkItems.Backlog", "Backlog") + .WithMany() + .HasForeignKey("BacklogId") + .OnDelete(DeleteBehavior.NoAction) + .IsRequired(); + + b.HasOne("Taskist.Core.Domain.Masters.CustomField", "CustomField") + .WithMany() + .HasForeignKey("CustomFieldId") + .OnDelete(DeleteBehavior.NoAction) + .IsRequired(); + + b.Navigation("Backlog"); + + b.Navigation("CustomField"); + }); + + modelBuilder.Entity("Taskist.Core.Domain.WorkItems.BacklogDocument", b => + { + b.HasOne("Taskist.Core.Domain.WorkItems.Backlog", "Backlog") + .WithMany() + .HasForeignKey("BacklogId") + .OnDelete(DeleteBehavior.NoAction) + .IsRequired(); + + b.HasOne("Taskist.Core.Domain.Users.User", "CreatedBy") + .WithMany() + .HasForeignKey("CreatedById") + .OnDelete(DeleteBehavior.NoAction) + .IsRequired(); + + b.HasOne("Taskist.Core.Domain.Masters.Document", "Document") + .WithMany() + .HasForeignKey("DocumentId") + .OnDelete(DeleteBehavior.NoAction) + .IsRequired(); + + b.Navigation("Backlog"); + + b.Navigation("CreatedBy"); + + b.Navigation("Document"); + }); + + modelBuilder.Entity("Taskist.Core.Domain.WorkItems.BacklogStatusLog", b => + { + b.HasOne("Taskist.Core.Domain.WorkItems.Backlog", "Backlog") + .WithMany() + .HasForeignKey("BacklogId") + .OnDelete(DeleteBehavior.NoAction) + .IsRequired(); + + b.HasOne("Taskist.Core.Domain.Users.User", "CreatedBy") + .WithMany() + .HasForeignKey("CreatedById") + .OnDelete(DeleteBehavior.NoAction) + .IsRequired(); + + b.HasOne("Taskist.Core.Domain.Masters.Status", "Status") + .WithMany() + .HasForeignKey("StatusId") + .OnDelete(DeleteBehavior.NoAction); + + b.Navigation("Backlog"); + + b.Navigation("CreatedBy"); + + b.Navigation("Status"); + }); + + modelBuilder.Entity("Taskist.Core.Domain.WorkItems.BacklogTag", b => + { + b.HasOne("Taskist.Core.Domain.WorkItems.Backlog", "Backlog") + .WithMany() + .HasForeignKey("BacklogId") + .OnDelete(DeleteBehavior.NoAction) + .IsRequired(); + + b.HasOne("Taskist.Core.Domain.Masters.Tag", "Tag") + .WithMany() + .HasForeignKey("TagId") + .OnDelete(DeleteBehavior.NoAction) + .IsRequired(); + + b.Navigation("Backlog"); + + b.Navigation("Tag"); + }); + + modelBuilder.Entity("Taskist.Core.Domain.WorkItems.GitBranch", b => + { + b.HasOne("Taskist.Core.Domain.Users.User", "CreatedBy") + .WithMany() + .HasForeignKey("CreatedById") + .OnDelete(DeleteBehavior.NoAction) + .IsRequired(); + + b.HasOne("Taskist.Core.Domain.Masters.Project", "Project") + .WithMany() + .HasForeignKey("ProjectId") + .OnDelete(DeleteBehavior.NoAction) + .IsRequired(); + + b.HasOne("Taskist.Core.Domain.Git.ProjectRepository", "ProjectRepository") + .WithMany() + .HasForeignKey("ProjectRepositoryId") + .OnDelete(DeleteBehavior.NoAction); + + b.Navigation("CreatedBy"); + + b.Navigation("Project"); + + b.Navigation("ProjectRepository"); + }); + + modelBuilder.Entity("Taskist.Core.Domain.WorkItems.GitBranchTask", b => + { + b.HasOne("Taskist.Core.Domain.WorkItems.Backlog", "Backlog") + .WithMany() + .HasForeignKey("BacklogId") + .OnDelete(DeleteBehavior.NoAction) + .IsRequired(); + + b.HasOne("Taskist.Core.Domain.WorkItems.GitBranch", "GitBranch") + .WithMany("Tasks") + .HasForeignKey("GitBranchId") + .OnDelete(DeleteBehavior.NoAction) + .IsRequired(); + + b.HasOne("Taskist.Core.Domain.Users.User", "LinkedBy") + .WithMany() + .HasForeignKey("LinkedById") + .OnDelete(DeleteBehavior.NoAction) + .IsRequired(); + + b.Navigation("Backlog"); + + b.Navigation("GitBranch"); + + b.Navigation("LinkedBy"); + }); + + modelBuilder.Entity("Taskist.Core.Domain.WorkItems.Release", b => + { + b.HasOne("Taskist.Core.Domain.Masters.Project", "Project") + .WithMany() + .HasForeignKey("ProjectId") + .OnDelete(DeleteBehavior.NoAction); + + b.Navigation("Project"); + }); + + modelBuilder.Entity("Taskist.Core.Domain.WorkItems.ReleaseProject", b => + { + b.HasOne("Taskist.Core.Domain.Masters.Project", "Project") + .WithMany() + .HasForeignKey("ProjectId") + .OnDelete(DeleteBehavior.NoAction) + .IsRequired(); + + b.HasOne("Taskist.Core.Domain.WorkItems.Release", "Release") + .WithMany("ReleaseProjects") + .HasForeignKey("ReleaseId") + .OnDelete(DeleteBehavior.NoAction) + .IsRequired(); + + b.Navigation("Project"); + + b.Navigation("Release"); + }); + + modelBuilder.Entity("Taskist.Core.Domain.WorkItems.StatusDurationMetric", b => + { + b.HasOne("Taskist.Core.Domain.Masters.Status", "FromStatus") + .WithMany() + .HasForeignKey("FromStatusId") + .OnDelete(DeleteBehavior.NoAction) + .IsRequired(); + + b.HasOne("Taskist.Core.Domain.Masters.Project", "Project") + .WithMany() + .HasForeignKey("ProjectId") + .OnDelete(DeleteBehavior.NoAction); + + b.HasOne("Taskist.Core.Domain.Masters.Status", "ToStatus") + .WithMany() + .HasForeignKey("ToStatusId") + .OnDelete(DeleteBehavior.NoAction) + .IsRequired(); + + b.Navigation("FromStatus"); + + b.Navigation("Project"); + + b.Navigation("ToStatus"); + }); + + modelBuilder.Entity("Taskist.Core.Domain.Announcements.Announcement", b => + { + b.Navigation("Roles"); + }); + + modelBuilder.Entity("Taskist.Core.Domain.Users.User", b => + { + b.Navigation("UserUserRoleMaps"); + }); + + modelBuilder.Entity("Taskist.Core.Domain.Users.UserRole", b => + { + b.Navigation("UserRolePermissionMaps"); + }); + + modelBuilder.Entity("Taskist.Core.Domain.Users.UserRolePermission", b => + { + b.Navigation("UserRolePermissionMaps"); + }); + + modelBuilder.Entity("Taskist.Core.Domain.WorkItems.GitBranch", b => + { + b.Navigation("Tasks"); + }); + + modelBuilder.Entity("Taskist.Core.Domain.WorkItems.Release", b => + { + b.Navigation("ReleaseProjects"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/Libraries/Taskist.Data/Migrations/20261112183742_AddUserTwoFactor.cs b/src/Libraries/Taskist.Data/Migrations/20261112183742_AddUserTwoFactor.cs new file mode 100644 index 0000000..fcb8832 --- /dev/null +++ b/src/Libraries/Taskist.Data/Migrations/20261112183742_AddUserTwoFactor.cs @@ -0,0 +1,78 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Taskist.Data.Migrations +{ + /// + public partial class AddUserTwoFactor : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "UserRecoveryCode", + columns: table => new + { + Id = table.Column(type: "int", nullable: false) + .Annotation("SqlServer:Identity", "1, 1"), + UserId = table.Column(type: "int", nullable: false), + CodeHash = table.Column(type: "nvarchar(64)", maxLength: 64, nullable: false), + CreatedOn = table.Column(type: "datetime2", nullable: false), + UsedOn = table.Column(type: "datetime2", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_UserRecoveryCode", x => x.Id); + table.ForeignKey( + name: "FK_UserRecoveryCode_User_UserId", + column: x => x.UserId, + principalTable: "User", + principalColumn: "Id"); + }); + + migrationBuilder.CreateTable( + name: "UserTwoFactor", + columns: table => new + { + Id = table.Column(type: "int", nullable: false) + .Annotation("SqlServer:Identity", "1, 1"), + UserId = table.Column(type: "int", nullable: false), + Secret = table.Column(type: "nvarchar(max)", nullable: false), + EnabledOn = table.Column(type: "datetime2", nullable: false), + LastUsedTimeStep = table.Column(type: "bigint", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_UserTwoFactor", x => x.Id); + table.ForeignKey( + name: "FK_UserTwoFactor_User_UserId", + column: x => x.UserId, + principalTable: "User", + principalColumn: "Id"); + }); + + migrationBuilder.CreateIndex( + name: "IX_UserRecoveryCode_UserId", + table: "UserRecoveryCode", + column: "UserId"); + + migrationBuilder.CreateIndex( + name: "IX_UserTwoFactor_UserId", + table: "UserTwoFactor", + column: "UserId", + unique: true); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "UserRecoveryCode"); + + migrationBuilder.DropTable( + name: "UserTwoFactor"); + } + } +} diff --git a/src/Libraries/Taskist.Data/Migrations/ApplicationContextModelSnapshot.cs b/src/Libraries/Taskist.Data/Migrations/ApplicationContextModelSnapshot.cs index ec614ff..f0e4890 100644 --- a/src/Libraries/Taskist.Data/Migrations/ApplicationContextModelSnapshot.cs +++ b/src/Libraries/Taskist.Data/Migrations/ApplicationContextModelSnapshot.cs @@ -1779,6 +1779,35 @@ protected override void BuildModel(ModelBuilder modelBuilder) b.ToTable("UserProjectMap", (string)null); }); + modelBuilder.Entity("Taskist.Core.Domain.Users.UserRecoveryCode", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("CodeHash") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("CreatedOn") + .HasColumnType("datetime2"); + + b.Property("UsedOn") + .HasColumnType("datetime2"); + + b.Property("UserId") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("UserRecoveryCode", (string)null); + }); + modelBuilder.Entity("Taskist.Core.Domain.Users.UserRole", b => { b.Property("Id") @@ -1873,6 +1902,35 @@ protected override void BuildModel(ModelBuilder modelBuilder) b.ToTable("UserRolePermissionMap", (string)null); }); + modelBuilder.Entity("Taskist.Core.Domain.Users.UserTwoFactor", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("EnabledOn") + .HasColumnType("datetime2"); + + b.Property("LastUsedTimeStep") + .HasColumnType("bigint"); + + b.Property("Secret") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("UserId") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex("UserId") + .IsUnique(); + + b.ToTable("UserTwoFactor", (string)null); + }); + modelBuilder.Entity("Taskist.Core.Domain.Wiki.WikiCategory", b => { b.Property("Id") @@ -2905,6 +2963,15 @@ protected override void BuildModel(ModelBuilder modelBuilder) b.Navigation("User"); }); + modelBuilder.Entity("Taskist.Core.Domain.Users.UserRecoveryCode", b => + { + b.HasOne("Taskist.Core.Domain.Users.User", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.NoAction) + .IsRequired(); + }); + modelBuilder.Entity("Taskist.Core.Domain.Users.UserRoleMap", b => { b.HasOne("Taskist.Core.Domain.Users.User", "User") @@ -2943,6 +3010,15 @@ protected override void BuildModel(ModelBuilder modelBuilder) b.Navigation("UserRole"); }); + modelBuilder.Entity("Taskist.Core.Domain.Users.UserTwoFactor", b => + { + b.HasOne("Taskist.Core.Domain.Users.User", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.NoAction) + .IsRequired(); + }); + modelBuilder.Entity("Taskist.Core.Domain.Wiki.WikiCategory", b => { b.HasOne("Taskist.Core.Domain.Wiki.WikiCategory", "ParentCategory") diff --git a/src/Libraries/Taskist.Service/Authentication/AuthenticationService.cs b/src/Libraries/Taskist.Service/Authentication/AuthenticationService.cs index 028c3fb..ebe721b 100644 --- a/src/Libraries/Taskist.Service/Authentication/AuthenticationService.cs +++ b/src/Libraries/Taskist.Service/Authentication/AuthenticationService.cs @@ -42,7 +42,9 @@ public AuthenticationService(IUserService userService, #region Methods - public async Task SignInAsync(User entity, bool isPersistent) + public Task SignInAsync(User entity, bool isPersistent) => SignInAsync(entity, isPersistent, null); + + public async Task SignInAsync(User entity, bool isPersistent, string authMethod) { if (entity == null) throw new ArgumentNullException(nameof(entity)); @@ -62,6 +64,9 @@ public async Task SignInAsync(User entity, bool isPersistent) var isAdmin = roles.Any(r => r.SystemName == UserConstant.AdministratorsRoleName); claims.Add(new Claim(ServiceConstant.IsAdminClaim, isAdmin.ToString(), ClaimValueTypes.Boolean, ServiceConstant.ClaimsIssuer)); + + if (!string.IsNullOrWhiteSpace(authMethod)) + claims.Add(new Claim(ServiceConstant.AuthMethodClaim, authMethod, ClaimValueTypes.String, ServiceConstant.ClaimsIssuer)); } var userIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme); diff --git a/src/Libraries/Taskist.Service/Authentication/IAuthenticationService.cs b/src/Libraries/Taskist.Service/Authentication/IAuthenticationService.cs index 154abef..49dc72f 100644 --- a/src/Libraries/Taskist.Service/Authentication/IAuthenticationService.cs +++ b/src/Libraries/Taskist.Service/Authentication/IAuthenticationService.cs @@ -6,6 +6,8 @@ public interface IAuthenticationService { Task SignInAsync(User entity, bool isPersistent); + Task SignInAsync(User entity, bool isPersistent, string authMethod); + Task SignOutAsync(); Task GetAuthenticatedUserAsync(); diff --git a/src/Libraries/Taskist.Service/Authentication/ITwoFactorService.cs b/src/Libraries/Taskist.Service/Authentication/ITwoFactorService.cs new file mode 100644 index 0000000..5a71beb --- /dev/null +++ b/src/Libraries/Taskist.Service/Authentication/ITwoFactorService.cs @@ -0,0 +1,22 @@ +using Taskist.Core.Domain.Users; + +namespace Taskist.Service.Authentication; + +public interface ITwoFactorService +{ + Task GetAsync(int userId); + + Task IsEnabledAsync(int userId); + + Task> EnableAsync(int userId, string secret, string code); + + Task VerifyCodeAsync(int userId, string code); + + Task UseRecoveryCodeAsync(int userId, string code); + + Task> RegenerateRecoveryCodesAsync(int userId); + + Task CountRemainingRecoveryCodesAsync(int userId); + + Task DisableAsync(int userId); +} diff --git a/src/Libraries/Taskist.Service/Authentication/TwoFactorService.cs b/src/Libraries/Taskist.Service/Authentication/TwoFactorService.cs new file mode 100644 index 0000000..c1f68c9 --- /dev/null +++ b/src/Libraries/Taskist.Service/Authentication/TwoFactorService.cs @@ -0,0 +1,122 @@ +using Microsoft.EntityFrameworkCore; +using Taskist.Core.Domain.Users; +using Taskist.Core.Security; +using Taskist.Data.Repository; + +namespace Taskist.Service.Authentication; + +public class TwoFactorService : ITwoFactorService +{ + #region Fields + + protected readonly IRepository _twoFactorRepository; + protected readonly IRepository _recoveryCodeRepository; + + #endregion + + #region Ctor + + public TwoFactorService(IRepository twoFactorRepository, + IRepository recoveryCodeRepository) + { + _twoFactorRepository = twoFactorRepository; + _recoveryCodeRepository = recoveryCodeRepository; + } + + #endregion + + #region Methods + + public async Task GetAsync(int userId) + { + return await _twoFactorRepository.Table.FirstOrDefaultAsync(x => x.UserId == userId); + } + + public async Task IsEnabledAsync(int userId) + { + return await _twoFactorRepository.Table.AnyAsync(x => x.UserId == userId); + } + + public async Task> EnableAsync(int userId, string secret, string code) + { + var step = Totp.Verify(secret, code, DateTimeOffset.UtcNow, 0); + if (step == null) + return null; + + var existing = await GetAsync(userId); + if (existing != null) + await _twoFactorRepository.DeleteAsync(existing); + + await _twoFactorRepository.InsertAsync(new UserTwoFactor + { + UserId = userId, + Secret = secret, + EnabledOn = DateTime.UtcNow, + LastUsedTimeStep = step.Value + }); + + return await RegenerateRecoveryCodesAsync(userId); + } + + public async Task VerifyCodeAsync(int userId, string code) + { + var entity = await GetAsync(userId); + if (entity == null) + return false; + + var step = Totp.Verify(entity.Secret, code, DateTimeOffset.UtcNow, entity.LastUsedTimeStep); + if (step == null) + return false; + + entity.LastUsedTimeStep = step.Value; + await _twoFactorRepository.UpdateAsync(entity); + return true; + } + + public async Task UseRecoveryCodeAsync(int userId, string code) + { + var hash = RecoveryCodes.Hash(code); + if (hash == null) + return false; + + var entity = await _recoveryCodeRepository.Table + .FirstOrDefaultAsync(x => x.UserId == userId && x.CodeHash == hash && x.UsedOn == null); + if (entity == null) + return false; + + entity.UsedOn = DateTime.UtcNow; + await _recoveryCodeRepository.UpdateAsync(entity); + return true; + } + + public async Task> RegenerateRecoveryCodesAsync(int userId) + { + await _recoveryCodeRepository.DeleteAsync(x => x.UserId == userId); + + var codes = RecoveryCodes.Generate(); + var now = DateTime.UtcNow; + await _recoveryCodeRepository.InsertAsync(codes + .Select(c => new UserRecoveryCode { UserId = userId, CodeHash = RecoveryCodes.Hash(c)!, CreatedOn = now }) + .ToList()); + + return codes; + } + + public async Task CountRemainingRecoveryCodesAsync(int userId) + { + return await _recoveryCodeRepository.Table.CountAsync(x => x.UserId == userId && x.UsedOn == null); + } + + public async Task DisableAsync(int userId) + { + var entity = await GetAsync(userId); + await _recoveryCodeRepository.DeleteAsync(x => x.UserId == userId); + if (entity == null) + return false; + + await _twoFactorRepository.DeleteAsync(entity); + return true; + } + + #endregion +} diff --git a/src/Libraries/Taskist.Service/Common/ServiceConstant.cs b/src/Libraries/Taskist.Service/Common/ServiceConstant.cs index 86134de..31b711c 100644 --- a/src/Libraries/Taskist.Service/Common/ServiceConstant.cs +++ b/src/Libraries/Taskist.Service/Common/ServiceConstant.cs @@ -20,6 +20,8 @@ public static class ServiceConstant public static string LanguageIdClaim => "wc.bl.languageid"; + public static string AuthMethodClaim => "wc.bl.amr"; + #endregion Auth #region Caching diff --git a/src/Libraries/Taskist.Service/Users/UserService.cs b/src/Libraries/Taskist.Service/Users/UserService.cs index 6ebb8e9..ec80b36 100644 --- a/src/Libraries/Taskist.Service/Users/UserService.cs +++ b/src/Libraries/Taskist.Service/Users/UserService.cs @@ -29,6 +29,7 @@ public class UserService : IUserService protected readonly IRepository _userRoleMapRepository; protected readonly IRepository _permissionMapRepository; protected readonly IRepository _userProjectMapRepository; + protected readonly IRepository _twoFactorRepository; protected readonly IAddressService _addressService; protected readonly IMessageService _messageService; protected readonly IEncryptionService _encryptionService; @@ -47,6 +48,7 @@ public UserService(UserSettings userSettings, IRepository userRoleMapRepository, IRepository permissionMapRepository, IRepository userProjectMapRepository, + IRepository twoFactorRepository, IEncryptionService encryptionService, ISettingService settingsService, IAddressService addressService, @@ -61,6 +63,7 @@ public UserService(UserSettings userSettings, _userRoleMapRepository = userRoleMapRepository; _permissionMapRepository = permissionMapRepository; _userProjectMapRepository = userProjectMapRepository; + _twoFactorRepository = twoFactorRepository; _encryptionService = encryptionService; _settingsService = settingsService; _addressService = addressService; @@ -579,7 +582,7 @@ public async Task ValidateAsync(string email, string password) if (!await IsRegisteredAsync(entity)) return LoginResult.NotRegistered; - if (entity.FailedLoginAttempts != 0) + if (entity.FailedLoginAttempts != 0 && !await _twoFactorRepository.Table.AnyAsync(x => x.UserId == entity.Id)) { entity.FailedLoginAttempts = 0; await _userRepository.UpdateAsync(entity); diff --git a/src/Presentation/Taskist.Web/Controllers/Common/AccountController.cs b/src/Presentation/Taskist.Web/Controllers/Common/AccountController.cs index 2ee9827..1a3dcb6 100644 --- a/src/Presentation/Taskist.Web/Controllers/Common/AccountController.cs +++ b/src/Presentation/Taskist.Web/Controllers/Common/AccountController.cs @@ -1,5 +1,8 @@ +using System.Globalization; +using System.Security.Claims; using AuthenticationProperties = Microsoft.AspNetCore.Authentication.AuthenticationProperties; using AuthenticationHttpContextExtensions = Microsoft.AspNetCore.Authentication.AuthenticationHttpContextExtensions; +using Microsoft.AspNetCore.DataProtection; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.RateLimiting; using Taskist.Core.Common; @@ -17,7 +20,9 @@ using Taskist.Web.Helpers.Appearance; using Taskist.Web.Helpers.Sso; +using Taskist.Web.Helpers.TwoFactor; using Taskist.Web.Infrastructure; +using Taskist.Core.Domain.Settings; namespace Taskist.Web.Controllers.Common; @@ -37,6 +42,16 @@ public class AccountController : Controller protected readonly ISsoSignInService _ssoSignInService; protected readonly OidcOptions _oidcOptions; protected readonly ILogger _logger; + protected readonly ITwoFactorService _twoFactorService; + protected readonly TwoFactorOptions _twoFactorOptions; + protected readonly ISettingService _settingService; + protected readonly IDataProtector _deviceProtector; + + private const string PendingUserClaim = "taskist:2fa:uid"; + private const string PendingRememberClaim = "taskist:2fa:remember"; + private const string PendingReturnUrlClaim = "taskist:2fa:return"; + private const string PendingAttemptsClaim = "taskist:2fa:attempts"; + private const string TwoFactorExpiredCode = "expired"; #endregion @@ -53,9 +68,17 @@ public AccountController(IUserService userService, ILocalizationService localizationService, ISsoSignInService ssoSignInService, OidcOptions oidcOptions, - ILogger logger) + ILogger logger, + ITwoFactorService twoFactorService, + TwoFactorOptions twoFactorOptions, + ISettingService settingService, + IDataProtectionProvider dataProtectionProvider) { _logger = logger; + _twoFactorService = twoFactorService; + _twoFactorOptions = twoFactorOptions; + _settingService = settingService; + _deviceProtector = dataProtectionProvider.CreateProtector(RememberedDeviceToken.Purpose); _appearanceService = appearanceService; _localizationService = localizationService; _ssoSignInService = ssoSignInService; @@ -73,11 +96,12 @@ public AccountController(IUserService userService, #region Actions - public IActionResult Login(string sso, string local) + public IActionResult Login(string sso, string local, string tf) { var model = new LoginModel { LocalLogin = LocalLoginSwitch.IsOn(local) }; PrepareLoginModel(model); model.SsoErrorCode = SsoErrorCode.Normalize(sso); + model.TwoFactorExpired = string.Equals(tf, TwoFactorExpiredCode, StringComparison.Ordinal); return View(model); } @@ -103,7 +127,7 @@ public async Task Login(LoginModel model, string returnUrl) return View(model); } - return await CompleteSignInAsync(user, model.RememberMe, "Signed in", returnUrl); + return await ContinueAfterPasswordAsync(user, model.RememberMe, returnUrl); } case LoginResult.NotExist: ModelState.AddModelError(string.Empty, "User doesn't exists"); @@ -172,7 +196,67 @@ public async Task ExternalCallback(string returnUrl) if (result.RolesAdded.Count > 0) note += $"; roles added: {string.Join(", ", result.RolesAdded)}"; - return await CompleteSignInAsync(result.User!, false, note, returnUrl); + return await CompleteSignInAsync(result.User!, false, note, returnUrl, AuthMethod.SingleSignOn); + } + + public async Task TwoFactor() + { + var pending = await AuthenticationHttpContextExtensions.AuthenticateAsync(HttpContext, TwoFactorOptions.PendingScheme); + if (!pending.Succeeded || pending.Principal == null) + return RedirectToAction(nameof(Login), new { tf = TwoFactorExpiredCode }); + + return View(new TwoFactorLoginModel { RememberDeviceDays = _twoFactorOptions.EffectiveRememberDeviceDays }); + } + + [HttpPost] + public async Task TwoFactor(TwoFactorLoginModel model) + { + var pending = await AuthenticationHttpContextExtensions.AuthenticateAsync(HttpContext, TwoFactorOptions.PendingScheme); + var principal = pending.Principal; + if (!pending.Succeeded || principal == null + || !int.TryParse(principal.FindFirst(PendingUserClaim)?.Value, NumberStyles.Integer, CultureInfo.InvariantCulture, out var userId)) + return RedirectToAction(nameof(Login), new { tf = TwoFactorExpiredCode }); + + var user = await _userService.GetByIdAsync(userId); + if (user == null || user.Deleted || user.Locked || user.Status != (int)UserStatus.Active) + return await AbandonTwoFactorAsync(); + + var rememberMe = principal.FindFirst(PendingRememberClaim)?.Value == bool.TrueString; + var returnUrl = principal.FindFirst(PendingReturnUrlClaim)?.Value; + model.RememberDeviceDays = _twoFactorOptions.EffectiveRememberDeviceDays; + + var verified = model.IsRecoveryMode + ? await _twoFactorService.UseRecoveryCodeAsync(user.Id, model.Code) + : await _twoFactorService.VerifyCodeAsync(user.Id, model.Code); + + if (!verified) + { + var attempts = (int.TryParse(principal.FindFirst(PendingAttemptsClaim)?.Value, out var count) ? count : 0) + 1; + var locked = await RegisterFailedAttemptAsync(user); + await _activityService.InsertAsync(user, ActivityType.LoginFailed, + model.IsRecoveryMode ? "Failed sign-in: wrong recovery code" : "Failed sign-in: wrong two-factor code"); + + if (locked || attempts >= TwoFactorOptions.MaxAttempts) + return await AbandonTwoFactorAsync(); + + await SignInPendingAsync(user.Id, rememberMe, returnUrl, attempts); + model.Code = null; + model.ErrorMessage = await ResourceOrDefaultAsync(model.IsRecoveryMode ? "Login.TwoFactor.WrongRecoveryCode" : "Login.TwoFactor.WrongCode", + model.IsRecoveryMode ? "That recovery code isn't valid or has already been used." : "That code isn't right. Check your authenticator app and try again."); + return View(model); + } + + await AuthenticationHttpContextExtensions.SignOutAsync(HttpContext, TwoFactorOptions.PendingScheme); + await ResetFailedAttemptsAsync(user); + + if (model.RememberDevice == true && _twoFactorOptions.CanRememberDevice) + await RememberDeviceAsync(user.Id); + + var note = model.IsRecoveryMode + ? $"Signed in with a recovery code ({await _twoFactorService.CountRemainingRecoveryCodesAsync(user.Id)} left)" + : "Signed in with a two-factor code"; + + return await CompleteSignInAsync(user, rememberMe, note, returnUrl, AuthMethod.LocalWithCode); } public async Task Logout() @@ -298,9 +382,90 @@ private async Task ResourceOrDefaultAsync(string key, string fallback) private string SafeReturnUrl(string returnUrl) => !string.IsNullOrEmpty(returnUrl) && Url.IsLocalUrl(returnUrl) ? returnUrl : null; - private async Task CompleteSignInAsync(User user, bool isPersistent, string note, string returnUrl) + private async Task ContinueAfterPasswordAsync(User user, bool rememberMe, string returnUrl) + { + var twoFactor = await _twoFactorService.GetAsync(user.Id); + if (twoFactor == null) + return await CompleteSignInAsync(user, rememberMe, "Signed in", returnUrl, AuthMethod.Local); + + if (_twoFactorOptions.CanRememberDevice + && RememberedDeviceToken.IsValid(_deviceProtector, Request.Cookies[TwoFactorOptions.RememberDeviceCookie], user.Id, twoFactor.EnabledOn.Ticks, DateTimeOffset.UtcNow)) + { + await ResetFailedAttemptsAsync(user); + return await CompleteSignInAsync(user, rememberMe, "Signed in (remembered device)", returnUrl, AuthMethod.LocalRememberedDevice); + } + + await SignInPendingAsync(user.Id, rememberMe, SafeReturnUrl(returnUrl), 0); + return RedirectToAction(nameof(TwoFactor)); + } + + private async Task SignInPendingAsync(int userId, bool rememberMe, string returnUrl, int attempts) + { + var claims = new List + { + new(PendingUserClaim, userId.ToString(CultureInfo.InvariantCulture)), + new(PendingRememberClaim, rememberMe ? bool.TrueString : bool.FalseString), + new(PendingAttemptsClaim, attempts.ToString(CultureInfo.InvariantCulture)) + }; + if (!string.IsNullOrEmpty(returnUrl)) + claims.Add(new Claim(PendingReturnUrlClaim, returnUrl)); + + var principal = new ClaimsPrincipal(new ClaimsIdentity(claims, TwoFactorOptions.PendingScheme)); + await AuthenticationHttpContextExtensions.SignInAsync(HttpContext, TwoFactorOptions.PendingScheme, principal, + new AuthenticationProperties { IsPersistent = false, ExpiresUtc = DateTimeOffset.UtcNow.AddMinutes(5) }); + } + + private async Task AbandonTwoFactorAsync() + { + await AuthenticationHttpContextExtensions.SignOutAsync(HttpContext, TwoFactorOptions.PendingScheme); + return RedirectToAction(nameof(Login), new { tf = TwoFactorExpiredCode }); + } + + private async Task RegisterFailedAttemptAsync(User user) + { + var security = await _settingService.LoadSettingAsync(); + if (security.MaxFailedLoginAttempts <= 0) + return false; + + user.FailedLoginAttempts++; + if (user.FailedLoginAttempts >= security.MaxFailedLoginAttempts) + user.Locked = true; + await _userService.UpdateAsync(user); + + return user.Locked; + } + + private async Task ResetFailedAttemptsAsync(User user) + { + if (user.FailedLoginAttempts == 0) + return; + + user.FailedLoginAttempts = 0; + await _userService.UpdateAsync(user); + } + + private async Task RememberDeviceAsync(int userId) + { + var twoFactor = await _twoFactorService.GetAsync(userId); + if (twoFactor == null) + return; + + var expires = DateTimeOffset.UtcNow.AddDays(_twoFactorOptions.EffectiveRememberDeviceDays); + Response.Cookies.Append(TwoFactorOptions.RememberDeviceCookie, + RememberedDeviceToken.Create(_deviceProtector, userId, twoFactor.EnabledOn.Ticks, expires), + new CookieOptions + { + HttpOnly = true, + IsEssential = true, + SameSite = SameSiteMode.Lax, + Secure = true, + Expires = expires + }); + } + + private async Task CompleteSignInAsync(User user, bool isPersistent, string note, string returnUrl, string authMethod) { - await _authenticationService.SignInAsync(user, isPersistent); + await _authenticationService.SignInAsync(user, isPersistent, authMethod); await _appearanceService.SyncCookieAsync(user); await _activityService.InsertAsync(user, ActivityType.Login, note); diff --git a/src/Presentation/Taskist.Web/Controllers/Users/ProfileController.cs b/src/Presentation/Taskist.Web/Controllers/Users/ProfileController.cs index d736f81..4cfb193 100644 --- a/src/Presentation/Taskist.Web/Controllers/Users/ProfileController.cs +++ b/src/Presentation/Taskist.Web/Controllers/Users/ProfileController.cs @@ -3,8 +3,11 @@ using Taskist.Core.Domain.Settings; using Taskist.Core.Enums; using Taskist.Service.Authentication; +using Taskist.Core.Domain.Users; +using Taskist.Core.Security; using Taskist.Service.Git; using Taskist.Service.Localization; +using Taskist.Service.Logging; using Taskist.Service.Masters; using Taskist.Service.Messages; using Taskist.Service.Security; @@ -13,6 +16,8 @@ using Taskist.Web.Helpers.Appearance; using Taskist.Web.Helpers.Attributes; using Taskist.Web.Helpers.Extensions; +using Taskist.Web.Helpers.TwoFactor; +using Taskist.Web.Infrastructure; using Taskist.Web.Models.Common; using Taskist.Web.Models.Users; @@ -34,6 +39,11 @@ public class ProfileController : BaseController protected readonly INotificationService _notificationService; protected readonly IAppearanceService _appearanceService; protected readonly IExternalLoginService _externalLoginService; + protected readonly ITwoFactorService _twoFactorService; + protected readonly TwoFactorOptions _twoFactorOptions; + protected readonly IAuthenticationService _authenticationService; + protected readonly IUserActivityService _activityService; + private const string TwoFactorSetupSessionKey = "taskist.2fa.setup"; #endregion @@ -48,8 +58,16 @@ public ProfileController(IUserService userService, IGitRepositoryService gitRepositoryService, INotificationService notificationService, IAppearanceService appearanceService, - IExternalLoginService externalLoginService) + IExternalLoginService externalLoginService, + ITwoFactorService twoFactorService, + TwoFactorOptions twoFactorOptions, + IAuthenticationService authenticationService, + IUserActivityService activityService) { + _twoFactorService = twoFactorService; + _twoFactorOptions = twoFactorOptions; + _authenticationService = authenticationService; + _activityService = activityService; _appearanceService = appearanceService; _externalLoginService = externalLoginService; _gitAccountService = gitAccountService; @@ -94,9 +112,94 @@ public async Task Index() .ToList() }; + model.HasPassword = await _userService.GetCurrentPasswordAsync(e.Id) != null; + model.TwoFactorEnabled = await _twoFactorService.IsEnabledAsync(e.Id); + model.RecoveryCodesRemaining = model.TwoFactorEnabled == true ? await _twoFactorService.CountRemainingRecoveryCodesAsync(e.Id) : 0; + model.TwoFactorSetupRequired = model.TwoFactorEnabled != true && TwoFactorSetupPolicy.IsSetupRequired( + _twoFactorOptions.RequireForAdministrators, IsAdministrator(), User.FindFirst(Taskist.Service.Common.ServiceConstant.AuthMethodClaim)?.Value); + return View(model); } + [CheckPermission(nameof(PermissionProvider.ManageDashboard))] + public async Task TwoFactorSetup() + { + var e = await _userService.GetByIdAsync(UserId); + var secret = Totp.GenerateSecret(); + HttpContext.Session.SetString(TwoFactorSetupSessionKey, secret); + + return PartialView(new TwoFactorSetupModel + { + AccountName = e.Email, + ManualKey = Base32.Group(secret), + QrCodeDataUri = TwoFactorQrCode.ToPngDataUri(OtpAuthUri.Build("Taskist", e.Email, secret)) + }); + } + + [HttpPost] + [CheckPermission(nameof(PermissionProvider.ManageDashboard))] + public async Task EnableTwoFactor(string code) + { + var secret = HttpContext.Session.GetString(TwoFactorSetupSessionKey); + if (string.IsNullOrEmpty(secret)) + return await TwoFactorErrorAsync("Profile.TwoFactor.SetupExpired"); + + var codes = await _twoFactorService.EnableAsync(UserId, secret, code); + if (codes == null) + return await TwoFactorErrorAsync("Profile.TwoFactor.WrongCode"); + + HttpContext.Session.Remove(TwoFactorSetupSessionKey); + var e = await _userService.GetByIdAsync(UserId); + await _activityService.InsertAsync(e, Taskist.Core.Common.ActivityType.TwoFactorEnabled, "Two-factor sign-in turned on"); + await RefreshSignInAsync(e); + + return new RecoveryCodesResponseModel + { + Status = HttpStatusCode.Success, + Message = await _localizationService.GetResourceAsync("Profile.TwoFactor.Enabled"), + Codes = codes + }; + } + + [HttpPost] + [CheckPermission(nameof(PermissionProvider.ManageDashboard))] + public async Task RegenerateRecoveryCodes(string code) + { + if (!await _twoFactorService.VerifyCodeAsync(UserId, code)) + return await TwoFactorErrorAsync("Profile.TwoFactor.WrongCode"); + + var codes = await _twoFactorService.RegenerateRecoveryCodesAsync(UserId); + var e = await _userService.GetByIdAsync(UserId); + await _activityService.InsertAsync(e, Taskist.Core.Common.ActivityType.TwoFactorEnabled, "New recovery codes generated"); + + return new RecoveryCodesResponseModel + { + Status = HttpStatusCode.Success, + Message = await _localizationService.GetResourceAsync("Profile.TwoFactor.CodesRegenerated"), + Codes = codes + }; + } + + [HttpPost] + [CheckPermission(nameof(PermissionProvider.ManageDashboard))] + public async Task DisableTwoFactor(string code) + { + var verified = await _twoFactorService.VerifyCodeAsync(UserId, code) + || await _twoFactorService.UseRecoveryCodeAsync(UserId, code); + if (!verified) + return await TwoFactorErrorAsync("Profile.TwoFactor.WrongCode"); + + await _twoFactorService.DisableAsync(UserId); + var e = await _userService.GetByIdAsync(UserId); + await _activityService.InsertAsync(e, Taskist.Core.Common.ActivityType.TwoFactorDisabled, "Two-factor sign-in turned off"); + + return new JsonResponseModel + { + Status = HttpStatusCode.Success, + Message = await _localizationService.GetResourceAsync("Profile.TwoFactor.Disabled") + }; + } + [HttpPost] [CheckPermission(nameof(PermissionProvider.ManageDashboard))] public async Task UnlinkSignIn(int id) @@ -394,5 +497,23 @@ public async Task ChangePassword(ChangePasswordModel model) private static string Base64Url(byte[] bytes) => Convert.ToBase64String(bytes).TrimEnd('=').Replace('+', '-').Replace('/', '_'); + private bool IsAdministrator() => + User.IsInRole(UserConstant.SystemAdministratorRoleName) || User.IsInRole(UserConstant.AdministratorsRoleName); + + private async Task TwoFactorErrorAsync(string resourceKey) => new() + { + Status = HttpStatusCode.ValidationError, + Message = await _localizationService.GetResourceAsync(resourceKey) + }; + + private async Task RefreshSignInAsync(User user) + { + var current = await Microsoft.AspNetCore.Authentication.AuthenticationHttpContextExtensions.AuthenticateAsync( + HttpContext, Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationDefaults.AuthenticationScheme); + var persistent = current.Properties?.IsPersistent ?? false; + + await _authenticationService.SignInAsync(user, persistent, AuthMethod.LocalWithCode); + } + #endregion } diff --git a/src/Presentation/Taskist.Web/Controllers/Users/UserController.cs b/src/Presentation/Taskist.Web/Controllers/Users/UserController.cs index b8ec174..3916b9e 100644 --- a/src/Presentation/Taskist.Web/Controllers/Users/UserController.cs +++ b/src/Presentation/Taskist.Web/Controllers/Users/UserController.cs @@ -34,6 +34,8 @@ public class UserController : BaseController protected readonly UsersMapper _usersMapper; protected readonly MastersMapper _mastersMapper; protected readonly IExternalLoginService _externalLoginService; + protected readonly ITwoFactorService _twoFactorService; + protected readonly Service.Logging.IUserActivityService _activityService; #endregion @@ -47,9 +49,13 @@ public UserController(IUserService userService, IWorkContext workContext, UsersMapper usersMapper, MastersMapper mastersMapper, - IExternalLoginService externalLoginService) + IExternalLoginService externalLoginService, + ITwoFactorService twoFactorService, + Service.Logging.IUserActivityService activityService) { _externalLoginService = externalLoginService; + _twoFactorService = twoFactorService; + _activityService = activityService; _userService = userService; _documentService = documentService; _languageService = languageService; @@ -241,6 +247,26 @@ public async Task RemoveSignIn(int userId, int id) }); } + [HttpPost] + public async Task ResetTwoFactor(int userId) + { + var target = await _userService.GetByIdAsync(userId); + var reset = target != null && await _twoFactorService.DisableAsync(userId); + + if (reset) + { + var admin = await _workContext.GetCurrentUserAsync(); + await _activityService.InsertAsync(admin, ActivityType.TwoFactorDisabled, $"Reset two-factor sign-in for {target!.Email}"); + await _activityService.InsertAsync(target, ActivityType.TwoFactorDisabled, $"Two-factor sign-in reset by {admin.Email}"); + } + + return Json(new JsonResponseModel + { + Status = reset ? HttpStatusCode.Success : HttpStatusCode.NoData, + Message = await _localizationService.GetResourceAsync(reset ? "UserPage.TwoFactor.ResetDone" : "FormNoData.Description") + }); + } + #endregion #region Data @@ -301,6 +327,7 @@ private async Task InitModelAsync(UserRegistrationModel model) if (model.User.Id > 0) { + model.TwoFactorEnabled = await _twoFactorService.IsEnabledAsync(model.User.Id); model.LinkedSignIns = (await _externalLoginService.GetForUserAsync(model.User.Id)) .Select(l => new LinkedSignInModel { diff --git a/src/Presentation/Taskist.Web/Helpers/TwoFactor/AuthMethod.cs b/src/Presentation/Taskist.Web/Helpers/TwoFactor/AuthMethod.cs new file mode 100644 index 0000000..edd31fc --- /dev/null +++ b/src/Presentation/Taskist.Web/Helpers/TwoFactor/AuthMethod.cs @@ -0,0 +1,16 @@ +namespace Taskist.Web.Helpers.TwoFactor; + +public static class AuthMethod +{ + #region Fields + + public const string Local = "pwd"; + + public const string LocalWithCode = "pwd+otp"; + + public const string LocalRememberedDevice = "pwd+device"; + + public const string SingleSignOn = "sso"; + + #endregion +} diff --git a/src/Presentation/Taskist.Web/Helpers/TwoFactor/RememberedDeviceToken.cs b/src/Presentation/Taskist.Web/Helpers/TwoFactor/RememberedDeviceToken.cs new file mode 100644 index 0000000..43aac90 --- /dev/null +++ b/src/Presentation/Taskist.Web/Helpers/TwoFactor/RememberedDeviceToken.cs @@ -0,0 +1,55 @@ +using System.Globalization; +using System.Security.Cryptography; +using Microsoft.AspNetCore.DataProtection; + +namespace Taskist.Web.Helpers.TwoFactor; + +public static class RememberedDeviceToken +{ + #region Fields + + public const string Purpose = "Taskist.TwoFactor.RememberDevice.v1"; + + #endregion + + #region Methods + + public static string Create(IDataProtector protector, int userId, long stamp, DateTimeOffset expiresUtc) + { + ArgumentNullException.ThrowIfNull(protector); + + var payload = string.Join('|', + userId.ToString(CultureInfo.InvariantCulture), + stamp.ToString(CultureInfo.InvariantCulture), + expiresUtc.ToUnixTimeSeconds().ToString(CultureInfo.InvariantCulture)); + + return protector.Protect(payload); + } + + public static bool IsValid(IDataProtector protector, string? token, int userId, long stamp, DateTimeOffset nowUtc) + { + ArgumentNullException.ThrowIfNull(protector); + + if (string.IsNullOrWhiteSpace(token)) + return false; + + string payload; + try + { + payload = protector.Unprotect(token); + } + catch (CryptographicException) + { + return false; + } + + var parts = payload.Split('|'); + return parts.Length == 3 + && int.TryParse(parts[0], NumberStyles.Integer, CultureInfo.InvariantCulture, out var tokenUser) && tokenUser == userId + && long.TryParse(parts[1], NumberStyles.Integer, CultureInfo.InvariantCulture, out var tokenStamp) && tokenStamp == stamp + && long.TryParse(parts[2], NumberStyles.Integer, CultureInfo.InvariantCulture, out var expires) + && DateTimeOffset.FromUnixTimeSeconds(expires) > nowUtc; + } + + #endregion +} diff --git a/src/Presentation/Taskist.Web/Helpers/TwoFactor/TwoFactorQrCode.cs b/src/Presentation/Taskist.Web/Helpers/TwoFactor/TwoFactorQrCode.cs new file mode 100644 index 0000000..c704bb6 --- /dev/null +++ b/src/Presentation/Taskist.Web/Helpers/TwoFactor/TwoFactorQrCode.cs @@ -0,0 +1,21 @@ +using QRCoder; + +namespace Taskist.Web.Helpers.TwoFactor; + +public static class TwoFactorQrCode +{ + #region Methods + + public static string ToPngDataUri(string content, int pixelsPerModule = 5) + { + ArgumentException.ThrowIfNullOrWhiteSpace(content); + + using var generator = new QRCodeGenerator(); + using var data = generator.CreateQrCode(content, QRCodeGenerator.ECCLevel.M); + var png = new PngByteQRCode(data).GetGraphic(pixelsPerModule); + + return $"data:image/png;base64,{Convert.ToBase64String(png)}"; + } + + #endregion +} diff --git a/src/Presentation/Taskist.Web/Helpers/TwoFactor/TwoFactorSetupPolicy.cs b/src/Presentation/Taskist.Web/Helpers/TwoFactor/TwoFactorSetupPolicy.cs new file mode 100644 index 0000000..c8d2315 --- /dev/null +++ b/src/Presentation/Taskist.Web/Helpers/TwoFactor/TwoFactorSetupPolicy.cs @@ -0,0 +1,23 @@ +namespace Taskist.Web.Helpers.TwoFactor; + +public static class TwoFactorSetupPolicy +{ + #region Fields + + private static readonly HashSet AllowedControllers = new(StringComparer.OrdinalIgnoreCase) + { + "Profile", "Account", "Notification", "Common" + }; + + #endregion + + #region Methods + + public static bool IsSetupRequired(bool requireForAdministrators, bool isAdministrator, string? authMethod) => + requireForAdministrators && isAdministrator && string.Equals(authMethod, AuthMethod.Local, StringComparison.Ordinal); + + public static bool IsAllowedDuringSetup(string? controller) => + !string.IsNullOrEmpty(controller) && AllowedControllers.Contains(controller); + + #endregion +} diff --git a/src/Presentation/Taskist.Web/Helpers/TwoFactor/TwoFactorSetupRequiredFilter.cs b/src/Presentation/Taskist.Web/Helpers/TwoFactor/TwoFactorSetupRequiredFilter.cs new file mode 100644 index 0000000..5473605 --- /dev/null +++ b/src/Presentation/Taskist.Web/Helpers/TwoFactor/TwoFactorSetupRequiredFilter.cs @@ -0,0 +1,62 @@ +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.Controllers; +using Microsoft.AspNetCore.Mvc.Filters; +using Taskist.Core.Domain.Users; +using Taskist.Service.Common; +using Taskist.Web.Infrastructure; + +namespace Taskist.Web.Helpers.TwoFactor; + +public class TwoFactorSetupRequiredFilter : IAsyncActionFilter +{ + #region Fields + + private readonly TwoFactorOptions _options; + + #endregion + + #region Ctor + + public TwoFactorSetupRequiredFilter(TwoFactorOptions options) + { + _options = options; + } + + #endregion + + #region Methods + + public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next) + { + var user = context.HttpContext.User; + if (!_options.RequireForAdministrators || user?.Identity?.IsAuthenticated != true) + { + await next(); + return; + } + + var isAdministrator = user.IsInRole(UserConstant.SystemAdministratorRoleName) || user.IsInRole(UserConstant.AdministratorsRoleName); + var method = user.FindFirst(ServiceConstant.AuthMethodClaim)?.Value; + var controller = (context.ActionDescriptor as ControllerActionDescriptor)?.ControllerName; + + if (!TwoFactorSetupPolicy.IsSetupRequired(true, isAdministrator, method) || TwoFactorSetupPolicy.IsAllowedDuringSetup(controller)) + { + await next(); + return; + } + + var request = context.HttpContext.Request; + var isAjax = string.Equals(request.Headers.XRequestedWith, "XMLHttpRequest", StringComparison.OrdinalIgnoreCase); + + context.Result = isAjax || !HttpMethods.IsGet(request.Method) + ? new ContentResult + { + StatusCode = StatusCodes.Status403Forbidden, + ContentType = "text/plain; charset=utf-8", + Content = "Set up two-factor sign-in under My profile → Security first." + } + : new RedirectResult($"{request.PathBase}/Profile?setup2fa=1#security"); + } + + #endregion +} diff --git a/src/Presentation/Taskist.Web/Infrastructure/ServiceCollectionExtensions.cs b/src/Presentation/Taskist.Web/Infrastructure/ServiceCollectionExtensions.cs index 7d21043..558a49f 100644 --- a/src/Presentation/Taskist.Web/Infrastructure/ServiceCollectionExtensions.cs +++ b/src/Presentation/Taskist.Web/Infrastructure/ServiceCollectionExtensions.cs @@ -214,6 +214,7 @@ public static IServiceCollection AddPresentation(this IServiceCollection service services.AddMvcCore(options => { options.Filters.Add(new AutoValidateAntiforgeryTokenAttribute()); + options.Filters.Add(); options.ModelMetadataDetailsProviders.Add(new MetadataProvider()); }).AddNewtonsoftJson(options => { diff --git a/src/Presentation/Taskist.Web/Infrastructure/TwoFactorAuthenticationExtensions.cs b/src/Presentation/Taskist.Web/Infrastructure/TwoFactorAuthenticationExtensions.cs new file mode 100644 index 0000000..5dfa069 --- /dev/null +++ b/src/Presentation/Taskist.Web/Infrastructure/TwoFactorAuthenticationExtensions.cs @@ -0,0 +1,29 @@ +namespace Taskist.Web.Infrastructure; + +public static class TwoFactorAuthenticationExtensions +{ + #region Methods + + public static IServiceCollection AddTwoFactorSignIn(this IServiceCollection services, IConfiguration configuration) + { + var options = configuration.GetSection(TwoFactorOptions.SectionName).Get() ?? new TwoFactorOptions(); + services.AddSingleton(options); + services.AddScoped(); + + services.AddAuthentication() + .AddCookie(TwoFactorOptions.PendingScheme, cookie => + { + cookie.Cookie.Name = "Taskist.TwoFactor"; + cookie.Cookie.HttpOnly = true; + cookie.Cookie.IsEssential = true; + cookie.Cookie.SameSite = SameSiteMode.Lax; + cookie.Cookie.SecurePolicy = CookieSecurePolicy.SameAsRequest; + cookie.ExpireTimeSpan = TimeSpan.FromMinutes(5); + cookie.SlidingExpiration = false; + }); + + return services; + } + + #endregion +} diff --git a/src/Presentation/Taskist.Web/Infrastructure/TwoFactorOptions.cs b/src/Presentation/Taskist.Web/Infrastructure/TwoFactorOptions.cs new file mode 100644 index 0000000..dd6b747 --- /dev/null +++ b/src/Presentation/Taskist.Web/Infrastructure/TwoFactorOptions.cs @@ -0,0 +1,30 @@ +namespace Taskist.Web.Infrastructure; + +public class TwoFactorOptions +{ + #region Fields + + public const string SectionName = "Authentication:TwoFactor"; + + public const string PendingScheme = "Taskist.TwoFactor"; + + public const string RememberDeviceCookie = "Taskist.TwoFactorDevice"; + + public const int MaxAttempts = 5; + + public const int MaxRememberDeviceDays = 365; + + #endregion + + #region Properties + + public bool RequireForAdministrators { get; set; } + + public int RememberDeviceDays { get; set; } = 30; + + public int EffectiveRememberDeviceDays => Math.Clamp(RememberDeviceDays, 0, MaxRememberDeviceDays); + + public bool CanRememberDevice => EffectiveRememberDeviceDays > 0; + + #endregion +} diff --git a/src/Presentation/Taskist.Web/Models/Users/LoginModel.cs b/src/Presentation/Taskist.Web/Models/Users/LoginModel.cs index 3a27876..cf34a8e 100644 --- a/src/Presentation/Taskist.Web/Models/Users/LoginModel.cs +++ b/src/Presentation/Taskist.Web/Models/Users/LoginModel.cs @@ -22,4 +22,6 @@ public class LoginModel public bool ShowPasswordForm { get; set; } = true; public string? SsoErrorCode { get; set; } + + public bool? TwoFactorExpired { get; set; } } diff --git a/src/Presentation/Taskist.Web/Models/Users/ProfileModel.cs b/src/Presentation/Taskist.Web/Models/Users/ProfileModel.cs index ec01585..c4312d8 100644 --- a/src/Presentation/Taskist.Web/Models/Users/ProfileModel.cs +++ b/src/Presentation/Taskist.Web/Models/Users/ProfileModel.cs @@ -43,6 +43,14 @@ public ProfileModel() public IList LinkedSignIns { get; set; } = []; + public bool? HasPassword { get; set; } + + public bool? TwoFactorEnabled { get; set; } + + public int? RecoveryCodesRemaining { get; set; } + + public bool? TwoFactorSetupRequired { get; set; } + [Display(Name = "Gender")] public int? Gender { get; set; } diff --git a/src/Presentation/Taskist.Web/Models/Users/RecoveryCodesResponseModel.cs b/src/Presentation/Taskist.Web/Models/Users/RecoveryCodesResponseModel.cs new file mode 100644 index 0000000..41f53c9 --- /dev/null +++ b/src/Presentation/Taskist.Web/Models/Users/RecoveryCodesResponseModel.cs @@ -0,0 +1,14 @@ +using Newtonsoft.Json; +using Taskist.Web.Models.Common; + +namespace Taskist.Web.Models.Users; + +public class RecoveryCodesResponseModel : JsonResponseModel +{ + #region Properties + + [JsonProperty("codes")] + public IReadOnlyList Codes { get; set; } = []; + + #endregion +} diff --git a/src/Presentation/Taskist.Web/Models/Users/TwoFactorLoginModel.cs b/src/Presentation/Taskist.Web/Models/Users/TwoFactorLoginModel.cs new file mode 100644 index 0000000..b32b530 --- /dev/null +++ b/src/Presentation/Taskist.Web/Models/Users/TwoFactorLoginModel.cs @@ -0,0 +1,20 @@ +namespace Taskist.Web.Models.Users; + +public class TwoFactorLoginModel +{ + #region Properties + + public string? Code { get; set; } + + public bool? UseRecoveryCode { get; set; } + + public bool? RememberDevice { get; set; } + + public int? RememberDeviceDays { get; set; } + + public string? ErrorMessage { get; set; } + + public bool IsRecoveryMode => UseRecoveryCode == true; + + #endregion +} diff --git a/src/Presentation/Taskist.Web/Models/Users/TwoFactorSetupModel.cs b/src/Presentation/Taskist.Web/Models/Users/TwoFactorSetupModel.cs new file mode 100644 index 0000000..fddfe22 --- /dev/null +++ b/src/Presentation/Taskist.Web/Models/Users/TwoFactorSetupModel.cs @@ -0,0 +1,14 @@ +namespace Taskist.Web.Models.Users; + +public class TwoFactorSetupModel +{ + #region Properties + + public string QrCodeDataUri { get; set; } = string.Empty; + + public string ManualKey { get; set; } = string.Empty; + + public string AccountName { get; set; } = string.Empty; + + #endregion +} diff --git a/src/Presentation/Taskist.Web/Models/Users/UserRegistrationModel.cs b/src/Presentation/Taskist.Web/Models/Users/UserRegistrationModel.cs index 123e7d2..229dfaf 100644 --- a/src/Presentation/Taskist.Web/Models/Users/UserRegistrationModel.cs +++ b/src/Presentation/Taskist.Web/Models/Users/UserRegistrationModel.cs @@ -22,4 +22,6 @@ public UserRegistrationModel() public List AvailableRoles { get; set; } public IList LinkedSignIns { get; set; } = []; + + public bool? TwoFactorEnabled { get; set; } } diff --git a/src/Presentation/Taskist.Web/Program.cs b/src/Presentation/Taskist.Web/Program.cs index 2f7f508..83e2375 100644 --- a/src/Presentation/Taskist.Web/Program.cs +++ b/src/Presentation/Taskist.Web/Program.cs @@ -29,6 +29,7 @@ .AddPresentation() .AddAppAuthentication() .AddOidcSignIn(builder.Configuration) + .AddTwoFactorSignIn(builder.Configuration) .AddProfiling() .AddBackgroundJobs(builder.Configuration, startServer: !builder.Environment.IsDevelopment()); diff --git a/src/Presentation/Taskist.Web/Taskist.Web.csproj b/src/Presentation/Taskist.Web/Taskist.Web.csproj index 92dd4d7..f463f4a 100644 --- a/src/Presentation/Taskist.Web/Taskist.Web.csproj +++ b/src/Presentation/Taskist.Web/Taskist.Web.csproj @@ -56,6 +56,7 @@ + diff --git a/src/Presentation/Taskist.Web/Views/Account/Login.cshtml b/src/Presentation/Taskist.Web/Views/Account/Login.cshtml index 470d40e..ebc8242 100644 --- a/src/Presentation/Taskist.Web/Views/Account/Login.cshtml +++ b/src/Presentation/Taskist.Web/Views/Account/Login.cshtml @@ -66,6 +66,11 @@

Sign in to continue to Taskist.

+ @if (Model.TwoFactorExpired == true) + { + + } + @if (!string.IsNullOrEmpty(Model.SsoErrorCode)) { diff --git a/src/Presentation/Taskist.Web/Views/Account/TwoFactor.cshtml b/src/Presentation/Taskist.Web/Views/Account/TwoFactor.cshtml new file mode 100644 index 0000000..8db7b9f --- /dev/null +++ b/src/Presentation/Taskist.Web/Views/Account/TwoFactor.cshtml @@ -0,0 +1,73 @@ +@model TwoFactorLoginModel +@inject Taskist.Service.Localization.ILocalizationService LocalizationService +@functions { + private async Task TextAsync(string key, string fallback) + { + var value = await LocalizationService.GetResourceAsync(key); + return string.IsNullOrWhiteSpace(value) || string.Equals(value, key, StringComparison.OrdinalIgnoreCase) ? fallback : value; + } +} +@{ + ViewData["Title"] = "Two-factor sign-in"; + Layout = "~/Views/Shared/_LayoutLogin.cshtml"; +} + +@section PageStyles { + +} + + + +@section PageScripts { + +} diff --git a/src/Presentation/Taskist.Web/Views/Profile/Index.cshtml b/src/Presentation/Taskist.Web/Views/Profile/Index.cshtml index dfb818b..9bcf80a 100644 --- a/src/Presentation/Taskist.Web/Views/Profile/Index.cshtml +++ b/src/Presentation/Taskist.Web/Views/Profile/Index.cshtml @@ -143,6 +143,14 @@
@Localize("Profile.Security").Text
+ @if (Model.TwoFactorSetupRequired == true) + { +
+ +
+ }
@Localize("Profile.ChangePassword").Text
@@ -150,6 +158,55 @@
+ @if (Model.HasPassword == true) + { +
+
+
+ @Localize("Profile.TwoFactor.Title").Text + @if (Model.TwoFactorEnabled == true) + { + @Localize("Profile.TwoFactor.On").Text + } + else + { + @Localize("Profile.TwoFactor.Off").Text + } +
+
@Localize("Profile.TwoFactor.Hint").Text
+ @if (Model.TwoFactorEnabled == true) + { +
+ @string.Format(Localize("Profile.TwoFactor.CodesLeft").Text, Model.RecoveryCodesRemaining) +
+ } +
+
+ @if (Model.TwoFactorEnabled == true) + { + + + } + else + { + + } +
+
+ } @if (Model.LinkedSignIns.Any()) {
+
    +
  1. +
    @Localize("Profile.TwoFactor.Step1").Text
    +
    @Localize("Profile.TwoFactor.Step1Hint").Text
    + @Localize( +
    @Localize("Profile.TwoFactor.ManualKey").Text
    + @Model.ManualKey +
    @Model.AccountName
    +
  2. +
  3. +
    @Localize("Profile.TwoFactor.Step2").Text
    +
    + + +
    + +
  4. +
+
diff --git a/src/Presentation/Taskist.Web/Views/User/Edit.cshtml b/src/Presentation/Taskist.Web/Views/User/Edit.cshtml index b6f5325..439475a 100644 --- a/src/Presentation/Taskist.Web/Views/User/Edit.cshtml +++ b/src/Presentation/Taskist.Web/Views/User/Edit.cshtml @@ -15,6 +15,22 @@ +@if (Model.TwoFactorEnabled == true) +{ +
+
+
+
@Localize("Profile.TwoFactor.Title").Text @Localize("Profile.TwoFactor.On").Text
+
@Localize("UserPage.TwoFactor.ResetHint").Text
+
+ +
+
+} + @if (Model.LinkedSignIns.Any()) {