Example #1
0
        public async Task <IActionResult> SignUp([FromBody] UserCredentialsDto userCredentials)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            const byte hashLength = 128;
            string     trimmedEmail = userCredentials.UserMail?.Trim().ToLower(), trimmedPasswordHash = userCredentials.UserPasswordHash?.Trim().ToUpper();

            if ((trimmedEmail == null) || (trimmedPasswordHash == null) || (trimmedEmail.Length == 0) || (trimmedPasswordHash.Length != hashLength))
            {
                return(BadRequest("Illegal register data"));
            }

            using (var transaction = _context.Database.BeginTransaction())
            {
                /*
                 *  Exception is throwed if using just Any(Async):
                 *      System.InvalidOperationException: "No coercion operator is defined between types 'System.Int16' and 'System.Boolean'."
                 *  Seems to be Oracle connector problem
                 */
                if (await _context.UserCredentials.ToAsyncEnumerable().Any((creds) => creds.UserMail == trimmedEmail))
                {
                    return(BadRequest("Email already exists"));
                }

                Role newUserRole = await _context.Roles.Where((role) => role.RoleAlias == "user").FirstOrDefaultAsync();

                if (newUserRole == null)
                {
                    throw new Exception("Error creating user: no needed role");
                }

                User newUser = (await _context.Users.AddAsync(new User {
                    RoleId = newUserRole.RoleId
                })).Entity;
                newUser.Role            = newUserRole;
                newUser.UserCredentials = (await _context.UserCredentials.AddAsync(new UserCredentials {
                    UserId = newUser.UserId, UserMail = trimmedEmail, UserPasswordHash = trimmedPasswordHash
                })).Entity;

                await _context.SaveChangesAsync();

                transaction.Commit();

                await Authenticate(newUser);

                return(Created(nameof(SignUp), new UserDto(newUser, false)));
            }
        }
        public async Task <IActionResult> AddRecognitionRequestWithMultiplePhotos([FromBody] RecognitionRequestWithMultiplePhotosDto recognitionRequest)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            using (var transaction = _context.Database.BeginTransaction())
            {
                if (!IsRequestCorrect(recognitionRequest))
                {
                    return(BadRequest("Request is incorrect"));
                }

                RecognitionRequest request = (await _context.RecognitionRequests.AddAsync(new RecognitionRequest()
                {
                    StatusId = (await _context.RecognitionStatuses.SingleAsync((status) => status.StatusAlias == recognitionRequest.RecognitionStatus.RecognitionStatusAlias)).StatusId,
                    EdibleStatusId = (recognitionRequest.EdibleStatus == null
                        ? null : await _context.EdibleStatuses.SingleOrDefaultAsync((status) => status.EdibleStatusAlias == recognitionRequest.EdibleStatus.EdibleStatusAlias))?.EdibleStatusId,
                    RequestDatetime = recognitionRequest.RequestDatetime.Value,
                    RequesterId = (await _context.UserCredentials.SingleAsync((creds) => creds.UserMail == User.Identity.Name)).UserId
                })).Entity;

                List <Task> photoAdditionTasks = new List <Task>(recognitionRequest.RequestPhotos.Length);
                foreach (RequestPhotoDto photo in recognitionRequest.RequestPhotos)
                {
                    photoAdditionTasks.Add(_context.RequestPhotos.AddAsync(new RequestPhoto {
                        RequestId = request.RequestId, PhotoFilename = new RequestPhotoSaver().SavePhoto(photo.PhotoData, photo.PhotoExtension)
                    }));
                }
                await Task.WhenAll(photoAdditionTasks);

                await _context.SaveChangesAsync();

                transaction.Commit();
                return(CreatedAtAction(nameof(AddRecognitionRequestWithMultiplePhotos), new RecognitionRequestWithMultiplePhotosDto(request)));
            }
        }
        public async Task <IActionResult> AddArticle([FromBody] ArticleDto article)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (!User.IsInRole("admin"))
            {
                return(Forbid());
            }

            string articleText = article.ArticleText;

            if (articleText == null)
            {
                return(BadRequest("You should specify article text"));
            }

            string articleTitle = article.ArticleTitle;

            if (articleTitle == null)
            {
                return(BadRequest("You should specify article title"));
            }

            if ((article.GpsTags == null) || (article.GpsTags.Length == 0))
            {
                return(BadRequest("Article should specify at least one place"));
            }

            foreach (GpsTagDto tag in article.GpsTags)
            {
                if (!tag.LatitudeSeconds.HasValue || !tag.LongitudeSeconds.HasValue)
                {
                    return(BadRequest(("Place in unspecified", tag)));
                }
                if ((Math.Abs(tag.LatitudeSeconds.Value) > MaxLatitudeSeconds) || (Math.Abs(tag.LongitudeSeconds.Value) > MaxLongitudeSeconds))
                {
                    return(BadRequest(("Not existing place", tag)));
                }
            }

            using (var transaction = _context.Database.BeginTransaction())
            {
                var newArticle = (await _context.Articles.AddAsync(new Article {
                    ArticleText = articleText, ArticleTitle = articleTitle
                })).Entity;

                List <Task> articleTagAddTasks = new List <Task>(article.GpsTags.Length);
                foreach (GpsTagDto tagDto in article.GpsTags)
                {
                    int dbTagId = (await _context.GpsTags.SingleOrDefaultAsync((tag) => (tag.LatitudeSeconds == tagDto.LatitudeSeconds.Value) && (tag.LongitudeSeconds == tagDto.LongitudeSeconds.Value))
                                   ?? (await _context.GpsTags.AddAsync(new GpsTag {
                        LatitudeSeconds = tagDto.LatitudeSeconds.Value, LongitudeSeconds = tagDto.LongitudeSeconds.Value
                    })).Entity).TagId;

                    articleTagAddTasks.Add(_context.AddAsync(new ArticleGpsTag {
                        ArticleId = newArticle.ArticleId, TagId = dbTagId
                    }));
                }

                await Task.WhenAll(articleTagAddTasks);

                await _context.SaveChangesAsync();

                transaction.Commit();

                return(Ok(new ArticleDto(newArticle)));
            }
        }