コード例 #1
0
        public async Task <List <CommentSockets> > GetAllCommentsForPost(int postId)
        {
            using (ShapeAppDbContext ctx = new ShapeAppDbContext())
            {
                Post post = await ctx.Posts.Where(p => p.Id == postId)
                            .Include(p => p.Comments)
                            .ThenInclude(c => c.Owner)
                            .Include(p => p.Owner).FirstAsync();

                List <Comment> orderedComments = post.Comments.OrderByDescending(c => c.TimeStamp).ToList();
                if (orderedComments.Any())
                {
                    List <CommentSockets> comments = new List <CommentSockets>();
                    foreach (var postComment in orderedComments)
                    {
                        UserShortVersion owner = new UserShortVersion {
                            UserId       = postComment.Owner.Id,
                            UserFullName = postComment.Owner.Name
                        };
                        comments.Add(new CommentSockets
                        {
                            Id        = postComment.Id,
                            Owner     = owner,
                            Content   = postComment.Content,
                            TimeStamp = postComment.TimeStamp
                        });
                    }

                    return(comments);
                }

                return(null);
            }
        }
コード例 #2
0
ファイル: UserSocket.cs プロジェクト: Toni751/SEP3_Tier3
        /// <summary>
        /// Retrieves a user short version instance with the given user id
        /// </summary>
        /// <param name="actualRequest">the client request to be handled</param>
        /// <returns>the response to the given request</returns>
        private ActualRequest GetUserShortVersionById(ActualRequest actualRequest)
        {
            Request          request  = actualRequest.Request;
            int              userId   = Convert.ToInt32(request.Argument.ToString());
            UserShortVersion user     = userRepo.GetUserShortVersionById(userId);
            Request          response = new Request
            {
                ActionType = ActionType.USER_GET_SV_BY_ID.ToString(),
                Argument   = JsonSerializer.Serialize(user)
            };
            List <byte[]> userAvatars = new List <byte[]>();

            if (user != null)
            {
                try {
                    var readAvatarFile = File.ReadAllBytes($"{FILE_PATH}/Users/{user.UserId}/avatar.jpg");
                    userAvatars.Add(ImagesUtil.ResizeImage(readAvatarFile, 20, 20));
                }
                catch (Exception e) {
                    Console.WriteLine("No avatar found for user " + user.UserId);
                }
            }
            return(new ActualRequest
            {
                Request = response,
                Images = userAvatars
            });
        }
        public async Task Login(Login login)
        {
            Console.WriteLine("Validating log in");
            if (string.IsNullOrEmpty(login.Email))
            {
                throw new Exception("Enter username");
            }
            if (string.IsNullOrEmpty(login.Password))
            {
                throw new Exception("Enter password");
            }

            ClaimsIdentity identity = new ClaimsIdentity();

            try
            {
                UserShortVersion currentLogged = await userManger.Login(login);

                identity = SetupClaimsForUser(currentLogged);

                string serialisedData = JsonSerializer.Serialize(currentLogged);
                await jsRuntime.InvokeVoidAsync("sessionStorage.setItem", "currentUser", serialisedData);

                CachedUser = currentLogged;
            }
            catch (Exception e)
            {
                throw e;
            }


            NotifyAuthenticationStateChanged(
                Task.FromResult <AuthenticationState>(new AuthenticationState(new ClaimsPrincipal(identity))));
        }
コード例 #4
0
        public async Task <PostShortVersion> GetPostByIdAsync(int postId, int userId)
        {
            using (ShapeAppDbContext ctx = new ShapeAppDbContext())
            {
                Post post = await ctx.Posts
                            .Include(p => p.Owner)
                            .FirstOrDefaultAsync(p => p.Id == postId);

                if (post == null)
                {
                    return(null);
                }

                UserShortVersion owner = new UserShortVersion
                {
                    UserId       = post.Owner.Id,
                    UserFullName = post.Owner.Name,
                };
                int countComments = ctx.Posts.Where(p => p.Id == post.Id)
                                    .Include(p => p.Comments).First().Comments.Count;
                Console.WriteLine("Post " + post.Id + " has " + countComments + " comments");

                int countLikes = ctx.PostActions.Count(pa => pa.PostId == post.Id && pa.IsLike);
                Console.WriteLine("Post " + post.Id + " has " + countLikes + " likes");

                PostAction postAction = await ctx.PostActions.FirstOrDefaultAsync(pa =>
                                                                                  pa.PostId == postId && pa.UserId == userId);

                bool[] postStatus = new bool[2];

                if (postAction == null)
                {
                    for (int i = 0; i < postStatus.Length; i++)
                    {
                        postStatus[i] = false;
                    }
                }
                else
                {
                    postStatus[0] = postAction.IsLike;
                    postStatus[1] = postAction.IsReport;
                }

                return(new PostShortVersion
                {
                    Id = post.Id,
                    Title = post.Title,
                    Content = post.Content,
                    Owner = owner,
                    TimeStamp = post.TimeStamp,
                    HasImage = post.HasImage,
                    NumberOfComments = countComments,
                    NumberOfLikes = countLikes,
                    PostStatus = postStatus
                });
            }
        }
        public async void Logout()
        {
            CachedUser = null;
            var user = new ClaimsPrincipal(new ClaimsIdentity());
            await jsRuntime.InvokeVoidAsync("sessionStorage.setItem", "currentUser", "");

            NotifyAuthenticationStateChanged(Task.FromResult(new AuthenticationState(user)));

            //websocket request
        }
        private ClaimsIdentity SetupClaimsForAdmin(UserShortVersion admin)
        {
            List <Claim> claims = new List <Claim>();

            claims.Add(new Claim("Id", admin.UserId.ToString()));
            claims.Add(new Claim("AccountType", admin.AccountType));
            ClaimsIdentity identity = new ClaimsIdentity(claims, "apiauth_type");

            return(identity);
        }
