コード例 #1
0
        public IActionResult GetImageById(uint id)
        {
            using var context = new flashcardsContext();
            var imageFileName = (from c in context.cards
                                 where c.id == id && (c.ownerId == LoggedInId() || c.isPublic)
                                 select c.picture).FirstOrDefault();

            if (imageFileName is null)
            {
                return(NotFound());
            }
            var path = Path.Combine(imagePath, imageFileName);

            System.Console.WriteLine(path);
            // var converter = new ImageConverter();
            if (path.EndsWith(".png", true, null))
            {
                return(PhysicalFile(path, "image/png"));
            }
            else if (path.EndsWith(".jpg", true, null) || path.EndsWith(".jpeg", true, null))
            {
                return(PhysicalFile(path, "image/jpeg"));
            }
            else if (path.EndsWith(".gif", true, null))
            {
                return(PhysicalFile(path, "image/gif"));
            }
            return(null);
            // return File((byte[])converter.ConvertTo(context.cards.First(c => c.id == id && (c.ownerId == LoggedInId() || c.isPublic)).picture, typeof(byte[])), "image/gif");
        }
コード例 #2
0
ファイル: Controller.Set.cs プロジェクト: MBernart/flashcards
        public IEnumerable <Set.Set> GetSetsAvailableForUser()
        {
            var id = LoggedInId();

            using var context = new flashcardsContext();
            return(context.sets.Where(s => s.ownerId == id || s.creatorId == id).ToList());
        }
コード例 #3
0
        // [Consumes("application/json")]
        // [Produces("application/json")]
        public IActionResult CreateCard([FromForm] MinCard c)
        {
            var id = LoggedInId();

            try
            {
                using var context = new flashcardsContext();
                if (!context.sets.Any(s => s.id == c.inSet))
                {
                    return(BadRequest($"There is no set with id {c.inSet}"));
                }
                if (!context.sets.Any(s => s.id == c.inSet && (s.creatorId == id ||
                                                               s.ownerId == id)))
                {
                    return(BadRequest("Access denied"));
                }
                var card = CreateCardFromMinCard(c, LoggedInId());
                context.cards.Add(card);

                // SaveImage(c.image, card.id);
                context.SaveChanges();

                card.picture = SaveImage(c.image, card.id);
                context.cards.Update(card);
                context.SaveChanges();

                return(Ok());
            }
            catch (Exception e)
            {
                return(BadRequest(e.Message));
            }
        }
コード例 #4
0
 public IActionResult Register(UserToRegister user)
 {
     try
     {
         var u = new User.User(user.username, user.email, user.name, user.surname);
         using var context = new flashcardsContext();
         if (!IsValidEmail(u.Email))
         {
             throw new FormatException("Email format is not valid.");
         }
         if (context.users.Any(us => us.UserName == u.UserName | us.Email == u.Email))
         {
             if (context.users.Any(us => us.UserName == u.UserName))
             {
                 throw new FormatException("Username is already used");
             }
             else
             {
                 throw new FormatException("Email is already used");
             }
         }
         u.ChangePassword(user.password);
         context.users.Add(u);
         context.SaveChanges();
         return(Ok(u));
     }
     catch (FormatException e)
     {
         return(BadRequest(e.Message));
     }
 }
コード例 #5
0
 public IActionResult IsEmailUsed(string email)
 {
     if (!IsValidEmail(email))
     {
         return(BadRequest($"'{email}' isn't correct email format."));
     }
     using var context = new flashcardsContext();
     return(Ok(context.users.Any(u => u.Email == email)));
 }
