public async Task <IActionResult> OnPostSetMyInfoAsync(RegisterRAppUser UserInfo)
        {
            LastError       = "";
            PasswordChanged = "";
            using (HttpClient secureClient = new HttpClient())
            {
                if (await GanjoorSessionChecker.PrepareClient(secureClient, Request, Response))
                {
                    var isAdminResponse = await secureClient.GetAsync($"{APIRoot.Url}/api/users/isadmin?userId={Request.Cookies["UserId"]}");

                    if (isAdminResponse.IsSuccessStatusCode)
                    {
                        UserInfo.IsAdmin = JsonConvert.DeserializeObject <bool>(await isAdminResponse.Content.ReadAsStringAsync());

                        var putResponse = await secureClient.PutAsync($"{APIRoot.Url}/api/users/{Request.Cookies["UserId"]}", new StringContent(JsonConvert.SerializeObject(UserInfo), Encoding.UTF8, "application/json"));

                        if (!putResponse.IsSuccessStatusCode)
                        {
                            LastError = JsonConvert.DeserializeObject <string>(await putResponse.Content.ReadAsStringAsync());
                        }
                    }
                    else
                    {
                        LastError = await isAdminResponse.Content.ReadAsStringAsync();
                    }
                }
                else
                {
                    LastError = "لطفا از گنجور خارج و مجددا به آن وارد شوید.";
                }
            }
            await _PreparePage();

            return(Page());
        }
        private async Task _PreparePage()
        {
            using (HttpClient secureClient = new HttpClient())
            {
                if (await GanjoorSessionChecker.PrepareClient(secureClient, Request, Response))
                {
                    var userInfoResponse = await secureClient.GetAsync($"{APIRoot.Url}/api/users/{Request.Cookies["UserId"]}");

                    if (userInfoResponse.IsSuccessStatusCode)
                    {
                        PublicRAppUser userInfo = JsonConvert.DeserializeObject <PublicRAppUser>(await userInfoResponse.Content.ReadAsStringAsync());

                        UserInfo = new RegisterRAppUser()
                        {
                            Id          = userInfo.Id,
                            Username    = userInfo.Username,
                            FirstName   = userInfo.FirstName,
                            SureName    = userInfo.SureName,
                            NickName    = userInfo.NickName,
                            PhoneNumber = userInfo.PhoneNumber,
                            Email       = userInfo.Email,
                            Website     = userInfo.Website,
                            Bio         = userInfo.Bio,
                            RImageId    = userInfo.RImageId,
                            Status      = userInfo.Status,
                            IsAdmin     = false,
                            Password    = ""
                        };
                    }
                    else
                    {
                        LastError = await userInfoResponse.Content.ReadAsStringAsync();
                    }
                }
                else
                {
                    LastError = "لطفا از گنجور خارج و مجددا به آن وارد شوید.";
                }
            }
        }
        public virtual async Task <IActionResult> Post([FromBody] RegisterRAppUser newUserInfo)
        {
            Guid loggedOnUserId = new Guid(User.Claims.FirstOrDefault(c => c.Type == "UserId").Value);

            if (newUserInfo.IsAdmin)
            {
                RServiceResult <bool> isAdmin = await _appUserService.IsAdmin(loggedOnUserId);

                if (!string.IsNullOrEmpty(isAdmin.ExceptionString))
                {
                    return(BadRequest(isAdmin.ExceptionString));
                }
                if (!isAdmin.Result)
                {
                    return(Forbid());//Only admin users can create admin users
                }
            }
            RServiceResult <RAppUser> result = await _appUserService.AddUser(newUserInfo);

            if (result.Result == null)
            {
                return(BadRequest(result.ExceptionString));
            }
            RegisterRAppUser registerRAppUser = new RegisterRAppUser()
            {
                Email       = result.Result.Email,
                Status      = result.Result.Status,
                FirstName   = result.Result.FirstName,
                SureName    = result.Result.SureName,
                Id          = result.Result.Id,
                IsAdmin     = newUserInfo.IsAdmin,
                PhoneNumber = newUserInfo.PhoneNumber,
                RImageId    = newUserInfo.RImageId,
                Username    = newUserInfo.Username
            };

            return(Ok(registerRAppUser));
        }
        public virtual async Task <IActionResult> Put(Guid id, [FromBody] RegisterRAppUser existingUserInfo)
        {
            Guid loggedOnUserId           = new Guid(User.Claims.FirstOrDefault(c => c.Type == "UserId").Value);
            RServiceResult <bool> isAdmin = await _appUserService.IsAdmin(loggedOnUserId);

            if (!string.IsNullOrEmpty(isAdmin.ExceptionString))
            {
                return(BadRequest(isAdmin.ExceptionString));
            }
            RServiceResult <PublicRAppUser> userInfo = await _appUserService.GetUserInformation(id);

            if (!isAdmin.Result)
            {
                if (!string.IsNullOrEmpty(userInfo.ExceptionString))
                {
                    return(BadRequest(userInfo.ExceptionString));
                }

                if (existingUserInfo.IsAdmin)
                {
                    return(Forbid());//You should be admin to make other users admin
                }
                RServiceResult <bool> isEditingUserAdmin = await _appUserService.IsAdmin(id);

                if (!string.IsNullOrEmpty(isEditingUserAdmin.ExceptionString))
                {
                    return(BadRequest(isEditingUserAdmin.ExceptionString));
                }
                if (isEditingUserAdmin.Result)
                {
                    return(Forbid());//You can not modify admin users.
                }
                if (loggedOnUserId != id)
                {
                    RServiceResult <bool> canViewAllUsersInformation =
                        await _userPermissionChecker.Check
                        (
                            loggedOnUserId,
                            new Guid(User.Claims.FirstOrDefault(c => c.Type == "SessionId").Value),
                            SecurableItem.UserEntityShortName,
                            SecurableItem.ModifyOperationShortName
                        );

                    if (!string.IsNullOrEmpty(canViewAllUsersInformation.ExceptionString))
                    {
                        return(BadRequest(canViewAllUsersInformation.ExceptionString));
                    }

                    if (!canViewAllUsersInformation.Result)
                    {
                        return(Forbid());
                    }
                }
            }

            if (loggedOnUserId == id && userInfo.Result.Username != existingUserInfo.Username)
            {
                return(BadRequest("You can not change your username!"));
            }
            if (loggedOnUserId == id && (existingUserInfo.Status != RAppUserStatus.Active))
            {
                return(BadRequest("You can not disable yourself!"));
            }
            if (loggedOnUserId == id && !string.IsNullOrEmpty(existingUserInfo.Password))
            {
                return(BadRequest("Please use setmypassword method to change your own password."));
            }

            RServiceResult <bool> res = await _appUserService.ModifyUser(id, existingUserInfo);

            if (!res.Result)
            {
                return(BadRequest(res.ExceptionString));
            }

            return(Ok(true));
        }
