コード例 #1
0
        public IActionResult Delete()
        {
            var userId = AuthMiddleware.GetUserId(User);

            _service.DeleteById(userId);
            return(Ok("Your account is successfully deleted!"));
        }
コード例 #2
0
        public void Update(UpdateUserDTO dto, int id)
        {
            var user = _unitOfWork.User.Get(id);

            if (!String.IsNullOrEmpty(dto.Email) && dto.Email.Contains("@"))
            {
                user.Email = dto.Email;
            }
            if (!String.IsNullOrEmpty(dto.FirstName))
            {
                user.FirstName = dto.FirstName;
            }
            if (!String.IsNullOrEmpty(dto.LastName))
            {
                user.LastName = dto.LastName;
            }
            if (!String.IsNullOrEmpty(dto.Password))
            {
                user.Password = AuthMiddleware.ComputeSha256Hash(dto.Password);
            }
            if (dto.IsDeleted == 0 || dto.IsDeleted == 1)
            {
                user.IsDeleted = dto.IsDeleted;
            }
            user.ModifiedAt = DateTime.Now;
            _unitOfWork.Save();
        }
コード例 #3
0
        public IActionResult Get()
        {
            var userId = AuthMiddleware.GetUserId(User);
            var wallet = _service.GetById(userId);

            return(Ok("Your balance is: " + wallet.Amount));
        }
コード例 #4
0
        public IActionResult Put([FromBody] UpdateUserDTO dto)
        {
            var userId = AuthMiddleware.GetUserId(User);

            _service.Update(dto, userId);
            return(Ok("Successfully updated!"));
        }
コード例 #5
0
        public ActionResult <PageResponse <TransactionDTO> > Transactions([FromQuery] TransactionSearch search)
        {
            var userId       = AuthMiddleware.GetUserId(User);
            var transactions = _service.GetTransactions(search, userId);

            return(Ok(transactions));
        }
コード例 #6
0
        public IActionResult Post([FromBody] WalletDTO dto)
        {
            var userId  = AuthMiddleware.GetUserId(User);
            var balance = _service.InsertMoney(dto, userId);

            return(Ok("Your current balance is: " + balance));
        }
コード例 #7
0
        public async Task TestInternalAuth(string goodKey, string requestKey, bool valid)
        {
            var options = new CrpcOptions
            {
                InternalKeys = new string[] { goodKey },
            };

            var middleware = new AuthMiddleware(_loggerFactory, Options.Create(options));
            var context    = new DefaultHttpContext();

            middleware.SetAuthentication(AuthenticationType.AllowInternalAuthentication);
            context.Request.Headers.Add("Authorization", $"bearer {requestKey}");

            if (valid)
            {
                await middleware.InvokeAsync(context, (ctx) => Task.CompletedTask);

                return;
            }

            var ex = await Assert.ThrowsAsync <CrpcException>(async() =>
            {
                await middleware.InvokeAsync(context, (ctx) => Task.CompletedTask);
            });

            Assert.Equal(CrpcCodes.Unauthorized, ex.Message);
        }
コード例 #8
0
        public string Login(LoginDTO data, IConfiguration config)
        {
            var token = "No token!";

            if (String.IsNullOrEmpty(data.Email))
            {
                throw new Exception("Email field is required!");
            }

            if (String.IsNullOrEmpty(data.Password))
            {
                throw new Exception("Password field is required!");
            }

            if (!data.Email.Contains("@"))
            {
                throw new Exception("Enter valid email!");
            }

            var pass = AuthMiddleware.ComputeSha256Hash(data.Password);
            var user = _unitOfWork.User.Find(u => u.Email == data.Email && u.Password == pass && u.IsDeleted == 0).FirstOrDefault();

            if (user != null)
            {
                token = AuthMiddleware.GenerateJsonWebToken(user, config);
                return(token);
            }
            throw new Exception("User not found!");
        }
コード例 #9
0
        public async void ShouldInvalidate_WhenApiKeyIsNull()
        {
            RequestDelegate next    = (HttpContext context) => Task.CompletedTask;
            var             context = new DefaultHttpContext();

            var authMiddleware = new AuthMiddleware(next);

            await authMiddleware.InvokeAsync(context, _mockAuthService.Object);

            context.Response.StatusCode.Should().Be((int)HttpStatusCode.Unauthorized);
        }
