Example #1
0
        public async Task <ActionResult> VerifyLogin([FromBody] AuthUserResource resource)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return(BadRequest(ModelState.GetErrorMessages()));
                }

                var user   = _mapper.Map <AuthUserResource, User>(resource);
                var result = await _userService.FirstOrDefaultAsync(user.Login, user.Password);

                if (result == null)
                {
                    return(BadRequest("Erro ao tentar realizar o login."));
                }

                var token = CryptoFunctions.GenerateToken(_configuration, user);

                return(Ok(new
                {
                    error = false,
                    result = new
                    {
                        token,
                        user = new { user.Id, user.Login }
                    }
                }));
            }
            catch (Exception ex)
            {
                var message = "Erro ao tentar realizar o login.";
                return(BadRequest(new { error = true, result = new { message } }));
            }
        }
Example #2
0
        public async Task Put_NewMetadataTypeAndTag_GetByName_EndpointsReturnSuccess_CorrectContentType(string url)
        {
            // Arrange

            var             client          = _factory.CreateDefaultClient();
            NewUserResource newUserResource = new NewUserResource();

            newUserResource.Mail     = "*****@*****.**";
            newUserResource.Password = "******";
            newUserResource.UserType = UserType.Municipality;
            await client.PutAsync("api/user", ResponseSerializer.Serialize(newUserResource));

            AuthUserResource loginResource = new AuthUserResource();

            loginResource.Mail     = newUserResource.Mail;
            loginResource.Password = newUserResource.Password;
            var loginResponse = await client.PostAsync("/api/user/auth", ResponseSerializer.Serialize(loginResource));

            Assert.NotNull(loginResponse.Content);
            var user = ResponseSerializer.Extract <PrivateSafeUserResource>(loginResponse);

            Assert.Equal(loginResource.Mail, user.Mail);
            string token = user.Token;

            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);


            var newCategory = new SaveMetadataCategoryResource {
                ParentUuid = null, Name = "Test Category"
            };
            var newCategoryResponse = await client.PutAsync("api/metadatacategory", ResponseSerializer.Serialize(newCategory));

            newCategoryResponse.EnsureSuccessStatusCode();

            var category = ResponseSerializer.Extract <MetadataCategory>(newCategoryResponse);

            SaveMetadataTypeResource newMetadataTypeResource = new SaveMetadataTypeResource
            {
                CategoryUuid = category.Uuid,
                Name         = "Test"
            };

            // Act

            var metadataTypeResponse = await client.PutAsync(url, ResponseSerializer.Serialize(newMetadataTypeResource));

            var metadataType = ResponseSerializer.Extract <MetadataTypeResource>(metadataTypeResponse);

            var responseForGetByName = await client.GetAsync(url + "/" + metadataType.Uuid);

            // Assert

            metadataTypeResponse.EnsureSuccessStatusCode(); // Status Code 200-299
            Assert.Equal("application/json; charset=utf-8",
                         metadataTypeResponse.Content.Headers.ContentType.ToString());

            responseForGetByName.EnsureSuccessStatusCode(); // Status Code 200-299
            Assert.Equal("application/json; charset=utf-8",
                         responseForGetByName.Content.Headers.ContentType.ToString());
        }
Example #3
0
        public async Task Post_UserSignIn_EndpointsReturnSuccess_CorrectContentType(string url)
        {
            // Arrange

            var             client          = _factory.CreateDefaultClient();
            NewUserResource newUserResource = new NewUserResource();

            newUserResource.Mail     = "*****@*****.**";
            newUserResource.Password = "******";

            // Act

            await client.PutAsync("api/user", new StringContent(JsonSerializer.Serialize(newUserResource), Encoding.UTF8, "application/json"));

            AuthUserResource resource = new AuthUserResource();

            resource.Mail     = newUserResource.Mail;
            resource.Password = newUserResource.Password;
            var response = await client.PostAsync(url, new StringContent(JsonSerializer.Serialize(resource), Encoding.UTF8, "application/json"));

            Assert.NotNull(response.Content);
            var user = ResponseSerializer.Extract <PrivateSafeUserResource>(response);

            Assert.Equal(resource.Mail, user.Mail);

            // Assert

            response.EnsureSuccessStatusCode(); // Status Code 200-299
            Assert.Equal("application/json; charset=utf-8",
                         response.Content.Headers.ContentType.ToString());
        }