Exemple #5
0
        public async Task <IActionResult> OnGetAsync()
        {
            if (string.IsNullOrEmpty(Request.Cookies["Token"]))
            {
                return(Redirect("/"));
            }

            LastError = "";
            using (HttpClient secureClient = new HttpClient())
                if (await GanjoorSessionChecker.PrepareClient(secureClient, Request, Response))
                {
                    {
                        var userInfoResponse = await secureClient.GetAsync($"{APIRoot.Url}/api/users/{Request.Cookies["UserId"]}");

                        if (userInfoResponse.IsSuccessStatusCode)
                        {
                            PublicRAppUser userInfo = JsonConvert.DeserializeObject <PublicRAppUser>(await userInfoResponse.Content.ReadAsStringAsync());

                            UserInfo = new RegisterRAppUser()
                            {
                                Id          = userInfo.Id,
                                Username    = userInfo.Username,
                                FirstName   = userInfo.FirstName,
                                SureName    = userInfo.SureName,
                                NickName    = userInfo.NickName,
                                PhoneNumber = userInfo.PhoneNumber,
                                Email       = userInfo.Email,
                                Website     = userInfo.Website,
                                Bio         = userInfo.Bio,
                                RImageId    = userInfo.RImageId,
                                Status      = userInfo.Status,
                                IsAdmin     = false,
                                Password    = ""
                            };
                        }
                        else
                        {
                            LastError = await userInfoResponse.Content.ReadAsStringAsync();
                        }

                        int pageNumber = 1;
                        if (!string.IsNullOrEmpty(Request.Query["page"]))
                        {
                            pageNumber = int.Parse(Request.Query["page"]);
                        }
                        var response = await secureClient.GetAsync($"{APIRoot.Url}/api/ganjoor/comments/mine?PageNumber={pageNumber}&PageSize=20");

                        if (!response.IsSuccessStatusCode)
                        {
                            LastError = JsonConvert.DeserializeObject <string>(await response.Content.ReadAsStringAsync());
                            return(Page());
                        }

                        Comments = JArray.Parse(await response.Content.ReadAsStringAsync()).ToObject <List <GanjoorCommentFullViewModel> >();

                        string paginnationMetadata = response.Headers.GetValues("paging-headers").FirstOrDefault();
                        if (!string.IsNullOrEmpty(paginnationMetadata))
                        {
                            PaginationMetadata paginationMetadata = JsonConvert.DeserializeObject <PaginationMetadata>(paginnationMetadata);
                            PaginationLinks = new List <NameIdUrlImage>();
                            if (paginationMetadata.totalPages > 1)
                            {
                                if (paginationMetadata.currentPage > 3)
                                {
                                    PaginationLinks.Add
                                    (
                                        new NameIdUrlImage()
                                    {
                                        Name = "صفحهٔ اول",
                                        Url  = "/User/MyComments/?page=1"
                                    }
                                    );
                                }
                                for (int i = (paginationMetadata.currentPage - 2); i <= (paginationMetadata.currentPage + 2); i++)
                                {
                                    if (i >= 1 && i <= paginationMetadata.totalPages)
                                    {
                                        if (i == paginationMetadata.currentPage)
                                        {
                                            PaginationLinks.Add
                                            (
                                                new NameIdUrlImage()
                                            {
                                                Name = i.ToPersianNumbers(),
                                            }
                                            );
                                        }
                                        else
                                        {
                                            PaginationLinks.Add
                                            (
                                                new NameIdUrlImage()
                                            {
                                                Name = i.ToPersianNumbers(),
                                                Url  = $"/User/MyComments/?page={i}"
                                            }
                                            );
                                        }
                                    }
                                }
                                if (paginationMetadata.totalPages > (paginationMetadata.currentPage + 2))
                                {
                                    PaginationLinks.Add
                                    (
                                        new NameIdUrlImage()
                                    {
                                        Name = "... ",
                                    }
                                    );

                                    PaginationLinks.Add
                                    (
                                        new NameIdUrlImage()
                                    {
                                        Name = "صفحهٔ آخر",
                                        Url  = $"/User/MyComments/?page={paginationMetadata.totalPages}"
                                    }
                                    );
                                }
                            }
                        }
                    }
                }
                else
                {
                    LastError = "لطفا از گنجور خارج و مجددا به آن وارد شوید.";
                }
            return(Page());
        }
