diff --git a/.env.example b/.env.example index 6beb9fc..8c22ddf 100644 --- a/.env.example +++ b/.env.example @@ -41,6 +41,21 @@ SENTRY_ENVIRONMENT= # Share of requests sent as performance traces (0 = errors only, 0.1 = 10%). SENTRY_TRACES_SAMPLE_RATE=0 +# ---- Single sign-on (optional) ---- +# Sign in with an OpenID Connect provider (Keycloak, Authentik, Entra ID, Google, Okta...). +# Off by default. Setup guide: docs/sso.md. Register this redirect URI at your provider: +# signin-oidc (for example http://localhost:8080/signin-oidc) +SSO_ENABLED=false +# Button text on the login page, e.g. "Keycloak" -> "Sign in with Keycloak". +SSO_DISPLAY_NAME= +SSO_AUTHORITY= +SSO_CLIENT_ID= +SSO_CLIENT_SECRET= +# true: create a Taskist account (Registered role only) on first sign-in. false: only existing users can sign in. +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 + # ---- 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 b1a9d5f..1073bfe 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. +- **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. - Startup checks: the Data Protection key folder must be writable; Production logs warnings for plain-HTTP cookies and an unprotected key ring. diff --git a/README.md b/README.md index a47d9de..d0a3ee1 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 +- Users, roles and fine-grained permissions; 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 @@ -172,10 +172,15 @@ Taskist reads `appsettings.json`, `appsettings.{Environment}.json`, user-secrets | `App:IsBeta` / `App:BetaMessage` | `true` / text | Beta banner | | `Sentry:Enabled` / `Sentry:Dsn` | `false` / — | Optional error tracking with [Sentry](https://sentry.io): unhandled exceptions and logged errors. Needs both; see [SECURITY.md](SECURITY.md#error-tracking-optional) for what is sent | | `Sentry:Environment` / `Sentry:TracesSampleRate` | environment name / `0` | Sentry environment label; share of requests sent as performance traces (`0` = errors only) | +| `Authentication:Oidc:Enabled` | `false` | Single sign-on with an OpenID Connect provider (Keycloak, Authentik, Entra ID, Google, Okta…). Needs `Authority` and `ClientId`; see [docs/sso.md](docs/sso.md) | +| `Authentication:Oidc:Authority` / `ClientId` / `ClientSecret` | — | Provider address and the client registered there. Redirect URI to register: `{App:BaseUrl}signin-oidc` | +| `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` | 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`. +**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. diff --git a/SECURITY.md b/SECURITY.md index 64148fb..edb7d73 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. +### 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)). + +- **Protocol:** authorization code flow with PKCE; state and nonce are checked, and the provider's signing keys and issuer are taken from its discovery document over HTTPS (`RequireHttpsMetadata`, on by default). Provider tokens are not stored. +- **Client secret** comes from configuration or environment variables only and is never stored in the database or shown in the UI. +- **Matching users:** a sign-in is tied to the provider's issuer and subject ID. On the first sign-in it is linked to an existing Taskist account only when the provider reports the e-mail address as **verified** (`RequireVerifiedEmail`, on by default), and never to an account already linked to a different identity at the same provider. +- **New accounts** are created only when `AutoProvision` is on, and get the *Registered* role only — no project access until an administrator grants it. +- **Role mapping** (`RoleClaim` + `RoleMappings`) only adds the roles listed in the mapping; it never removes roles and cannot grant a role that isn't listed. Mapping a group to `SystemAdministrator` makes that group's membership at the provider equivalent to admin rights in Taskist — do so deliberately. +- **Account status still applies:** locked, inactive and deleted users are refused, and existing sessions are re-checked every 15 minutes as before. +- **SSO-only mode** (`DisableLocalLogin`) hides the password form and refuses password sign-in for everyone except system administrators, who keep it at `/Login?local=1` so a broken identity provider can't lock you out. Keep at least one administrator with a strong password. +- Signing out of Taskist does not sign the user out of the identity provider. + ### Wiki access - A project's wiki — page content, tree, history, linked tasks and Word export — is visible only to members of that project who also hold the *Wiki* permission. Requests for pages in other projects get an empty or "not found" response that does not reveal whether the page exists. diff --git a/docker-compose.yml b/docker-compose.yml index 7402ab9..c7a16ab 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -57,6 +57,14 @@ services: Sentry__Dsn: ${SENTRY_DSN:-} Sentry__Environment: ${SENTRY_ENVIRONMENT:-} Sentry__TracesSampleRate: ${SENTRY_TRACES_SAMPLE_RATE:-0} + # optional single sign-on; see SSO_* in .env.example and docs/sso.md + Authentication__Oidc__Enabled: ${SSO_ENABLED:-false} + Authentication__Oidc__DisplayName: ${SSO_DISPLAY_NAME:-} + Authentication__Oidc__Authority: ${SSO_AUTHORITY:-} + Authentication__Oidc__ClientId: ${SSO_CLIENT_ID:-} + Authentication__Oidc__ClientSecret: ${SSO_CLIENT_SECRET:-} + Authentication__Oidc__AutoProvision: ${SSO_AUTO_PROVISION:-false} + Authentication__Oidc__DisableLocalLogin: ${SSO_DISABLE_LOCAL_LOGIN:-false} ports: - "${TASKIST_PORT:-8080}:8080" volumes: diff --git a/docs/sso.md b/docs/sso.md new file mode 100644 index 0000000..364fcf3 --- /dev/null +++ b/docs/sso.md @@ -0,0 +1,201 @@ +# Single sign-on (OpenID Connect) + +Taskist can let people sign in with the account they already have at your identity provider: Keycloak, Authentik, Microsoft Entra ID, Google, Okta, or any other OpenID Connect provider. It's off by default and set up entirely in configuration (`appsettings.json` or environment variables). There's no admin screen for it. + +- [How it works](#how-it-works) +- [Before you start](#before-you-start) +- [Settings](#settings) +- [Keycloak: step by step](#keycloak-step-by-step) +- [Microsoft Entra ID](#microsoft-entra-id) +- [Google](#google) +- [Other providers](#other-providers) +- [Mapping provider groups to roles](#mapping-provider-groups-to-roles) +- [SSO-only mode](#sso-only-mode) +- [Troubleshooting](#troubleshooting) +- [Limitations](#limitations) + +## How it works + +The login page shows a **Sign in with …** button. After the person signs in at the provider, Taskist decides who they are: + +| Situation | What happens | +| --- | --- | +| They have signed in with SSO before | Signed in to the same Taskist account, even if their e-mail has changed since. | +| First SSO sign-in, and a Taskist user has the same e-mail | The two are linked and they're signed in, **if the provider says the e-mail is verified**. | +| First SSO sign-in, no Taskist user with that e-mail | Refused with "ask your administrator", unless `AutoProvision` is on: then an account is created with the *Registered* role only. | +| The Taskist user is locked, inactive or deleted | Refused, as with a password sign-in. | + +Everything after that is unchanged: roles, permissions, project access, session length and lock-out all work exactly as for password sign-in. People can see their linked sign-ins under **My profile → Security**, and administrators see them on the user's edit page. + +## Before you start + +1. **Set `App:BaseUrl`** to the address people use to reach Taskist, for example `https://taskist.example.com/`. +2. **The redirect URI** to register at your provider is that address followed by `signin-oidc`: + `https://taskist.example.com/signin-oidc` +3. **Behind a reverse proxy** (nginx, Traefik, IIS, a load balancer), set `Security:ForwardedHeaders:Enabled` and list the proxy, as described in the [README](../README.md#configuration). Otherwise Taskist sees plain `http` and sends the wrong redirect URI, and the provider rejects it. +4. **Create the users first** (or turn on `AutoProvision`), using the same e-mail addresses they have at the provider. + +## Settings + +All settings live under `Authentication:Oidc`. In environment variables, use a double underscore: `Authentication__Oidc__ClientId`. The Docker sample maps the `SSO_*` variables in `.env` to the most common ones. + +| Setting | Default | Description | +| --- | --- | --- | +| `Enabled` | `false` | Turns single sign-on on. Needs `Authority` and `ClientId`; if either is missing or invalid, SSO stays off and a warning is logged at startup. | +| `DisplayName` | `Single sign-on` | Button text: "Sign in with *DisplayName*". | +| `Authority` | — | The provider's issuer address (the part before `/.well-known/openid-configuration`). Must be `https`. | +| `ClientId` / `ClientSecret` | — | The client registered at the provider. The secret is read from configuration only, never stored in the database. | +| `Scopes` | `openid profile email` | Scopes to request. `openid` is always added. Add a groups scope here if your provider needs one. | +| `RequireVerifiedEmail` | `true` | Link to an existing account or create one only when the provider marks the e-mail as verified. See [Entra ID](#microsoft-entra-id) before changing it. | +| `AutoProvision` | `false` | Create a Taskist account on first sign-in, with the *Registered* role only. | +| `RoleClaim` / `RoleMappings` | — | Optional group → role mapping; see [below](#mapping-provider-groups-to-roles). | +| `DisableLocalLogin` | `false` | Hide the password form; see [SSO-only mode](#sso-only-mode). | +| `RequireHttpsMetadata` | `true` | Only set to `false` to test against a provider on plain `http://localhost`. Never in production. | + +Example `appsettings.Production.json`: + +```json +{ + "App": { "BaseUrl": "https://taskist.example.com/" }, + "Authentication": { + "Oidc": { + "Enabled": true, + "DisplayName": "Acme SSO", + "Authority": "https://id.example.com/realms/acme", + "ClientId": "taskist", + "ClientSecret": "" + } + } +} +``` + +Keep the client secret out of files you commit: use an environment variable (`Authentication__Oidc__ClientSecret`), user-secrets or your hosting platform's secret store. + +## Keycloak: step by step + +This sets up a throwaway Keycloak on your machine to try SSO in a few minutes. For production, follow the same steps in your real realm over HTTPS. + +**1. Start Keycloak (test only):** + +```bash +docker run --name keycloak -p 8081:8080 \ + -e KC_BOOTSTRAP_ADMIN_USERNAME=admin -e KC_BOOTSTRAP_ADMIN_PASSWORD=admin \ + quay.io/keycloak/keycloak:26.0 start-dev +``` + +Open http://localhost:8081 and sign in as `admin` / `admin`. + +**2. Create a realm** (top-left menu → *Create realm*), for example `acme`. + +**3. Create the client:** *Clients → Create client* + +- Client type: **OpenID Connect**, Client ID: `taskist` → *Next* +- **Client authentication: On**, Authentication flow: **Standard flow** only → *Next* +- **Valid redirect URIs:** `http://localhost:8080/signin-oidc` (your Taskist address + `signin-oidc`) +- **Web origins:** `http://localhost:8080` → *Save* +- Copy the secret from the **Credentials** tab. + +**4. Create a user:** *Users → Create new user* with the same e-mail as a Taskist user, tick **Email verified**, then set a password on the *Credentials* tab. + +**5. Configure Taskist.** With the Docker sample, in `.env`: + +```bash +SSO_ENABLED=true +SSO_DISPLAY_NAME=Keycloak +SSO_AUTHORITY=http://host.docker.internal:8081/realms/acme +SSO_CLIENT_ID=taskist +SSO_CLIENT_SECRET= +``` + +Because this test Keycloak runs on plain HTTP, also add `Authentication__Oidc__RequireHttpsMetadata: "false"` to the `web` service's `environment` in `docker-compose.yml`. Don't do this in production. Then run `docker compose up -d`. + +> The Taskist container and your browser must reach Keycloak at the **same** address, because the provider's address is part of every token. `host.docker.internal` works with Docker Desktop; on Linux, add `extra_hosts: ["host.docker.internal:host-gateway"]` to the `web` service and open Keycloak in your browser at `http://host.docker.internal:8081` too. + +**6. Try it:** open Taskist, click **Sign in with Keycloak**, sign in as the user from step 4. You're signed in to the matching Taskist account, and **My profile → Security** shows the linked sign-in. + +**Groups (optional):** in the client, *Client scopes → taskist-dedicated → Configure a new mapper → Group Membership*, token claim name `groups`, **Full group path off**. Then set `RoleClaim` to `groups` and add `RoleMappings` (see below). + +## Microsoft Entra ID + +1. *Entra admin center → App registrations → New registration.* Supported account types: **this organizational directory only** (single tenant). Redirect URI: platform **Web**, `https://taskist.example.com/signin-oidc`. +2. *Certificates & secrets → New client secret*; copy the value. +3. *Token configuration → Add optional claim → ID → `email`*. +4. Configure Taskist: + - `Authority`: `https://login.microsoftonline.com//v2.0` + - `ClientId`: the application (client) ID; `ClientSecret`: the secret from step 2. + +**E-mail verification:** Entra ID does not send the `email_verified` claim, so with the default `RequireVerifiedEmail: true` first-time sign-ins can't be linked to existing accounts. For a **single-tenant** app whose e-mail addresses your organisation controls, set `RequireVerifiedEmail` to `false`. Don't do this for multi-tenant apps or tenants with guest users whose e-mail addresses you don't control: someone could then sign in as a Taskist user whose address they put on their own account. + +**Groups:** *Token configuration → Add groups claim*. Entra sends group **object IDs** (GUIDs), so use those as keys in `RoleMappings`, with `RoleClaim` set to `groups`. + +## Google + +1. *Google Cloud console → APIs & Services → Credentials → Create credentials → OAuth client ID*, type **Web application**, authorised redirect URI `https://taskist.example.com/signin-oidc`. +2. Configure Taskist: `Authority` `https://accounts.google.com`, plus the client ID and secret. + +Google sends verified e-mail addresses, so the defaults work. It does not send groups. To limit sign-ins to your company domain, keep `AutoProvision` off and only create Taskist users for your own addresses. + +## Other providers + +Any provider that supports OpenID Connect discovery works. Use the issuer address as `Authority`: + +| Provider | `Authority` | +| --- | --- | +| Authentik | `https://auth.example.com/application/o//` | +| Okta | `https://.okta.com` (or a custom authorisation server) | +| GitLab | `https://gitlab.com` or your self-managed address | +| Auth0 | `https://.auth0.com/` | + +Register `https://taskist.example.com/signin-oidc` as the redirect URI, and make sure the `email` scope is allowed. + +## Mapping provider groups to roles + +Taskist can **add** roles based on the groups the provider sends. Set `RoleClaim` to the claim that carries the groups (often `groups`) and list the mappings, group → Taskist role *system name*: + +```json +"RoleClaim": "groups", +"RoleMappings": { + "taskist-leads": "TeamLead", + "taskist-qa": "QualityAssurance", + "taskist-pm": "ProjectManager" +} +``` + +As environment variables: `Authentication__Oidc__RoleClaim=groups`, `Authentication__Oidc__RoleMappings__taskist-leads=TeamLead`, and so on. These work in `docker-compose.yml` and on Windows, but a Linux shell can't `export` a variable whose name contains `-`. If your group names have dashes, put the mappings in `appsettings.Production.json`, or start the process with `env "Authentication__Oidc__RoleMappings__taskist-leads=TeamLead" …`. + +- Roles are added at each SSO sign-in and **never removed**. Removing someone from a group at the provider doesn't take the role away in Taskist; an administrator does that on the user's page. If the group still maps to the role, it comes back at the next sign-in, so remove the group membership too. +- Only groups listed in `RoleMappings` have any effect, and group names are matched case-insensitively. +- Mapping a group to `SystemAdministrator` makes membership of that group equivalent to full admin rights. Do it deliberately. +- Roles are global. Project access (which projects someone sees) is still granted per project in Taskist. + +## SSO-only mode + +With `DisableLocalLogin: true` the login page shows only the SSO button, and password sign-in is refused for everyone **except system administrators**. Administrators can still use their password at: + +``` +https://taskist.example.com/Login?local=1 +``` + +That's your way back in if the identity provider is down or misconfigured. Keep at least one administrator account with a strong password, and don't turn this mode on until you've tested SSO. + +## Troubleshooting + +| What you see | Likely cause | +| --- | --- | +| No SSO button | `Enabled` is false, or `Authority`/`ClientId` is missing or invalid; the startup log says which. | +| The provider shows "invalid redirect URI" | The registered redirect URI isn't exactly `signin-oidc`, or Taskist runs behind a proxy without forwarded headers (it sends `http://…`). | +| "Single sign-on didn't work" | The sign-in failed after the provider: check the Taskist log for "Single sign-on failed". Common causes: wrong client secret, the server clock is off, or the container reaches the provider at a different address than the browser. | +| "You don't have a Taskist account yet" | No Taskist user has that e-mail and `AutoProvision` is off. Create the user, or turn on auto-provisioning. | +| "Your e-mail address isn't verified" | The provider didn't mark the e-mail as verified. Verify it at the provider (Keycloak: *Email verified*), or see [Entra ID](#microsoft-entra-id). | +| "Your identity provider didn't send an e-mail address" | The `email` scope is missing or not allowed for the client. | +| "Already linked to a different account at your identity provider" | The Taskist user is linked to another identity at the same provider (for example, the account was re-created there). An administrator removes the old link on the user's page. | +| "Password sign-in is turned off" | SSO-only mode is on and this user isn't a system administrator. | + +Successful SSO sign-ins are recorded in the activity log (**Configuration → Activity log**), including when an account was linked or created and which roles were added. Refused sign-ins are written to the application log as "Single sign-on refused (*reason*)", with the reason codes from the table above (`NotProvisioned`, `UnverifiedEmail`, `MissingEmail`, `LinkConflict`, `Unavailable`). + +## Limitations + +- One identity provider at a time. +- Signing out of Taskist doesn't sign you out of the provider; the next SSO sign-in may go straight through. +- Accounts created by `AutoProvision` have no mobile number or address. The user's edit page and **My profile** ask for them on the next save. +- SSO users don't need a Taskist password. Without one, they can't unlink their last SSO sign-in, and if SSO is turned off they need a password reset from an administrator. diff --git a/sql-scripts/01_schema.sql b/sql-scripts/01_schema.sql index 45ce7f3..9796240 100644 --- a/sql-scripts/01_schema.sql +++ b/sql-scripts/01_schema.sql @@ -1985,3 +1985,50 @@ END; COMMIT; GO +BEGIN TRANSACTION; +IF NOT EXISTS ( + SELECT * FROM [__EFMigrationsHistory] + WHERE [MigrationId] = N'20261110190700_AddUserExternalLogin' +) +BEGIN + CREATE TABLE [UserExternalLogin] ( + [Id] int NOT NULL IDENTITY, + [UserId] int NOT NULL, + [Provider] nvarchar(255) NOT NULL, + [Subject] nvarchar(255) NOT NULL, + [Email] nvarchar(150) NULL, + [CreatedOn] datetime2 NOT NULL, + [LastUsedOn] datetime2 NULL, + CONSTRAINT [PK_UserExternalLogin] PRIMARY KEY ([Id]), + CONSTRAINT [FK_UserExternalLogin_User_UserId] FOREIGN KEY ([UserId]) REFERENCES [User] ([Id]) + ); +END; + +IF NOT EXISTS ( + SELECT * FROM [__EFMigrationsHistory] + WHERE [MigrationId] = N'20261110190700_AddUserExternalLogin' +) +BEGIN + CREATE UNIQUE INDEX [IX_UserExternalLogin_Provider_Subject] ON [UserExternalLogin] ([Provider], [Subject]); +END; + +IF NOT EXISTS ( + SELECT * FROM [__EFMigrationsHistory] + WHERE [MigrationId] = N'20261110190700_AddUserExternalLogin' +) +BEGIN + CREATE INDEX [IX_UserExternalLogin_UserId] ON [UserExternalLogin] ([UserId]); +END; + +IF NOT EXISTS ( + SELECT * FROM [__EFMigrationsHistory] + WHERE [MigrationId] = N'20261110190700_AddUserExternalLogin' +) +BEGIN + INSERT INTO [__EFMigrationsHistory] ([MigrationId], [ProductVersion]) + VALUES (N'20261110190700_AddUserExternalLogin', N'10.0.13'); +END; + +COMMIT; +GO + diff --git a/sql-scripts/03_locale.sql b/sql-scripts/03_locale.sql index 22541d1..4a3ff2e 100644 --- a/sql-scripts/03_locale.sql +++ b/sql-scripts/03_locale.sql @@ -611,6 +611,18 @@ FROM (VALUES (N'Log.ViewChanges', N'View'), (N'Log.ViewRaw', N'View raw data'), (N'Log.When', N'When'), + (N'Login.Sso.AdministratorSignIn', N'Administrator sign-in'), + (N'Login.Sso.Error.Denied', N'Sign-in was cancelled at your identity provider.'), + (N'Login.Sso.Error.Failed', N'Single sign-on didn’t work. Try again, or contact your administrator.'), + (N'Login.Sso.Error.LinkConflict', N'Your Taskist account is already linked to a different account at your identity provider. Ask your administrator to remove the old link.'), + (N'Login.Sso.Error.MissingEmail', N'Your identity provider didn’t send an e-mail address, so Taskist can’t find your account. Ask your administrator to check the single sign-on setup.'), + (N'Login.Sso.Error.MissingSubject', N'Your identity provider didn’t send a user ID. Ask your administrator to check the single sign-on setup.'), + (N'Login.Sso.Error.NotProvisioned', N'You don’t have a Taskist account yet. Ask your administrator to create one for your e-mail address.'), + (N'Login.Sso.Error.Unavailable', N'Your Taskist account is inactive or locked. Contact your administrator.'), + (N'Login.Sso.Error.UnverifiedEmail', N'Your e-mail address isn’t verified at your identity provider, so it can’t be used to sign in to Taskist. Verify it there, or ask your administrator.'), + (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'Message.DeleteSuccess', N'Deleted successfully'), (N'Message.SaveSuccess', N'Saved successfully'), (N'Message.UpdateSuccess', N'Updated successfully'), @@ -739,6 +751,15 @@ FROM (VALUES (N'Profile.Section.Unsaved', N'Unsaved changes'), (N'Profile.Security', N'Security'), (N'Profile.Security.PasswordHint', N'Change the password you use to sign in to Taskist.'), + (N'Profile.SignIns.Intro', N'These accounts at your identity provider can sign you in to Taskist.'), + (N'Profile.SignIns.LastMethod', N'You can’t unlink your only way to sign in. Ask your administrator to set a password for you first.'), + (N'Profile.SignIns.LastUsed', N'Last used'), + (N'Profile.SignIns.Never', N'never'), + (N'Profile.SignIns.NotFound', N'This sign-in no longer exists.'), + (N'Profile.SignIns.Title', N'Single sign-on'), + (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.ZoomIn', N'Zoom in'), (N'Profile.ZoomOut', N'Zoom out'), (N'ProfilePage.Title', N'My Profile'), @@ -1288,6 +1309,8 @@ FROM (VALUES (N'UserModel.UserNumber', N'User Number'), (N'UserModel.UserNumber.MaxLengthMsg', N'The length of employee number must be 20 characters or fewer'), (N'UserModel.UserNumber.RequiredMsg', N'User No is required'), + (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'UserProjectModel.CanAddWiki', N'Can Add Wiki'), (N'UserProjectModel.CanChangeProject', N'Can Change Project'), diff --git a/src/Libraries/Taskist.Core/Domain/Users/UserExternalLogin.cs b/src/Libraries/Taskist.Core/Domain/Users/UserExternalLogin.cs new file mode 100644 index 0000000..c97354e --- /dev/null +++ b/src/Libraries/Taskist.Core/Domain/Users/UserExternalLogin.cs @@ -0,0 +1,18 @@ +using Taskist.Core.Domain.Common; + +namespace Taskist.Core.Domain.Users; + +public class UserExternalLogin : BaseEntity +{ + public int UserId { get; set; } + + public string Provider { get; set; } + + public string Subject { get; set; } + + public string? Email { get; set; } + + public DateTime CreatedOn { get; set; } + + public DateTime? LastUsedOn { get; set; } +} diff --git a/src/Libraries/Taskist.Data/Configuration/Users/UserExternalLoginConfig.cs b/src/Libraries/Taskist.Data/Configuration/Users/UserExternalLoginConfig.cs new file mode 100644 index 0000000..20302eb --- /dev/null +++ b/src/Libraries/Taskist.Data/Configuration/Users/UserExternalLoginConfig.cs @@ -0,0 +1,38 @@ +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Metadata.Builders; +using Taskist.Core.Domain.Users; + +namespace Taskist.Data.Configuration.Users; + +public class UserExternalLoginConfig : EntityTypeConfiguration +{ + public override void Configure(EntityTypeBuilder builder) + { + builder.ToTable(nameof(UserExternalLogin)); + + builder.HasKey(x => x.Id); + + builder.Property(x => x.Provider) + .HasMaxLength(255) + .IsRequired(); + + builder.Property(x => x.Subject) + .HasMaxLength(255) + .IsRequired(); + + builder.Property(x => x.Email) + .HasMaxLength(150); + + builder.HasIndex(x => new { x.Provider, x.Subject }) + .IsUnique(); + + 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/Migrations/20261110190700_AddUserExternalLogin.Designer.cs b/src/Libraries/Taskist.Data/Migrations/20261110190700_AddUserExternalLogin.Designer.cs new file mode 100644 index 0000000..5dd8a55 --- /dev/null +++ b/src/Libraries/Taskist.Data/Migrations/20261110190700_AddUserExternalLogin.Designer.cs @@ -0,0 +1,3421 @@ +// +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("20261110190700_AddUserExternalLogin")] + partial class AddUserExternalLogin + { + /// + 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.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.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.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.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/20261110190700_AddUserExternalLogin.cs b/src/Libraries/Taskist.Data/Migrations/20261110190700_AddUserExternalLogin.cs new file mode 100644 index 0000000..8e01063 --- /dev/null +++ b/src/Libraries/Taskist.Data/Migrations/20261110190700_AddUserExternalLogin.cs @@ -0,0 +1,56 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Taskist.Data.Migrations +{ + /// + public partial class AddUserExternalLogin : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "UserExternalLogin", + columns: table => new + { + Id = table.Column(type: "int", nullable: false) + .Annotation("SqlServer:Identity", "1, 1"), + UserId = table.Column(type: "int", nullable: false), + Provider = table.Column(type: "nvarchar(255)", maxLength: 255, nullable: false), + Subject = table.Column(type: "nvarchar(255)", maxLength: 255, nullable: false), + Email = table.Column(type: "nvarchar(150)", maxLength: 150, nullable: true), + CreatedOn = table.Column(type: "datetime2", nullable: false), + LastUsedOn = table.Column(type: "datetime2", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_UserExternalLogin", x => x.Id); + table.ForeignKey( + name: "FK_UserExternalLogin_User_UserId", + column: x => x.UserId, + principalTable: "User", + principalColumn: "Id"); + }); + + migrationBuilder.CreateIndex( + name: "IX_UserExternalLogin_Provider_Subject", + table: "UserExternalLogin", + columns: new[] { "Provider", "Subject" }, + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_UserExternalLogin_UserId", + table: "UserExternalLogin", + column: "UserId"); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "UserExternalLogin"); + } + } +} diff --git a/src/Libraries/Taskist.Data/Migrations/ApplicationContextModelSnapshot.cs b/src/Libraries/Taskist.Data/Migrations/ApplicationContextModelSnapshot.cs index d3c929c..ec614ff 100644 --- a/src/Libraries/Taskist.Data/Migrations/ApplicationContextModelSnapshot.cs +++ b/src/Libraries/Taskist.Data/Migrations/ApplicationContextModelSnapshot.cs @@ -1595,6 +1595,47 @@ protected override void BuildModel(ModelBuilder modelBuilder) 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") @@ -2814,6 +2855,15 @@ protected override void BuildModel(ModelBuilder modelBuilder) 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") diff --git a/src/Libraries/Taskist.Service/Authentication/ExternalLoginService.cs b/src/Libraries/Taskist.Service/Authentication/ExternalLoginService.cs new file mode 100644 index 0000000..fb414eb --- /dev/null +++ b/src/Libraries/Taskist.Service/Authentication/ExternalLoginService.cs @@ -0,0 +1,77 @@ +using Microsoft.EntityFrameworkCore; +using Taskist.Core.Domain.Users; +using Taskist.Data.Repository; + +namespace Taskist.Service.Authentication; + +public class ExternalLoginService : IExternalLoginService +{ + #region Fields + + protected readonly IRepository _externalLoginRepository; + + #endregion + + #region Ctor + + public ExternalLoginService(IRepository externalLoginRepository) + { + _externalLoginRepository = externalLoginRepository; + } + + #endregion + + #region Methods + + public async Task GetAsync(string provider, string subject) + { + if (string.IsNullOrWhiteSpace(provider) || string.IsNullOrWhiteSpace(subject)) + return null; + + return await _externalLoginRepository.Table + .FirstOrDefaultAsync(x => x.Provider == provider && x.Subject == subject); + } + + public async Task> GetForUserAsync(int userId) + { + return await _externalLoginRepository.Table + .Where(x => x.UserId == userId) + .OrderBy(x => x.CreatedOn) + .ToListAsync(); + } + + public async Task CountForUserAsync(int userId) + { + return await _externalLoginRepository.Table.CountAsync(x => x.UserId == userId); + } + + public async Task InsertAsync(UserExternalLogin entity) + { + ArgumentNullException.ThrowIfNull(entity); + + await _externalLoginRepository.InsertAsync(entity); + } + + public async Task MarkUsedAsync(UserExternalLogin entity, string email) + { + ArgumentNullException.ThrowIfNull(entity); + + entity.LastUsedOn = DateTime.UtcNow; + if (!string.IsNullOrWhiteSpace(email)) + entity.Email = email.Length > 150 ? email[..150] : email; + + await _externalLoginRepository.UpdateAsync(entity); + } + + public async Task DeleteAsync(int id, int userId) + { + var entity = await _externalLoginRepository.Table.FirstOrDefaultAsync(x => x.Id == id && x.UserId == userId); + if (entity == null) + return false; + + await _externalLoginRepository.DeleteAsync(entity); + return true; + } + + #endregion +} diff --git a/src/Libraries/Taskist.Service/Authentication/IExternalLoginService.cs b/src/Libraries/Taskist.Service/Authentication/IExternalLoginService.cs new file mode 100644 index 0000000..8d0ce54 --- /dev/null +++ b/src/Libraries/Taskist.Service/Authentication/IExternalLoginService.cs @@ -0,0 +1,18 @@ +using Taskist.Core.Domain.Users; + +namespace Taskist.Service.Authentication; + +public interface IExternalLoginService +{ + Task GetAsync(string provider, string subject); + + Task> GetForUserAsync(int userId); + + Task CountForUserAsync(int userId); + + Task InsertAsync(UserExternalLogin entity); + + Task MarkUsedAsync(UserExternalLogin entity, string email); + + Task DeleteAsync(int id, int userId); +} diff --git a/src/Presentation/Taskist.Web/Controllers/Common/AccountController.cs b/src/Presentation/Taskist.Web/Controllers/Common/AccountController.cs index 44ca685..2ee9827 100644 --- a/src/Presentation/Taskist.Web/Controllers/Common/AccountController.cs +++ b/src/Presentation/Taskist.Web/Controllers/Common/AccountController.cs @@ -1,8 +1,12 @@ +using AuthenticationProperties = Microsoft.AspNetCore.Authentication.AuthenticationProperties; +using AuthenticationHttpContextExtensions = Microsoft.AspNetCore.Authentication.AuthenticationHttpContextExtensions; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.RateLimiting; using Taskist.Core.Common; +using Taskist.Core.Domain.Users; using Taskist.Core.Enums; using Taskist.Service.Authentication; +using Taskist.Service.Localization; using Taskist.Service.Logging; using Taskist.Service.Masters; using Taskist.Service.Messages; @@ -12,6 +16,8 @@ using Taskist.Web.Models.Users; using Taskist.Web.Helpers.Appearance; +using Taskist.Web.Helpers.Sso; +using Taskist.Web.Infrastructure; namespace Taskist.Web.Controllers.Common; @@ -27,6 +33,10 @@ public class AccountController : Controller protected readonly IMessageService _messageService; protected readonly IUserActivityService _activityService; protected readonly IAppearanceService _appearanceService; + protected readonly ILocalizationService _localizationService; + protected readonly ISsoSignInService _ssoSignInService; + protected readonly OidcOptions _oidcOptions; + protected readonly ILogger _logger; #endregion @@ -39,9 +49,17 @@ public AccountController(IUserService userService, IEncryptionService encryptionService, IMessageService messageService, IUserActivityService activityService, - IAppearanceService appearanceService) + IAppearanceService appearanceService, + ILocalizationService localizationService, + ISsoSignInService ssoSignInService, + OidcOptions oidcOptions, + ILogger logger) { + _logger = logger; _appearanceService = appearanceService; + _localizationService = localizationService; + _ssoSignInService = ssoSignInService; + _oidcOptions = oidcOptions; _userService = userService; _systemService = systemService; _genericAttributeService = genericAttributeService; @@ -55,9 +73,13 @@ public AccountController(IUserService userService, #region Actions - public async Task Login() + public IActionResult Login(string sso, string local) { - return View(new LoginModel()); + var model = new LoginModel { LocalLogin = LocalLoginSwitch.IsOn(local) }; + PrepareLoginModel(model); + model.SsoErrorCode = SsoErrorCode.Normalize(sso); + + return View(model); } [HttpPost] @@ -72,16 +94,16 @@ public async Task Login(LoginModel model, string returnUrl) case LoginResult.Successful: { var user = await _userService.GetByEmailAsync(model.Email); - await _authenticationService.SignInAsync(user, model.RememberMe); - await _appearanceService.SyncCookieAsync(user); - - await _activityService.InsertAsync(user, ActivityType.Login, "Signed in"); - - await _systemService.ResetCacheAsync(); - - if (string.IsNullOrEmpty(returnUrl) || !Url.IsLocalUrl(returnUrl)) - return RedirectToAction("Index", "Home"); - return Redirect(returnUrl); + if (_oidcOptions.LocalLoginRestricted && !await IsAdministratorAsync(user)) + { + ModelState.AddModelError(string.Empty, await ResourceOrDefaultAsync("Login.Sso.PasswordSignInDisabled", + $"Password sign-in is turned off. Use \"Sign in with {_oidcOptions.EffectiveDisplayName}\" instead.")); + await _activityService.InsertAsync(user, ActivityType.LoginFailed, "Failed sign-in: password sign-in is limited to administrators while single sign-on is required"); + PrepareLoginModel(model); + return View(model); + } + + return await CompleteSignInAsync(user, model.RememberMe, "Signed in", returnUrl); } case LoginResult.NotExist: ModelState.AddModelError(string.Empty, "User doesn't exists"); @@ -108,9 +130,51 @@ await _activityService.InsertAsync(await _userService.GetByEmailAsync(model.Emai ActivityType.LoginFailed, $"Failed sign-in: {loginResult}"); } + PrepareLoginModel(model); return View(model); } + [HttpPost] + public IActionResult ExternalLogin(string returnUrl) + { + if (!_oidcOptions.IsActive) + return NotFound(); + + var callback = Url.Action(nameof(ExternalCallback), "Account", new { returnUrl = SafeReturnUrl(returnUrl) }); + var properties = new AuthenticationProperties { RedirectUri = callback }; + + return Challenge(properties, OidcOptions.SchemeName); + } + + public async Task ExternalCallback(string returnUrl) + { + if (!_oidcOptions.IsActive) + return NotFound(); + + var external = await AuthenticationHttpContextExtensions.AuthenticateAsync(HttpContext, OidcOptions.ExternalCookieScheme); + await AuthenticationHttpContextExtensions.SignOutAsync(HttpContext, OidcOptions.ExternalCookieScheme); + + if (!external.Succeeded || external.Principal == null) + return RedirectToAction(nameof(Login), new { sso = SsoErrorCode.Failed }); + + var identity = ExternalIdentityReader.Read(external.Principal.Claims, _oidcOptions.EffectiveRoleClaim); + var result = await _ssoSignInService.ResolveAsync(identity); + + if (!result.Succeeded) + { + _logger.LogWarning("Single sign-on refused ({Reason}) for an identity from {Issuer}.", result.ErrorCode, identity.Issuer); + return RedirectToAction(nameof(Login), new { sso = result.ErrorCode }); + } + + var note = result.Provisioned ? "Signed in with single sign-on (account created)" + : result.Linked ? "Signed in with single sign-on (account linked)" + : "Signed in with single sign-on"; + if (result.RolesAdded.Count > 0) + note += $"; roles added: {string.Join(", ", result.RolesAdded)}"; + + return await CompleteSignInAsync(result.User!, false, note, returnUrl); + } + public async Task Logout() { await _activityService.InsertAsync(ActivityType.Logout, "Signed out"); @@ -206,4 +270,48 @@ public async Task Activate(SetPasswordModel model) } #endregion + + #region Utilities + + private void PrepareLoginModel(LoginModel model) + { + model.SsoEnabled = _oidcOptions.IsActive; + model.SsoDisplayName = _oidcOptions.EffectiveDisplayName; + model.ShowPasswordForm = !_oidcOptions.LocalLoginRestricted || model.LocalLogin; + } + + private async Task IsAdministratorAsync(User user) + { + if (user == null) + return false; + + return await _userService.IsInUserRoleAsync(user, UserConstant.SystemAdministratorRoleName) + || await _userService.IsAdminAsync(user); + } + + private async Task ResourceOrDefaultAsync(string key, string fallback) + { + var value = await _localizationService.GetResourceAsync(key); + return string.IsNullOrWhiteSpace(value) || string.Equals(value, key, StringComparison.OrdinalIgnoreCase) ? fallback : value; + } + + 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) + { + await _authenticationService.SignInAsync(user, isPersistent); + await _appearanceService.SyncCookieAsync(user); + + await _activityService.InsertAsync(user, ActivityType.Login, note); + + await _systemService.ResetCacheAsync(); + + var target = SafeReturnUrl(returnUrl); + if (target == null) + return RedirectToAction("Index", "Home"); + return Redirect(target); + } + + #endregion } \ No newline at end of file diff --git a/src/Presentation/Taskist.Web/Controllers/Users/ProfileController.cs b/src/Presentation/Taskist.Web/Controllers/Users/ProfileController.cs index 6fc10bf..d736f81 100644 --- a/src/Presentation/Taskist.Web/Controllers/Users/ProfileController.cs +++ b/src/Presentation/Taskist.Web/Controllers/Users/ProfileController.cs @@ -2,6 +2,7 @@ using Taskist.Core.Common; using Taskist.Core.Domain.Settings; using Taskist.Core.Enums; +using Taskist.Service.Authentication; using Taskist.Service.Git; using Taskist.Service.Localization; using Taskist.Service.Masters; @@ -32,6 +33,7 @@ public class ProfileController : BaseController protected readonly IGitRepositoryService _gitRepositoryService; protected readonly INotificationService _notificationService; protected readonly IAppearanceService _appearanceService; + protected readonly IExternalLoginService _externalLoginService; #endregion @@ -45,9 +47,11 @@ public ProfileController(IUserService userService, IGitAccountService gitAccountService, IGitRepositoryService gitRepositoryService, INotificationService notificationService, - IAppearanceService appearanceService) + IAppearanceService appearanceService, + IExternalLoginService externalLoginService) { _appearanceService = appearanceService; + _externalLoginService = externalLoginService; _gitAccountService = gitAccountService; _gitRepositoryService = gitRepositoryService; _notificationService = notificationService; @@ -77,12 +81,47 @@ public async Task Index() Email = e.Email, HasPhoto = e.PhotoDocumentId.HasValue, GitConnections = await _gitAccountService.GetStatusesAsync(e), - Appearance = await _appearanceService.GetForUserAsync(e) + Appearance = await _appearanceService.GetForUserAsync(e), + LinkedSignIns = (await _externalLoginService.GetForUserAsync(e.Id)) + .Select(l => new LinkedSignInModel + { + Id = l.Id, + ProviderName = LinkedSignInModel.ProviderNameFrom(l.Provider), + Email = l.Email, + CreatedOn = l.CreatedOn, + LastUsedOn = l.LastUsedOn + }) + .ToList() }; return View(model); } + [HttpPost] + [CheckPermission(nameof(PermissionProvider.ManageDashboard))] + public async Task UnlinkSignIn(int id) + { + var hasPassword = await _userService.GetCurrentPasswordAsync(UserId) != null; + var linkCount = await _externalLoginService.CountForUserAsync(UserId); + + if (!hasPassword && linkCount <= 1) + { + return new JsonResponseModel + { + Status = HttpStatusCode.ValidationError, + Message = await _localizationService.GetResourceAsync("Profile.SignIns.LastMethod") + }; + } + + var removed = await _externalLoginService.DeleteAsync(id, UserId); + + return new JsonResponseModel + { + Status = removed ? HttpStatusCode.Success : HttpStatusCode.ValidationError, + Message = await _localizationService.GetResourceAsync(removed ? "Profile.SignIns.Unlinked" : "Profile.SignIns.NotFound") + }; + } + [CheckPermission(nameof(PermissionProvider.ManageDashboard))] public async Task GitConnection(int connectionId) { diff --git a/src/Presentation/Taskist.Web/Controllers/Users/UserController.cs b/src/Presentation/Taskist.Web/Controllers/Users/UserController.cs index b5d0288..b8ec174 100644 --- a/src/Presentation/Taskist.Web/Controllers/Users/UserController.cs +++ b/src/Presentation/Taskist.Web/Controllers/Users/UserController.cs @@ -4,6 +4,7 @@ using Taskist.Core.Common; using Taskist.Core.Domain.Users; using Taskist.Core.Enums; +using Taskist.Service.Authentication; using Taskist.Service.Git; using Taskist.Service.Localization; using Taskist.Service.Masters; @@ -32,6 +33,7 @@ public class UserController : BaseController protected readonly IWorkContext _workContext; protected readonly UsersMapper _usersMapper; protected readonly MastersMapper _mastersMapper; + protected readonly IExternalLoginService _externalLoginService; #endregion @@ -44,8 +46,10 @@ public UserController(IUserService userService, IGitRepositoryService gitRepositoryService, IWorkContext workContext, UsersMapper usersMapper, - MastersMapper mastersMapper) + MastersMapper mastersMapper, + IExternalLoginService externalLoginService) { + _externalLoginService = externalLoginService; _userService = userService; _documentService = documentService; _languageService = languageService; @@ -225,6 +229,18 @@ public async Task UnlockConfirmed(int id) }); } + [HttpPost] + public async Task RemoveSignIn(int userId, int id) + { + var removed = await _externalLoginService.DeleteAsync(id, userId); + + return Json(new JsonResponseModel + { + Status = removed ? HttpStatusCode.Success : HttpStatusCode.NoData, + Message = await _localizationService.GetResourceAsync(removed ? "Profile.SignIns.Unlinked" : "Profile.SignIns.NotFound") + }); + } + #endregion #region Data @@ -283,6 +299,20 @@ private async Task InitModelAsync(UserRegistrationModel model) { model.User.GitLabConfigured = await _gitRepositoryService.GetDefaultConnectionAsync() != null; + if (model.User.Id > 0) + { + model.LinkedSignIns = (await _externalLoginService.GetForUserAsync(model.User.Id)) + .Select(l => new LinkedSignInModel + { + Id = l.Id, + ProviderName = LinkedSignInModel.ProviderNameFrom(l.Provider), + Email = l.Email, + CreatedOn = l.CreatedOn, + LastUsedOn = l.LastUsedOn + }) + .ToList(); + } + var languages = await _languageService.GetAllActiveAsync(); var userRoles = await _userService.GetAllUserRolesAsync(); diff --git a/src/Presentation/Taskist.Web/Helpers/Sso/ExternalIdentity.cs b/src/Presentation/Taskist.Web/Helpers/Sso/ExternalIdentity.cs new file mode 100644 index 0000000..6ef223c --- /dev/null +++ b/src/Presentation/Taskist.Web/Helpers/Sso/ExternalIdentity.cs @@ -0,0 +1,24 @@ +namespace Taskist.Web.Helpers.Sso; + +public class ExternalIdentity +{ + #region Properties + + public string Issuer { get; set; } = string.Empty; + + public string Subject { get; set; } = string.Empty; + + public string? Email { get; set; } + + public bool EmailVerified { get; set; } + + public string? GivenName { get; set; } + + public string? FamilyName { get; set; } + + public string? Name { get; set; } + + public IReadOnlyList Groups { get; set; } = []; + + #endregion +} diff --git a/src/Presentation/Taskist.Web/Helpers/Sso/ExternalIdentityReader.cs b/src/Presentation/Taskist.Web/Helpers/Sso/ExternalIdentityReader.cs new file mode 100644 index 0000000..81b29d9 --- /dev/null +++ b/src/Presentation/Taskist.Web/Helpers/Sso/ExternalIdentityReader.cs @@ -0,0 +1,62 @@ +using System.Security.Claims; + +namespace Taskist.Web.Helpers.Sso; + +public static class ExternalIdentityReader +{ + #region Methods + + public static ExternalIdentity Read(IEnumerable claims, string? roleClaim) + { + var list = claims?.ToList() ?? []; + + var subjectClaim = list.FirstOrDefault(c => c.Type == "sub"); + var issuer = Value(list, "iss") ?? subjectClaim?.Issuer ?? string.Empty; + + var groups = string.IsNullOrWhiteSpace(roleClaim) + ? [] + : list.Where(c => c.Type == roleClaim) + .Select(c => c.Value?.Trim()) + .Where(v => !string.IsNullOrEmpty(v)) + .Select(v => v!) + .Distinct(StringComparer.OrdinalIgnoreCase) + .ToList(); + + return new ExternalIdentity + { + Issuer = NormalizeIssuer(issuer), + Subject = subjectClaim?.Value?.Trim() ?? string.Empty, + Email = Value(list, "email"), + EmailVerified = IsTrue(Value(list, "email_verified")), + GivenName = Value(list, "given_name"), + FamilyName = Value(list, "family_name"), + Name = Value(list, "name"), + Groups = groups + }; + } + + public static string NormalizeIssuer(string? issuer) + { + if (string.IsNullOrWhiteSpace(issuer)) + return string.Empty; + + return issuer.Trim().TrimEnd('/'); + } + + public static bool IsTrue(string? value) + { + if (string.IsNullOrWhiteSpace(value)) + return false; + + var trimmed = value.Trim(); + return trimmed.Equals("true", StringComparison.OrdinalIgnoreCase) || trimmed == "1"; + } + + private static string? Value(List claims, string type) + { + var value = claims.FirstOrDefault(c => c.Type == type)?.Value?.Trim(); + return string.IsNullOrEmpty(value) ? null : value; + } + + #endregion +} diff --git a/src/Presentation/Taskist.Web/Helpers/Sso/ExternalNameSplitter.cs b/src/Presentation/Taskist.Web/Helpers/Sso/ExternalNameSplitter.cs new file mode 100644 index 0000000..45c96aa --- /dev/null +++ b/src/Presentation/Taskist.Web/Helpers/Sso/ExternalNameSplitter.cs @@ -0,0 +1,40 @@ +namespace Taskist.Web.Helpers.Sso; + +public static class ExternalNameSplitter +{ + #region Fields + + public const int MaxLength = 50; + + #endregion + + #region Methods + + public static (string FirstName, string LastName) Split(ExternalIdentity identity) + { + ArgumentNullException.ThrowIfNull(identity); + + var first = identity.GivenName?.Trim(); + var last = identity.FamilyName?.Trim(); + + if (string.IsNullOrEmpty(first) && !string.IsNullOrWhiteSpace(identity.Name)) + { + var parts = identity.Name.Trim().Split(' ', 2, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries); + first = parts[0]; + if (string.IsNullOrEmpty(last) && parts.Length > 1) + last = parts[1]; + } + + if (string.IsNullOrEmpty(first) && !string.IsNullOrWhiteSpace(identity.Email)) + first = identity.Email.Split('@')[0].Trim(); + + if (string.IsNullOrEmpty(first)) + first = "User"; + + return (Truncate(first), Truncate(last ?? string.Empty)); + } + + private static string Truncate(string value) => value.Length > MaxLength ? value[..MaxLength] : value; + + #endregion +} diff --git a/src/Presentation/Taskist.Web/Helpers/Sso/ISsoSignInService.cs b/src/Presentation/Taskist.Web/Helpers/Sso/ISsoSignInService.cs new file mode 100644 index 0000000..3994cd4 --- /dev/null +++ b/src/Presentation/Taskist.Web/Helpers/Sso/ISsoSignInService.cs @@ -0,0 +1,6 @@ +namespace Taskist.Web.Helpers.Sso; + +public interface ISsoSignInService +{ + Task ResolveAsync(ExternalIdentity identity); +} diff --git a/src/Presentation/Taskist.Web/Helpers/Sso/LocalLoginSwitch.cs b/src/Presentation/Taskist.Web/Helpers/Sso/LocalLoginSwitch.cs new file mode 100644 index 0000000..0236117 --- /dev/null +++ b/src/Presentation/Taskist.Web/Helpers/Sso/LocalLoginSwitch.cs @@ -0,0 +1,15 @@ +namespace Taskist.Web.Helpers.Sso; + +public static class LocalLoginSwitch +{ + #region Methods + + public static bool IsOn(string? value) + { + var text = value?.Trim(); + + return text == "1" || string.Equals(text, bool.TrueString, StringComparison.OrdinalIgnoreCase); + } + + #endregion +} diff --git a/src/Presentation/Taskist.Web/Helpers/Sso/OidcRoleMapper.cs b/src/Presentation/Taskist.Web/Helpers/Sso/OidcRoleMapper.cs new file mode 100644 index 0000000..92d93ec --- /dev/null +++ b/src/Presentation/Taskist.Web/Helpers/Sso/OidcRoleMapper.cs @@ -0,0 +1,37 @@ +namespace Taskist.Web.Helpers.Sso; + +public static class OidcRoleMapper +{ + #region Methods + + public static IReadOnlyList MapRoles(IEnumerable? groups, IReadOnlyDictionary? mappings) + { + if (groups == null || mappings == null || mappings.Count == 0) + return []; + + var normalized = mappings + .Where(m => !string.IsNullOrWhiteSpace(m.Key) && !string.IsNullOrWhiteSpace(m.Value)) + .GroupBy(m => m.Key.Trim(), StringComparer.OrdinalIgnoreCase) + .ToDictionary(g => g.Key, g => g.First().Value.Trim(), StringComparer.OrdinalIgnoreCase); + + return groups + .Where(g => !string.IsNullOrWhiteSpace(g)) + .Select(g => g.Trim()) + .Where(normalized.ContainsKey) + .Select(g => normalized[g]) + .Distinct(StringComparer.OrdinalIgnoreCase) + .ToList(); + } + + public static IReadOnlyList RolesToAdd(IEnumerable mappedRoles, IEnumerable currentRoles) + { + var current = new HashSet(currentRoles ?? [], StringComparer.OrdinalIgnoreCase); + + return (mappedRoles ?? []) + .Where(r => !current.Contains(r)) + .Distinct(StringComparer.OrdinalIgnoreCase) + .ToList(); + } + + #endregion +} diff --git a/src/Presentation/Taskist.Web/Helpers/Sso/SsoErrorCode.cs b/src/Presentation/Taskist.Web/Helpers/Sso/SsoErrorCode.cs new file mode 100644 index 0000000..689f360 --- /dev/null +++ b/src/Presentation/Taskist.Web/Helpers/Sso/SsoErrorCode.cs @@ -0,0 +1,48 @@ +namespace Taskist.Web.Helpers.Sso; + +public static class SsoErrorCode +{ + #region Fields + + public const string Failed = "Failed"; + + public const string Denied = "Denied"; + + public const string Unavailable = "Unavailable"; + + public const string MissingSubject = "MissingSubject"; + + public const string MissingEmail = "MissingEmail"; + + public const string UnverifiedEmail = "UnverifiedEmail"; + + public const string LinkConflict = "LinkConflict"; + + public const string NotProvisioned = "NotProvisioned"; + + private static readonly HashSet Known = new(StringComparer.Ordinal) + { + Failed, Denied, Unavailable, MissingSubject, MissingEmail, UnverifiedEmail, LinkConflict, NotProvisioned + }; + + #endregion + + #region Methods + + public static string? FromDecision(SsoSignInDecision decision) => decision switch + { + SsoSignInDecision.RejectMissingSubject => MissingSubject, + SsoSignInDecision.RejectMissingEmail => MissingEmail, + SsoSignInDecision.RejectUnverifiedEmail => UnverifiedEmail, + SsoSignInDecision.RejectLinkConflict => LinkConflict, + SsoSignInDecision.RejectNotProvisioned => NotProvisioned, + _ => null + }; + + public static string? Normalize(string? code) => + !string.IsNullOrWhiteSpace(code) && Known.Contains(code.Trim()) ? code.Trim() : null; + + public static string ResourceKey(string code) => $"Login.Sso.Error.{code}"; + + #endregion +} diff --git a/src/Presentation/Taskist.Web/Helpers/Sso/SsoSignInDecision.cs b/src/Presentation/Taskist.Web/Helpers/Sso/SsoSignInDecision.cs new file mode 100644 index 0000000..cf32810 --- /dev/null +++ b/src/Presentation/Taskist.Web/Helpers/Sso/SsoSignInDecision.cs @@ -0,0 +1,13 @@ +namespace Taskist.Web.Helpers.Sso; + +public enum SsoSignInDecision +{ + UseLinkedUser, + LinkExistingUser, + ProvisionUser, + RejectMissingSubject, + RejectMissingEmail, + RejectUnverifiedEmail, + RejectLinkConflict, + RejectNotProvisioned +} diff --git a/src/Presentation/Taskist.Web/Helpers/Sso/SsoSignInPlanner.cs b/src/Presentation/Taskist.Web/Helpers/Sso/SsoSignInPlanner.cs new file mode 100644 index 0000000..373ba57 --- /dev/null +++ b/src/Presentation/Taskist.Web/Helpers/Sso/SsoSignInPlanner.cs @@ -0,0 +1,49 @@ +namespace Taskist.Web.Helpers.Sso; + +public static class SsoSignInPlanner +{ + #region Methods + + public static SsoSignInDecision Decide(ExternalIdentity identity, + bool hasLinkedUser, + bool hasUserWithEmail, + bool emailUserLinkedToThisProvider, + bool requireVerifiedEmail, + bool autoProvision) + { + ArgumentNullException.ThrowIfNull(identity); + + if (string.IsNullOrWhiteSpace(identity.Subject) || string.IsNullOrWhiteSpace(identity.Issuer)) + return SsoSignInDecision.RejectMissingSubject; + + if (hasLinkedUser) + return SsoSignInDecision.UseLinkedUser; + + if (string.IsNullOrWhiteSpace(identity.Email)) + return SsoSignInDecision.RejectMissingEmail; + + if (hasUserWithEmail) + { + if (requireVerifiedEmail && !identity.EmailVerified) + return SsoSignInDecision.RejectUnverifiedEmail; + + if (emailUserLinkedToThisProvider) + return SsoSignInDecision.RejectLinkConflict; + + return SsoSignInDecision.LinkExistingUser; + } + + if (!autoProvision) + return SsoSignInDecision.RejectNotProvisioned; + + if (requireVerifiedEmail && !identity.EmailVerified) + return SsoSignInDecision.RejectUnverifiedEmail; + + return SsoSignInDecision.ProvisionUser; + } + + public static bool IsRejection(SsoSignInDecision decision) => + decision is not (SsoSignInDecision.UseLinkedUser or SsoSignInDecision.LinkExistingUser or SsoSignInDecision.ProvisionUser); + + #endregion +} diff --git a/src/Presentation/Taskist.Web/Helpers/Sso/SsoSignInResult.cs b/src/Presentation/Taskist.Web/Helpers/Sso/SsoSignInResult.cs new file mode 100644 index 0000000..56b4662 --- /dev/null +++ b/src/Presentation/Taskist.Web/Helpers/Sso/SsoSignInResult.cs @@ -0,0 +1,28 @@ +using Taskist.Core.Domain.Users; + +namespace Taskist.Web.Helpers.Sso; + +public class SsoSignInResult +{ + #region Properties + + public User? User { get; init; } + + public string? ErrorCode { get; init; } + + public bool Linked { get; init; } + + public bool Provisioned { get; init; } + + public IReadOnlyList RolesAdded { get; init; } = []; + + public bool Succeeded => User != null && ErrorCode == null; + + #endregion + + #region Methods + + public static SsoSignInResult Fail(string code) => new() { ErrorCode = code }; + + #endregion +} diff --git a/src/Presentation/Taskist.Web/Helpers/Sso/SsoSignInService.cs b/src/Presentation/Taskist.Web/Helpers/Sso/SsoSignInService.cs new file mode 100644 index 0000000..cd696cd --- /dev/null +++ b/src/Presentation/Taskist.Web/Helpers/Sso/SsoSignInService.cs @@ -0,0 +1,196 @@ +using Taskist.Core.Domain.Masters; +using Taskist.Core.Domain.Users; +using Taskist.Core.Enums; +using Taskist.Service.Authentication; +using Taskist.Service.Localization; +using Taskist.Service.Users; +using Taskist.Web.Infrastructure; + +namespace Taskist.Web.Helpers.Sso; + +public class SsoSignInService : ISsoSignInService +{ + #region Fields + + private readonly OidcOptions _options; + private readonly IUserService _userService; + private readonly IExternalLoginService _externalLoginService; + private readonly ILanguageService _languageService; + private readonly ILogger _logger; + + #endregion + + #region Ctor + + public SsoSignInService(OidcOptions options, + IUserService userService, + IExternalLoginService externalLoginService, + ILanguageService languageService, + ILogger logger) + { + _options = options; + _userService = userService; + _externalLoginService = externalLoginService; + _languageService = languageService; + _logger = logger; + } + + #endregion + + #region Methods + + public async Task ResolveAsync(ExternalIdentity identity) + { + ArgumentNullException.ThrowIfNull(identity); + + var link = await _externalLoginService.GetAsync(identity.Issuer, identity.Subject); + var linkedUser = link == null ? null : await _userService.GetByIdAsync(link.UserId); + + User? emailUser = null; + var emailUserLinked = false; + if (linkedUser == null && !string.IsNullOrWhiteSpace(identity.Email)) + { + emailUser = await _userService.GetByEmailAsync(identity.Email); + if (emailUser != null) + emailUserLinked = (await _externalLoginService.GetForUserAsync(emailUser.Id)) + .Any(l => string.Equals(l.Provider, identity.Issuer, StringComparison.Ordinal)); + } + + var decision = SsoSignInPlanner.Decide(identity, + hasLinkedUser: linkedUser != null, + hasUserWithEmail: emailUser != null, + emailUserLinkedToThisProvider: emailUserLinked, + requireVerifiedEmail: _options.RequireVerifiedEmail, + autoProvision: _options.AutoProvision); + + if (SsoSignInPlanner.IsRejection(decision)) + return SsoSignInResult.Fail(SsoErrorCode.FromDecision(decision) ?? SsoErrorCode.Failed); + + User? user; + var linked = false; + var provisioned = false; + + switch (decision) + { + case SsoSignInDecision.UseLinkedUser: + user = linkedUser; + break; + case SsoSignInDecision.LinkExistingUser: + user = emailUser; + break; + default: + user = await ProvisionAsync(identity); + provisioned = user != null; + break; + } + + if (user == null) + return SsoSignInResult.Fail(SsoErrorCode.Failed); + + if (!await IsUsableAsync(user)) + return SsoSignInResult.Fail(SsoErrorCode.Unavailable); + + if (link == null) + { + await _externalLoginService.InsertAsync(new UserExternalLogin + { + UserId = user.Id, + Provider = identity.Issuer, + Subject = identity.Subject, + Email = identity.Email, + CreatedOn = DateTime.UtcNow, + LastUsedOn = DateTime.UtcNow + }); + linked = true; + } + else + { + await _externalLoginService.MarkUsedAsync(link, identity.Email); + } + + var rolesAdded = await ApplyRoleMappingsAsync(user, identity); + + return new SsoSignInResult + { + User = user, + Linked = linked && !provisioned, + Provisioned = provisioned, + RolesAdded = rolesAdded + }; + } + + #endregion + + #region Utilities + + private async Task IsUsableAsync(User user) + { + if (user.Deleted || user.Locked || user.Status != (int)UserStatus.Active) + return false; + + return await _userService.IsRegisteredAsync(user); + } + + private async Task ProvisionAsync(ExternalIdentity identity) + { + var languages = await _languageService.GetAllActiveAsync(); + var language = languages.FirstOrDefault(); + if (language == null) + { + _logger.LogWarning("SSO could not create a user because no active language exists."); + return null; + } + + var (firstName, lastName) = ExternalNameSplitter.Split(identity); + var user = new User + { + FirstName = firstName, + LastName = lastName, + Email = identity.Email!.Trim(), + MobileNumber = string.Empty, + DateOfJoin = DateOnly.FromDateTime(DateTime.UtcNow), + LastActivityDate = DateTime.UtcNow + }; + var address = new Address { Address1 = string.Empty, ZipPostalCode = string.Empty }; + + var result = await _userService.RegisterAsync(user, address, [], new User { LanguageId = language.Id }, emailWelcomeKit: false); + if (result != RegistrationResult.Successful) + { + _logger.LogWarning("SSO could not create a user for a new sign-in (result {Result}).", result); + return null; + } + + return await _userService.GetByEmailAsync(user.Email); + } + + private async Task> ApplyRoleMappingsAsync(User user, ExternalIdentity identity) + { + var mapped = OidcRoleMapper.MapRoles(identity.Groups, _options.RoleMappings); + if (mapped.Count == 0) + return []; + + var current = (await _userService.GetUserRolesAsync(user, showHidden: true)).Select(r => r.SystemName); + var toAdd = OidcRoleMapper.RolesToAdd(mapped, current); + if (toAdd.Count == 0) + return []; + + var roles = await _userService.GetAllUserRolesAsync(); + var added = new List(); + foreach (var roleName in toAdd) + { + var role = roles.FirstOrDefault(r => string.Equals(r.SystemName, roleName, StringComparison.OrdinalIgnoreCase)); + if (role == null) + { + _logger.LogWarning("Authentication:Oidc:RoleMappings refers to role '{Role}', which does not exist or is inactive.", roleName); + continue; + } + + await _userService.AddUserRoleMappingAsync(new UserRoleMap { UserId = user.Id, UserRoleId = role.Id }); + added.Add(role.SystemName); + } + + return added; + } + + #endregion +} diff --git a/src/Presentation/Taskist.Web/Infrastructure/OidcAuthenticationExtensions.cs b/src/Presentation/Taskist.Web/Infrastructure/OidcAuthenticationExtensions.cs new file mode 100644 index 0000000..1f32252 --- /dev/null +++ b/src/Presentation/Taskist.Web/Infrastructure/OidcAuthenticationExtensions.cs @@ -0,0 +1,91 @@ +using Microsoft.AspNetCore.Authentication; +using Microsoft.AspNetCore.Authentication.OpenIdConnect; +using Microsoft.IdentityModel.Protocols.OpenIdConnect; +using Taskist.Web.Helpers.Sso; + +namespace Taskist.Web.Infrastructure; + +public static class OidcAuthenticationExtensions +{ + #region Methods + + public static IServiceCollection AddOidcSignIn(this IServiceCollection services, IConfiguration configuration) + { + var options = configuration.GetSection(OidcOptions.SectionName).Get() ?? new OidcOptions(); + services.AddSingleton(options); + services.AddScoped(); + + if (!options.IsActive) + return services; + + services.AddAuthentication() + .AddCookie(OidcOptions.ExternalCookieScheme, cookie => + { + cookie.Cookie.Name = "Taskist.External"; + cookie.Cookie.HttpOnly = true; + cookie.Cookie.IsEssential = true; + cookie.Cookie.SameSite = SameSiteMode.Lax; + cookie.Cookie.SecurePolicy = CookieSecurePolicy.SameAsRequest; + cookie.ExpireTimeSpan = TimeSpan.FromMinutes(10); + cookie.SlidingExpiration = false; + }) + .AddOpenIdConnect(OidcOptions.SchemeName, oidc => + { + oidc.SignInScheme = OidcOptions.ExternalCookieScheme; + oidc.Authority = options.Authority!.Trim(); + oidc.ClientId = options.ClientId!.Trim(); + if (!string.IsNullOrWhiteSpace(options.ClientSecret)) + oidc.ClientSecret = options.ClientSecret.Trim(); + + oidc.RequireHttpsMetadata = options.RequireHttpsMetadata; + oidc.ResponseType = OpenIdConnectResponseType.Code; + oidc.ResponseMode = OpenIdConnectResponseMode.Query; + oidc.UsePkce = true; + oidc.SaveTokens = false; + oidc.GetClaimsFromUserInfoEndpoint = true; + oidc.MapInboundClaims = false; + oidc.CallbackPath = OidcOptions.CallbackPath; + oidc.TokenValidationParameters.NameClaimType = "name"; + + oidc.Scope.Clear(); + foreach (var scope in options.EffectiveScopes) + oidc.Scope.Add(scope); + + oidc.ClaimActions.MapUniqueJsonKey("email_verified", "email_verified"); + if (options.EffectiveRoleClaim != null) + oidc.ClaimActions.MapJsonKey(options.EffectiveRoleClaim, options.EffectiveRoleClaim); + + oidc.CorrelationCookie.SameSite = SameSiteMode.Lax; + oidc.CorrelationCookie.SecurePolicy = CookieSecurePolicy.SameAsRequest; + oidc.NonceCookie.SameSite = SameSiteMode.Lax; + oidc.NonceCookie.SecurePolicy = CookieSecurePolicy.SameAsRequest; + + oidc.Events = new OpenIdConnectEvents + { + OnRemoteFailure = context => RedirectToLogin(context, SsoErrorCode.Failed), + OnAccessDenied = context => RedirectToLogin(context, SsoErrorCode.Denied) + }; + }); + + return services; + } + + #endregion + + #region Utilities + + private static Task RedirectToLogin(HandleRequestContext context, string code) + { + if (context is RemoteFailureContext failure && failure.Failure != null) + { + var logger = context.HttpContext.RequestServices.GetRequiredService().CreateLogger(nameof(OidcAuthenticationExtensions)); + logger.LogWarning("Single sign-on failed: {Reason}", failure.Failure.Message); + } + + context.Response.Redirect($"{context.Request.PathBase}/Login?sso={code}"); + context.HandleResponse(); + return Task.CompletedTask; + } + + #endregion +} diff --git a/src/Presentation/Taskist.Web/Infrastructure/OidcOptions.cs b/src/Presentation/Taskist.Web/Infrastructure/OidcOptions.cs new file mode 100644 index 0000000..bee72d6 --- /dev/null +++ b/src/Presentation/Taskist.Web/Infrastructure/OidcOptions.cs @@ -0,0 +1,81 @@ +namespace Taskist.Web.Infrastructure; + +public class OidcOptions +{ + #region Fields + + public const string SectionName = "Authentication:Oidc"; + + public const string SchemeName = "oidc"; + + public const string ExternalCookieScheme = "Taskist.External"; + + public const string CallbackPath = "/signin-oidc"; + + private const string DefaultScopes = "openid profile email"; + + #endregion + + #region Properties + + public bool Enabled { get; set; } + + public string? DisplayName { get; set; } + + public string? Authority { get; set; } + + public string? ClientId { get; set; } + + public string? ClientSecret { get; set; } + + public string? Scopes { get; set; } + + public bool RequireHttpsMetadata { get; set; } = true; + + public bool RequireVerifiedEmail { get; set; } = true; + + public bool AutoProvision { get; set; } + + public string? RoleClaim { get; set; } + + public Dictionary RoleMappings { get; set; } = new(StringComparer.OrdinalIgnoreCase); + + public bool DisableLocalLogin { get; set; } + + public bool HasValidAuthority => + Uri.TryCreate(Authority?.Trim(), UriKind.Absolute, out var uri) + && (uri.Scheme == Uri.UriSchemeHttps || (uri.Scheme == Uri.UriSchemeHttp && !RequireHttpsMetadata)) + && string.IsNullOrEmpty(uri.UserInfo) + && string.IsNullOrEmpty(uri.Query) + && string.IsNullOrEmpty(uri.Fragment); + + public bool HasClientId => !string.IsNullOrWhiteSpace(ClientId); + + public bool IsActive => Enabled && HasValidAuthority && HasClientId; + + public bool IsMisconfigured => Enabled && !IsActive; + + public bool LocalLoginRestricted => IsActive && DisableLocalLogin; + + public string EffectiveDisplayName => string.IsNullOrWhiteSpace(DisplayName) ? "Single sign-on" : DisplayName.Trim(); + + public string? EffectiveRoleClaim => string.IsNullOrWhiteSpace(RoleClaim) ? null : RoleClaim.Trim(); + + public IReadOnlyList EffectiveScopes + { + get + { + var scopes = (string.IsNullOrWhiteSpace(Scopes) ? DefaultScopes : Scopes) + .Split([' ', ',', ';'], StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries) + .Distinct(StringComparer.Ordinal) + .ToList(); + + if (!scopes.Contains("openid", StringComparer.Ordinal)) + scopes.Insert(0, "openid"); + + return scopes; + } + } + + #endregion +} diff --git a/src/Presentation/Taskist.Web/Infrastructure/StartupDiagnostics.cs b/src/Presentation/Taskist.Web/Infrastructure/StartupDiagnostics.cs index e77ef0f..60835b6 100644 --- a/src/Presentation/Taskist.Web/Infrastructure/StartupDiagnostics.cs +++ b/src/Presentation/Taskist.Web/Infrastructure/StartupDiagnostics.cs @@ -33,4 +33,28 @@ public static void LogErrorTrackingStatus(this WebApplication app) else if (errorTracking.IsActive) logger.LogInformation("Error tracking is on: unhandled exceptions and errors are sent to Sentry (traces sample rate {Rate}).", errorTracking.EffectiveTracesSampleRate); } + + public static void LogSingleSignOnStatus(this WebApplication app) + { + var logger = app.Services.GetRequiredService().CreateLogger(nameof(StartupDiagnostics)); + var oidc = app.Services.GetRequiredService(); + + if (oidc.IsMisconfigured) + { + logger.LogWarning("Authentication:Oidc:Enabled is true but Authority or ClientId is missing or invalid, so single sign-on is off. Authority must be an https URL (http only with RequireHttpsMetadata false)."); + return; + } + + if (!oidc.IsActive) + return; + + logger.LogInformation("Single sign-on is on ({DisplayName}, {Authority}). Auto-provisioning: {AutoProvision}. Password sign-in limited to administrators: {Restricted}.", + oidc.EffectiveDisplayName, oidc.Authority, oidc.AutoProvision, oidc.LocalLoginRestricted); + + if (!oidc.RequireHttpsMetadata) + logger.LogWarning("Authentication:Oidc:RequireHttpsMetadata is false. Only use this for local testing; in production the identity provider must be reached over HTTPS."); + + if (!oidc.RequireVerifiedEmail) + logger.LogWarning("Authentication:Oidc:RequireVerifiedEmail is false, so an SSO sign-in can be linked to an existing Taskist account by e-mail even when the identity provider has not verified that address. Only use this with a provider whose e-mail addresses you control."); + } } diff --git a/src/Presentation/Taskist.Web/Models/Users/LinkedSignInModel.cs b/src/Presentation/Taskist.Web/Models/Users/LinkedSignInModel.cs new file mode 100644 index 0000000..c2a8c70 --- /dev/null +++ b/src/Presentation/Taskist.Web/Models/Users/LinkedSignInModel.cs @@ -0,0 +1,30 @@ +namespace Taskist.Web.Models.Users; + +public class LinkedSignInModel +{ + #region Properties + + public int Id { get; set; } + + public string ProviderName { get; set; } = string.Empty; + + public string? Email { get; set; } + + public DateTime CreatedOn { get; set; } + + public DateTime? LastUsedOn { get; set; } + + #endregion + + #region Methods + + public static string ProviderNameFrom(string? issuer) + { + if (string.IsNullOrWhiteSpace(issuer)) + return string.Empty; + + return Uri.TryCreate(issuer, UriKind.Absolute, out var uri) ? uri.Host : issuer; + } + + #endregion +} diff --git a/src/Presentation/Taskist.Web/Models/Users/LoginModel.cs b/src/Presentation/Taskist.Web/Models/Users/LoginModel.cs index afd868f..3a27876 100644 --- a/src/Presentation/Taskist.Web/Models/Users/LoginModel.cs +++ b/src/Presentation/Taskist.Web/Models/Users/LoginModel.cs @@ -12,4 +12,14 @@ public class LoginModel [Display(Name = "Remember Me")] public bool RememberMe { get; set; } = true; -} \ No newline at end of file + + public bool LocalLogin { get; set; } + + public bool SsoEnabled { get; set; } + + public string? SsoDisplayName { get; set; } + + public bool ShowPasswordForm { get; set; } = true; + + public string? SsoErrorCode { get; set; } +} diff --git a/src/Presentation/Taskist.Web/Models/Users/ProfileModel.cs b/src/Presentation/Taskist.Web/Models/Users/ProfileModel.cs index b23d97d..ec01585 100644 --- a/src/Presentation/Taskist.Web/Models/Users/ProfileModel.cs +++ b/src/Presentation/Taskist.Web/Models/Users/ProfileModel.cs @@ -41,6 +41,8 @@ public ProfileModel() public IList GitConnections { get; set; } = []; + public IList LinkedSignIns { get; set; } = []; + [Display(Name = "Gender")] public int? Gender { get; set; } diff --git a/src/Presentation/Taskist.Web/Models/Users/UserRegistrationModel.cs b/src/Presentation/Taskist.Web/Models/Users/UserRegistrationModel.cs index eb2b3d3..123e7d2 100644 --- a/src/Presentation/Taskist.Web/Models/Users/UserRegistrationModel.cs +++ b/src/Presentation/Taskist.Web/Models/Users/UserRegistrationModel.cs @@ -20,4 +20,6 @@ public UserRegistrationModel() public List AvailableLanguages { get; set; } public List AvailableRoles { get; set; } + + public IList LinkedSignIns { get; set; } = []; } diff --git a/src/Presentation/Taskist.Web/Program.cs b/src/Presentation/Taskist.Web/Program.cs index 43a9b9b..2f7f508 100644 --- a/src/Presentation/Taskist.Web/Program.cs +++ b/src/Presentation/Taskist.Web/Program.cs @@ -28,6 +28,7 @@ .AddAssetPipeline() .AddPresentation() .AddAppAuthentication() + .AddOidcSignIn(builder.Configuration) .AddProfiling() .AddBackgroundJobs(builder.Configuration, startServer: !builder.Environment.IsDevelopment()); @@ -37,6 +38,7 @@ app.LogSecurityWarnings(); app.LogErrorTrackingStatus(); +app.LogSingleSignOnStatus(); await GitStartup.UpgradeLegacySettingsAsync(app.Services); diff --git a/src/Presentation/Taskist.Web/Taskist.Web.csproj b/src/Presentation/Taskist.Web/Taskist.Web.csproj index 85ccd7f..92dd4d7 100644 --- a/src/Presentation/Taskist.Web/Taskist.Web.csproj +++ b/src/Presentation/Taskist.Web/Taskist.Web.csproj @@ -53,6 +53,7 @@ + diff --git a/src/Presentation/Taskist.Web/Views/Account/Login.cshtml b/src/Presentation/Taskist.Web/Views/Account/Login.cshtml index 05ab94d..470d40e 100644 --- a/src/Presentation/Taskist.Web/Views/Account/Login.cshtml +++ b/src/Presentation/Taskist.Web/Views/Account/Login.cshtml @@ -1,6 +1,14 @@ @model LoginModel @inject Taskist.Service.Masters.ISettingService SettingService @inject Taskist.Core.Configuration.IAppInfoProvider AppInfo +@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"] = "Login"; Layout = "~/Views/Shared/_LayoutLogin.cshtml"; @@ -58,7 +66,34 @@