Example #4
0
        public async Task Get_EndpointsReturnSuccess_CorrectContentType(string url)
        {
            // Arrange

            var             client          = _factory.CreateDefaultClient();
            NewUserResource newUserResource = new NewUserResource();

            newUserResource.Mail     = "*****@*****.**";
            newUserResource.Password = "******";

            // Act

            await client.PutAsync("api/user", new StringContent(JsonSerializer.Serialize(newUserResource), Encoding.UTF8, "application/json"));

            AuthUserResource loginResource = new AuthUserResource();

            loginResource.Mail     = newUserResource.Mail;
            loginResource.Password = newUserResource.Password;
            var loginResponse = await client.PostAsync("/api/user/auth", new StringContent(JsonSerializer.Serialize(loginResource), Encoding.UTF8, "application/json"));

            Assert.NotNull(loginResponse.Content);
            var user = ResponseSerializer.Extract <PrivateSafeUserResource>(loginResponse);

            Assert.Equal(loginResource.Mail, user.Mail);
            string token = user.Token;

            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
            var response = await client.GetAsync(url);

            // Assert

            response.EnsureSuccessStatusCode(); // Status Code 200-299
            Assert.Equal("application/json; charset=utf-8",
                         response.Content.Headers.ContentType.ToString());
        }
Example #5
0
        public async Task <IActionResult> Authenticate([FromBody] AuthUserResource authUserResource)
        {
            User user = await usersService.AuthenticateAsync(authUserResource.Mail, authUserResource.Password);

            if (user == null)
            {
                return(Unauthorized(new { message = "Incorrect mail or password" }));
            }

            PrivateSafeUserResource privateSafeUser = mapper.Map <User, PrivateSafeUserResource>(user);

            return(Ok(privateSafeUser));
        }
Example #6
0
        public async Task FetchDescriptionsTest()
        {
            var client = _factory.CreateDefaultClient();

            NewUserResource newUserResource = new NewUserResource();

            newUserResource.Mail     = "*****@*****.**";
            newUserResource.Password = "******";
            newUserResource.UserType = UserType.Municipality;
            await client.PutAsync("api/user", ResponseSerializer.Serialize(newUserResource));

            AuthUserResource loginResource = new AuthUserResource();

            loginResource.Mail     = newUserResource.Mail;
            loginResource.Password = newUserResource.Password;
            var loginResponse = client.PostAsync("/api/user/auth", ResponseSerializer.Serialize(loginResource)).Result;

            Assert.NotNull(loginResponse.Content);
            var user = ResponseSerializer.Extract <PrivateSafeUserResource>(loginResponse);

            Assert.Equal(loginResource.Mail, user.Mail);
            string token = user.Token;

            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);


            var newCategory = new SaveMetadataCategoryResource {
                ParentUuid = null, Name = "Super Category"
            };
            var newCategoryResponse = await client.PutAsync("api/metadatacategory", ResponseSerializer.Serialize(newCategory));

            newCategoryResponse.EnsureSuccessStatusCode();

            var category = ResponseSerializer.Extract <MetadataCategory>(newCategoryResponse);

            SaveMetadataTypeResource newMetadataTypeResource = new SaveMetadataTypeResource {
                CategoryUuid = category.Uuid, Name = "Super MetadataType"
            };
            var newMetadataTypeResponse = await client.PutAsync("api/metadatatype", ResponseSerializer.Serialize(newMetadataTypeResource));

            newMetadataTypeResponse.EnsureSuccessStatusCode();
            var metadataType = ResponseSerializer.Extract <MetadataTypeResource>(newMetadataTypeResponse);

            var fetchDescriptionsResponse = await client.GetAsync("api/metadatatype/" + metadataType.Uuid + "/description");

            fetchDescriptionsResponse.EnsureSuccessStatusCode();
        }
