예제 #1
0
        public HttpResponseMessage DeleteComment(int id,
            [ValueProvider(typeof(HeaderValueProviderFactory<string>))]string sessionKey)
        {
            var responseMsg = this.PerformOperationAndHandleExceptions(() =>
            {
                var context = new BookstoreContext();

                var user = context.Users.FirstOrDefault(usr => usr.SessionKey == sessionKey);
                if (user == null)
                {
                    throw new UnauthorizedAccessException("Invalid username or password");
                }

                var commentEntity = context.Comments.Include("User").SingleOrDefault(u => u.Id == id);
                if (commentEntity == null)
                {
                    throw new ServerErrorException("User does not exist.");
                }

                if (commentEntity.User.Id != user.Id)
                {
                    throw new ServerErrorException("You do not have permissions to delete other users' comments.");
                }

                context.Comments.Remove(commentEntity);
                context.SaveChanges();

                return Request.CreateResponse(HttpStatusCode.OK);
            });

            return responseMsg;
        }
예제 #2
0
        public IQueryable<UserFullModel> GetAll(
            [ValueProvider(typeof(HeaderValueProviderFactory<string>))] string sessionKey)
        {
            var responseMsg = this.PerformOperationAndHandleExceptions(() =>
            {
                var context = new BookstoreContext();

                var adminUser = context.Users.FirstOrDefault(usr => usr.SessionKey == sessionKey);
                if (adminUser == null)
                {
                    throw new UnauthorizedAccessException("Invalid username or password");
                }

                if (adminUser.IsAdmin != true)
                {
                    throw new UnauthorizedAccessException("You dont have permissions to access this resourse!");
                }

                var userEntities = context.Users;
                var models =
                    (from userEntity in userEntities
                     select new UserFullModel()
                     {
                         Id = userEntity.Id,
                         Username = userEntity.Username,
                         IsActive = userEntity.IsActive,
                         IsAdmin = userEntity.IsAdmin,
                         AuthCode = userEntity.AuthCode
                     });
                return models;
            });

            return responseMsg;
        }
예제 #3
0
        public HttpResponseMessage CreateBook([FromBody]BookShortModel book,
            [ValueProvider(typeof(HeaderValueProviderFactory<string>))] string sessionKey)
        {
            var responseMsg = this.PerformOperationAndHandleExceptions(() =>
            {
                var context = new BookstoreContext();

                var user = context.Users.FirstOrDefault(usr => usr.SessionKey == sessionKey);
                if (user == null)
                {
                    throw new InvalidOperationException("Invalid username or password");
                }

                var bookToAdd = new Book();
                bookToAdd.Title = book.Title;
                if (book.PublishDate != null)
                {
                    bookToAdd.PublishDate = book.PublishDate;
                }

                bookToAdd.CoverUrl = book.CoverUrl;

                context.Books.Add(bookToAdd);
                context.SaveChanges();
                return Request.CreateResponse(HttpStatusCode.Created);
            });

            return responseMsg;
        }
예제 #4
0
        public HttpResponseMessage DeleteUser(int id,
            [ValueProvider(typeof(HeaderValueProviderFactory<string>))]string sessionKey)
        {
            var responseMsg = this.PerformOperationAndHandleExceptions(() =>
            {
                var context = new BookstoreContext();

                var adminUser = context.Users.FirstOrDefault(usr => usr.SessionKey == sessionKey);
                if (adminUser == null)
                {
                    throw new UnauthorizedAccessException("Invalid username or password");
                }

                if (adminUser.IsAdmin != true)
                {
                    throw new UnauthorizedAccessException("You dont have permissions to access this resourse!");
                }

                var userEntity = context.Users.SingleOrDefault(u => u.Id == id);
                if (userEntity == null)
                {
                    throw new ServerErrorException("User does not exist.");
                }

                userEntity.IsActive = false;
                context.SaveChanges();

                return Request.CreateResponse(HttpStatusCode.OK);
            });

            return responseMsg;
        }