コード例 #10
0
        public IActionResult Delete(int id)
        {
            var userId = AuthMiddleware.GetUserId(User);

            if (_service.CheckItemExist(userId, id))
            {
                _service.DeleteById(id);
                return(Ok("Successfully deleted!"));
            }

            return(BadRequest("Order with that id does not exist in your cart!"));
        }
コード例 #11
0
        public IActionResult Submit()
        {
            var userId = AuthMiddleware.GetUserId(User);

            try
            {
                _service.Purchase(userId);
                return(Ok("Your order successfully purchased!"));
            }
            catch (Exception e)
            {
                return(BadRequest(e.Message));
            }
        }
コード例 #12
0
        public IActionResult Post([FromBody] InsertCartDTO dto)
        {
            var userId = AuthMiddleware.GetUserId(User);

            try
            {
                _service.Insert(dto, userId);
                return(Ok("Successfully added to cart!"));
            }
            catch (Exception e)
            {
                return(BadRequest(e.Message));
            }
        }
コード例 #13
0
        public ActionResult <CartDTO> Get()
        {
            var userId = AuthMiddleware.GetUserId(User);

            try
            {
                var items = _service.ListCart(userId);
                return(Ok(items));
            }
            catch (Exception e)
            {
                return(Ok(e.Message));
            }
        }
コード例 #14
0
        public string Upload(IFormFile file)
        {
            var fileName  = file.FileName;
            var extension = Path.GetExtension(file.FileName);
            var name      = "images/" + AuthMiddleware.ComputeSha256Hash(DateTime.UtcNow.ToTimestamp() + fileName) + extension;
            var path      = Path.Combine(Directory.GetParent(Directory.GetCurrentDirectory()) + "/WebApp", "wwwroot", name);

            using (var fileStream = new FileStream(path, FileMode.Create))
            {
                file.CopyTo(fileStream);
            }

            return(name);
        }
コード例 #15
0
        public async void ShouldInvalidate_WhenApiKeyIsInvalid()
        {
            _mockAuthService.Setup(service => service.GetUserIdByToken(It.IsAny <string>())).Returns(Task.FromResult <int?>(null));
            RequestDelegate next    = (HttpContext context) => Task.CompletedTask;
            var             context = new DefaultHttpContext();

            context.Request.Headers.Add("X-API-Key", "foobar");

            var authMiddleware = new AuthMiddleware(next);

            await authMiddleware.InvokeAsync(context, _mockAuthService.Object);

            context.Response.StatusCode.Should().Be(401);
        }
コード例 #16
0
        public IActionResult Contact([FromBody] MailDTO dto)
        {
            var userId = AuthMiddleware.GetUserId(User);

            try
            {
                _service.SendMail(dto, userId);
                return(Ok("Mail sent!"));
            }
            catch (Exception e)
            {
                return(BadRequest("Something went wrong!"));
            }
        }
コード例 #17
0
        public ActionResult <PageResponse <OrderDTO> > Get([FromQuery] OrderSearch search)
        {
            var userId = AuthMiddleware.GetUserId(User);

            search.UserId = userId;

            var orders = _service.Execute(search);

            if (orders == null)
            {
                return(Ok("You don't have any orders yet!"));
            }
            return(Ok(orders));
        }
コード例 #18
0
        public async void ShouldAssignIdentity_WhenApiKeyIsValid()
        {
            _mockAuthService.Setup(service => service.GetUserIdByToken(It.IsAny <string>())).Returns(Task.FromResult((int?)1));
            RequestDelegate next    = (HttpContext context) => Task.CompletedTask;
            var             context = new DefaultHttpContext();

            context.Request.Headers.Add("X-API-Key", "foobar");

            var authMiddleware = new AuthMiddleware(next);

            await authMiddleware.InvokeAsync(context, _mockAuthService.Object);

            context.User.Identity.Name.Should().Be("1");
        }