Example #7
0
        public async Task <AuthenticationResponse> Authenticate(Authenticate authModel)
        {
            if (string.IsNullOrEmpty(authModel.Username))
            {
                return(new AuthenticationResponse("Username cannot be empty"));
            }
            else if (string.IsNullOrEmpty(authModel.Password))
            {
                return(new AuthenticationResponse("Password cannot be empty"));
            }
            else
            {
                var user = await this.userRepository.Authenticate(authModel);

                if (user == null)
                {
                    return(new AuthenticationResponse("Username or password is incorrect"));
                }
                //Create authentication token.
                var tokenHandler    = new JwtSecurityTokenHandler();
                var key             = Encoding.ASCII.GetBytes(this.appSettings.Secret);
                var tokenDescriptor = new SecurityTokenDescriptor
                {
                    Subject = new ClaimsIdentity(new Claim[]
                    {
                        new Claim(ClaimTypes.Name, user.UserID.ToString())
                    }),
                    Expires            = DateTime.UtcNow.AddDays(7),
                    SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
                };
                var token       = tokenHandler.CreateToken(tokenDescriptor);
                var tokenString = tokenHandler.WriteToken(token);

                //By right should use AutoMapper but i don't want to blur the lies between them.
                AuthUserResource authUser = new AuthUserResource();
                authUser.UserID     = user.UserID;
                authUser.Username   = user.Username;
                authUser.FirstName  = user.FirstName;
                authUser.Address    = user.Address;
                authUser.PostalCode = user.PostalCode;
                authUser.LastName   = user.LastName;
                authUser.Token      = tokenString;

                return(new AuthenticationResponse(authUser));
            }
        }
Example #8
0
        public async Task Put_NewMunicipalityUser_EndpointsReturnSuccess_CorrectContentType(string url)
        {
            // Arrange

            var             client   = _factory.CreateDefaultClient();
            NewUserResource resource = new NewUserResource();

            resource.Mail     = "*****@*****.**";
            resource.Password = "******";
            resource.UserType = UserType.Municipality;

            // Act

            var response = await client.PutAsync(url, new StringContent(JsonSerializer.Serialize(resource), Encoding.UTF8, "application/json"));

            AuthUserResource loginResource = new AuthUserResource();

            loginResource.Mail     = resource.Mail;
            loginResource.Password = resource.Password;
            var loginResponse = await client.PostAsync("/api/user/auth", new StringContent(JsonSerializer.Serialize(loginResource), Encoding.UTF8, "application/json"));

            Assert.NotNull(loginResponse.Content);
            var user = ResponseSerializer.Extract <PrivateSafeUserResource>(loginResponse);

            Assert.Equal(loginResource.Mail, user.Mail);

            // Assert

            Assert.NotEqual(UserType.Standard, user.UserType);
            Assert.NotEqual(UserType.Admin, user.UserType);
            Assert.Equal(UserType.Municipality, user.UserType);
            Assert.Equal("Test", user.MunicipalityName);
            response.EnsureSuccessStatusCode(); // Status Code 200-299
            Assert.Equal("application/json; charset=utf-8",
                         response.Content.Headers.ContentType.ToString());
        }