コード例 #6
0
        // [Consumes("application/json")]
        // [Produces("application/json")]
        public IActionResult UpdateCard([FromForm] UpdateRequest updateRequest)
        {
            try
            {
                Console.WriteLine(updateRequest.id);

                using var context = new flashcardsContext();

                var card = context.cards.First(c => c.id == updateRequest.id &&
                                               c.ownerId == LoggedInId());

                //db.GetCardById(updateRequest.id);
                Console.WriteLine("check after card");
                var what = updateRequest.what;
                var to   = updateRequest.to;
                switch (what.ToLower())
                {
                case "question":
                    card.question = to;
                    break;

                case "answer":
                    card.answer = to;
                    break;

                case "image":
                    card.picture = SaveImage(updateRequest.image, card.id);
                    break;

                default:
                    return(BadRequest($"{what} isn't a proper value"));
                }
                context.Update(card);
                context.SaveChanges();

                return(Ok());
            }
            catch (InvalidOperationException)
            {
                return(Unauthorized("Access denied"));
            }
            catch (Exception e)
            {
                return(BadRequest(e));
            }
        }
コード例 #7
0
 // [Produces("application/json")]
 public IEnumerable <PublicCard> GetCardsBySetId(uint id)
 {
     try
     {
         using var context = new flashcardsContext();
         if (!context.sets.Any(s => s.id == id && (s.ownerId == LoggedInId() || s.isPublic)))
         {
             return(null);
         }
         var tempCard = context.cards.Where(c => c.inSet == id && (c.ownerId == LoggedInId() ||
                                                                   c.isPublic)).ToList();
         return(CreatePublicCardFromCard(tempCard));
     }
     catch (Exception)
     {
         return(null);
     }
 }
コード例 #8
0
        public IActionResult UpdateUserData(UpdateRequest updateRequest)
        {
            if (updateRequest.id != LoggedInId())
            {
                return(Unauthorized("Access denied"));
            }

            using var context = new flashcardsContext();
            var user = context.users.First(u => u.Id == updateRequest.id);

            var to   = updateRequest.to;
            var what = updateRequest.what;

            switch (what.ToLower())
            {
            case "email":
                if (!IsValidEmail(to))
                {
                    return(BadRequest($"'{to}' isn't correct email format."));
                }
                user.Email = to;
                break;

            case "name":
                user.name = to;
                break;

            case "surname":
                user.surname = to;
                break;

            case "password":
                user.ChangePassword(to);
                break;

            default:
                return(BadRequest($"'{what}' is not valid property"));
            }

            context.Update(user);
            context.SaveChanges();

            return(Ok("Successfully changed"));
        }
コード例 #9
0
        public IActionResult UploadImage([FromForm] UploadImageViewModel model)
        {
            var cardId = model.cardId;
            var file   = model.file;

            // checks extension
            if (!imageExtensions.Any(x => file.FileName.EndsWith(x)))
            {
                return(UnprocessableEntity());
            }

            using var context = new flashcardsContext();

            // returns card if exists and is public or the user is owner
            // if doesn't exist returns null
            var card = (from c in context.cards
                        where c.id == model.cardId &&
                        (c.ownerId == LoggedInId() || c.isPublic)
                        select c).SingleOrDefault();

            // 404 if card not found
            if (card is null)
            {
                return(NotFound());
            }

            // user cannot edit card if is not owner
            if (card.ownerId != LoggedInId())
            {
                return(Forbid());
            }

            var name = SaveImage(file, cardId);

            if (name is null)
            {
                return(BadRequest());
            }
            card.picture = name;
            context.cards.Update(card);
            context.SaveChanges();
            return(Ok());
        }
コード例 #10
0
ファイル: Controller.Set.cs プロジェクト: MBernart/flashcards
        // [Consumes("application/json")]
        // [Produces("application/json")]
        public IActionResult CreateSet([FromForm] SetToCreate setToCreate)
        {
            try
            {
                using var context = new flashcardsContext();

                var id  = LoggedInId();
                var set = new Set.Set(setToCreate.name, id, id, setToCreate.isPublic);
                context.sets.Add(set);
                context.SaveChanges();


                return(Ok());
            }
            catch (Exception e)
            {
                return(BadRequest(e.Message));
            }
        }
コード例 #11
0
 public PublicUser GetUserPublic(uint id, string username)
 {
     try
     {
         using var context = new flashcardsContext();
         return(new PublicUser(context.users.First(u => u.Id == id)));
     }
     catch (Exception)
     {
         try
         {
             using var context = new flashcardsContext();
             return(new PublicUser(context.users.First(u => u.UserName == username)));
         }
         catch (Exception)
         {
             return(null);
         }
     }
 }