コード例 #19
0
        public int Register(RegisterDTO data)
        {
            if (String.IsNullOrEmpty(data.FirstName))
            {
                throw new Exception("First name field is required!");
            }

            if (String.IsNullOrEmpty(data.LastName))
            {
                throw new Exception("Last name field is required!");
            }

            if (String.IsNullOrEmpty(data.Email))
            {
                throw new Exception("Email field is required!");
            }

            if (String.IsNullOrEmpty(data.Password))
            {
                throw new Exception("Password field is required!");
            }

            if (!data.Email.Contains("@"))
            {
                throw new Exception("Enter valid email!");
            }

            data.Password = AuthMiddleware.ComputeSha256Hash(data.Password);
            var user = new User()
            {
                FirstName = data.FirstName,
                LastName  = data.LastName,
                Email     = data.Email,
                Password  = data.Password,
                RoleId    = 2
            };

            _unitOfWork.User.Add(user);
            _unitOfWork.Save();
            var wallet = new Wallet()
            {
                Balance = 0,
                UserId  = user.Id
            };

            _unitOfWork.Wallet.Add(wallet);
            _unitOfWork.Save();
            return(user.Id);
        }
コード例 #20
0
        public async Task TestNoAuthenticationTypeSet()
        {
            var options    = new CrpcOptions();
            var middleware = new AuthMiddleware(_loggerFactory, Options.Create(options));
            var context    = new DefaultHttpContext();

            context.Response.Body = new MemoryStream();

            var ex = await Assert.ThrowsAsync <InvalidOperationException>(async() =>
            {
                await middleware.InvokeAsync(context, (ctx) => Task.CompletedTask);
            });

            Assert.Equal("Authentication type not set", ex.Message);
        }
コード例 #21
0
        public async Task TestUnsafeNoAuth(string key)
        {
            var options = new CrpcOptions
            {
                InternalKeys = new string[] { key },
            };

            var middleware = new AuthMiddleware(_loggerFactory, Options.Create(options));
            var context    = new DefaultHttpContext();

            middleware.SetAuthentication(AuthenticationType.UnsafeNoAuthentication);
            context.Request.Headers.Add("Authorization", $"bearer {key}");

            await middleware.InvokeAsync(context, (ctx) => Task.CompletedTask);
        }
コード例 #22
0
        public IActionResult Put(int id, [FromBody] UpdateCartDTO dto)
        {
            var userId = AuthMiddleware.GetUserId(User);

            try
            {
                if (_service.CheckItemExist(userId, id))
                {
                    _service.Update(dto, id);
                    return(Ok("Quantity successfully updated!"));
                }
                return(BadRequest("Order with that id does not exist in your cart!"));
            }
            catch (Exception e)
            {
                return(BadRequest(e.Message));
            }
        }
コード例 #23
0
        public ActionResult Create(IFormCollection collection)
        {
            try
            {
                var dto = new RegisterDTO()
                {
                    FirstName = collection["FirstName"],
                    LastName  = collection["LastName"],
                    Email     = collection["Email"],
                    Password  = AuthMiddleware.ComputeSha256Hash(collection["Password"]),
                };
                _service.Register(dto);

                return(RedirectToAction(nameof(Index)));
            }
            catch
            {
                return(View());
            }
        }
コード例 #24
0
        public static RequestResponse Process(RawRequest rawRequest)
        {
            var requestType = RequestBuilder.GetRequestTypeFromRaw(rawRequest);

            switch (requestType)
            {
            case RequestTypes.Login:
                return(AuthModule.Login(
                           rawRequest.Data.SelectToken("login").Value <string>() ?? "",
                           rawRequest.Data.SelectToken("pass").Value <string>() ?? ""
                           ));

            case RequestTypes.LogOut:
                return(AuthModule.Logout(
                           rawRequest.Data.SelectToken("token").Value <string>() ?? ""
                           ));

            case RequestTypes.Register:
                return(AuthModule.Register(
                           rawRequest.Data.SelectToken("login").Value <string>() ?? "",
                           rawRequest.Data.SelectToken("pass").Value <string>() ?? "",
                           rawRequest.Data.SelectToken("email").Value <string>() ?? ""
                           ));
            }

            var token  = (string)rawRequest.Data["token"] ?? "";
            int userId = rawRequest.Data.Value <int?>("userId") ?? 0;

            var authMiddleware = AuthMiddleware.IsUserLoggedIn(
                token, userId
                );

            if (authMiddleware.Code != ReturnCodes.Success)
            {
                return(new RequestResponse(requestType, authMiddleware.Code));
            }

            // Next request requires auth

            return(null);
        }