Example #9
0
        public async Task PutCommentsAndReplyToCommentTest()
        {
            var client = _factory.CreateDefaultClient();

            NewUserResource newUserResource = new NewUserResource();

            newUserResource.Mail     = "*****@*****.**";
            newUserResource.Password = "******";
            newUserResource.UserType = UserType.Municipality;
            await client.PutAsync("api/user", ResponseSerializer.Serialize(newUserResource));

            AuthUserResource loginResource = new AuthUserResource();

            loginResource.Mail     = newUserResource.Mail;
            loginResource.Password = newUserResource.Password;
            var loginResponse = client.PostAsync("/api/user/auth", ResponseSerializer.Serialize(loginResource)).Result;

            Assert.NotNull(loginResponse.Content);
            var user = ResponseSerializer.Extract <PrivateSafeUserResource>(loginResponse);

            Assert.Equal(loginResource.Mail, user.Mail);
            string token = user.Token;

            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);


            var newCategory = new SaveMetadataCategoryResource {
                ParentUuid = null, Name = "Super Category"
            };
            var newCategoryResponse = await client.PutAsync("api/metadatacategory", ResponseSerializer.Serialize(newCategory));

            newCategoryResponse.EnsureSuccessStatusCode();

            var category = ResponseSerializer.Extract <MetadataCategory>(newCategoryResponse);

            SaveMetadataTypeResource newMetadataTypeResource = new SaveMetadataTypeResource {
                CategoryUuid = category.Uuid, Name = "Super MetadataType"
            };
            var newMetadataTypeResponse = await client.PutAsync("api/metadatatype", ResponseSerializer.Serialize(newMetadataTypeResource));

            newMetadataTypeResponse.EnsureSuccessStatusCode();
            var metadataType = ResponseSerializer.Extract <MetadataTypeResource>(newMetadataTypeResponse);

            SaveMetadataResource saveMetadata = new SaveMetadataResource {
                Description      = "Test",
                MetadataTypeUuid = metadataType.Uuid,
                MunicipalityName = user.MunicipalityName,
                ReleaseState     = EReleaseState.Green
            };

            var newMetadataResponse = await client.PutAsync("api/metadata/", ResponseSerializer.Serialize(saveMetadata));

            newMetadataResponse.EnsureSuccessStatusCode();
            var metadata = ResponseSerializer.Extract <MetadataResource>(newMetadataResponse);

            var newComment = new NewCommentResource {
                Content = "Well hello there!"
            };
            var putCommentResponse = await client.PutAsync("api/comment/metadata/" + metadata.Uuid, ResponseSerializer.Serialize(newComment));

            putCommentResponse.EnsureSuccessStatusCode();
            var comment = ResponseSerializer.Extract <CommentResource>(putCommentResponse);

            Assert.Equal(newComment.Content, comment.Content);
            Assert.Equal(user.Mail, comment.UserMail);

            var newReplyComment = new NewCommentResource {
                Content = "Well, well, well hello there!"
            };

            var replyCommentResponse = await client.PutAsync("api/comment/reply/" + comment.Uuid, ResponseSerializer.Serialize(newReplyComment));

            replyCommentResponse.EnsureSuccessStatusCode();
            var replyComment = ResponseSerializer.Extract <CommentResource>(replyCommentResponse);

            Assert.Equal(comment.Uuid, replyComment.ParentCommentUuid);
            Assert.Equal(newReplyComment.Content, replyComment.Content);
            Assert.Equal(user.Mail, replyComment.UserMail);

            var newExperiencePost = new SaveExperiencePostResource {
                Title    = "Big Test",
                Contents = "Test"
            };
            var newExperiencePostResponse = await client.PutAsync("api/metadata/" + metadata.Uuid + "/experience", ResponseSerializer.Serialize(newExperiencePost));

            newExperiencePostResponse.EnsureSuccessStatusCode();
            var experiencePost = ResponseSerializer.Extract <ExperiencePostResource>(newExperiencePostResponse);

            var newCommentExperiencePost = new NewCommentResource {
                Content = "Well hello there experience!"
            };
            var putCommentExperiencePost = await client.PutAsync("api/comment/experiencepost/" + experiencePost.Uuid, ResponseSerializer.Serialize(newCommentExperiencePost));

            putCommentExperiencePost.EnsureSuccessStatusCode();
            var commentExperiencePost = ResponseSerializer.Extract <CommentResource>(putCommentExperiencePost);

            Assert.Equal(newCommentExperiencePost.Content, commentExperiencePost.Content);
            Assert.Equal(user.Mail, commentExperiencePost.UserMail);
        }
Example #10
0
 /// <summary>
 /// Creates a success response.
 /// </summary>
 /// <param name="Authenticate response"></param>
 /// <returns>Response.</returns>
 public AuthenticationResponse(AuthUserResource user) : this(true, string.Empty, user)
 {
 }
Example #11
0
 public AuthenticationResponse(bool success, string message, AuthUserResource user) : base(success, message)
 {
     this.User = user;
 }
