示例#1
0
        public async Task <ActionResult <UserGetDto> > PostUser(UserPostDto user)
        {
            await using var transaction = await _context.Database.BeginTransactionAsync(IsolationLevel.Serializable);

            try
            {
                if (await _context.UserGroups.FindAsync(user.GroupId) == null)
                {
                    return(BadRequest());
                }

                if (!await _adminElevation.CanEnterGroup(user.GroupId))
                {
                    return(BadRequest());
                }

                if (!await _signupThrottler.IsSignupAllowed(user.Login))
                {
                    return(Conflict());
                }

                var activeState = await _context.GetActiveStateAsync();

                var hashed = _passwordHasher.Hash(user.Password);
                var entity = new User
                {
                    Login        = user.Login,
                    PasswordHash = hashed.Hash,
                    Salt         = hashed.Salt,
                    CreatedDate  = DateTime.Now,
                    GroupId      = user.GroupId,
                    StateId      = activeState.Id
                };

                _context.Users.Add(entity);
                await _context.SaveChangesAsync();

                await transaction.CommitAsync();

                return(CreatedAtAction("GetUser", new { id = entity.Id }, _mapper.Map <UserGetDto>(entity)));
            }
            catch (DBConcurrencyException e)
            {
                Console.WriteLine(e);
                return(Conflict());
            }
        }