コード例 #7
0
        public async Task <bool> EditUser(User editedUser, UserShortVersion currentLogged)
        {
            if (editedUser.Avatar == currentLogged.Avatar)
            {
                editedUser.Avatar = null;
            }

            HttpResponseMessage response = await client.PutAsync($"{uri}/{editedUser.Id}", PrepareObjectForRequest(editedUser));

            if (response.IsSuccessStatusCode && response.StatusCode != HttpStatusCode.BadRequest)
            {
                return(true);
            }
            return(false);
        }
コード例 #8
0
        public static UserShortVersion GetLoggedUser(AuthenticationState state)
        {
            UserShortVersion user = new UserShortVersion
            {
                UserId       = Int32.Parse(state.User.Claims.First(c => c.Type.Equals("Id")).Value),
                AccountType  = state.User.Claims.First(c => c.Type.Equals("AccountType")).Value,
                UserFullName = state.User.Claims.First(c => c.Type.Equals("Name")).Value
            };

            if (!user.AccountType.Equals("Administrator"))
            {
                user.Avatar = Convert.FromBase64String(state.User.Claims.First(c => c.Type.Equals("Avatar")).Value);
            }

            return(user);
        }
コード例 #9
0
ファイル: UserSocket.cs プロジェクト: Toni751/SEP3_Tier3
        /// <summary>
        /// Retrieves the user with the given email and password, if any
        /// </summary>
        /// <param name="actualRequest">the client request to be handled</param>
        /// <returns>the response to the given request</returns>
        private async Task <ActualRequest> LoginAsync(ActualRequest actualRequest)
        {
            Request          request           = actualRequest.Request;
            string           credentialsAsJson = request.Argument.ToString();
            LoginCredentials loginCredentials  = JsonSerializer.Deserialize <LoginCredentials>(credentialsAsJson);

            Console.WriteLine("Got login credentials " + loginCredentials.Email + loginCredentials.Password);
            UserShortVersion loginResult = await userRepo.LoginAsync(loginCredentials.Email, loginCredentials.Password);

            Request requestResponse = new Request
            {
                ActionType = ActionType.USER_LOGIN.ToString(),
                Argument   = JsonSerializer.Serialize(loginResult)
            };

            if (loginResult == null)
            {
                return new ActualRequest
                       {
                           Request = requestResponse,
                           Images  = null
                       }
            }
            ;
            List <byte[]> images = new List <byte[]>();

            if (!loginResult.AccountType.Equals("Administrator"))
            {
                try
                {
                    byte[] readFile = File.ReadAllBytes($"{FILE_PATH}/Users/{loginResult.UserId}/avatar.jpg");
                    images.Add(readFile);
                }
                catch (Exception e)
                {
                    Console.WriteLine("No avatar found for user " + loginResult.UserId);
                }
            }

            return(new ActualRequest
            {
                Request = requestResponse,
                Images = images
            });
        }
コード例 #10
0
        public async Task <UserShortVersion> Login(Login login)
        {
            HttpResponseMessage result =
                await client.GetAsync($"{uri}/login?email={login.Email}&password={login.Password}");

            if (result.IsSuccessStatusCode)
            {
                string responseString = await result.Content.ReadAsStringAsync();

                UserShortVersion user = JsonSerializer.Deserialize <UserShortVersion>(responseString);


                Console.WriteLine("TYPETYPETYPE" + user.AccountType);
                return(user);
            }

            return(null);
        }
        private ClaimsIdentity SetupClaimsForUser(UserShortVersion user)
        {
            List <Claim> claims = new List <Claim>();

            claims.Add(new Claim("Id", user.UserId.ToString()));
            if (user.UserFullName != null)
            {
                claims.Add(new Claim("Name", user.UserFullName));
            }
            claims.Add(new Claim("AccountType", user.AccountType));
            if (user.Avatar != null)
            {
                claims.Add(new Claim("Avatar", Convert.ToBase64String(user.Avatar)));
            }

            ClaimsIdentity identity = new ClaimsIdentity(claims, "apiauth_type");

            return(identity);
        }
        public override async Task <AuthenticationState> GetAuthenticationStateAsync()
        {
            var identity = new ClaimsIdentity();

            if (CachedUser == null)
            {
                string userAsJson = await jsRuntime.InvokeAsync <string>("sessionStorage.getItem", "currentUser");

                if (!string.IsNullOrEmpty(userAsJson))
                {
                    CachedUser = JsonSerializer.Deserialize <UserShortVersion>(userAsJson);
                    identity   = SetupClaimsForUser(CachedUser);
                }
            }
            else
            {
                identity = SetupClaimsForUser(CachedUser);
            }

            ClaimsPrincipal cachedClaimsPrincipal = new ClaimsPrincipal(identity);

            return(await Task.FromResult(new AuthenticationState(cachedClaimsPrincipal)));
        }
コード例 #13
0
 public static string GetUserAvatar(UserShortVersion user)
 {
     return(String.Format("data:image/gif;base64,{0}", Convert.ToBase64String(user.Avatar)));
 }