Example #12
0
        public async Task Put_NewReleasedMetaData_NewDataSource_GetMetaData_GetMetaDataLike_AttachExperiencePost_EndpointsReturnSuccess_CorrectContentType()
        {
            // Arrange

            var             client          = _factory.CreateDefaultClient();
            NewUserResource newUserResource = new NewUserResource();

            newUserResource.Mail     = "*****@*****.**";
            newUserResource.Password = "******";
            newUserResource.UserType = UserType.Municipality;
            await client.PutAsync("api/user", new StringContent(JsonSerializer.Serialize(newUserResource), Encoding.UTF8, "application/json"));

            AuthUserResource loginResource = new AuthUserResource();

            loginResource.Mail     = newUserResource.Mail;
            loginResource.Password = newUserResource.Password;
            var loginResponse = await client.PostAsync("/api/user/auth", new StringContent(JsonSerializer.Serialize(loginResource), Encoding.UTF8, "application/json"));

            Assert.NotNull(loginResponse.Content);
            var user = ResponseSerializer.Extract <PrivateSafeUserResource>(loginResponse);

            Assert.Equal(loginResource.Mail, user.Mail);
            string token = user.Token;

            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);

            SaveMetadataResource metaDataResource = new SaveMetadataResource();

            metaDataResource.Description      = "Test Description";
            metaDataResource.MunicipalityName = "Test";
            metaDataResource.ReleaseState     = EReleaseState.Released;

            // Act

            var metaDataResponse = await client.PutAsync("/api/metadata", new StringContent(JsonSerializer.Serialize(metaDataResource), Encoding.UTF8, "application/json"));

            var metadata = ResponseSerializer.Extract <Metadata>(metaDataResponse);

            var metaDataGetResponse = await client.GetAsync("/api/metadata/" + metadata.Uuid);

            var metaDataLikeGetResponse = await client.GetAsync("/api/metadata/" + metadata.Uuid + "/like");

            Assert.Equal(user.MunicipalityName, metadata.MunicipalityName);

            SaveExperiencePostResource experiencePostResource = new SaveExperiencePostResource();
            var experienceResponse = await client.PutAsync("/api/metadata/" + metadata.Uuid + "/experience", new StringContent(JsonSerializer.Serialize(experiencePostResource), Encoding.UTF8, "application/json"));

            NewDataFormatResource dataFormatResource = new NewDataFormatResource();

            dataFormatResource.Name             = "Name of this dataformat";
            dataFormatResource.Description      = "Describing this dataformat";
            dataFormatResource.DocumentationUrl = "this URL";
            dataFormatResource.MimeType         = "this MimeType";
            var dataFormatResponse = await client.PutAsync("/api/dataformat", new StringContent(JsonSerializer.Serialize(dataFormatResource), Encoding.UTF8, "application/json"));

            var dataformat = ResponseSerializer.Extract <DataFormat>(dataFormatResponse);

            NewDataSourceResource dataSourceResource = new NewDataSourceResource();

            dataSourceResource.MetadataUuid       = metadata.Uuid;
            dataSourceResource.Url                = "This cool url";
            dataSourceResource.Description        = "Some test source";
            dataSourceResource.StartDate          = System.DateTime.MinValue;
            dataSourceResource.EndDate            = System.DateTime.MaxValue;
            dataSourceResource.DataFormatMimeType = dataformat.MimeType;
            Assert.NotEqual(dataSourceResource.StartDate, dataSourceResource.EndDate);

            var dataSourceResponse = await client.PutAsync("/api/metadata/url", new StringContent(JsonSerializer.Serialize(dataSourceResource), Encoding.UTF8, "application/json"));

            // Assert

            metaDataResponse.EnsureSuccessStatusCode(); // Status Code 200-299
            Assert.Equal("application/json; charset=utf-8",
                         metaDataResponse.Content.Headers.ContentType.ToString());

            metaDataGetResponse.EnsureSuccessStatusCode(); // Status Code 200-299
            Assert.Equal("application/json; charset=utf-8",
                         metaDataGetResponse.Content.Headers.ContentType.ToString());

            metaDataLikeGetResponse.EnsureSuccessStatusCode(); // Status Code 200-299
            Assert.Equal("application/json; charset=utf-8",
                         metaDataLikeGetResponse.Content.Headers.ContentType.ToString());

            experienceResponse.EnsureSuccessStatusCode(); // Status Code 200-299
            Assert.Equal("application/json; charset=utf-8",
                         experienceResponse.Content.Headers.ContentType.ToString());

            dataSourceResponse.EnsureSuccessStatusCode(); // Status Code 200-299
            Assert.Equal("application/json; charset=utf-8",
                         dataSourceResponse.Content.Headers.ContentType.ToString());
        }