Exemple #6
0
        /// <summary>
        /// modify existing user /*update related entities cache*/
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="updateUserInfo"></param>
        /// <returns></returns>
        public override async Task <RServiceResult <bool> > ModifyUser(Guid userId, RegisterRAppUser updateUserInfo)
        {
            try
            {
                RAppUser unmodifiedUserInfo = await _userManager.FindByIdAsync(userId.ToString());

                if (unmodifiedUserInfo == null)
                {
                    return(new RServiceResult <bool>(false, "کاربر مورد نظر یافت نشد"));
                }

                string nickName = updateUserInfo.NickName;

                if (string.IsNullOrEmpty(nickName))
                {
                    return(new RServiceResult <bool>(false, "نام مستعار نمی‌تواند خالی باشد."));
                }

                nickName = nickName.Trim();

                RServiceResult <bool> res = await base.ModifyUser(userId, updateUserInfo);

                if (res.Result)
                {
                    try
                    {
                        if (nickName != updateUserInfo.NickName)
                        {
                            RMuseumDbContext context = _context as RMuseumDbContext;
                            var poemIdSet            = await context.GanjoorComments.AsNoTracking().Where(c => c.UserId == userId).Select(c => c.PoemId).ToListAsync();

                            foreach (var poemId in poemIdSet)
                            {
                                //await _ganjoorService.CacheCleanForPageById(poemId); /*had error in service initializtion, so done it in the dirty way*/

                                var dbPage = await context.GanjoorPages.Where(p => p.Id == poemId).AsNoTracking().SingleOrDefaultAsync();

                                if (dbPage != null)
                                {
                                    //CacheCleanForPageByUrl(dbPage.FullUrl);
                                    var url     = dbPage.FullUrl;
                                    var cachKey = $"GanjoorService::GetPageByUrl::{url}";
                                    if (_memoryCache.TryGetValue(cachKey, out GanjoorPageCompleteViewModel page))
                                    {
                                        _memoryCache.Remove(cachKey);

                                        var poemCachKey = $"GetPoemById({page.Id}, {true}, {false}, {true}, {true}, {true}, {true}, {true}, {true}, {true})";
                                        if (_memoryCache.TryGetValue(poemCachKey, out GanjoorPoemCompleteViewModel p))
                                        {
                                            _memoryCache.Remove(poemCachKey);
                                        }
                                    }
                                }
                            }
                        }
                    }
                    catch
                    {
                        return(new RServiceResult <bool>(true)); //ignore this error! because main operation was successfull!
                    }
                }
                return(res);
            }
            catch (Exception exp)
            {
                return(new RServiceResult <bool>(false, exp.ToString()));
            }
        }