예제 #5
0
        public IQueryable<AuthorModel> GetAll(
            [ValueProvider(typeof(HeaderValueProviderFactory<string>))] string sessionKey)
        {
            var responseMsg = this.PerformOperationAndHandleExceptions(() =>
            {
                var context = new BookstoreContext();

                var user = context.Users.FirstOrDefault(usr => usr.SessionKey == sessionKey);
                if (user == null)
                {
                    throw new InvalidOperationException("Invalid username or password");
                }

                var authorEntities = context.Authors;
                var models =
                    (from authorEntity in authorEntities
                     select new AuthorModel()
                     {
                         Id = authorEntity.Id,
                         FirstName = authorEntity.FirstName,
                         LastName = authorEntity.LastName,
                         BirthDate = authorEntity.BirthDate
                     });
                return models;
            });

            return responseMsg;
        }
예제 #6
0
        public IQueryable<CommentModel> GetByBookId(int bookId,
            [ValueProvider(typeof(HeaderValueProviderFactory<string>))] string sessionKey)
        {
            var responseMsg = this.PerformOperationAndHandleExceptions(() =>
            {
                var context = new BookstoreContext();

                var user = context.Users.FirstOrDefault(usr => usr.SessionKey == sessionKey);
                if (user == null)
                {
                    throw new InvalidOperationException("Invalid username or password");
                }

                var commentEntities = context.Comments.Include("User").Include("Book")
                    .Where(c => c.Book.Id == bookId);
                var models =
                    (from commentEntity in commentEntities
                     select new CommentModel()
                     {
                         Id = commentEntity.Id,
                         BookTitle = commentEntity.Book.Title,
                         Text = commentEntity.Text,
                         Username = commentEntity.User.Username
                     });
                return models;
            });

            return responseMsg;
        }
 internal static void Main()
 {
     var db = new BookstoreContext();
     var xmlDoc = XElement.Load(@"../../../DataFiles/complex-books.xml");
     var parser = new DataParser(db, xmlDoc);
     parser.Parse();
     xmlDoc = XElement.Load(@"../../../DataFiles/reviews-queries.xml");
     var querer = new QueryParser(db, xmlDoc);
     querer.Parse();
 }
 public static void Main()
 {
     Database.SetInitializer(new MigrateDatabaseToLatestVersion<BookstoreContext, Configuration>());
     using (BookstoreContext context = new BookstoreContext())
     {
         var user = new User();
         user.Username = "******";
         user.AuthCode = "0123456789012345678901234567890123456789";
         context.Users.Add(user);
         context.SaveChanges();
     }
 }
예제 #9
0
        public HttpResponseMessage DeleteBook(int id,
            [ValueProvider(typeof(HeaderValueProviderFactory<string>))]string sessionKey)
        {
            var responseMsg = this.PerformOperationAndHandleExceptions(() =>
            {
                BookstoreContext context = new BookstoreContext();
                var bookEntity = context.Books.SingleOrDefault(u => u.Id == id);
                if (bookEntity == null)
                {
                    throw new ServerErrorException("User does not exist.");
                }

                context.Books.Remove(bookEntity);
                context.SaveChanges();

                return Request.CreateResponse(HttpStatusCode.OK);
            });

            return responseMsg;
        }
예제 #10
0
        public HttpResponseMessage LogoutUser([
            ValueProvider(typeof(HeaderValueProviderFactory<string>))] string sessionKey)
        {
            var responseMessage = this.PerformOperationAndHandleExceptions(() =>
            {
                var context = new BookstoreContext();
                using (context)
                {
                    this.ValidateSessionKey(context, sessionKey);
                    var existingUser = context.Users.SingleOrDefault(u => u.SessionKey == sessionKey);

                    /* If you want the comparison to be case-sensitive, please uncomment.
                    if (existingUser == null /*|| existingUser.SessionKey != sessionKey)
                    {
                        throw new ServerErrorException("Invalid session key", "inv_session_key");
                    }*/

                    existingUser.SessionKey = null;
                    context.SaveChanges();

                    return Request.CreateResponse(HttpStatusCode.OK);
                }
            });

            return responseMessage;
        }
