| | | 1 | | using System.Linq.Expressions; |
| | | 2 | | using System.Runtime.CompilerServices; |
| | | 3 | | using ArturRios.Data.Relational.Core.Repositories; |
| | | 4 | | using ArturRios.Heimdall.Data.Configuration; |
| | | 5 | | using ArturRios.Heimdall.Domain.Entities; |
| | | 6 | | using ArturRios.Heimdall.Domain.Enums; |
| | | 7 | | using ArturRios.Heimdall.Domain.Persistence; |
| | | 8 | | using Microsoft.EntityFrameworkCore; |
| | | 9 | | using Microsoft.EntityFrameworkCore.Query; |
| | | 10 | | |
| | | 11 | | namespace ArturRios.Heimdall.Data.Persistence; |
| | | 12 | | |
| | | 13 | | /// <summary> |
| | | 14 | | /// <see cref="IAtomicWrites" /> on EF Core's <c>ExecuteUpdate</c>: each method is a single |
| | | 15 | | /// <c>UPDATE … WHERE</c> whose condition is the rule being enforced, and whose affected-row count |
| | | 16 | | /// says whether this caller won. |
| | | 17 | | /// </summary> |
| | | 18 | | /// <remarks> |
| | | 19 | | /// <para> |
| | | 20 | | /// PostgreSQL makes the condition and the write one step: under READ COMMITTED, an |
| | | 21 | | /// <c>UPDATE</c> that waits on another transaction's lock re-evaluates its <c>WHERE</c> |
| | | 22 | | /// against the row as that transaction left it. So two requests spending the same code both |
| | | 23 | | /// reach the row, one writes, and the other finds "unused" no longer true and writes nothing. |
| | | 24 | | /// No row version is needed, and no table changes shape for it. |
| | | 25 | | /// </para> |
| | | 26 | | /// <para> |
| | | 27 | | /// <c>ExecuteUpdate</c> bypasses the change tracker, which would leave the caller's tracked |
| | | 28 | | /// instance stale — and a later save would write the stale values back over the atomic ones. |
| | | 29 | | /// <see cref="Accept{T,TProperty}" /> sets the instance's current and original values to what |
| | | 30 | | /// was written, so the tracker sees nothing to save. |
| | | 31 | | /// </para> |
| | | 32 | | /// </remarks> |
| | 822 | 33 | | public sealed class AtomicWrites(AppDbContext context) : IAtomicWrites |
| | | 34 | | { |
| | | 35 | | public async Task<bool> TryReserveLoginAttemptAsync( |
| | | 36 | | Person person, int maxAttempts, DateTime now, DateTime lockedOutUntil) |
| | | 37 | | { |
| | | 38 | | // One statement, so the attempt that reaches the limit is also the one that locks: every |
| | | 39 | | // right-hand side reads the row as it was before the update. A request that dies after this |
| | | 40 | | // returns — shed by the hash gate, or cut off by a database fault — has still left a lock that |
| | | 41 | | // expires, and not a counter at the limit that nothing could ever reset. A row already at or |
| | | 42 | | // past the limit with no lockout date (left by an older instance, or by a lowered limit) is |
| | | 43 | | // admitted too: the same >= test locks it and resets the counter, so it heals itself. |
| | 102 | 44 | | var reserved = await context.Persons |
| | 102 | 45 | | .Where(x => x.Id == person.Id && |
| | 102 | 46 | | ((x.FailedLoginAttempts < maxAttempts && |
| | 102 | 47 | | (x.LockedOutUntil == null || x.LockedOutUntil <= now)) || |
| | 102 | 48 | | (x.FailedLoginAttempts >= maxAttempts && x.LockedOutUntil == null))) |
| | 204 | 49 | | .ExecuteUpdateAsync(set => set |
| | 204 | 50 | | .SetProperty(x => x.LockedOutUntil, |
| | 204 | 51 | | x => x.FailedLoginAttempts + 1 >= maxAttempts ? lockedOutUntil : x.LockedOutUntil) |
| | 204 | 52 | | .SetProperty(x => x.FailedLoginAttempts, |
| | 204 | 53 | | x => x.FailedLoginAttempts + 1 >= maxAttempts ? 0 : x.FailedLoginAttempts + 1)) == 1; |
| | | 54 | | |
| | 102 | 55 | | if (reserved) |
| | | 56 | | { |
| | 101 | 57 | | var reachedLimit = person.FailedLoginAttempts + 1 >= maxAttempts; |
| | | 58 | | |
| | 101 | 59 | | if (reachedLimit) |
| | | 60 | | { |
| | 4 | 61 | | Accept(person, x => x.LockedOutUntil, lockedOutUntil); |
| | | 62 | | } |
| | | 63 | | |
| | 101 | 64 | | Accept(person, x => x.FailedLoginAttempts, reachedLimit ? 0 : person.FailedLoginAttempts + 1); |
| | | 65 | | } |
| | | 66 | | |
| | 102 | 67 | | return reserved; |
| | 102 | 68 | | } |
| | | 69 | | |
| | | 70 | | public async Task<bool> TryChargePendingRegistrationGuessAsync(PendingRegistration pending, int maxGuesses) |
| | | 71 | | { |
| | 18 | 72 | | var charged = await context.PendingRegistrations |
| | 18 | 73 | | .Where(x => x.Id == pending.Id && x.FailedAttempts < maxGuesses) |
| | 36 | 74 | | .ExecuteUpdateAsync(set => set.SetProperty(x => x.FailedAttempts, x => x.FailedAttempts + 1)) == 1; |
| | | 75 | | |
| | 18 | 76 | | if (charged) |
| | | 77 | | { |
| | 15 | 78 | | Accept(pending, x => x.FailedAttempts, pending.FailedAttempts + 1); |
| | | 79 | | } |
| | | 80 | | |
| | 18 | 81 | | return charged; |
| | 18 | 82 | | } |
| | | 83 | | |
| | | 84 | | public async Task ClearLoginAttemptsAsync(Person person) |
| | | 85 | | { |
| | 81 | 86 | | await context.Persons |
| | 81 | 87 | | .Where(x => x.Id == person.Id) |
| | 162 | 88 | | .ExecuteUpdateAsync(set => set |
| | 162 | 89 | | .SetProperty(x => x.FailedLoginAttempts, 0) |
| | 162 | 90 | | .SetProperty(x => x.LockedOutUntil, (DateTime?)null)); |
| | | 91 | | |
| | 81 | 92 | | Accept(person, x => x.FailedLoginAttempts, 0); |
| | 81 | 93 | | Accept(person, x => x.LockedOutUntil, null); |
| | 81 | 94 | | } |
| | | 95 | | |
| | | 96 | | public async Task<bool> TryReserveSecondFactorAttemptAsync( |
| | | 97 | | Person person, int maxAttempts, DateTime now, IReadOnlyList<DateTime> lockedOutUntil) |
| | | 98 | | { |
| | 54 | 99 | | ArgumentOutOfRangeException.ThrowIfZero(lockedOutUntil.Count, nameof(lockedOutUntil)); |
| | | 100 | | |
| | | 101 | | // The login reservation's shape, for the same reasons: the reservation that reaches the limit |
| | | 102 | | // is the one that locks, and a row at or past the limit with no live lock — none at all, or |
| | | 103 | | // one that has run out, as a lowered limit would leave — is admitted and locked, so it heals |
| | | 104 | | // itself rather than being refused for good. What differs |
| | | 105 | | // is the lock's length, which depends on how many locks came before — so it is chosen by the |
| | | 106 | | // stored lockout count, inside the same statement, rather than from the count this request |
| | | 107 | | // read: two requests that both read "one lock so far" cannot both set the second lock's end. |
| | 54 | 108 | | var reserved = await context.Persons |
| | 54 | 109 | | .Where(x => x.Id == person.Id && |
| | 54 | 110 | | ((x.FailedSecondFactorAttempts < maxAttempts && |
| | 54 | 111 | | (x.SecondFactorLockedOutUntil == null || x.SecondFactorLockedOutUntil <= now)) || |
| | 54 | 112 | | (x.FailedSecondFactorAttempts >= maxAttempts && |
| | 54 | 113 | | (x.SecondFactorLockedOutUntil == null || x.SecondFactorLockedOutUntil <= now)))) |
| | 108 | 114 | | .ExecuteUpdateAsync(set => set |
| | 108 | 115 | | .SetProperty(x => x.SecondFactorLockedOutUntil, SecondFactorLockEnd(maxAttempts, lockedOutUntil)) |
| | 108 | 116 | | .SetProperty(x => x.SecondFactorLockouts, |
| | 108 | 117 | | x => x.FailedSecondFactorAttempts + 1 >= maxAttempts |
| | 108 | 118 | | ? x.SecondFactorLockouts + 1 |
| | 108 | 119 | | : x.SecondFactorLockouts) |
| | 108 | 120 | | .SetProperty(x => x.FailedSecondFactorAttempts, |
| | 108 | 121 | | x => x.FailedSecondFactorAttempts + 1 >= maxAttempts ? 0 : x.FailedSecondFactorAttempts + 1)) == 1; |
| | | 122 | | |
| | 54 | 123 | | if (reserved) |
| | | 124 | | { |
| | 49 | 125 | | var reachedLimit = person.FailedSecondFactorAttempts + 1 >= maxAttempts; |
| | | 126 | | |
| | 49 | 127 | | if (reachedLimit) |
| | | 128 | | { |
| | 4 | 129 | | Accept(person, x => x.SecondFactorLockedOutUntil, LockEndAfter(person.SecondFactorLockouts, lockedOutUnt |
| | 4 | 130 | | Accept(person, x => x.SecondFactorLockouts, person.SecondFactorLockouts + 1); |
| | | 131 | | } |
| | | 132 | | |
| | 49 | 133 | | Accept(person, x => x.FailedSecondFactorAttempts, reachedLimit ? 0 : person.FailedSecondFactorAttempts + 1); |
| | | 134 | | } |
| | | 135 | | else |
| | | 136 | | { |
| | 5 | 137 | | await TouchAsync(person); |
| | | 138 | | } |
| | | 139 | | |
| | 54 | 140 | | return reserved; |
| | 54 | 141 | | } |
| | | 142 | | |
| | | 143 | | public async Task ClearSecondFactorAttemptsAsync(Person person) |
| | | 144 | | { |
| | 24 | 145 | | await context.Persons |
| | 24 | 146 | | .Where(x => x.Id == person.Id) |
| | 48 | 147 | | .ExecuteUpdateAsync(set => set |
| | 48 | 148 | | .SetProperty(x => x.FailedSecondFactorAttempts, 0) |
| | 48 | 149 | | .SetProperty(x => x.SecondFactorLockedOutUntil, (DateTime?)null) |
| | 48 | 150 | | .SetProperty(x => x.SecondFactorLockouts, 0)); |
| | | 151 | | |
| | 24 | 152 | | Accept(person, x => x.FailedSecondFactorAttempts, 0); |
| | 24 | 153 | | Accept(person, x => x.SecondFactorLockedOutUntil, null); |
| | 24 | 154 | | Accept(person, x => x.SecondFactorLockouts, 0); |
| | 24 | 155 | | } |
| | | 156 | | |
| | | 157 | | public async Task<bool> TryReserveReauthenticationAsync( |
| | | 158 | | Person person, int maxFailures, DateTime now, DateTime windowStartedBy, DateTime pausedUntil) |
| | | 159 | | { |
| | | 160 | | // One statement, every right-hand side reading the row as it was. The window is open when it |
| | | 161 | | // started after windowStartedBy (a NULL start is no window, and compares false); the failure |
| | | 162 | | // counted here is then the window's next, or else the first of a new window. The failure that |
| | | 163 | | // reaches the limit pauses and closes the window in the same write, as the login reservation |
| | | 164 | | // locks, so a burst cannot each read "below the limit" and pass it together. |
| | 114 | 165 | | var reserved = await context.Persons |
| | 114 | 166 | | .Where(x => x.Id == person.Id && |
| | 114 | 167 | | (x.ReauthenticationPausedUntil == null || x.ReauthenticationPausedUntil <= now)) |
| | 228 | 168 | | .ExecuteUpdateAsync(set => set |
| | 228 | 169 | | .SetProperty(x => x.ReauthenticationPausedUntil, |
| | 228 | 170 | | x => (x.ReauthenticationWindowStartedAt > windowStartedBy |
| | 228 | 171 | | ? x.FailedReauthenticationAttempts + 1 |
| | 228 | 172 | | : 1) >= maxFailures |
| | 228 | 173 | | ? (DateTime?)pausedUntil |
| | 228 | 174 | | : x.ReauthenticationPausedUntil) |
| | 228 | 175 | | .SetProperty(x => x.ReauthenticationWindowStartedAt, |
| | 228 | 176 | | x => (x.ReauthenticationWindowStartedAt > windowStartedBy |
| | 228 | 177 | | ? x.FailedReauthenticationAttempts + 1 |
| | 228 | 178 | | : 1) >= maxFailures |
| | 228 | 179 | | ? null |
| | 228 | 180 | | : x.ReauthenticationWindowStartedAt > windowStartedBy |
| | 228 | 181 | | ? x.ReauthenticationWindowStartedAt |
| | 228 | 182 | | : (DateTime?)now) |
| | 228 | 183 | | .SetProperty(x => x.FailedReauthenticationAttempts, |
| | 228 | 184 | | x => (x.ReauthenticationWindowStartedAt > windowStartedBy |
| | 228 | 185 | | ? x.FailedReauthenticationAttempts + 1 |
| | 228 | 186 | | : 1) >= maxFailures |
| | 228 | 187 | | ? 0 |
| | 228 | 188 | | : x.ReauthenticationWindowStartedAt > windowStartedBy |
| | 228 | 189 | | ? x.FailedReauthenticationAttempts + 1 |
| | 228 | 190 | | : 1)) == 1; |
| | | 191 | | |
| | 114 | 192 | | if (reserved) |
| | | 193 | | { |
| | 99 | 194 | | var windowOpen = person.ReauthenticationWindowStartedAt > windowStartedBy; |
| | 99 | 195 | | var failures = windowOpen ? person.FailedReauthenticationAttempts + 1 : 1; |
| | 99 | 196 | | var paused = failures >= maxFailures; |
| | | 197 | | |
| | 99 | 198 | | if (paused) |
| | | 199 | | { |
| | 3 | 200 | | Accept(person, x => x.ReauthenticationPausedUntil, pausedUntil); |
| | | 201 | | } |
| | | 202 | | |
| | 99 | 203 | | Accept(person, x => x.ReauthenticationWindowStartedAt, |
| | 99 | 204 | | paused ? null : windowOpen ? person.ReauthenticationWindowStartedAt : now); |
| | 99 | 205 | | Accept(person, x => x.FailedReauthenticationAttempts, paused ? 0 : failures); |
| | | 206 | | } |
| | | 207 | | else |
| | | 208 | | { |
| | 15 | 209 | | await TouchAsync(person); |
| | | 210 | | } |
| | | 211 | | |
| | 114 | 212 | | return reserved; |
| | 114 | 213 | | } |
| | | 214 | | |
| | | 215 | | public async Task<AccountEmailReservation> TryReserveAccountEmailAsync( |
| | | 216 | | Person person, int maxPerWindow, DateTime now, DateTime lastSentBefore, DateTime windowEndsAt) |
| | | 217 | | { |
| | | 218 | | // One statement, every right-hand side reading the row as it was. Admitted only out of the |
| | | 219 | | // cooldown and under the window's count; an ended (or never opened) window starts again at |
| | | 220 | | // this send. Concurrent reservations queue on the row lock and re-read it, so a burst gets |
| | | 221 | | // exactly what is left — one inside a cooldown, at most the cap with none. |
| | 55 | 222 | | var reserved = await context.Persons |
| | 55 | 223 | | .Where(x => x.Id == person.Id && |
| | 55 | 224 | | (x.AccountEmailLastSentAt == null || x.AccountEmailLastSentAt <= lastSentBefore) && |
| | 55 | 225 | | (x.AccountEmailWindowEndsAt == null || x.AccountEmailWindowEndsAt <= now || |
| | 55 | 226 | | x.AccountEmailsSent < maxPerWindow)) |
| | 110 | 227 | | .ExecuteUpdateAsync(set => set |
| | 110 | 228 | | .SetProperty(x => x.AccountEmailsSent, |
| | 110 | 229 | | x => x.AccountEmailWindowEndsAt == null || x.AccountEmailWindowEndsAt <= now |
| | 110 | 230 | | ? 1 |
| | 110 | 231 | | : x.AccountEmailsSent + 1) |
| | 110 | 232 | | .SetProperty(x => x.AccountEmailWindowEndsAt, |
| | 110 | 233 | | x => x.AccountEmailWindowEndsAt == null || x.AccountEmailWindowEndsAt <= now |
| | 110 | 234 | | ? (DateTime?)windowEndsAt |
| | 110 | 235 | | : x.AccountEmailWindowEndsAt) |
| | 110 | 236 | | .SetProperty(x => x.AccountEmailLastSentAt, (DateTime?)now)) == 1; |
| | | 237 | | |
| | 55 | 238 | | if (reserved) |
| | | 239 | | { |
| | 26 | 240 | | var windowOpen = person.AccountEmailWindowEndsAt > now; |
| | | 241 | | |
| | 26 | 242 | | Accept(person, x => x.AccountEmailsSent, windowOpen ? person.AccountEmailsSent + 1 : 1); |
| | 26 | 243 | | Accept(person, x => x.AccountEmailWindowEndsAt, windowOpen ? person.AccountEmailWindowEndsAt : windowEndsAt) |
| | 26 | 244 | | Accept(person, x => x.AccountEmailLastSentAt, now); |
| | | 245 | | |
| | 26 | 246 | | return AccountEmailReservation.Reserved; |
| | | 247 | | } |
| | | 248 | | |
| | | 249 | | // Refused: read the row as it now is, to say which bound refused it and when it ends, and bring |
| | | 250 | | // the instance in line with it. The daily one is the more useful answer when both apply, since |
| | | 251 | | // waiting out the cooldown would not help. A row gone since it was loaded (a hard delete in |
| | | 252 | | // between) is refused too: nothing may be sent to a person who no longer exists. |
| | 29 | 253 | | var stored = await context.Persons |
| | 29 | 254 | | .AsNoTracking() |
| | 29 | 255 | | .Where(x => x.Id == person.Id) |
| | 29 | 256 | | .Select(x => new { x.AccountEmailsSent, x.AccountEmailWindowEndsAt, x.AccountEmailLastSentAt }) |
| | 29 | 257 | | .SingleOrDefaultAsync(); |
| | | 258 | | |
| | 29 | 259 | | if (stored is null) |
| | | 260 | | { |
| | 1 | 261 | | return AccountEmailReservation.CoolingDown; |
| | | 262 | | } |
| | | 263 | | |
| | 28 | 264 | | Accept(person, x => x.AccountEmailsSent, stored.AccountEmailsSent); |
| | 28 | 265 | | Accept(person, x => x.AccountEmailWindowEndsAt, stored.AccountEmailWindowEndsAt); |
| | 28 | 266 | | Accept(person, x => x.AccountEmailLastSentAt, stored.AccountEmailLastSentAt); |
| | | 267 | | |
| | 28 | 268 | | return stored.AccountEmailWindowEndsAt > now && stored.AccountEmailsSent >= maxPerWindow |
| | 28 | 269 | | ? AccountEmailReservation.DailyLimitReached |
| | 28 | 270 | | : AccountEmailReservation.CoolingDown; |
| | 55 | 271 | | } |
| | | 272 | | |
| | | 273 | | public async Task ClearReauthenticationAttemptsAsync(Person person) |
| | | 274 | | { |
| | 57 | 275 | | await context.Persons |
| | 57 | 276 | | .Where(x => x.Id == person.Id) |
| | 114 | 277 | | .ExecuteUpdateAsync(set => set |
| | 114 | 278 | | .SetProperty(x => x.FailedReauthenticationAttempts, 0) |
| | 114 | 279 | | .SetProperty(x => x.ReauthenticationWindowStartedAt, (DateTime?)null) |
| | 114 | 280 | | .SetProperty(x => x.ReauthenticationPausedUntil, (DateTime?)null)); |
| | | 281 | | |
| | 57 | 282 | | Accept(person, x => x.FailedReauthenticationAttempts, 0); |
| | 57 | 283 | | Accept(person, x => x.ReauthenticationWindowStartedAt, null); |
| | 57 | 284 | | Accept(person, x => x.ReauthenticationPausedUntil, null); |
| | 57 | 285 | | } |
| | | 286 | | |
| | | 287 | | public async Task StartChallengeAsync(TwoFactorAuth configuration, Guid challengeId) |
| | | 288 | | { |
| | 28 | 289 | | await context.TwoFactorAuths |
| | 28 | 290 | | .Where(x => x.Id == configuration.Id) |
| | 56 | 291 | | .ExecuteUpdateAsync(set => set |
| | 56 | 292 | | .SetProperty(x => x.ChallengeId, challengeId) |
| | 56 | 293 | | .SetProperty(x => x.EmailCodeReissueCount, 0) |
| | 56 | 294 | | .SetProperty(x => x.ChallengeAttempts, 0)); |
| | | 295 | | |
| | 28 | 296 | | Accept(configuration, x => x.ChallengeId, challengeId); |
| | 28 | 297 | | Accept(configuration, x => x.EmailCodeReissueCount, 0); |
| | 28 | 298 | | Accept(configuration, x => x.ChallengeAttempts, 0); |
| | 28 | 299 | | } |
| | | 300 | | |
| | | 301 | | public async Task<bool> TryChargeChallengeGuessAsync(TwoFactorAuth configuration, Guid challengeId, int maxGuesses) |
| | | 302 | | { |
| | 39 | 303 | | var charged = await context.TwoFactorAuths |
| | 39 | 304 | | .Where(x => x.Id == configuration.Id && x.ChallengeId == challengeId && x.ChallengeAttempts < maxGuesses) |
| | 78 | 305 | | .ExecuteUpdateAsync(set => set.SetProperty(x => x.ChallengeAttempts, x => x.ChallengeAttempts + 1)) == 1; |
| | | 306 | | |
| | 39 | 307 | | if (charged) |
| | | 308 | | { |
| | 39 | 309 | | Accept(configuration, x => x.ChallengeAttempts, configuration.ChallengeAttempts + 1); |
| | | 310 | | } |
| | | 311 | | |
| | 39 | 312 | | return charged; |
| | 39 | 313 | | } |
| | | 314 | | |
| | | 315 | | public async Task ExpireChallengeIfExhaustedAsync(TwoFactorAuth configuration, Guid challengeId, int maxGuesses) |
| | | 316 | | { |
| | 19 | 317 | | var expired = await context.TwoFactorAuths |
| | 19 | 318 | | .Where(x => x.Id == configuration.Id && x.ChallengeId == challengeId && x.ChallengeAttempts >= maxGuesses) |
| | 38 | 319 | | .ExecuteUpdateAsync(set => set.SetProperty(x => x.ChallengeId, (Guid?)null)) == 1; |
| | | 320 | | |
| | 19 | 321 | | if (expired) |
| | | 322 | | { |
| | 2 | 323 | | Accept(configuration, x => x.ChallengeId, null); |
| | | 324 | | } |
| | 19 | 325 | | } |
| | | 326 | | |
| | | 327 | | public async Task<bool> TryRedeemChallengeAsync(TwoFactorAuth configuration, Guid challengeId) |
| | | 328 | | { |
| | 24 | 329 | | var redeemed = await context.TwoFactorAuths |
| | 24 | 330 | | .Where(x => x.Id == configuration.Id && x.ChallengeId == challengeId) |
| | 48 | 331 | | .ExecuteUpdateAsync(set => set.SetProperty(x => x.ChallengeId, (Guid?)null)) == 1; |
| | | 332 | | |
| | 24 | 333 | | if (redeemed) |
| | | 334 | | { |
| | 20 | 335 | | Accept(configuration, x => x.ChallengeId, null); |
| | | 336 | | } |
| | | 337 | | |
| | 24 | 338 | | return redeemed; |
| | 24 | 339 | | } |
| | | 340 | | |
| | | 341 | | public async Task<bool> TryChargeEmailCodeReissueAsync(TwoFactorAuth configuration, Guid challengeId, int maxReissue |
| | | 342 | | { |
| | 21 | 343 | | var charged = await context.TwoFactorAuths |
| | 21 | 344 | | .Where(x => x.Id == configuration.Id && x.ChallengeId == challengeId && x.EmailCodeReissueCount < maxReissue |
| | 42 | 345 | | .ExecuteUpdateAsync(set => set.SetProperty(x => x.EmailCodeReissueCount, x => x.EmailCodeReissueCount + 1)) |
| | | 346 | | |
| | 21 | 347 | | if (charged) |
| | | 348 | | { |
| | 16 | 349 | | Accept(configuration, x => x.EmailCodeReissueCount, configuration.EmailCodeReissueCount + 1); |
| | | 350 | | } |
| | | 351 | | |
| | 21 | 352 | | return charged; |
| | 21 | 353 | | } |
| | | 354 | | |
| | | 355 | | public async Task<bool> TryAdvanceTotpStepAsync(TwoFactorAuth configuration, long timeStep, DateTime now) |
| | | 356 | | { |
| | 22 | 357 | | var advanced = await context.TwoFactorAuths |
| | 22 | 358 | | .Where(x => x.Id == configuration.Id && |
| | 22 | 359 | | (x.LastTotpTimeStepUsed == null || x.LastTotpTimeStepUsed < timeStep)) |
| | 44 | 360 | | .ExecuteUpdateAsync(set => set |
| | 44 | 361 | | .SetProperty(x => x.LastTotpTimeStepUsed, timeStep) |
| | 44 | 362 | | .SetProperty(x => x.UpdatedAt, now)) == 1; |
| | | 363 | | |
| | 22 | 364 | | if (advanced) |
| | | 365 | | { |
| | 14 | 366 | | Accept(configuration, x => x.LastTotpTimeStepUsed, timeStep); |
| | 14 | 367 | | Accept(configuration, x => x.UpdatedAt, now); |
| | | 368 | | } |
| | | 369 | | |
| | 22 | 370 | | return advanced; |
| | 22 | 371 | | } |
| | | 372 | | |
| | | 373 | | public async Task<bool> TryChargeEmailCodeGuessAsync(TwoFactorEmailCode code, int maxGuesses, DateTime now) |
| | | 374 | | { |
| | 23 | 375 | | var charged = await context.TwoFactorEmailCodes |
| | 23 | 376 | | .Where(x => x.Id == code.Id && !x.Used && x.ExpiresAt > now && x.FailedAttempts < maxGuesses) |
| | 46 | 377 | | .ExecuteUpdateAsync(set => set.SetProperty(x => x.FailedAttempts, x => x.FailedAttempts + 1)) == 1; |
| | | 378 | | |
| | 23 | 379 | | if (charged) |
| | | 380 | | { |
| | 18 | 381 | | Accept(code, x => x.FailedAttempts, code.FailedAttempts + 1); |
| | | 382 | | } |
| | | 383 | | |
| | 23 | 384 | | return charged; |
| | 23 | 385 | | } |
| | | 386 | | |
| | | 387 | | public async Task RetireEmailCodeIfExhaustedAsync(TwoFactorEmailCode code, int maxGuesses) |
| | | 388 | | { |
| | 7 | 389 | | var retired = await context.TwoFactorEmailCodes |
| | 7 | 390 | | .Where(x => x.Id == code.Id && x.FailedAttempts >= maxGuesses) |
| | 14 | 391 | | .ExecuteUpdateAsync(set => set.SetProperty(x => x.Used, true)) == 1; |
| | | 392 | | |
| | 7 | 393 | | if (retired) |
| | | 394 | | { |
| | 5 | 395 | | Accept(code, x => x.Used, true); |
| | | 396 | | } |
| | 7 | 397 | | } |
| | | 398 | | |
| | | 399 | | public async Task<bool> TryConsumeEmailCodeAsync(TwoFactorEmailCode code) |
| | | 400 | | { |
| | 9 | 401 | | var consumed = await context.TwoFactorEmailCodes |
| | 9 | 402 | | .Where(x => x.Id == code.Id && !x.Used) |
| | 18 | 403 | | .ExecuteUpdateAsync(set => set.SetProperty(x => x.Used, true)) == 1; |
| | | 404 | | |
| | 9 | 405 | | if (consumed) |
| | | 406 | | { |
| | 9 | 407 | | Accept(code, x => x.Used, true); |
| | | 408 | | } |
| | | 409 | | |
| | 9 | 410 | | return consumed; |
| | 9 | 411 | | } |
| | | 412 | | |
| | | 413 | | public async Task<bool> TryConsumeRecoveryCodeAsync(TwoFactorRecoveryCode code, DateTime usedAt) |
| | | 414 | | { |
| | 21 | 415 | | var consumed = await context.TwoFactorRecoveryCodes |
| | 21 | 416 | | .Where(x => x.Id == code.Id && !x.Used) |
| | 42 | 417 | | .ExecuteUpdateAsync(set => set |
| | 42 | 418 | | .SetProperty(x => x.Used, true) |
| | 42 | 419 | | .SetProperty(x => x.UsedAt, usedAt)) == 1; |
| | | 420 | | |
| | 21 | 421 | | if (consumed) |
| | | 422 | | { |
| | 17 | 423 | | Accept(code, x => x.Used, true); |
| | 17 | 424 | | Accept(code, x => x.UsedAt, usedAt); |
| | | 425 | | } |
| | | 426 | | |
| | 21 | 427 | | return consumed; |
| | 21 | 428 | | } |
| | | 429 | | |
| | | 430 | | public async Task<bool> TryConsumePasswordResetTokenAsync(PasswordResetToken token, DateTime now) |
| | | 431 | | { |
| | 17 | 432 | | var consumed = await context.PasswordResetTokens |
| | 17 | 433 | | .Where(x => x.Id == token.Id && !x.Used && x.ExpiresAt > now) |
| | 34 | 434 | | .ExecuteUpdateAsync(set => set.SetProperty(x => x.Used, true)) == 1; |
| | | 435 | | |
| | 17 | 436 | | if (consumed) |
| | | 437 | | { |
| | 13 | 438 | | Accept(token, x => x.Used, true); |
| | | 439 | | } |
| | | 440 | | |
| | 17 | 441 | | return consumed; |
| | 17 | 442 | | } |
| | | 443 | | |
| | | 444 | | public async Task<bool> TryConsumeEmailVerificationTokenAsync(EmailVerificationToken token, DateTime now) |
| | | 445 | | { |
| | 19 | 446 | | var consumed = await context.EmailVerificationTokens |
| | 19 | 447 | | .Where(x => x.Id == token.Id && !x.Used && x.ExpiresAt > now) |
| | 38 | 448 | | .ExecuteUpdateAsync(set => set.SetProperty(x => x.Used, true)) == 1; |
| | | 449 | | |
| | 19 | 450 | | if (consumed) |
| | | 451 | | { |
| | 12 | 452 | | Accept(token, x => x.Used, true); |
| | | 453 | | } |
| | | 454 | | |
| | 19 | 455 | | return consumed; |
| | 19 | 456 | | } |
| | | 457 | | |
| | | 458 | | public async Task<bool> TrySetPasswordAsync(Person person, byte[] passwordHash, byte[] salt, DateTime now) |
| | | 459 | | { |
| | 17 | 460 | | var stamp = Guid.NewGuid(); |
| | | 461 | | |
| | 17 | 462 | | var written = await context.Persons |
| | 17 | 463 | | .Where(RedeemableAsRead(person)) |
| | 34 | 464 | | .ExecuteUpdateAsync(set => set |
| | 34 | 465 | | .SetProperty(x => x.PasswordHash, passwordHash) |
| | 34 | 466 | | .SetProperty(x => x.Salt, salt) |
| | 34 | 467 | | .SetProperty(x => x.SecurityStamp, stamp) |
| | 34 | 468 | | .SetProperty(x => x.UpdatedAt, now)) == 1; |
| | | 469 | | |
| | 16 | 470 | | if (written) |
| | | 471 | | { |
| | 11 | 472 | | Accept(person, x => x.PasswordHash, passwordHash); |
| | 11 | 473 | | Accept(person, x => x.Salt, salt); |
| | 11 | 474 | | Accept(person, x => x.SecurityStamp, stamp); |
| | 11 | 475 | | Accept(person, x => x.UpdatedAt, now); |
| | | 476 | | } |
| | | 477 | | |
| | 16 | 478 | | return written; |
| | 16 | 479 | | } |
| | | 480 | | |
| | | 481 | | public async Task<bool> TryMarkEmailVerifiedAsync(Person person, DateTime now) |
| | | 482 | | { |
| | 15 | 483 | | var written = await context.Persons |
| | 15 | 484 | | .Where(RedeemableAsRead(person)) |
| | 30 | 485 | | .ExecuteUpdateAsync(set => set |
| | 30 | 486 | | .SetProperty(x => x.EmailVerified, true) |
| | 30 | 487 | | .SetProperty(x => x.UpdatedAt, now)) == 1; |
| | | 488 | | |
| | 14 | 489 | | if (written) |
| | | 490 | | { |
| | 10 | 491 | | Accept(person, x => x.EmailVerified, true); |
| | 10 | 492 | | Accept(person, x => x.UpdatedAt, now); |
| | | 493 | | } |
| | | 494 | | |
| | 14 | 495 | | return written; |
| | 14 | 496 | | } |
| | | 497 | | |
| | | 498 | | public async Task<bool> TryStampCredentialUseAsync(ApplicationCredential credential, DateTime now) |
| | | 499 | | { |
| | 12 | 500 | | var stamped = await context.ApplicationCredentials |
| | 12 | 501 | | .Where(x => x.Id == credential.Id) |
| | 12 | 502 | | .Where(ApplicationCredential.LiveAt(now)) |
| | 24 | 503 | | .ExecuteUpdateAsync(set => set.SetProperty(x => x.LastUsedAt, now)) == 1; |
| | | 504 | | |
| | 12 | 505 | | if (stamped) |
| | | 506 | | { |
| | 11 | 507 | | Accept(credential, x => x.LastUsedAt, now); |
| | | 508 | | } |
| | | 509 | | |
| | 12 | 510 | | return stamped; |
| | 12 | 511 | | } |
| | | 512 | | |
| | | 513 | | public async Task<bool> TryRevokeCredentialAsync(ApplicationCredential credential, DateTime revokedAt) |
| | | 514 | | { |
| | 6 | 515 | | var revoked = await context.ApplicationCredentials |
| | 6 | 516 | | .Where(x => x.Id == credential.Id && x.RevokedAt == null) |
| | 12 | 517 | | .ExecuteUpdateAsync(set => set.SetProperty(x => x.RevokedAt, revokedAt)) == 1; |
| | | 518 | | |
| | 6 | 519 | | if (revoked) |
| | | 520 | | { |
| | 4 | 521 | | Accept(credential, x => x.RevokedAt, revokedAt); |
| | | 522 | | } |
| | | 523 | | |
| | 6 | 524 | | return revoked; |
| | 6 | 525 | | } |
| | | 526 | | |
| | | 527 | | public async Task RotateSecurityStampAsync(Person person) |
| | | 528 | | { |
| | 43 | 529 | | var stamp = Guid.NewGuid(); |
| | | 530 | | |
| | 43 | 531 | | await context.Persons |
| | 43 | 532 | | .Where(x => x.Id == person.Id) |
| | 86 | 533 | | .ExecuteUpdateAsync(set => set.SetProperty(x => x.SecurityStamp, stamp)); |
| | | 534 | | |
| | 43 | 535 | | Accept(person, x => x.SecurityStamp, stamp); |
| | 43 | 536 | | } |
| | | 537 | | |
| | | 538 | | public async Task<AccountChangeOutcome> TryChangeEmailAndRoleAsync( |
| | | 539 | | Person person, string email, long roleId, DateTime now, Func<Task<bool>> saveAlongside) |
| | | 540 | | { |
| | 24 | 541 | | var id = person.Id; |
| | 24 | 542 | | var readEmail = person.Email; |
| | 24 | 543 | | var readRoleId = person.RoleId; |
| | 24 | 544 | | var emailChanged = !string.Equals(email, readEmail, StringComparison.Ordinal); |
| | 24 | 545 | | var roleChanged = roleId != readRoleId; |
| | | 546 | | |
| | | 547 | | // A change of case alone names the same mailbox — sign-in, recovery and uniqueness all match |
| | | 548 | | // addresses case-insensitively — so the verification it earned stands (#225). |
| | 24 | 549 | | var mailboxChanged = emailChanged && |
| | 24 | 550 | | !string.Equals(email.ToLower(), readEmail.ToLower(), StringComparison.Ordinal); |
| | | 551 | | |
| | | 552 | | // The caller's save has to land with the change or not at all, so the two share a |
| | | 553 | | // transaction — one of their own, unless the caller already runs in one. |
| | 24 | 554 | | await using var transaction = context.Database.CurrentTransaction is null |
| | 24 | 555 | | ? await context.Database.BeginTransactionAsync() |
| | 24 | 556 | | : null; |
| | | 557 | | |
| | | 558 | | int written; |
| | | 559 | | |
| | | 560 | | try |
| | | 561 | | { |
| | | 562 | | // Only the columns that change are set: an address change leaves the role and scope as |
| | | 563 | | // they are, and a role change the address and its flag. |
| | 24 | 564 | | written = await context.Persons |
| | 24 | 565 | | .Where(x => x.Id == id && x.Email == readEmail && x.RoleId == readRoleId && |
| | 24 | 566 | | !x.IsDeleted && x.AnonymisedAt == null) |
| | 24 | 567 | | .ExecuteUpdateAsync(set => |
| | 24 | 568 | | { |
| | 24 | 569 | | set.SetProperty(x => x.UpdatedAt, now); |
| | 24 | 570 | | |
| | 24 | 571 | | if (emailChanged) |
| | 24 | 572 | | { |
| | 15 | 573 | | set.SetProperty(x => x.Email, email); |
| | 24 | 574 | | |
| | 15 | 575 | | if (mailboxChanged) |
| | 24 | 576 | | { |
| | 14 | 577 | | set.SetProperty(x => x.EmailVerified, false); |
| | 24 | 578 | | } |
| | 24 | 579 | | } |
| | 24 | 580 | | |
| | 24 | 581 | | if (roleChanged) |
| | 24 | 582 | | { |
| | 9 | 583 | | set.SetProperty(x => x.RoleId, roleId); |
| | 9 | 584 | | set.SetProperty(x => x.ScopeId, (long?)null); |
| | 24 | 585 | | } |
| | 48 | 586 | | }); |
| | 23 | 587 | | } |
| | 1 | 588 | | catch (Exception exception) when (RelationalErrors.IsUniqueViolation(exception)) |
| | | 589 | | { |
| | | 590 | | // FR-PE-09's partial unique indexes: another identity took the address in the namespace |
| | | 591 | | // the new role puts it in, between the caller's check and this write. |
| | 1 | 592 | | DiscardPendingChanges(); |
| | | 593 | | |
| | 1 | 594 | | return AccountChangeOutcome.AddressTaken; |
| | | 595 | | } |
| | | 596 | | |
| | 23 | 597 | | if (written != 1) |
| | | 598 | | { |
| | 2 | 599 | | DiscardPendingChanges(); |
| | | 600 | | |
| | 2 | 601 | | return AccountChangeOutcome.Stale; |
| | | 602 | | } |
| | | 603 | | |
| | 21 | 604 | | Accept(person, x => x.UpdatedAt, now); |
| | | 605 | | |
| | 21 | 606 | | if (emailChanged) |
| | | 607 | | { |
| | 13 | 608 | | Accept(person, x => x.Email, email); |
| | | 609 | | |
| | 13 | 610 | | if (mailboxChanged) |
| | | 611 | | { |
| | 12 | 612 | | Accept(person, x => x.EmailVerified, false); |
| | | 613 | | } |
| | | 614 | | } |
| | | 615 | | |
| | 21 | 616 | | if (roleChanged) |
| | | 617 | | { |
| | 8 | 618 | | Accept(person, x => x.RoleId, roleId); |
| | 8 | 619 | | Accept(person, x => x.ScopeId, null); |
| | | 620 | | |
| | | 621 | | // FR-PE-10: the membership goes with the role, as its copy in ScopeId just did. Detached before |
| | | 622 | | // the navigation is cleared: severed while still tracked, the row would be deleted again by the |
| | | 623 | | // next save, and that delete would find nothing. |
| | 8 | 624 | | await context.ScopeUsers.Where(x => x.PersonId == id).ExecuteDeleteAsync(); |
| | | 625 | | |
| | 30 | 626 | | foreach (var membership in context.ChangeTracker.Entries<ScopeUser>() |
| | 15 | 627 | | .Where(entry => entry.Entity.PersonId == id).ToList()) |
| | | 628 | | { |
| | 7 | 629 | | membership.State = EntityState.Detached; |
| | | 630 | | } |
| | | 631 | | |
| | 8 | 632 | | person.ScopeMembership = null; |
| | | 633 | | } |
| | | 634 | | |
| | 21 | 635 | | if (!await saveAlongside()) |
| | | 636 | | { |
| | | 637 | | // Rolled back when the transaction is disposed. The instance keeps the values accepted |
| | | 638 | | // above, but nothing the mapping lets a whole-row save write, so nothing writes them. |
| | 0 | 639 | | DiscardPendingChanges(); |
| | | 640 | | |
| | 0 | 641 | | return AccountChangeOutcome.SaveFailed; |
| | | 642 | | } |
| | | 643 | | |
| | 21 | 644 | | if (transaction is not null) |
| | | 645 | | { |
| | 21 | 646 | | await transaction.CommitAsync(); |
| | | 647 | | } |
| | | 648 | | |
| | 21 | 649 | | return AccountChangeOutcome.Changed; |
| | 24 | 650 | | } |
| | | 651 | | |
| | | 652 | | public async Task<bool> TryRenameAsync(Person person, string name, DateTime now) |
| | | 653 | | { |
| | 22 | 654 | | var readRoleId = person.RoleId; |
| | | 655 | | |
| | 22 | 656 | | var written = await context.Persons |
| | 22 | 657 | | .Where(x => x.Id == person.Id && x.RoleId == readRoleId && !x.IsDeleted) |
| | 44 | 658 | | .ExecuteUpdateAsync(set => set |
| | 44 | 659 | | .SetProperty(x => x.Name, name) |
| | 44 | 660 | | .SetProperty(x => x.UpdatedAt, now)) == 1; |
| | | 661 | | |
| | 22 | 662 | | if (written) |
| | | 663 | | { |
| | 20 | 664 | | Accept(person, x => x.Name, name); |
| | 20 | 665 | | Accept(person, x => x.UpdatedAt, now); |
| | | 666 | | } |
| | | 667 | | |
| | 22 | 668 | | return written; |
| | 22 | 669 | | } |
| | | 670 | | |
| | | 671 | | public async Task<ScopeUpdateOutcome> TryUpdateScopeDetailsAsync(Scope scope, string name, string? description, |
| | | 672 | | int? defaultLegalBasis, string? privacyNoticeUri, DateTime now) |
| | | 673 | | { |
| | | 674 | | bool written; |
| | | 675 | | |
| | | 676 | | try |
| | | 677 | | { |
| | 4 | 678 | | written = await context.Scopes |
| | 4 | 679 | | .Where(x => x.Id == scope.Id && !x.IsDeleted) |
| | 8 | 680 | | .ExecuteUpdateAsync(set => set |
| | 8 | 681 | | .SetProperty(x => x.Name, name) |
| | 8 | 682 | | .SetProperty(x => x.Description, description) |
| | 8 | 683 | | .SetProperty(x => x.DefaultLegalBasis, defaultLegalBasis) |
| | 8 | 684 | | .SetProperty(x => x.PrivacyNoticeUri, privacyNoticeUri) |
| | 8 | 685 | | .SetProperty(x => x.UpdatedAt, now)) == 1; |
| | 3 | 686 | | } |
| | 1 | 687 | | catch (Exception exception) when (RelationalErrors.IsUniqueViolation(exception)) |
| | | 688 | | { |
| | | 689 | | // AF-03b's unique index on the name: another scope took it between the caller's check and this |
| | | 690 | | // write. |
| | 1 | 691 | | return ScopeUpdateOutcome.NameTaken; |
| | | 692 | | } |
| | | 693 | | |
| | 3 | 694 | | if (!written) |
| | | 695 | | { |
| | 1 | 696 | | return ScopeUpdateOutcome.NotFound; |
| | | 697 | | } |
| | | 698 | | |
| | 2 | 699 | | Accept(scope, x => x.Name, name); |
| | 2 | 700 | | Accept(scope, x => x.Description, description); |
| | 2 | 701 | | Accept(scope, x => x.DefaultLegalBasis, defaultLegalBasis); |
| | 2 | 702 | | Accept(scope, x => x.PrivacyNoticeUri, privacyNoticeUri); |
| | 2 | 703 | | Accept(scope, x => x.UpdatedAt, now); |
| | | 704 | | |
| | 2 | 705 | | return ScopeUpdateOutcome.Updated; |
| | 4 | 706 | | } |
| | | 707 | | |
| | | 708 | | public async Task<bool> TryMarkScopeDeletedAsync(Scope scope, DateTime at) |
| | | 709 | | { |
| | 6 | 710 | | var written = await context.Scopes |
| | 6 | 711 | | .Where(x => x.Id == scope.Id && !x.IsDeleted) |
| | 12 | 712 | | .ExecuteUpdateAsync(set => set |
| | 12 | 713 | | .SetProperty(x => x.IsDeleted, true) |
| | 12 | 714 | | .SetProperty(x => x.UpdatedAt, at)) == 1; |
| | | 715 | | |
| | 6 | 716 | | if (written) |
| | | 717 | | { |
| | 6 | 718 | | Accept(scope, x => x.IsDeleted, true); |
| | 6 | 719 | | Accept(scope, x => x.UpdatedAt, at); |
| | | 720 | | } |
| | | 721 | | |
| | 6 | 722 | | return written; |
| | 6 | 723 | | } |
| | | 724 | | |
| | | 725 | | public async Task<bool> TrySetGoogleSignInAsync(Scope scope, bool enabled, DateTime now) |
| | | 726 | | { |
| | 6 | 727 | | var written = await context.Scopes |
| | 6 | 728 | | .Where(x => x.Id == scope.Id && !x.IsDeleted) |
| | 12 | 729 | | .ExecuteUpdateAsync(set => set |
| | 12 | 730 | | .SetProperty(x => x.GoogleSignInEnabled, enabled) |
| | 12 | 731 | | .SetProperty(x => x.UpdatedAt, now)) == 1; |
| | | 732 | | |
| | 6 | 733 | | if (written) |
| | | 734 | | { |
| | 5 | 735 | | Accept(scope, x => x.GoogleSignInEnabled, enabled); |
| | 5 | 736 | | Accept(scope, x => x.UpdatedAt, now); |
| | | 737 | | } |
| | | 738 | | |
| | 6 | 739 | | return written; |
| | 6 | 740 | | } |
| | | 741 | | |
| | | 742 | | public async Task<bool> TrySetSelfRegistrationAsync(Scope scope, bool enabled, DateTime now) |
| | | 743 | | { |
| | 3 | 744 | | var written = await context.Scopes |
| | 3 | 745 | | .Where(x => x.Id == scope.Id && !x.IsDeleted) |
| | 6 | 746 | | .ExecuteUpdateAsync(set => set |
| | 6 | 747 | | .SetProperty(x => x.SelfRegistrationEnabled, enabled) |
| | 6 | 748 | | .SetProperty(x => x.UpdatedAt, now)) == 1; |
| | | 749 | | |
| | 3 | 750 | | if (written) |
| | | 751 | | { |
| | 2 | 752 | | Accept(scope, x => x.SelfRegistrationEnabled, enabled); |
| | 2 | 753 | | Accept(scope, x => x.UpdatedAt, now); |
| | | 754 | | } |
| | | 755 | | |
| | 3 | 756 | | return written; |
| | 3 | 757 | | } |
| | | 758 | | |
| | | 759 | | public async Task<bool> TrySetEmailLinksAsync( |
| | | 760 | | Scope scope, string? emailVerificationUrl, string? passwordResetUrl, DateTime now) |
| | | 761 | | { |
| | 5 | 762 | | var written = await context.Scopes |
| | 5 | 763 | | .Where(x => x.Id == scope.Id && !x.IsDeleted) |
| | 10 | 764 | | .ExecuteUpdateAsync(set => set |
| | 10 | 765 | | .SetProperty(x => x.EmailVerificationUrl, emailVerificationUrl) |
| | 10 | 766 | | .SetProperty(x => x.PasswordResetUrl, passwordResetUrl) |
| | 10 | 767 | | .SetProperty(x => x.UpdatedAt, now)) == 1; |
| | | 768 | | |
| | 5 | 769 | | if (written) |
| | | 770 | | { |
| | 4 | 771 | | Accept(scope, x => x.EmailVerificationUrl, emailVerificationUrl); |
| | 4 | 772 | | Accept(scope, x => x.PasswordResetUrl, passwordResetUrl); |
| | 4 | 773 | | Accept(scope, x => x.UpdatedAt, now); |
| | | 774 | | } |
| | | 775 | | |
| | 5 | 776 | | return written; |
| | 5 | 777 | | } |
| | | 778 | | |
| | | 779 | | public async Task<bool> TryMarkDeletedAsync(GoogleUser googleUser, DeletionKinds kind, DateTime at) |
| | | 780 | | { |
| | 6 | 781 | | var deletionKind = (int)kind; |
| | | 782 | | |
| | 6 | 783 | | var written = await context.GoogleUsers |
| | 6 | 784 | | .Where(x => x.Id == googleUser.Id && !x.IsDeleted) |
| | 12 | 785 | | .ExecuteUpdateAsync(set => set |
| | 12 | 786 | | .SetProperty(x => x.IsDeleted, true) |
| | 12 | 787 | | .SetProperty(x => x.DeletedAt, at) |
| | 12 | 788 | | .SetProperty(x => x.DeletionKind, deletionKind) |
| | 12 | 789 | | .SetProperty(x => x.UpdatedAt, at)) == 1; |
| | | 790 | | |
| | 6 | 791 | | if (written) |
| | | 792 | | { |
| | 5 | 793 | | Accept(googleUser, x => x.IsDeleted, true); |
| | 5 | 794 | | Accept(googleUser, x => x.DeletedAt, at); |
| | 5 | 795 | | Accept(googleUser, x => x.DeletionKind, deletionKind); |
| | 5 | 796 | | Accept(googleUser, x => x.UpdatedAt, at); |
| | | 797 | | } |
| | | 798 | | |
| | 6 | 799 | | return written; |
| | 6 | 800 | | } |
| | | 801 | | |
| | | 802 | | public async Task<bool> TryRestrictProcessingAsync(GoogleUser googleUser, int ground, DateTime at) |
| | | 803 | | { |
| | 2 | 804 | | var written = await context.GoogleUsers |
| | 2 | 805 | | .Where(x => x.Id == googleUser.Id && x.ProcessingRestrictedAt == null && x.AnonymisedAt == null) |
| | 4 | 806 | | .ExecuteUpdateAsync(set => set |
| | 4 | 807 | | .SetProperty(x => x.ProcessingRestrictedAt, at) |
| | 4 | 808 | | .SetProperty(x => x.RestrictionGround, ground) |
| | 4 | 809 | | .SetProperty(x => x.RestrictionLiftNotifiedAt, (DateTime?)null) |
| | 4 | 810 | | .SetProperty(x => x.UpdatedAt, at)) == 1; |
| | | 811 | | |
| | 2 | 812 | | if (written) |
| | | 813 | | { |
| | 1 | 814 | | Accept(googleUser, x => x.ProcessingRestrictedAt, at); |
| | 1 | 815 | | Accept(googleUser, x => x.RestrictionGround, ground); |
| | 1 | 816 | | Accept(googleUser, x => x.RestrictionLiftNotifiedAt, null); |
| | 1 | 817 | | Accept(googleUser, x => x.UpdatedAt, at); |
| | | 818 | | } |
| | | 819 | | |
| | 2 | 820 | | return written; |
| | 2 | 821 | | } |
| | | 822 | | |
| | | 823 | | public async Task<bool> TryLiftRestrictionAsync(GoogleUser googleUser, DateTime? notifiedAt, DateTime now) |
| | | 824 | | { |
| | 1 | 825 | | if (googleUser.ProcessingRestrictedAt is not { } restrictedAt) |
| | | 826 | | { |
| | 0 | 827 | | return false; |
| | | 828 | | } |
| | | 829 | | |
| | | 830 | | // The restriction read, by when it began, as for a person. |
| | 1 | 831 | | var written = await context.GoogleUsers |
| | 1 | 832 | | .Where(x => x.Id == googleUser.Id && x.ProcessingRestrictedAt == restrictedAt) |
| | 2 | 833 | | .ExecuteUpdateAsync(set => set |
| | 2 | 834 | | .SetProperty(x => x.ProcessingRestrictedAt, (DateTime?)null) |
| | 2 | 835 | | .SetProperty(x => x.RestrictionGround, (int?)null) |
| | 2 | 836 | | .SetProperty(x => x.RestrictionLiftNotifiedAt, notifiedAt) |
| | 2 | 837 | | .SetProperty(x => x.UpdatedAt, now)) == 1; |
| | | 838 | | |
| | 1 | 839 | | if (written) |
| | | 840 | | { |
| | 0 | 841 | | Accept(googleUser, x => x.ProcessingRestrictedAt, null); |
| | 0 | 842 | | Accept(googleUser, x => x.RestrictionGround, null); |
| | 0 | 843 | | Accept(googleUser, x => x.RestrictionLiftNotifiedAt, notifiedAt); |
| | 0 | 844 | | Accept(googleUser, x => x.UpdatedAt, now); |
| | | 845 | | } |
| | | 846 | | |
| | 1 | 847 | | return written; |
| | 1 | 848 | | } |
| | | 849 | | |
| | | 850 | | public async Task<bool> TryRecordErasureRequestAsync(GoogleUser googleUser, DateTime requestedAt, DateTime dueAt) |
| | | 851 | | { |
| | | 852 | | const int subjectRequested = (int)DeletionKinds.SubjectRequested; |
| | | 853 | | |
| | | 854 | | // One statement: the request, the lifted restriction and the suspension, as for a person (UC-42). |
| | 1 | 855 | | var written = await context.GoogleUsers |
| | 1 | 856 | | .Where(x => x.Id == googleUser.Id && x.ErasureRequestedAt == null && !x.IsDeleted && |
| | 1 | 857 | | x.AnonymisedAt == null) |
| | 2 | 858 | | .ExecuteUpdateAsync(set => set |
| | 2 | 859 | | .SetProperty(x => x.ErasureRequestedAt, requestedAt) |
| | 2 | 860 | | .SetProperty(x => x.ErasureDueAt, dueAt) |
| | 2 | 861 | | .SetProperty(x => x.ProcessingRestrictedAt, (DateTime?)null) |
| | 2 | 862 | | .SetProperty(x => x.RestrictionGround, (int?)null) |
| | 2 | 863 | | .SetProperty(x => x.RestrictionLiftNotifiedAt, (DateTime?)null) |
| | 2 | 864 | | .SetProperty(x => x.IsDeleted, true) |
| | 2 | 865 | | .SetProperty(x => x.DeletedAt, requestedAt) |
| | 2 | 866 | | .SetProperty(x => x.DeletionKind, subjectRequested) |
| | 2 | 867 | | .SetProperty(x => x.UpdatedAt, requestedAt)) == 1; |
| | | 868 | | |
| | 1 | 869 | | if (written) |
| | | 870 | | { |
| | 1 | 871 | | Accept(googleUser, x => x.ErasureRequestedAt, requestedAt); |
| | 1 | 872 | | Accept(googleUser, x => x.ErasureDueAt, dueAt); |
| | 1 | 873 | | Accept(googleUser, x => x.ProcessingRestrictedAt, null); |
| | 1 | 874 | | Accept(googleUser, x => x.RestrictionGround, null); |
| | 1 | 875 | | Accept(googleUser, x => x.RestrictionLiftNotifiedAt, null); |
| | 1 | 876 | | Accept(googleUser, x => x.IsDeleted, true); |
| | 1 | 877 | | Accept(googleUser, x => x.DeletedAt, requestedAt); |
| | 1 | 878 | | Accept(googleUser, x => x.DeletionKind, subjectRequested); |
| | 1 | 879 | | Accept(googleUser, x => x.UpdatedAt, requestedAt); |
| | | 880 | | } |
| | | 881 | | |
| | 1 | 882 | | return written; |
| | 1 | 883 | | } |
| | | 884 | | |
| | | 885 | | public async Task<bool> TryRefreshEmailVerifiedAsync(GoogleUser googleUser, bool emailVerified, DateTime now) |
| | | 886 | | { |
| | 3 | 887 | | var written = await context.GoogleUsers |
| | 3 | 888 | | .Where(x => x.Id == googleUser.Id && !x.IsDeleted && x.ProcessingRestrictedAt == null && |
| | 3 | 889 | | x.AnonymisedAt == null) |
| | 6 | 890 | | .ExecuteUpdateAsync(set => set |
| | 6 | 891 | | .SetProperty(x => x.EmailVerified, emailVerified) |
| | 6 | 892 | | .SetProperty(x => x.UpdatedAt, now)) == 1; |
| | | 893 | | |
| | 3 | 894 | | if (written) |
| | | 895 | | { |
| | 2 | 896 | | Accept(googleUser, x => x.EmailVerified, emailVerified); |
| | 2 | 897 | | Accept(googleUser, x => x.UpdatedAt, now); |
| | | 898 | | } |
| | | 899 | | |
| | 3 | 900 | | return written; |
| | 3 | 901 | | } |
| | | 902 | | |
| | | 903 | | public async Task<bool> TryAnonymiseAsync( |
| | | 904 | | GoogleUser googleUser, string name, string email, string googleId, DateTime at) |
| | | 905 | | { |
| | 8 | 906 | | var written = await context.GoogleUsers |
| | 8 | 907 | | .Where(x => x.Id == googleUser.Id && x.IsDeleted && x.AnonymisedAt == null && |
| | 8 | 908 | | x.ProcessingRestrictedAt == null) |
| | 16 | 909 | | .ExecuteUpdateAsync(set => SetAnonymised(set, name, email, googleId, at)) == 1; |
| | | 910 | | |
| | 8 | 911 | | if (written) |
| | | 912 | | { |
| | 7 | 913 | | AcceptAnonymised(googleUser, name, email, googleId, at); |
| | | 914 | | } |
| | | 915 | | |
| | 8 | 916 | | return written; |
| | 8 | 917 | | } |
| | | 918 | | |
| | | 919 | | public async Task<bool> TryReapplyErasureAsync( |
| | | 920 | | GoogleUser googleUser, string name, string email, string googleId, DateTime at) |
| | | 921 | | { |
| | | 922 | | const int subjectRequested = (int)DeletionKinds.SubjectRequested; |
| | | 923 | | |
| | 0 | 924 | | var written = await context.GoogleUsers |
| | 0 | 925 | | .Where(x => x.Id == googleUser.Id && x.AnonymisedAt == null) |
| | 0 | 926 | | .ExecuteUpdateAsync(set => |
| | 0 | 927 | | { |
| | 0 | 928 | | set.SetProperty(x => x.IsDeleted, true); |
| | 0 | 929 | | set.SetProperty(x => x.DeletedAt, x => x.DeletedAt ?? at); |
| | 0 | 930 | | set.SetProperty(x => x.DeletionKind, subjectRequested); |
| | 0 | 931 | | SetAnonymised(set, name, email, googleId, at); |
| | 0 | 932 | | }) == 1; |
| | | 933 | | |
| | 0 | 934 | | if (written) |
| | | 935 | | { |
| | 0 | 936 | | Accept(googleUser, x => x.IsDeleted, true); |
| | 0 | 937 | | Accept(googleUser, x => x.DeletedAt, googleUser.DeletedAt ?? at); |
| | 0 | 938 | | Accept(googleUser, x => x.DeletionKind, subjectRequested); |
| | 0 | 939 | | AcceptAnonymised(googleUser, name, email, googleId, at); |
| | | 940 | | } |
| | | 941 | | |
| | 0 | 942 | | return written; |
| | 0 | 943 | | } |
| | | 944 | | |
| | | 945 | | public async Task<bool> TryMarkDeletedAsync(Person person, DeletionKinds kind, DateTime at) |
| | | 946 | | { |
| | 9 | 947 | | var deletionKind = (int)kind; |
| | | 948 | | |
| | 9 | 949 | | var written = await context.Persons |
| | 9 | 950 | | .Where(x => x.Id == person.Id && !x.IsDeleted) |
| | 18 | 951 | | .ExecuteUpdateAsync(set => set |
| | 18 | 952 | | .SetProperty(x => x.IsDeleted, true) |
| | 18 | 953 | | .SetProperty(x => x.DeletedAt, at) |
| | 18 | 954 | | .SetProperty(x => x.DeletionKind, deletionKind) |
| | 18 | 955 | | .SetProperty(x => x.UpdatedAt, at)) == 1; |
| | | 956 | | |
| | 9 | 957 | | if (written) |
| | | 958 | | { |
| | 9 | 959 | | Accept(person, x => x.IsDeleted, true); |
| | 9 | 960 | | Accept(person, x => x.DeletedAt, at); |
| | 9 | 961 | | Accept(person, x => x.DeletionKind, deletionKind); |
| | 9 | 962 | | Accept(person, x => x.UpdatedAt, at); |
| | | 963 | | } |
| | | 964 | | |
| | 9 | 965 | | return written; |
| | 9 | 966 | | } |
| | | 967 | | |
| | | 968 | | public async Task<bool> TryRecordErasureRequestAsync( |
| | | 969 | | Person person, DateTime requestedAt, DateTime dueAt, string? blockedReason) |
| | | 970 | | { |
| | | 971 | | const int subjectRequested = (int)DeletionKinds.SubjectRequested; |
| | 16 | 972 | | var suspend = blockedReason is null; |
| | | 973 | | |
| | | 974 | | // One statement: the request, the lifted restriction, and either the suspension or the |
| | | 975 | | // reason it waits, so none of them can be written without the others (UC-42). |
| | 16 | 976 | | var written = await context.Persons |
| | 16 | 977 | | .Where(x => x.Id == person.Id && x.ErasureRequestedAt == null && !x.IsDeleted && x.AnonymisedAt == null) |
| | 16 | 978 | | .ExecuteUpdateAsync(set => |
| | 16 | 979 | | { |
| | 16 | 980 | | set.SetProperty(x => x.ErasureRequestedAt, requestedAt); |
| | 16 | 981 | | set.SetProperty(x => x.ErasureDueAt, dueAt); |
| | 16 | 982 | | set.SetProperty(x => x.ProcessingRestrictedAt, (DateTime?)null); |
| | 16 | 983 | | set.SetProperty(x => x.RestrictionGround, (int?)null); |
| | 16 | 984 | | set.SetProperty(x => x.RestrictionLiftNotifiedAt, (DateTime?)null); |
| | 16 | 985 | | set.SetProperty(x => x.UpdatedAt, requestedAt); |
| | 16 | 986 | | |
| | 16 | 987 | | if (suspend) |
| | 16 | 988 | | { |
| | 13 | 989 | | set.SetProperty(x => x.IsDeleted, true); |
| | 13 | 990 | | set.SetProperty(x => x.DeletedAt, requestedAt); |
| | 13 | 991 | | set.SetProperty(x => x.DeletionKind, subjectRequested); |
| | 16 | 992 | | } |
| | 16 | 993 | | else |
| | 16 | 994 | | { |
| | 3 | 995 | | set.SetProperty(x => x.ErasureBlockedReason, blockedReason); |
| | 16 | 996 | | } |
| | 19 | 997 | | }) == 1; |
| | | 998 | | |
| | 16 | 999 | | if (!written) |
| | | 1000 | | { |
| | 0 | 1001 | | return false; |
| | | 1002 | | } |
| | | 1003 | | |
| | 16 | 1004 | | Accept(person, x => x.ErasureRequestedAt, requestedAt); |
| | 16 | 1005 | | Accept(person, x => x.ErasureDueAt, dueAt); |
| | 16 | 1006 | | Accept(person, x => x.ProcessingRestrictedAt, null); |
| | 16 | 1007 | | Accept(person, x => x.RestrictionGround, null); |
| | 16 | 1008 | | Accept(person, x => x.RestrictionLiftNotifiedAt, null); |
| | 16 | 1009 | | Accept(person, x => x.UpdatedAt, requestedAt); |
| | | 1010 | | |
| | 16 | 1011 | | if (suspend) |
| | | 1012 | | { |
| | 13 | 1013 | | Accept(person, x => x.IsDeleted, true); |
| | 13 | 1014 | | Accept(person, x => x.DeletedAt, requestedAt); |
| | 13 | 1015 | | Accept(person, x => x.DeletionKind, subjectRequested); |
| | | 1016 | | } |
| | | 1017 | | else |
| | | 1018 | | { |
| | 3 | 1019 | | Accept(person, x => x.ErasureBlockedReason, blockedReason); |
| | | 1020 | | } |
| | | 1021 | | |
| | 16 | 1022 | | return true; |
| | 16 | 1023 | | } |
| | | 1024 | | |
| | | 1025 | | public async Task<bool> TrySuspendBlockedErasureAsync(Person person, DateTime now) |
| | | 1026 | | { |
| | | 1027 | | const int subjectRequested = (int)DeletionKinds.SubjectRequested; |
| | | 1028 | | |
| | | 1029 | | // Dated from the request, read from the row itself rather than from the instance. |
| | 2 | 1030 | | var written = await context.Persons |
| | 2 | 1031 | | .Where(x => x.Id == person.Id && !x.IsDeleted && x.ErasureRequestedAt != null && |
| | 2 | 1032 | | x.ErasureBlockedReason != null && x.ProcessingRestrictedAt == null) |
| | 4 | 1033 | | .ExecuteUpdateAsync(set => set |
| | 4 | 1034 | | .SetProperty(x => x.IsDeleted, true) |
| | 4 | 1035 | | .SetProperty(x => x.DeletedAt, x => x.ErasureRequestedAt) |
| | 4 | 1036 | | .SetProperty(x => x.DeletionKind, subjectRequested) |
| | 4 | 1037 | | .SetProperty(x => x.ErasureBlockedReason, (string?)null) |
| | 4 | 1038 | | .SetProperty(x => x.UpdatedAt, now)) == 1; |
| | | 1039 | | |
| | 2 | 1040 | | if (written) |
| | | 1041 | | { |
| | 2 | 1042 | | Accept(person, x => x.IsDeleted, true); |
| | 2 | 1043 | | Accept(person, x => x.DeletedAt, person.ErasureRequestedAt); |
| | 2 | 1044 | | Accept(person, x => x.DeletionKind, subjectRequested); |
| | 2 | 1045 | | Accept(person, x => x.ErasureBlockedReason, null); |
| | 2 | 1046 | | Accept(person, x => x.UpdatedAt, now); |
| | | 1047 | | } |
| | | 1048 | | |
| | 2 | 1049 | | return written; |
| | 2 | 1050 | | } |
| | | 1051 | | |
| | | 1052 | | public async Task<bool> TryRestrictProcessingAsync(Person person, int ground, DateTime at) |
| | | 1053 | | { |
| | 12 | 1054 | | var written = await context.Persons |
| | 12 | 1055 | | .Where(x => x.Id == person.Id && x.ProcessingRestrictedAt == null && x.AnonymisedAt == null) |
| | 24 | 1056 | | .ExecuteUpdateAsync(set => set |
| | 24 | 1057 | | .SetProperty(x => x.ProcessingRestrictedAt, at) |
| | 24 | 1058 | | .SetProperty(x => x.RestrictionGround, ground) |
| | 24 | 1059 | | .SetProperty(x => x.RestrictionLiftNotifiedAt, (DateTime?)null) |
| | 24 | 1060 | | .SetProperty(x => x.UpdatedAt, at)) == 1; |
| | | 1061 | | |
| | 12 | 1062 | | if (written) |
| | | 1063 | | { |
| | 11 | 1064 | | Accept(person, x => x.ProcessingRestrictedAt, at); |
| | 11 | 1065 | | Accept(person, x => x.RestrictionGround, ground); |
| | 11 | 1066 | | Accept(person, x => x.RestrictionLiftNotifiedAt, null); |
| | 11 | 1067 | | Accept(person, x => x.UpdatedAt, at); |
| | | 1068 | | } |
| | | 1069 | | |
| | 12 | 1070 | | return written; |
| | 12 | 1071 | | } |
| | | 1072 | | |
| | | 1073 | | public async Task<bool> TryLiftRestrictionAsync(Person person, DateTime? notifiedAt, DateTime now) |
| | | 1074 | | { |
| | 4 | 1075 | | if (person.ProcessingRestrictedAt is not { } restrictedAt) |
| | | 1076 | | { |
| | 0 | 1077 | | return false; |
| | | 1078 | | } |
| | | 1079 | | |
| | | 1080 | | // The restriction read, by when it began: one lifted meanwhile is not there to lift, and |
| | | 1081 | | // one imposed again meanwhile is not the one the subject was told about. |
| | 4 | 1082 | | var written = await context.Persons |
| | 4 | 1083 | | .Where(x => x.Id == person.Id && x.ProcessingRestrictedAt == restrictedAt) |
| | 8 | 1084 | | .ExecuteUpdateAsync(set => set |
| | 8 | 1085 | | .SetProperty(x => x.ProcessingRestrictedAt, (DateTime?)null) |
| | 8 | 1086 | | .SetProperty(x => x.RestrictionGround, (int?)null) |
| | 8 | 1087 | | .SetProperty(x => x.RestrictionLiftNotifiedAt, notifiedAt) |
| | 8 | 1088 | | .SetProperty(x => x.UpdatedAt, now)) == 1; |
| | | 1089 | | |
| | 4 | 1090 | | if (written) |
| | | 1091 | | { |
| | 4 | 1092 | | Accept(person, x => x.ProcessingRestrictedAt, null); |
| | 4 | 1093 | | Accept(person, x => x.RestrictionGround, null); |
| | 4 | 1094 | | Accept(person, x => x.RestrictionLiftNotifiedAt, notifiedAt); |
| | 4 | 1095 | | Accept(person, x => x.UpdatedAt, now); |
| | | 1096 | | } |
| | | 1097 | | |
| | 4 | 1098 | | return written; |
| | 4 | 1099 | | } |
| | | 1100 | | |
| | | 1101 | | public async Task<bool> TryAnonymiseAsync(Person person, string name, string email, DateTime at) |
| | | 1102 | | { |
| | 16 | 1103 | | var written = await context.Persons |
| | 16 | 1104 | | .Where(x => x.Id == person.Id && x.IsDeleted && x.AnonymisedAt == null && x.ProcessingRestrictedAt == null) |
| | 32 | 1105 | | .ExecuteUpdateAsync(set => SetAnonymised(set, name, email, at)) == 1; |
| | | 1106 | | |
| | 16 | 1107 | | if (written) |
| | | 1108 | | { |
| | 16 | 1109 | | AcceptAnonymised(person, name, email, at); |
| | | 1110 | | } |
| | | 1111 | | |
| | 16 | 1112 | | return written; |
| | 16 | 1113 | | } |
| | | 1114 | | |
| | | 1115 | | public async Task<bool> TryReapplyErasureAsync(Person person, string name, string email, DateTime at) |
| | | 1116 | | { |
| | | 1117 | | const int subjectRequested = (int)DeletionKinds.SubjectRequested; |
| | | 1118 | | |
| | 3 | 1119 | | var written = await context.Persons |
| | 3 | 1120 | | .Where(x => x.Id == person.Id && x.AnonymisedAt == null) |
| | 3 | 1121 | | .ExecuteUpdateAsync(set => |
| | 3 | 1122 | | { |
| | 3 | 1123 | | set.SetProperty(x => x.IsDeleted, true); |
| | 3 | 1124 | | set.SetProperty(x => x.DeletedAt, x => x.DeletedAt ?? at); |
| | 3 | 1125 | | set.SetProperty(x => x.DeletionKind, subjectRequested); |
| | 3 | 1126 | | SetAnonymised(set, name, email, at); |
| | 6 | 1127 | | }) == 1; |
| | | 1128 | | |
| | 3 | 1129 | | if (written) |
| | | 1130 | | { |
| | 3 | 1131 | | Accept(person, x => x.IsDeleted, true); |
| | 3 | 1132 | | Accept(person, x => x.DeletedAt, person.DeletedAt ?? at); |
| | 3 | 1133 | | Accept(person, x => x.DeletionKind, subjectRequested); |
| | 3 | 1134 | | AcceptAnonymised(person, name, email, at); |
| | | 1135 | | } |
| | | 1136 | | |
| | 3 | 1137 | | return written; |
| | 3 | 1138 | | } |
| | | 1139 | | |
| | | 1140 | | public async Task<bool> TryAddScopeOwnerAsync(Person person, long scopeId) |
| | | 1141 | | { |
| | | 1142 | | // Table names come from the model, never from input, so building them into the SQL is safe; |
| | | 1143 | | // the values stay parameters. The insert selects from the person's own row, so it lands only |
| | | 1144 | | // while that row is a live administrator, and ON CONFLICT answers AF-21d without an error. |
| | 12 | 1145 | | var ownerTable = context.Model.FindEntityType(typeof(ScopeOwner))!.GetSchemaQualifiedTableName(); |
| | 12 | 1146 | | var personTable = context.Model.FindEntityType(typeof(Person))!.GetSchemaQualifiedTableName(); |
| | | 1147 | | |
| | 12 | 1148 | | var sql = |
| | 12 | 1149 | | $$""" |
| | 12 | 1150 | | INSERT INTO {{ownerTable}} (scope_id, person_id) |
| | 12 | 1151 | | SELECT {0}, person.id FROM {{personTable}} AS person |
| | 12 | 1152 | | WHERE person.id = {1} AND NOT person.is_deleted AND person.role_id IN ({2}, {3}) |
| | 12 | 1153 | | ON CONFLICT DO NOTHING |
| | 12 | 1154 | | """; |
| | | 1155 | | |
| | 12 | 1156 | | var added = await context.Database.ExecuteSqlRawAsync( |
| | 12 | 1157 | | sql, scopeId, person.Id, (long)Roles.ScopeAdmin, (long)Roles.SystemAdmin) == 1; |
| | | 1158 | | |
| | 12 | 1159 | | if (added) |
| | | 1160 | | { |
| | 10 | 1161 | | var ownership = new ScopeOwner { ScopeId = scopeId, PersonId = person.Id }; |
| | | 1162 | | |
| | | 1163 | | // Tracked as already stored, which also adds it to a tracked person's collection, so a |
| | | 1164 | | // later save in the same unit of work does not insert it a second time. |
| | 10 | 1165 | | if (context.Entry(person).State is EntityState.Detached) |
| | | 1166 | | { |
| | 0 | 1167 | | person.ScopeOwnerships.Add(ownership); |
| | | 1168 | | } |
| | | 1169 | | else |
| | | 1170 | | { |
| | 10 | 1171 | | context.Entry(ownership).State = EntityState.Unchanged; |
| | | 1172 | | } |
| | | 1173 | | } |
| | | 1174 | | |
| | 12 | 1175 | | return added; |
| | 12 | 1176 | | } |
| | | 1177 | | |
| | | 1178 | | public async Task<bool> TryRemoveScopeOwnerAsync(Person person, long scopeId) |
| | | 1179 | | { |
| | 6 | 1180 | | var personId = person.Id; |
| | | 1181 | | |
| | | 1182 | | // An active co-owner, by the one definition of active (Person.Active, #211). |
| | 6 | 1183 | | var activeCoOwners = context.Persons |
| | 6 | 1184 | | .Where(Person.Active) |
| | 6 | 1185 | | .Where(other => other.Id != personId && other.ScopeOwnerships.Any(ownership => ownership.ScopeId == scopeId) |
| | | 1186 | | |
| | 6 | 1187 | | var removed = await context.ScopeOwners |
| | 6 | 1188 | | .Where(x => x.ScopeId == scopeId && x.PersonId == personId && activeCoOwners.Any()) |
| | 6 | 1189 | | .ExecuteDeleteAsync() == 1; |
| | | 1190 | | |
| | 6 | 1191 | | if (removed) |
| | | 1192 | | { |
| | | 1193 | | // Detached before it leaves the collection: removed from a tracked person's collection |
| | | 1194 | | // while still tracked, it would be deleted again by the next save. |
| | 25 | 1195 | | foreach (var ownership in person.ScopeOwnerships.Where(x => x.ScopeId == scopeId).ToList()) |
| | | 1196 | | { |
| | 5 | 1197 | | context.Entry(ownership).State = EntityState.Detached; |
| | 5 | 1198 | | person.ScopeOwnerships.Remove(ownership); |
| | | 1199 | | } |
| | | 1200 | | } |
| | | 1201 | | |
| | 6 | 1202 | | return removed; |
| | 6 | 1203 | | } |
| | | 1204 | | |
| | | 1205 | | public async Task<bool> TryRecordGoogleIdTokenUseAsync(string tokenHash, DateTime expiresAt) |
| | | 1206 | | { |
| | | 1207 | | // The table name comes from the model, never from input, so building it into the SQL is safe; |
| | | 1208 | | // the values stay parameters. A competing insert of the same key waits for the first to commit |
| | | 1209 | | // and then inserts nothing, so the affected-row count says which request recorded the use. |
| | 50 | 1210 | | var table = context.Model.FindEntityType(typeof(GoogleIdTokenUse))!.GetSchemaQualifiedTableName(); |
| | | 1211 | | |
| | 50 | 1212 | | var sql = |
| | 50 | 1213 | | $$""" |
| | 50 | 1214 | | INSERT INTO {{table}} (token_hash, expires_at) |
| | 50 | 1215 | | VALUES ({0}, {1}) |
| | 50 | 1216 | | ON CONFLICT (token_hash) DO NOTHING |
| | 50 | 1217 | | """; |
| | | 1218 | | |
| | 50 | 1219 | | return await context.Database.ExecuteSqlRawAsync(sql, tokenHash, expiresAt) == 1; |
| | 50 | 1220 | | } |
| | | 1221 | | |
| | | 1222 | | /// <summary>The columns anonymisation overwrites (NFR-20), for both of its writes.</summary> |
| | | 1223 | | private static void SetAnonymised(UpdateSettersBuilder<Person> set, string name, string email, DateTime at) |
| | | 1224 | | { |
| | 19 | 1225 | | byte[] empty = []; |
| | | 1226 | | |
| | 19 | 1227 | | set.SetProperty(x => x.Name, name); |
| | 19 | 1228 | | set.SetProperty(x => x.Email, email); |
| | 19 | 1229 | | set.SetProperty(x => x.PasswordHash, empty); |
| | 19 | 1230 | | set.SetProperty(x => x.Salt, empty); |
| | 19 | 1231 | | set.SetProperty(x => x.FailedSecondFactorAttempts, 0); |
| | 19 | 1232 | | set.SetProperty(x => x.SecondFactorLockedOutUntil, (DateTime?)null); |
| | 19 | 1233 | | set.SetProperty(x => x.SecondFactorLockouts, 0); |
| | 19 | 1234 | | set.SetProperty(x => x.FailedReauthenticationAttempts, 0); |
| | 19 | 1235 | | set.SetProperty(x => x.ReauthenticationWindowStartedAt, (DateTime?)null); |
| | 19 | 1236 | | set.SetProperty(x => x.ReauthenticationPausedUntil, (DateTime?)null); |
| | 19 | 1237 | | set.SetProperty(x => x.AccountEmailsSent, 0); |
| | 19 | 1238 | | set.SetProperty(x => x.AccountEmailWindowEndsAt, (DateTime?)null); |
| | 19 | 1239 | | set.SetProperty(x => x.AccountEmailLastSentAt, (DateTime?)null); |
| | 19 | 1240 | | set.SetProperty(x => x.EmailVerified, false); |
| | 19 | 1241 | | set.SetProperty(x => x.FailedLoginAttempts, 0); |
| | 19 | 1242 | | set.SetProperty(x => x.LockedOutUntil, (DateTime?)null); |
| | 19 | 1243 | | set.SetProperty(x => x.ErasureBlockedReason, (string?)null); |
| | 19 | 1244 | | set.SetProperty(x => x.AnonymisedAt, at); |
| | 19 | 1245 | | set.SetProperty(x => x.UpdatedAt, at); |
| | 19 | 1246 | | } |
| | | 1247 | | |
| | | 1248 | | private static void SetAnonymised( |
| | | 1249 | | UpdateSettersBuilder<GoogleUser> set, string name, string email, string googleId, DateTime at) |
| | | 1250 | | { |
| | 8 | 1251 | | set.SetProperty(x => x.Name, name); |
| | 8 | 1252 | | set.SetProperty(x => x.Email, email); |
| | 8 | 1253 | | set.SetProperty(x => x.GoogleId, googleId); |
| | 8 | 1254 | | set.SetProperty(x => x.ProfilePictureUrl, (string?)null); |
| | 8 | 1255 | | set.SetProperty(x => x.EmailVerified, false); |
| | 8 | 1256 | | set.SetProperty(x => x.AnonymisedAt, at); |
| | 8 | 1257 | | set.SetProperty(x => x.UpdatedAt, at); |
| | 8 | 1258 | | } |
| | | 1259 | | |
| | | 1260 | | private void AcceptAnonymised(GoogleUser googleUser, string name, string email, string googleId, DateTime at) |
| | | 1261 | | { |
| | 7 | 1262 | | Accept(googleUser, x => x.Name, name); |
| | 7 | 1263 | | Accept(googleUser, x => x.Email, email); |
| | 7 | 1264 | | Accept(googleUser, x => x.GoogleId, googleId); |
| | 7 | 1265 | | Accept(googleUser, x => x.ProfilePictureUrl, null); |
| | 7 | 1266 | | Accept(googleUser, x => x.EmailVerified, false); |
| | 7 | 1267 | | Accept(googleUser, x => x.AnonymisedAt, at); |
| | 7 | 1268 | | Accept(googleUser, x => x.UpdatedAt, at); |
| | 7 | 1269 | | } |
| | | 1270 | | |
| | | 1271 | | private void AcceptAnonymised(Person person, string name, string email, DateTime at) |
| | | 1272 | | { |
| | 19 | 1273 | | Accept(person, x => x.Name, name); |
| | 19 | 1274 | | Accept(person, x => x.Email, email); |
| | 19 | 1275 | | Accept(person, x => x.PasswordHash, []); |
| | 19 | 1276 | | Accept(person, x => x.Salt, []); |
| | 19 | 1277 | | Accept(person, x => x.FailedSecondFactorAttempts, 0); |
| | 19 | 1278 | | Accept(person, x => x.SecondFactorLockedOutUntil, null); |
| | 19 | 1279 | | Accept(person, x => x.SecondFactorLockouts, 0); |
| | 19 | 1280 | | Accept(person, x => x.FailedReauthenticationAttempts, 0); |
| | 19 | 1281 | | Accept(person, x => x.ReauthenticationWindowStartedAt, null); |
| | 19 | 1282 | | Accept(person, x => x.ReauthenticationPausedUntil, null); |
| | 19 | 1283 | | Accept(person, x => x.AccountEmailsSent, 0); |
| | 19 | 1284 | | Accept(person, x => x.AccountEmailWindowEndsAt, null); |
| | 19 | 1285 | | Accept(person, x => x.AccountEmailLastSentAt, null); |
| | 19 | 1286 | | Accept(person, x => x.EmailVerified, false); |
| | 19 | 1287 | | Accept(person, x => x.FailedLoginAttempts, 0); |
| | 19 | 1288 | | Accept(person, x => x.LockedOutUntil, null); |
| | 19 | 1289 | | Accept(person, x => x.ErasureBlockedReason, null); |
| | 19 | 1290 | | Accept(person, x => x.AnonymisedAt, at); |
| | 19 | 1291 | | Accept(person, x => x.UpdatedAt, at); |
| | 19 | 1292 | | } |
| | | 1293 | | |
| | | 1294 | | /// <summary> |
| | | 1295 | | /// After a refused or rolled-back <see cref="TryChangeEmailAndRoleAsync" />, drops whatever the |
| | | 1296 | | /// caller had staged on its tracked entities — added rows, removed rows, changed columns — so |
| | | 1297 | | /// the next save in the same unit of work, the audit entry's among them, cannot write part of a |
| | | 1298 | | /// change that was refused. |
| | | 1299 | | /// </summary> |
| | | 1300 | | private void DiscardPendingChanges() |
| | | 1301 | | { |
| | 16 | 1302 | | foreach (var entry in context.ChangeTracker.Entries().ToList()) |
| | | 1303 | | { |
| | 5 | 1304 | | switch (entry.State) |
| | | 1305 | | { |
| | | 1306 | | case EntityState.Added: |
| | | 1307 | | case EntityState.Deleted: |
| | 0 | 1308 | | entry.State = EntityState.Detached; |
| | 0 | 1309 | | break; |
| | | 1310 | | case EntityState.Modified: |
| | 0 | 1311 | | entry.State = EntityState.Unchanged; |
| | | 1312 | | break; |
| | | 1313 | | } |
| | | 1314 | | } |
| | 3 | 1315 | | } |
| | | 1316 | | |
| | | 1317 | | /// <summary> |
| | | 1318 | | /// The row <paramref name="person" /> was read from, if it still holds the address it was |
| | | 1319 | | /// read with and is not deleted, restricted or anonymised: the condition a single-use token |
| | | 1320 | | /// is redeemed under (FR-PR-08, FR-EV-08). The address is captured now, so the comparison is |
| | | 1321 | | /// against the value the caller read, not whatever the row holds by the time it runs. |
| | | 1322 | | /// </summary> |
| | | 1323 | | private static Expression<Func<Person, bool>> RedeemableAsRead(Person person) |
| | | 1324 | | { |
| | 32 | 1325 | | var id = person.Id; |
| | 32 | 1326 | | var email = person.Email; |
| | | 1327 | | |
| | 32 | 1328 | | return x => x.Id == id && x.Email == email && !x.IsDeleted && |
| | 32 | 1329 | | x.ProcessingRestrictedAt == null && x.AnonymisedAt == null; |
| | | 1330 | | } |
| | | 1331 | | |
| | | 1332 | | /// <summary> |
| | | 1333 | | /// Writes the person's row without changing it, after a factor reservation was refused. |
| | | 1334 | | /// </summary> |
| | | 1335 | | /// <remarks> |
| | | 1336 | | /// A refused reservation's <c>UPDATE</c> matches no row, so PostgreSQL assigns it no transaction |
| | | 1337 | | /// and flushes no commit, and it answers measurably sooner than an admitted one. That would |
| | | 1338 | | /// tell a caller the second factor is locked, or re-authentication paused, without a word of |
| | | 1339 | | /// the answer differing (FR-AU-12, FR-AU-13). Setting a column to itself writes a new row |
| | | 1340 | | /// version and commits like the admitted write does; what remains is one more round trip. |
| | | 1341 | | /// </remarks> |
| | | 1342 | | private Task TouchAsync(Person person) => |
| | 20 | 1343 | | context.Persons |
| | 20 | 1344 | | .Where(x => x.Id == person.Id) |
| | 40 | 1345 | | .ExecuteUpdateAsync(set => set.SetProperty(x => x.FailedSecondFactorAttempts, x => x.FailedSecondFactorAttem |
| | | 1346 | | |
| | | 1347 | | /// <summary> |
| | | 1348 | | /// The value <see cref="TryReserveSecondFactorAttemptAsync" /> writes to the lock: unchanged, |
| | | 1349 | | /// unless this reservation reaches <paramref name="maxAttempts" />, and then the entry of |
| | | 1350 | | /// <paramref name="lockedOutUntil" /> the stored lockout count selects — a <c>CASE</c> over the |
| | | 1351 | | /// count, with the last entry for every count from its own on. |
| | | 1352 | | /// </summary> |
| | | 1353 | | /// <remarks> |
| | | 1354 | | /// Built as an expression tree because the number of entries is the caller's. Each end is read |
| | | 1355 | | /// from a box rather than inlined, so EF Core sends it as a parameter, and the statement — and |
| | | 1356 | | /// its cached plan — is the same on every call. |
| | | 1357 | | /// </remarks> |
| | | 1358 | | private static Expression<Func<Person, DateTime?>> SecondFactorLockEnd( |
| | | 1359 | | int maxAttempts, IReadOnlyList<DateTime> lockedOutUntil) |
| | | 1360 | | { |
| | 54 | 1361 | | var row = Expression.Parameter(typeof(Person), "x"); |
| | 54 | 1362 | | var lockouts = Expression.Property(row, nameof(Person.SecondFactorLockouts)); |
| | | 1363 | | |
| | 54 | 1364 | | Expression end = Boxed(lockedOutUntil[^1]); |
| | | 1365 | | |
| | 864 | 1366 | | for (var lockout = lockedOutUntil.Count - 2; lockout >= 0; lockout--) |
| | | 1367 | | { |
| | 378 | 1368 | | end = Expression.Condition( |
| | 378 | 1369 | | Expression.Equal(lockouts, Expression.Constant(lockout)), Boxed(lockedOutUntil[lockout]), end); |
| | | 1370 | | } |
| | | 1371 | | |
| | 54 | 1372 | | var reachesLimit = Expression.GreaterThanOrEqual( |
| | 54 | 1373 | | Expression.Add(Expression.Property(row, nameof(Person.FailedSecondFactorAttempts)), Expression.Constant(1)), |
| | 54 | 1374 | | Boxed(maxAttempts)); |
| | | 1375 | | |
| | 54 | 1376 | | return Expression.Lambda<Func<Person, DateTime?>>( |
| | 54 | 1377 | | Expression.Condition(reachesLimit, end, Expression.Property(row, nameof(Person.SecondFactorLockedOutUntil))) |
| | 54 | 1378 | | row); |
| | | 1379 | | } |
| | | 1380 | | |
| | | 1381 | | /// <summary>The lock end <see cref="SecondFactorLockEnd" /> selects, for the instance.</summary> |
| | | 1382 | | private static DateTime LockEndAfter(int lockouts, IReadOnlyList<DateTime> lockedOutUntil) => |
| | 4 | 1383 | | lockouts >= 0 && lockouts < lockedOutUntil.Count - 1 ? lockedOutUntil[lockouts] : lockedOutUntil[^1]; |
| | | 1384 | | |
| | | 1385 | | private static MemberExpression Boxed(DateTime value) => |
| | 432 | 1386 | | Expression.Field(Expression.Constant(new StrongBox<DateTime?>(value)), nameof(StrongBox<DateTime?>.Value)); |
| | | 1387 | | |
| | | 1388 | | private static MemberExpression Boxed(int value) => |
| | 54 | 1389 | | Expression.Field(Expression.Constant(new StrongBox<int>(value)), nameof(StrongBox<int>.Value)); |
| | | 1390 | | |
| | | 1391 | | /// <summary> |
| | | 1392 | | /// Brings the caller's instance in line with a write the change tracker did not see: the new |
| | | 1393 | | /// value becomes both current and original, so the property is not saved again later. |
| | | 1394 | | /// </summary> |
| | | 1395 | | private void Accept<T, TProperty>(T entity, Expression<Func<T, TProperty>> property, TProperty value) |
| | | 1396 | | where T : class |
| | | 1397 | | { |
| | 2197 | 1398 | | var entry = context.Entry(entity); |
| | 2197 | 1399 | | var member = entry.Property(property); |
| | | 1400 | | |
| | 2197 | 1401 | | member.CurrentValue = value; |
| | | 1402 | | |
| | 2197 | 1403 | | if (entry.State is EntityState.Unchanged or EntityState.Modified) |
| | | 1404 | | { |
| | 2197 | 1405 | | member.OriginalValue = value; |
| | 2197 | 1406 | | member.IsModified = false; |
| | | 1407 | | } |
| | 2197 | 1408 | | } |
| | | 1409 | | } |