コード例 #12
0
        public IActionResult Login(LoginData loginData)
        {
            using var context = new flashcardsContext();
            IActionResult response = Unauthorized();

            try
            {
                var user = context.users.First(u => u.UserName == loginData.login);
                if (!user.ValidatePassword(loginData.password))
                {
                    return(response);
                }
                var token = GenerateJsonWebToken(user);
                response = Ok(new { token });
                return(response);
            }
            catch (InvalidOperationException)
            {
                return(response);
            }
        }
コード例 #13
0
 public PublicCard GetCardById(uint id)
 {
     try
     {
         using var context = new flashcardsContext();
         // var tempCard = context.cards.First(c => c.id == id && (c.ownerId == LoggedInId() || c.isPublic)); // A
         var tempCard =
             (
                 from c in context.cards
                 where c.id == id && (c.ownerId == LoggedInId() || c.isPublic)
                 select c
             ).First();
         return(CreatePublicCardFromCard(tempCard));
     }
     catch (ArgumentNullException)
     {
         return(null);
     }
     catch (InvalidOperationException)
     {
         return(null);
     }
 }
コード例 #14
0
        private User.User GetClaim(string token, string claimType)
        {
            if (!ValidateCurrentToken(token))
            {
                throw new NotImplementedException("bad token");
            }
            var tokenHandler  = new JwtSecurityTokenHandler();
            var securityToken = tokenHandler.ReadToken(token) as JwtSecurityToken;


            using var context = new flashcardsContext();
            if (securityToken == null)
            {
                throw new NotImplementedException("token is null");
            }
            var userId = int.Parse(securityToken.Claims.First(claim => claim.Type == claimType).Value);

            if (securityToken.ValidTo < DateTime.UtcNow)
            {
                throw new NotImplementedException("expired");
            }
            return(context.users.First(u => u.Id == userId));
        }
コード例 #15
0
ファイル: Controller.Set.cs プロジェクト: MBernart/flashcards
        public IActionResult TransferOwnership(ChangeOwnership change)
        {
            try
            {
                using var context = new flashcardsContext();

                var set = context.sets.First(s => s.id == change.setId);
                if (set.ownerId != LoggedInId())
                {
                    return(Unauthorized("Access denied for this set"));
                }

                var user = context.users.First(u => u.Id == change.userId);

                set.ownerId = user.Id;
                context.SaveChanges();

                return(Ok());
            }
            catch (ArgumentNullException e)
            {
                return(BadRequest(e.Message));
            }
        }
コード例 #16
0
ファイル: Controller.Set.cs プロジェクト: MBernart/flashcards
 public IEnumerable <Set.Set> GetAllSets()
 {
     using var context = new flashcardsContext();
     return(context.sets.Where(s => s.isPublic).ToList());
 }
コード例 #17
0
 public User.User GetMe()
 {
     using var context = new flashcardsContext();
     return(context.users.First(u => u.Id == LoggedInId()));
 }
コード例 #18
0
 public IActionResult IsUsernameUsed(string username)
 {
     using var context = new flashcardsContext();
     return(Ok(context.users.Any(u => u.UserName == username)));
 }
コード例 #19
0
ファイル: Controller.Set.cs プロジェクト: MBernart/flashcards
 public IEnumerable <Set.Set> GetPublicSetsByNameLike(string name)
 {
     using var context = new flashcardsContext();
     return(context.sets.Where(s => s.name.Contains(name)).ToList());
 }
コード例 #20
0
ファイル: Controller.Set.cs プロジェクト: MBernart/flashcards
 public Set.Set GetSetById(uint id)
 {
     using var context = new flashcardsContext();
     return(context.sets.First(s => s.id == id));
 }
コード例 #21
0
 public IEnumerable <PublicUser> GetPublicUsers()
 {
     using var context = new flashcardsContext();
     return(context.users.Cast <PublicUser>().ToList());
 }