示例#1
0
        /// <summary>
        /// Creates a new server.
        /// </summary>
        /// <param name="createServerDto">The creation request data.</param>
        /// <param name="owner">The user creating the server.</param>
        /// <returns>The result of the creation.</returns>
        public async Task <CreateServerResult> CreateServerAsync(CreateServerDto createServerDto, ApplicationUser owner)
        {
            var validationResult = AnnotationValidator.TryValidate(createServerDto);

            if (validationResult.Failed)
            {
                return(CreateServerResult.Fail(validationResult.Error.ToErrorList()));
            }

            var server   = new Server(createServerDto.Name, createServerDto.PrivacyLevel, createServerDto.Description);
            var category = Category.CreateDefaultWelcomeCategory(server);

            server.Categories.Add(category);
            server.Members.Add(owner);

            var adminRole = ServerRole.CreateDefaultAdminRole(server);

            await _serverRepository.InsertAsync(server);

            await _serverRoleRepository.InsertAsync(adminRole);

            await _userRoleRepository.InsertAsync(new IdentityUserRole <Guid>
            {
                UserId = owner.Id,
                RoleId = adminRole.Id
            });

            await _serverRepository.CommitAsync();

            return(CreateServerResult.Ok(server));
        }
示例#2
0
        public async Task <IActionResult> Register([FromBody] CreateAccountDto createAccountDto)
        {
            try
            {
                var validationResult = AnnotationValidator.TryValidate(createAccountDto);

                if (validationResult.Failed)
                {
                    return(BadRequest(validationResult.Error.ToErrorList()));
                }

                var user = new ApplicationUser
                {
                    Email          = createAccountDto.Email,
                    UserName       = createAccountDto.Email,
                    DisplayName    = createAccountDto.DisplayName,
                    Tag            = await _accountService.GenerateDiscriminatorTagAsync(createAccountDto.DisplayName),
                    EmailConfirmed = false,
                    CreatedAt      = DateTime.UtcNow
                };

                var result = await _userManager.CreateAsync(user, createAccountDto.Password);

                if (!result.Succeeded)
                {
                    return(BadRequest(result.Errors.ToErrorList()));
                }

                var mailToken = await _userManager.GenerateEmailConfirmationTokenAsync(user);

                var confirmationUrl = Url.Link("ConfirmEmail", new { token = mailToken, id = user.Id });
                await _mailProvider.SendMailAsync(
                    user.Email,
                    "Agree - Welcome",
                    $"<html><body>Welcome to Agree! Please click <a href=\"{confirmationUrl}\">HERE</a> to confirm your email.</body></html>");

                await _signInManager.SignInAsync(user, false);

                var userViewModel = ApplicationUserViewModel.FromEntity(user);

                var token = await _tokenService.GenerateAccessTokenAsync(user);

                await _signInManager.SignInAsync(user, false);

                Response.Cookies.Append(AccessTokenCookieName, token.Token, new CookieOptions
                {
                    HttpOnly = true,
                    SameSite = SameSiteMode.Strict
                });

                return(Created(
                           Url.Link("GetAccountById", new { Id = user.Id }),
                           new RegisterResponse(userViewModel)));
            }
            catch
            {
                return(InternalServerError());
            }
        }
示例#3
0
        public AnnotationValidatorTests()
        {
            var _options = new ValidationOptions();

            _options.AnnotationEnabled        = true;
            _options.FailureIfProjectNotMatch = false;
            AnnotationValidator = AnnotationValidator.GetInstance(_options);
        }
示例#4
0
        public async Task <FriendshipRequestResult> SendFriendshipRequest(SendFriendshipRequestDto friendshipRequestDto)
        {
            var validationResult = AnnotationValidator.TryValidate(friendshipRequestDto);

            if (validationResult.Failed)
            {
                if (friendshipRequestDto.From.NameTag == friendshipRequestDto.ToNameTag)
                {
                    return(FriendshipRequestResult.Fail(validationResult.Error.ToErrorList().AddError("ToNameTag", "Cannot send a friendship request to yourself.")));
                }
                return(FriendshipRequestResult.Fail(validationResult.Error.ToErrorList()));
            }

            if (friendshipRequestDto.From.NameTag == friendshipRequestDto.ToNameTag)
            {
                return(FriendshipRequestResult.Fail(new ErrorList().AddError("ToNameTag", "Cannot send a friendship request to yourself.")));
            }

            var nameTag     = friendshipRequestDto.ToNameTag.Split('#');
            var displayName = nameTag[0];
            var tag         = DiscriminatorTag.Parse(nameTag[1]);
            var toUser      = await _accountRepository.GetFirstAsync(new NameTagEqualSpecification(tag, displayName));

            if (toUser == null)
            {
                return(FriendshipRequestResult.Fail(new ErrorList().AddError("ToNameTag", "User does not exists.")));
            }

            var isAlreadyFriend = await _friendshipRepository.GetFirstAsync(new FriendshipExistsSpecification(friendshipRequestDto.From.Id, toUser.Id));

            if (isAlreadyFriend != null)
            {
                var errorMessage = isAlreadyFriend.Accepted
                    ? "You are already friends with this user"
                    : isAlreadyFriend.FromId == friendshipRequestDto.From.Id
                        ? "You have already sent a friendship request to this user."
                        : "The user has already sent a friendship request to you.";
                return(FriendshipRequestResult.Fail(new ErrorList().AddError("Friendship", errorMessage)));
            }

            var friendship = new Friendship(friendshipRequestDto.From, toUser);

            await _friendshipRepository.InsertAsync(friendship);

            await _friendshipRepository.CommitAsync();

            return(FriendshipRequestResult.Ok(friendship));
        }
示例#5
0
        public void Test_Validation2()
        {
            var person = new Person {
                Name = "Alex"
            };

            person.Relatives = new List <Person>();
            person.Relatives.Add(new Person {
                Name = "Sofia"
            });

            var validator = new AnnotationValidator();
            var results   = validator.Validate(person).ToList();

            Assert.AreEqual(5, results.Count);
            Assert.IsTrue(!results.SingleOrDefault(result =>
                                                   result.Attribute.GetType() == typeof(RequiredAttribute) && result.Path.ToString() == "Person.NullArg").HasDefaultValue());
            Assert.IsTrue(!results.SingleOrDefault(result =>
                                                   result.Attribute.GetType() == typeof(RequiredAttribute) && result.Path.ToString() == "Person.Relatives[0].NullArg").HasDefaultValue());
            Assert.IsTrue(!results.SingleOrDefault(result =>
                                                   result.Attribute.GetType() == typeof(RequiredAttribute) && result.Path.ToString() == "Person.Relatives[0].Relatives").HasDefaultValue());

            Assert.AreEqual(2, results.Select(result => result.Attribute).OfType <CustomValidationAttribute>().Count(custom => custom.ValidatorType == typeof(PersonValidator)));
        }