예제 #11
0
        public HttpResponseMessage LoginUser([FromBody]UserUnloggedModel userModel)
        {
            var responseMessage = this.PerformOperationAndHandleExceptions(() =>
            {
                var context = new BookstoreContext();
                using (context)
                {
                    if (userModel == null)
                    {
                        throw new ServerErrorException("User credentials not passed correctly", "invalid_credentials");
                    }

                    this.ValidateUsername(userModel.Username);
                    this.ValidateAuthCode(userModel.AuthCode);

                    var lowerCaseUsername = userModel.Username.ToLower();

                    var existingUser = context.Users.SingleOrDefault(u => u.Username == lowerCaseUsername &&
                        u.AuthCode == userModel.AuthCode);

                    if (existingUser == null)
                    {
                        throw new ServerErrorException("User with that username or password does not exist.", "user_does_not_exist");
                    }

                    if (existingUser.IsActive == false)
                    {
                        throw new ServerErrorException("User is not active.", "user_is_not_active");
                    }

                    if (existingUser.SessionKey == null)
                    {
                        var sessionKey = this.GenerateSessionKey(existingUser.Id);
                        existingUser.SessionKey = sessionKey;
                        context.SaveChanges();
                    }

                    var userReturnModel = new UserLoggedModel();
                    userReturnModel.SessionKey = existingUser.SessionKey;
                    userReturnModel.DisplayName = existingUser.Username;

                    return Request.CreateResponse(HttpStatusCode.Created, userReturnModel);
                }
            });

            return responseMessage;
        }
예제 #12
0
        public UserFullModel GetUserById(int id,
           [ValueProvider(typeof(HeaderValueProviderFactory<string>))]string sessionKey)
        {
            var responseMsg = this.PerformOperationAndHandleExceptions(() =>
            {
                var context = new BookstoreContext();

                var adminUser = context.Users.FirstOrDefault(usr => usr.SessionKey == sessionKey);
                if (adminUser == null)
                {
                    throw new UnauthorizedAccessException("Invalid username or password");
                }

                if (adminUser.IsAdmin != true)
                {
                    throw new UnauthorizedAccessException("You dont have permissions to access this resourse!");
                }

                var models = this.GetAll(sessionKey)
                    .SingleOrDefault(u => u.Id == id);

                if (models == null)
                {
                    throw new ServerErrorException("Invalid user id.");
                }

                return models;
            });

            return responseMsg;
        }
예제 #13
0
        public HttpResponseMessage GetByTitle(string title)
        {
            var responseMsg = this.PerformOperationAndHandleExceptions(() =>
            {
                BookstoreContext context = new BookstoreContext();
                var bookEntities = context.Books.Include("Authors")
                    .Where(b => b.Title.ToLower().Contains(title.ToLower())).ToList();

                var bookModels = (from book in bookEntities
                                  select new BookShortModel()
                                  {
                                      Id = book.Id,
                                      Title = book.Title,
                                      PublishDate = book.PublishDate,
                                      AuthorNames = (from author in book.Authors
                                                     select author.FirstName + " " + author.LastName).ToList()
                                  });

                return Request.CreateResponse(HttpStatusCode.OK, bookModels);
            });

            return responseMsg;
        }
예제 #14
0
        public HttpResponseMessage PostComment([FromBody]CommentPostModel comment,
            [ValueProvider(typeof(HeaderValueProviderFactory<string>))] string sessionKey)
        {
            var responseMsg = this.PerformOperationAndHandleExceptions(() =>
            {
                var context = new BookstoreContext();

                var user = context.Users.FirstOrDefault(usr => usr.SessionKey == sessionKey);
                if (user == null)
                {
                    throw new InvalidOperationException("Invalid username or password");
                }

                var book = context.Books.SingleOrDefault(b => b.Id == comment.BookId);
                if (book == null)
                {
                    throw new ServerErrorException("Book to comment does not exist.");
                }

                var commentToAdd = new Comment();
                commentToAdd.Text = comment.Text;
                commentToAdd.User = user;
                commentToAdd.Book = book;
                context.Comments.Add(commentToAdd);
                context.SaveChanges();
                return Request.CreateResponse(HttpStatusCode.Created);
            });

            return responseMsg;
        }