コード例 #25
0
        static void Main(string[] args)
        {
            using (var unitOfWork = new UnitOfWork(new LibraryContext()))
            {
                #region Faking data

                string[] categories = new string[] { "Biography", "Fiction", "History", "Crime & Thriller", "Sport" };
                string[] authors    = new string[] { "Stephen Hawking", "Anne Frank", "Sally Rooney", "Amor Towles", "Adam Higginbotham", "Jonathan Clements", "Michael Connelly", "Denise Mina", "Peter Crouch", "James Witts" };
                foreach (var cat in categories)
                {
                    var category = new Category
                    {
                        Name = cat
                    };

                    unitOfWork.Category.Add(category);
                }
                foreach (var a in authors)
                {
                    var author = new Author()
                    {
                        FullName = a
                    };

                    unitOfWork.Author.Add(author);
                }
                unitOfWork.Save();
                List <Book> books = new List <Book>();

                books.Add(new Book()
                {
                    Title       = "Brief Answers to the Big Questions : the final book from Stephen Hawking",
                    Description = "The world-famous cosmologist and #1 bestselling author of A Brief History of Time leaves us with his final thoughts on the universe's biggest questions in this brilliant posthumous work.",
                    Price       = 200.00,
                    Pages       = 256,
                    AuthorId    = 1,
                    Image       = "images/da12ebfb0aa48fd8ec52ecb381c0d3c87f2d1fcc2c0feca0a354816fed22b21c.jpg",
                    CategoryId  = 1
                });
                books.Add(new Book()
                {
                    Title       = "The Diary of a Young Girl",
                    Description = "For almost fifty years, Anne Frank's diary has moved millions with its testament to the human spirit's indestructibility, but readers have never seen the full text of this beloved book--until now. This new translation, performed by Winona Ryder, restores nearly one third of Anne's entries excised by her father in previous editions, revealing her burgeoning sexuality, her stormy relationship with her mother, and more. ",
                    Price       = 250.00,
                    Pages       = 283,
                    AuthorId    = 2,
                    Image       = "images/5b8c161f3152a8408015682be99d1c0d3b71791a78855a8fe4c7a5eaccef1fcf.jpg",
                    CategoryId  = 1
                });

                books.Add(new Book()
                {
                    Title       = "Normal People",
                    Description = "WINNER OF THE COSTA NOVEL AWARD 2018",
                    Price       = 300.00,
                    Pages       = 288,
                    AuthorId    = 3,
                    Image       = "images/4d2b62f7b0d1e808d0433d3cd172f61ee9b282a98e906982f78759e7126a9ded.jpg",
                    CategoryId  = 2
                });
                books.Add(new Book()
                {
                    Title       = "A Gentleman in Moscow",
                    Description = "OVER A MILLION COPIES SOLD",
                    Price       = 660.00,
                    Pages       = 480,
                    AuthorId    = 4,
                    Image       = "images/10f39e930aa325bb3756b7d7ddc4f76271e42baa3207814b8f9f43efce2fc150.jpg",
                    CategoryId  = 2
                });

                books.Add(new Book()
                {
                    Title       = "Midnight in Chernobyl : The Story of the World's Greatest Nuclear Disaster",
                    Description = "Early in the morning of April 26, 1986, Reactor Number Four of the Chernobyl Atomic Energy Station exploded, triggering history's worst nuclear disaster. In the thirty years since then, Chernobyl has become lodged in the collective nightmares of the world: shorthand for the spectral horrors of radiation poisoning, for a dangerous technology slipping its leash, for ecological fragility, and for what can happen when a dishonest and careless state endangers not only its own citizens, but all of humanity. ",
                    Price       = 750.00,
                    Pages       = 560,
                    AuthorId    = 5,
                    Image       = "images/cc04f3a8216c6c570af0f626cf743f64caae46818e04012806561cd4f85dbfd6.jpg",
                    CategoryId  = 3
                });
                books.Add(new Book()
                {
                    Title       = "A Brief History of the Samurai",
                    Description = "From a leading expert in Japanese history, this is one of the first full histories of the art and culture of the Samurai warrior. The Samurai emerged as a warrior caste in Medieval Japan and would have a powerful influence on the history and culture of the country from the next 500 years. Clements also looks at the Samurai wars that tore Japan apart in the 17th and 18th centuries and how the caste was finally demolished in the advent of the mechanized world. ",
                    Price       = 660.00,
                    Pages       = 384,
                    AuthorId    = 6,
                    Image       = "images/3ec46a399bf262b79b95200e7862fed6a56acee48b2e3e9f0b79e30163d49f14.jpg",
                    CategoryId  = 3
                });

                books.Add(new Book()
                {
                    Title       = "Dark Sacred Night : The Brand New Ballard and Bosch Thriller",
                    Description = "A MURDER HE CAN'T FORGET. A CASE ONLY SHE CAN SOLVE.",
                    Price       = 350.00,
                    Pages       = 544,
                    AuthorId    = 7,
                    Image       = "images/ffc682d54bcaebae7fed9c70506fc6f629cdd8d8a6b3c7159b97e3294f5a9d05.jpg",
                    CategoryId  = 4
                });
                books.Add(new Book()
                {
                    Title       = "Conviction",
                    Description = "From 'the woman who may be Britain's finest living crime novelist' (Daily Telegraph), Conviction stars a strong female protagonist who is obsessed by true-crime podcasts and decides, one day, to investigate one of the unsolved crimes herself.",
                    Price       = 980.00,
                    Pages       = 384,
                    AuthorId    = 8,
                    Image       = "images/c32cdbfb569a3ef4da8c2356f3668def517323f605ffec02f57fde9007c0e8b5.jpg",
                    CategoryId  = 4
                });

                books.Add(new Book()
                {
                    Title       = "How to Be a Footballer",
                    Description = "You become a footballer because you love football. And then you are a footballer, and you're suddenly in the strangest, most baffling world of all.",
                    Price       = 50.00,
                    Pages       = 304,
                    AuthorId    = 9,
                    Image       = "images/171a1d3855b4aa00a7dff07e92dd70a740439a6d876d502cac31d92ca1429c10.jpg",
                    CategoryId  = 5
                });
                books.Add(new Book()
                {
                    Title       = "Bike Book : Complete bicycle maintenance",
                    Description = "Now in its 23rd year of publication, The Bike Book continues to be a bestseller. Compiled by a new author, this seventh edition is a major update to include all new developments in the cycling world along with a thorough check and revision of all existing material. New photography together with a refreshed page design offer the reader a user-friendly and contemporary manual - but still with the clear step-by-step approach for which Haynes is famous. ",
                    Price       = 70.00,
                    Pages       = 194,
                    AuthorId    = 10,
                    Image       = "images/699b56f78d2e7f5df6f61c5cfd4bdb01473302cd28bd2e93722fd50689eb3ef2.jpg",
                    CategoryId  = 5
                });

                foreach (var book in books)
                {
                    unitOfWork.Book.Add(book);
                }

                unitOfWork.Role.Add(new Role()
                {
                    Name = "Admin", CreatedAt = DateTime.Now
                });
                unitOfWork.Role.Add(new Role()
                {
                    Name = "Customer", CreatedAt = DateTime.Now
                });
                unitOfWork.Save();
                unitOfWork.User.Add(new User()
                {
                    FirstName = "Admin",
                    LastName  = "Adminic",
                    Email     = "*****@*****.**",
                    Password  = AuthMiddleware.ComputeSha256Hash("admin123"),
                    CreatedAt = DateTime.Now,
                    RoleId    = 1
                });
                unitOfWork.User.Add(new User()
                {
                    FirstName = "Korisnik",
                    LastName  = "Korisnicic",
                    Email     = "*****@*****.**",
                    Password  = AuthMiddleware.ComputeSha256Hash("user123"),
                    CreatedAt = DateTime.Now,
                    RoleId    = 2
                });
                unitOfWork.Save();
                unitOfWork.Wallet.Add(new Wallet()
                {
                    UserId  = 1,
                    Balance = 0
                });
                unitOfWork.Wallet.Add(new Wallet()
                {
                    UserId  = 2,
                    Balance = 0
                });
                #endregion

                unitOfWork.Save();
                Console.WriteLine("Finished!");
            }
        }