Sign in to continue to Taskist.

+ @if (!string.IsNullOrEmpty(Model.SsoErrorCode)) + { + + } + + @if (Model.SsoEnabled) + { + + + @if (Model.ShowPasswordForm) + { + + } + } + + @if (!Model.ShowPasswordForm) + { + + + } + else + {
+
@@ -94,6 +129,7 @@ + }
diff --git a/src/Presentation/Taskist.Web/Views/Profile/Index.cshtml b/src/Presentation/Taskist.Web/Views/Profile/Index.cshtml index c631e79..dfb818b 100644 --- a/src/Presentation/Taskist.Web/Views/Profile/Index.cshtml +++ b/src/Presentation/Taskist.Web/Views/Profile/Index.cshtml @@ -150,6 +150,32 @@ + @if (Model.LinkedSignIns.Any()) + { +
+
@Localize("Profile.SignIns.Title").Text
+
@Localize("Profile.SignIns.Intro").Text
+ @foreach (var link in Model.LinkedSignIns) + { +
+
+ @link.ProviderName + @if (!string.IsNullOrEmpty(link.Email)) + { + · @link.Email + } +
+ @Localize("Profile.SignIns.LastUsed").Text: + @(link.LastUsedOn.HasValue ? link.LastUsedOn.Value.ToLocalTime().ToString("g") : Localize("Profile.SignIns.Never").Text) +
+
+ +
+ } +
+ }
diff --git a/src/Presentation/Taskist.Web/Views/User/Edit.cshtml b/src/Presentation/Taskist.Web/Views/User/Edit.cshtml index 10b2af1..b6f5325 100644 --- a/src/Presentation/Taskist.Web/Views/User/Edit.cshtml +++ b/src/Presentation/Taskist.Web/Views/User/Edit.cshtml @@ -15,6 +15,37 @@ +@if (Model.LinkedSignIns.Any()) +{ +
+
@Localize("Profile.SignIns.Title").Text
+
+
@Localize("UserPage.SignIns.Intro").Text
+ @foreach (var link in Model.LinkedSignIns) + { +
+
+ @link.ProviderName + @if (!string.IsNullOrEmpty(link.Email)) + { + · @link.Email + } +
+ @Localize("Profile.SignIns.LastUsed").Text: + @(link.LastUsedOn.HasValue ? link.LastUsedOn.Value.ToLocalTime().ToString("g") : Localize("Profile.SignIns.Never").Text) +
+
+ +
+ } +
+
+} + @section PageScripts { + } \ No newline at end of file diff --git a/src/Presentation/Taskist.Web/appsettings.json b/src/Presentation/Taskist.Web/appsettings.json index d3d21e4..d3c5caa 100644 --- a/src/Presentation/Taskist.Web/appsettings.json +++ b/src/Presentation/Taskist.Web/appsettings.json @@ -31,6 +31,22 @@ "TracesSampleRate": 0.0, "Debug": false }, + "Authentication": { + "Oidc": { + "Enabled": false, + "DisplayName": "", + "Authority": "", + "ClientId": "", + "ClientSecret": "", + "Scopes": "openid profile email", + "RequireHttpsMetadata": true, + "RequireVerifiedEmail": true, + "AutoProvision": false, + "RoleClaim": "", + "RoleMappings": {}, + "DisableLocalLogin": false + } + }, "Security": { "RequireHttpsCookies": true, "ForwardedHeaders": { diff --git a/src/Presentation/Taskist.Web/wwwroot/css/pages/login.css b/src/Presentation/Taskist.Web/wwwroot/css/pages/login.css index 2da5abe..2b76b12 100644 --- a/src/Presentation/Taskist.Web/wwwroot/css/pages/login.css +++ b/src/Presentation/Taskist.Web/wwwroot/css/pages/login.css @@ -327,6 +327,51 @@ color: #9aa6b8; } +/* Single sign-on button, "or" divider and the administrator sign-in link */ +.login-sso { + margin-bottom: 4px; +} + +.login-sso-button { + width: 100%; + height: 42px; + font-weight: 600; +} + +.login-divider { + display: flex; + align-items: center; + gap: 12px; + margin: 18px 0; + font-size: 0.8rem; + color: #9aa6b8; + text-transform: uppercase; + letter-spacing: 0.04em; +} + +.login-divider::before, +.login-divider::after { + content: ""; + flex: 1; + border-top: 1px solid #dfe5ec; +} + +.login-local-link { + margin: 18px 0 0; + text-align: center; + font-size: 0.85rem; +} + +.login-local-link a { + color: #6c757d; + text-decoration: none; +} + +.login-local-link a:hover { + color: #0e7c93; + text-decoration: underline; +} + /* Responsive: single column, brand panel hidden (handled by d-none/d-lg-flex) */ @media (max-width: 991.98px) { .login-card { diff --git a/src/Presentation/Taskist.Web/wwwroot/js/pages/profile.js b/src/Presentation/Taskist.Web/wwwroot/js/pages/profile.js index c8897bb..eb25331 100644 --- a/src/Presentation/Taskist.Web/wwwroot/js/pages/profile.js +++ b/src/Presentation/Taskist.Web/wwwroot/js/pages/profile.js @@ -229,6 +229,36 @@ function profileSaved(response) { })(); +/* Linked single sign-on accounts (Security section): unlink one after confirmation, then reload on #security. */ +(function () { + "use strict"; + + $(document).on("click", ".js-unlink-signin", function () { + var $btn = $(this); + var $root = $("#linkedSignIns"); + + JSManager.confirm($root.data("unlink-confirm"), function () { + $btn.prop("disabled", true); + $.ajax({ + type: "POST", + url: $root.data("unlink-url"), + data: JSManager.addAntiForgeryToken({ id: $btn.data("id") }), + success: function (r) { + if (r && r.status === 2000) { + JSManager.showSuccess(r.message); + setTimeout(function () { window.location.hash = "security"; window.location.reload(); }, 700); + } else { + JSManager.showSwal((r && r.message) || "Could not unlink this sign-in.", "error"); + } + }, + error: function (xhr) { JSManager.showSwal("Request failed (" + xhr.status + ").", "error"); }, + complete: function () { $btn.prop("disabled", false); } + }); + }); + }); +})(); + + /* Settings-style sections: the left list shows one section at a time, addressed by the URL hash (#details, #appearance, #security, #git) so Back works and other pages can deep-link. Links are handled here because the layout's would otherwise resolve "#x" against the site root. Hidden sections keep diff --git a/src/Presentation/Taskist.Web/wwwroot/js/pages/user-signins.js b/src/Presentation/Taskist.Web/wwwroot/js/pages/user-signins.js new file mode 100644 index 0000000..1dac75d --- /dev/null +++ b/src/Presentation/Taskist.Web/wwwroot/js/pages/user-signins.js @@ -0,0 +1,29 @@ +/* User edit page: an administrator removes a user's linked single sign-on account. The user can sign in with + single sign-on again afterwards; if their e-mail still matches, the account is linked again. */ +(function () { + "use strict"; + + $(document).on("click", ".js-remove-signin", function () { + var $btn = $(this); + var $root = $("#userSignIns"); + + JSManager.confirm($root.data("remove-confirm"), function () { + $btn.prop("disabled", true); + $.ajax({ + type: "POST", + url: $root.data("remove-url"), + data: JSManager.addAntiForgeryToken({ userId: $root.data("user-id"), id: $btn.data("id") }), + success: function (r) { + if (r && r.status === 2000) { + JSManager.showSuccess(r.message); + setTimeout(function () { window.location.reload(); }, 700); + } else { + JSManager.showSwal((r && r.message) || "Could not remove this sign-in.", "error"); + } + }, + error: function (xhr) { JSManager.showSwal("Request failed (" + xhr.status + ").", "error"); }, + complete: function () { $btn.prop("disabled", false); } + }); + }); + }); +})(); diff --git a/src/Tests/Taskist.Tests/Sso/ExternalIdentityReaderTests.cs b/src/Tests/Taskist.Tests/Sso/ExternalIdentityReaderTests.cs new file mode 100644 index 0000000..b5b6754 --- /dev/null +++ b/src/Tests/Taskist.Tests/Sso/ExternalIdentityReaderTests.cs @@ -0,0 +1,106 @@ +using System.Security.Claims; +using Taskist.Web.Helpers.Sso; + +namespace Taskist.Tests.Sso; + +public class ExternalIdentityReaderTests +{ + #region Fields + + private const string Issuer = "https://id.example.com/realms/acme"; + + #endregion + + #region Tests + + [Fact] + public void Read_MapsStandardClaims() + { + var identity = ExternalIdentityReader.Read( + [ + new Claim("iss", Issuer + "/"), + new Claim("sub", " 1234 "), + new Claim("email", "ana@example.com"), + new Claim("email_verified", "true"), + new Claim("given_name", "Ana"), + new Claim("family_name", "Silva"), + new Claim("name", "Ana Silva") + ], roleClaim: null); + + Assert.Equal(Issuer, identity.Issuer); + Assert.Equal("1234", identity.Subject); + Assert.Equal("ana@example.com", identity.Email); + Assert.True(identity.EmailVerified); + Assert.Equal("Ana", identity.GivenName); + Assert.Equal("Silva", identity.FamilyName); + Assert.Equal("Ana Silva", identity.Name); + Assert.Empty(identity.Groups); + } + + [Fact] + public void Read_UsesClaimIssuer_WhenIssClaimIsMissing() + { + var identity = ExternalIdentityReader.Read([new Claim("sub", "1", ClaimValueTypes.String, Issuer)], null); + + Assert.Equal(Issuer, identity.Issuer); + } + + [Theory] + [InlineData("true", true)] + [InlineData("True", true)] + [InlineData("1", true)] + [InlineData("false", false)] + [InlineData("0", false)] + [InlineData("yes", false)] + [InlineData("", false)] + public void Read_ParsesEmailVerified(string value, bool expected) + { + var identity = ExternalIdentityReader.Read([new Claim("sub", "1"), new Claim("email_verified", value)], null); + + Assert.Equal(expected, identity.EmailVerified); + } + + [Fact] + public void Read_MissingEmailVerified_IsNotVerified() + { + var identity = ExternalIdentityReader.Read([new Claim("sub", "1"), new Claim("email", "ana@example.com")], null); + + Assert.False(identity.EmailVerified); + } + + [Fact] + public void Read_CollectsGroups_FromConfiguredClaim_Distinct() + { + var identity = ExternalIdentityReader.Read( + [ + new Claim("sub", "1"), + new Claim("groups", "taskist-leads"), + new Claim("groups", "TASKIST-LEADS"), + new Claim("groups", " devs "), + new Claim("groups", ""), + new Claim("roles", "ignored") + ], "groups"); + + Assert.Equal(["taskist-leads", "devs"], identity.Groups); + } + + [Fact] + public void Read_NoGroups_WhenRoleClaimIsNotConfigured() + { + var identity = ExternalIdentityReader.Read([new Claim("sub", "1"), new Claim("groups", "devs")], null); + + Assert.Empty(identity.Groups); + } + + [Fact] + public void Read_EmptyClaims_GivesEmptyIdentity() + { + var identity = ExternalIdentityReader.Read([], null); + + Assert.Equal(string.Empty, identity.Subject); + Assert.Equal(string.Empty, identity.Issuer); + Assert.Null(identity.Email); + } + + #endregion +} diff --git a/src/Tests/Taskist.Tests/Sso/ExternalNameSplitterTests.cs b/src/Tests/Taskist.Tests/Sso/ExternalNameSplitterTests.cs new file mode 100644 index 0000000..23d1aa5 --- /dev/null +++ b/src/Tests/Taskist.Tests/Sso/ExternalNameSplitterTests.cs @@ -0,0 +1,75 @@ +using Taskist.Web.Helpers.Sso; +using Taskist.Web.Models.Users; + +namespace Taskist.Tests.Sso; + +public class ExternalNameSplitterTests +{ + #region Tests + + [Fact] + public void UsesGivenAndFamilyName() + { + var (first, last) = ExternalNameSplitter.Split(new ExternalIdentity { GivenName = " Ana ", FamilyName = "Silva", Name = "Someone Else" }); + + Assert.Equal("Ana", first); + Assert.Equal("Silva", last); + } + + [Fact] + public void SplitsFullName_WhenGivenNameIsMissing() + { + var (first, last) = ExternalNameSplitter.Split(new ExternalIdentity { Name = "Ana Maria Silva" }); + + Assert.Equal("Ana", first); + Assert.Equal("Maria Silva", last); + } + + [Fact] + public void FallsBackToEmailLocalPart() + { + var (first, last) = ExternalNameSplitter.Split(new ExternalIdentity { Email = "ana.silva@example.com" }); + + Assert.Equal("ana.silva", first); + Assert.Equal(string.Empty, last); + } + + [Fact] + public void FallsBackToUser_WhenNothingIsKnown() + { + var (first, _) = ExternalNameSplitter.Split(new ExternalIdentity()); + + Assert.Equal("User", first); + } + + [Fact] + public void TruncatesToColumnLength() + { + var (first, last) = ExternalNameSplitter.Split(new ExternalIdentity { GivenName = new string('a', 80), FamilyName = new string('b', 80) }); + + Assert.Equal(ExternalNameSplitter.MaxLength, first.Length); + Assert.Equal(ExternalNameSplitter.MaxLength, last.Length); + } + + [Theory] + [InlineData("https://id.example.com/realms/acme", "id.example.com")] + [InlineData("not-a-url", "not-a-url")] + [InlineData("", "")] + public void ProviderName_IsTheIssuerHost(string issuer, string expected) + { + Assert.Equal(expected, LinkedSignInModel.ProviderNameFrom(issuer)); + } + + [Theory] + [InlineData("NotProvisioned", "NotProvisioned")] + [InlineData(" Failed ", "Failed")] + [InlineData("