예제 #15
0
        public IEnumerable<BookShortModel> GetAll()
        {
            var responseMsg = this.PerformOperationAndHandleExceptions(() =>
            {
                BookstoreContext context = new BookstoreContext();
                var bookEntities = (from book in context.Books.Include("Authors").ToList()
                                    select new BookShortModel()
                                    {
                                        Id = book.Id,
                                        Title = book.Title,
                                        PublishDate = book.PublishDate,
                                        CoverUrl = book.CoverUrl,
                                        AuthorNames = (from author in book.Authors
                                                       select author.FirstName + " " + author.LastName).ToList()
                                    });

                return bookEntities;
            });

            return responseMsg;
        }
예제 #16
0
        public HttpResponseMessage UpdateBook([FromBody] BookShortModel bookModel,
            [ValueProvider(typeof(HeaderValueProviderFactory<string>))]string sessionKey)
        {
            var responseMsg = this.PerformOperationAndHandleExceptions(() =>
            {
                BookstoreContext context = new BookstoreContext();
                var bookEntity = context.Books.SingleOrDefault(u => u.Id == bookModel.Id);
                if (bookModel.Title != null)
                {
                    bookEntity.Title = bookModel.Title;
                }

                if (bookModel.PublishDate != null)
                {
                    bookEntity.PublishDate = bookModel.PublishDate;
                }

                if (bookModel.CoverUrl != null)
                {
                    bookEntity.CoverUrl = bookModel.CoverUrl;
                }

                context.SaveChanges();

                return Request.CreateResponse(HttpStatusCode.OK);
            });

            return responseMsg;
        }
예제 #17
0
        public HttpResponseMessage RegisterUser([FromBody]UserUnloggedModel userModel)
        {
            var responseMessage = this.PerformOperationAndHandleExceptions(() =>
            {
                var context = new BookstoreContext();
                using (context)
                {
                    if (userModel == null)
                    {
                        throw new ServerErrorException("User credentials not passed correctly",
                            "invalid_credentials");
                    }

                    this.ValidateUsername(userModel.Username);
                    this.ValidateAuthCode(userModel.AuthCode);

                    var lowerCaseUsername = userModel.Username.ToLower();

                    var existingUser = context.Users.SingleOrDefault(u => u.Username == lowerCaseUsername);

                    if (existingUser != null)
                    {
                        throw new ServerErrorException("User with that username or nickname already exists.", "user_exists");
                    }

                    var newUser = new User();
                    newUser.Username = lowerCaseUsername;
                    newUser.AuthCode = userModel.AuthCode;
                    newUser.IsActive = true;
                    context.Users.Add(newUser);
                    context.SaveChanges();

                    var sessionKey = this.GenerateSessionKey(newUser.Id);
                    newUser.SessionKey = sessionKey;
                    context.SaveChanges();

                    var userReturnModel = new UserLoggedModel();
                    userReturnModel.SessionKey = newUser.SessionKey;
                    userReturnModel.DisplayName = newUser.Username;

                    return Request.CreateResponse(HttpStatusCode.Created, userReturnModel);
                }
            });

            return responseMessage;
        }
예제 #18
0
        public HttpResponseMessage UpdateUser([FromBody] UserFullModel userModel,
            [ValueProvider(typeof(HeaderValueProviderFactory<string>))]string sessionKey)
        {
            var responseMsg = this.PerformOperationAndHandleExceptions(() =>
               {
               var context = new BookstoreContext();

               var adminUser = context.Users.FirstOrDefault(usr => usr.SessionKey == sessionKey);
               if (adminUser == null)
               {
                   throw new UnauthorizedAccessException("Invalid username or password");
               }

               if (adminUser.IsAdmin != true)
               {
                   throw new UnauthorizedAccessException("You dont have permissions to access this resourse!");
               }

               var userEntity = context.Users.SingleOrDefault(u => u.Id == userModel.Id);
               if (userModel.Username != null)
               {
                   userEntity.Username = userModel.Username;
               }

               if (userModel.IsActive != null)
               {
                   userEntity.IsActive = userModel.IsActive.Value;
               }

               if (userModel.IsAdmin != null)
               {
                   userEntity.IsAdmin = userModel.IsAdmin.Value;
               }

               context.SaveChanges();

               return Request.CreateResponse(HttpStatusCode.OK);
               });

            return responseMsg;
        }
예제 #19
0
        public HttpResponseMessage GetByDateInterval([ValueProvider(typeof(HeaderValueProviderFactory<string>))]
            string startDate, [ValueProvider(typeof(HeaderValueProviderFactory<string>))]
            string endDate)
        {
            var responseMsg = this.PerformOperationAndHandleExceptions(() =>
            {
                DateTime? StartDate = null;
                if (startDate != null)
                {
                    StartDate = DateTime.Parse(startDate, CultureInfo.InvariantCulture);
                }

                DateTime? EndDate = null;
                if (endDate != null)
                {
                    EndDate = DateTime.Parse(endDate, CultureInfo.InvariantCulture);
                }

                BookstoreContext context = new BookstoreContext();
                var bookEntities = new List<Book>();

                if (startDate == null)
                {
                    if (endDate == null)
                    {
                        bookEntities = context.Books.Include("Authors").ToList();
                    }
                    else
                    {
                        bookEntities = context.Books.Include("Authors")
                            .Where(b => b.PublishDate <= EndDate.Value).ToList();
                    }
                }
                else
                {
                    if (endDate == null)
                    {
                        bookEntities = context.Books.Include("Authors")
                            .Where(b => b.PublishDate >= StartDate.Value).ToList();
                    }
                    else
                    {
                        bookEntities = context.Books.Include("Authors")
                            .Where(b => b.PublishDate >= StartDate.Value
                                && b.PublishDate <= EndDate.Value).ToList();
                    }
                }

                var bookModels = (from book in bookEntities
                                  select new BookShortModel()
                                  {
                                      Id = book.Id,
                                      Title = book.Title,
                                      PublishDate = book.PublishDate,
                                      AuthorNames = (from author in book.Authors
                                                     select author.FirstName + " " + author.LastName).ToList()
                                  });

                return Request.CreateResponse(HttpStatusCode.OK, bookModels);
            });

            return responseMsg;
        }
예제 #20
0
 public QueryParser(BookstoreContext db, XElement query)
 {
     this.db = db;
     this.xmlQuery = query;
 }
예제 #21
0
        public HttpResponseMessage GetById(int id)
        {
            var responseMsg = this.PerformOperationAndHandleExceptions(() =>
            {
                BookstoreContext context = new BookstoreContext();
                var bookEntity = context.Books.Include("Authors")
                    .SingleOrDefault(b => b.Id == id);

                if (bookEntity == null)
                {
                    throw new ServerErrorException("Book does not exist");
                }

                var bookModel = new BookFullModel()
                {
                    Id = bookEntity.Id,
                    CoverUrl = bookEntity.CoverUrl,
                    PublishDate = bookEntity.PublishDate,
                    Title = bookEntity.Title,
                    Authors = new HashSet<AuthorModel>()
                };

                foreach (var author in bookEntity.Authors)
                {
                    bookModel.Authors.Add(new AuthorModel()
                    {
                        Id = author.Id,
                        FirstName = author.FirstName,
                        LastName = author.LastName,
                        BirthDate = author.BirthDate
                    });
                }

                return Request.CreateResponse(HttpStatusCode.OK, bookModel);
            });

            return responseMsg;
        }