/// <summary>
        /// 记录授权成功后的信息
        /// </summary>
        /// <param name="principal"></param>
        /// <param name="openId"></param>
        /// <returns></returns>
        public async Task <long> SaveGitHubAsync(ClaimsPrincipal principal, string openId)
        {
            string email        = principal.FindFirst(ClaimTypes.Email)?.Value;
            string name         = principal.FindFirst(ClaimTypes.Name)?.Value;
            string gitHubName   = principal.FindFirst(GitHubAuthenticationConstants.Claims.Name)?.Value;
            string gitHubApiUrl = principal.FindFirst(GitHubAuthenticationConstants.Claims.Url)?.Value;
            string avatarUrl    = principal.FindFirst(LinConsts.Claims.AvatarUrl)?.Value;
            string bio          = principal.FindFirst(LinConsts.Claims.BIO)?.Value;
            string blogAddress  = principal.FindFirst(LinConsts.Claims.BlogAddress)?.Value;
            Expression <Func <LinUserIdentity, bool> > expression = r =>
                                                                    r.IdentityType == LinUserIdentity.GitHub && r.Credential == openId;

            LinUserIdentity linUserIdentity = await _userIdentityRepository.Where(expression).FirstAsync();

            long userId = 0;

            if (linUserIdentity == null)
            {
                LinUser user = new LinUser
                {
                    Active        = (int)UserActive.Active,
                    Avatar        = avatarUrl,
                    CreateTime    = DateTime.Now,
                    LastLoginTime = DateTime.Now,
                    Email         = email,
                    Introduction  = bio,
                    LinUserGroups = new List <LinUserGroup>()
                    {
                        new LinUserGroup()
                        {
                            GroupId = LinConsts.Group.User
                        }
                    },
                    Nickname         = gitHubName,
                    Username         = "",
                    BlogAddress      = blogAddress,
                    LinUserIdentitys = new List <LinUserIdentity>()
                    {
                        new LinUserIdentity
                        {
                            CreateTime   = DateTime.Now,
                            Credential   = openId,
                            IdentityType = LinUserIdentity.GitHub,
                            Identifier   = name,
                        }
                    }
                };
                await _userRepository.InsertAsync(user);

                userId = user.Id;
            }
            else
            {
                userId = linUserIdentity.CreateUserId;
                await _userRepository.UpdateLastLoginTimeAsync(linUserIdentity.CreateUserId);
            }

            return(userId);
        }
        public async Task ChangePasswordAsync(long userId, string newpassword)
        {
            var linUserIdentity = await _userIdentityRepository
                                  .Where(a => a.CreateUserId == userId && a.IdentityType == LinUserIdentity.Password)
                                  .FirstAsync();

            await this.ChangePasswordAsync(linUserIdentity, newpassword);
        }
        public async Task <GroupDto> GetAsync(long id)
        {
            LinGroup group = await _groupRepository.Where(r => r.Id == id).FirstAsync();

            GroupDto groupDto = _mapper.Map <GroupDto>(group);

            groupDto.Permissions = await _permissionService.GetPermissionByGroupIds(new List <long>() { id });

            return(groupDto);
        }
        /// <summary>
        /// 检查当前登录的用户的分组权限
        /// </summary>
        /// <param name="permission"></param>
        /// <returns></returns>
        public async Task <bool> CheckPermissionAsync(string permission)
        {
            long[] groups = CurrentUser.Groups;

            LinPermission linPermission = await _permissionRepository.Where(r => r.Name == permission).FirstAsync();

            bool existPermission = await _groupPermissionRepository.Select
                                   .AnyAsync(r => groups.Contains(r.GroupId) && r.PermissionId == linPermission.Id);

            return(existPermission);
        }
Example #5
0
        protected override async Task HandleRequirementAsync(AuthorizationHandlerContext context, ValidJtiRequirement requirement)
        {
            //检查是否登录
            AuthorizationFilterContext?filterContext      = context.Resource as AuthorizationFilterContext;
            DefaultHttpContext?        defaultHttpContext = context.Resource as DefaultHttpContext;

            if (!context.User.Identity.IsAuthenticated)
            {
                HandlerAuthenticationFailed(filterContext, "认证失败,请检查请求头或者重新登陆", ErrorCode.AuthenticationFailed);
                context.Fail();
                return;
            }

            // 检查 jti 是否在黑名单
            string?jti = await _contextAccessor.HttpContext.GetTokenAsync("Bearer", "access_token");

            var tokenExists = _blackRecordRepository.Where(r => r.Jti == jti).Any();

            if (tokenExists)
            {
                HandlerAuthenticationFailed(filterContext, "The token is expired!", ErrorCode.AuthenticationFailed);
                context.Fail();
                return;
            }
            context.Succeed(requirement);
        }
        public async Task <UnifyResponseDto> UploadTagByJson()
        {
            string tagPath = Path.Combine(_hostingEnv.WebRootPath, "json-tag.json");
            string text    = System.IO.File.ReadAllText(tagPath);

            JObject json = JsonConvert.DeserializeObject <JObject>(text);

            foreach (var tag in json["d"]["tags"])
            {
                string tagName = tag["title"].ToString();
                bool   valid   = await _tagAuditBaseRepository.Where(r => r.TagName == tagName).AnyAsync();

                if (valid)
                {
                    Console.WriteLine($"{tagName}已存在,不需要生成");
                    continue;
                }

                FileDto fileDto = this.UploadToQiniu(tag["icon"].ToString());

                var tagEntity = new CreateUpdateTagDto()
                {
                    TagName   = tagName,
                    Alias     = tag["alias"].ToString(),
                    Status    = true,
                    Thumbnail = fileDto.Path
                };
                await _tagService.CreateAsync(tagEntity);
            }

            return(UnifyResponseDto.Success());
        }
Example #7
0
        public async Task UpdateLikeQuantityAysnc(Guid subjectId, int likesQuantity)
        {
            Article article = await _articleRepository.Where(r => r.Id == subjectId).ToOneAsync();

            article.UpdateLikeQuantity(likesQuantity);
            await _articleRepository.UpdateAsync(article);
        }
        public async Task <List <LinPermission> > GetPermissionByGroupIds(List <long> groupIds)
        {
            List <long> permissionIds = _groupPermissionRepository
                                        .Where(a => groupIds.Contains(a.GroupId))
                                        .ToList(r => r.PermissionId);

            List <LinPermission> listPermissions = await _permissionRepository
                                                   .Where(a => permissionIds.Contains(a.Id))
                                                   .ToListAsync();

            return(listPermissions);
        }
Example #9
0
        public override async Task <long> SaveUserAsync(ClaimsPrincipal principal, string openId)
        {
            LinUserIdentity linUserIdentity = await _userIdentityRepository.Where(r => r.IdentityType == LinUserIdentity.Gitee && r.Credential == openId).FirstAsync();

            long userId = 0;

            if (linUserIdentity == null)
            {
                string email = principal.FindFirst(ClaimTypes.Email)?.Value;
                string name  = principal.FindFirst(ClaimTypes.Name)?.Value;

                //string giteeUrl = principal.FindFirst(GiteeAuthenticationConstants.Claims.Url)?.Value;
                string nickname = principal.FindFirst(GiteeAuthenticationConstants.Claims.Name)?.Value;

                string avatarUrl   = principal.FindFirst("urn:gitee:avatar_url")?.Value;
                string blogAddress = principal.FindFirst("urn:gitee:blog")?.Value;
                string bio         = principal.FindFirst("urn:gitee:bio")?.Value;
                string htmlUrl     = principal.FindFirst("urn:gitee:html_url")?.Value;

                LinUser user = new LinUser
                {
                    Active        = UserActive.Active,
                    Avatar        = avatarUrl,
                    LastLoginTime = DateTime.Now,
                    Email         = email,
                    Introduction  = bio + htmlUrl,
                    LinUserGroups = new List <LinUserGroup>()
                    {
                        new LinUserGroup()
                        {
                            GroupId = LinConsts.Group.User
                        }
                    },
                    Nickname         = nickname,
                    Username         = "",
                    BlogAddress      = blogAddress,
                    LinUserIdentitys = new List <LinUserIdentity>()
                    {
                        new LinUserIdentity(LinUserIdentity.Gitee, name, openId, DateTime.Now)
                    }
                };
                await _userRepository.InsertAsync(user);

                userId = user.Id;
            }
            else
            {
                userId = linUserIdentity.CreateUserId;
            }

            return(userId);
        }
Example #10
0
        /// <summary>
        /// 本地文件上传,秒传(根据lin_file表中的md5,与当前文件的路径是否在本地),如果不在,重新上传,覆盖文件表记录
        /// </summary>
        /// <param name="file"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        public async Task <FileDto> UploadAsync(IFormFile file, int key = 0)
        {
            string  md5     = LinCmsUtils.GetHash <MD5>(file.OpenReadStream());
            LinFile linFile = await _fileRepository.Where(r => r.Md5 == md5 && r.Type == 1).OrderByDescending(r => r.CreateTime).FirstAsync();

            if (linFile != null && File.Exists(Path.Combine(_hostingEnv.WebRootPath, linFile.Path)))
            {
                return(new FileDto
                {
                    Id = linFile.Id,
                    Key = "file_" + key,
                    Path = linFile.Path,
                    Url = _fileStorageOption.LocalFile.Host + linFile.Path
                });
            }

            long id;

            var(path, len) = await this.LocalUploadAsync(file);

            if (linFile == null)
            {
                LinFile saveLinFile = new LinFile()
                {
                    Extension = Path.GetExtension(file.FileName),
                    Md5       = md5,
                    Name      = file.FileName,
                    Path      = path,
                    Type      = 1,
                    Size      = len
                };
                id = (await _fileRepository.InsertAsync(saveLinFile)).Id;
            }
            else
            {
                linFile.Path = path;
                await _fileRepository.UpdateAsync(linFile);

                id = linFile.Id;
            }

            return(new FileDto
            {
                Id = id,
                Key = "file_" + key,
                Path = path,
                Url = _fileStorageOption.LocalFile.Host + path
            });
        }
        /// <summary>
        /// qq快速登录的信息,唯一值openid,昵称(nickname),性别(gender),picture(30像素),picture_medium(50像素),picture_full 100 像素,avatar(40像素),avatar_full(100像素)
        /// </summary>
        /// <param name="principal"></param>
        /// <param name="openId"></param>
        /// <returns></returns>
        public override async Task <long> SaveUserAsync(ClaimsPrincipal principal, string openId)
        {
            LinUserIdentity linUserIdentity = await _userIdentityRepository.Where(r => r.IdentityType == LinUserIdentity.QQ && r.Credential == openId).FirstAsync();

            long userId = 0;

            if (linUserIdentity == null)
            {
                string nickname       = principal.FindFirst(ClaimTypes.Name)?.Value ?? "默认昵称";
                string gender         = principal.FindFirst(ClaimTypes.Gender)?.Value;
                string picture        = principal.FindFirst(QQAuthenticationConstants.Claims.PictureUrl)?.Value;
                string picture_medium = principal.FindFirst(QQAuthenticationConstants.Claims.PictureMediumUrl)?.Value;
                string picture_full   = principal.FindFirst(QQAuthenticationConstants.Claims.PictureFullUrl)?.Value;
                string avatarUrl      = principal.FindFirst(QQAuthenticationConstants.Claims.AvatarUrl)?.Value;
                string avatarFullUrl  = principal.FindFirst(QQAuthenticationConstants.Claims.AvatarFullUrl)?.Value;

                LinUser user = new LinUser
                {
                    Active        = UserActive.Active,
                    Avatar        = avatarFullUrl,
                    LastLoginTime = DateTime.Now,
                    Email         = "",
                    Introduction  = "",
                    LinUserGroups = new List <LinUserGroup>()
                    {
                        new LinUserGroup()
                        {
                            GroupId = LinConsts.Group.User
                        }
                    },
                    Nickname         = nickname,
                    Username         = "",
                    BlogAddress      = "",
                    LinUserIdentitys = new List <LinUserIdentity>()
                    {
                        new LinUserIdentity(LinUserIdentity.QQ, nickname, openId, DateTime.Now)
                    }
                };
                await _userRepository.InsertAsync(user);

                userId = user.Id;
            }
            else
            {
                userId = linUserIdentity.CreateUserId;
            }

            return(userId);
        }
Example #12
0
        private async Task <UnifyResponseDto> BindAsync(string identityType, string name, string openId, long userId)
        {
            LinUserIdentity linUserIdentity = await _userIdentityRepository.Where(r => r.IdentityType == identityType && r.Credential == openId).FirstAsync();

            if (linUserIdentity == null)
            {
                var userIdentity = new LinUserIdentity(identityType, name, openId, DateTime.Now);
                userIdentity.CreateUserId = userId;
                await _userIdentityRepository.InsertAsync(userIdentity);

                return(UnifyResponseDto.Success("绑定成功"));
            }
            else
            {
                return(UnifyResponseDto.Error("绑定失败,该用户已绑定其他账号"));
            }
        }
Example #13
0
        /// <summary>
        /// 根据用户点赞类型:文章、评论,得到消息的NotificationRespUserId的值
        /// </summary>
        /// <param name="createUpdateUserLike"></param>
        /// <returns></returns>
        private async Task PublishUserLikeNotification(CreateUpdateUserLikeDto createUpdateUserLike)
        {
            var createNotificationDto = new CreateNotificationDto()
            {
                UserInfoId = _currentUser.Id ?? 0,
                CreateTime = DateTime.Now,
            };

            switch (createUpdateUserLike.SubjectType)
            {
            case UserLikeSubjectType.UserLikeArticle:

                Article subjectArticle = await _articleRepository.Where(r => r.Id == createUpdateUserLike.SubjectId).ToOneAsync();

                createNotificationDto.NotificationRespUserId = subjectArticle.CreateUserId;
                createNotificationDto.NotificationType       = NotificationType.UserLikeArticle;
                createNotificationDto.ArticleId = createUpdateUserLike.SubjectId;
                break;

            case UserLikeSubjectType.UserLikeComment:

                Comment subjectComment = await _commentRepository.Where(r => r.Id == createUpdateUserLike.SubjectId).ToOneAsync();

                createNotificationDto.NotificationRespUserId = subjectComment.CreateUserId;
                createNotificationDto.NotificationType       = NotificationType.UserLikeArticleComment;
                createNotificationDto.ArticleId = subjectComment.SubjectId;
                createNotificationDto.CommentId = createUpdateUserLike.SubjectId;
                break;
            }


            if (createNotificationDto.NotificationRespUserId != 0 && _currentUser.Id != createNotificationDto.NotificationRespUserId)
            {
                using ICapTransaction trans = UnitOfWork.BeginTransaction(_capBus, false);

                _capBus.Publish("NotificationController.Post", createNotificationDto);

                trans.Commit();
            }
        }
Example #14
0
        /// <summary>
        /// 上传文件至七牛云,如果本地存在这条记录,直接返回文件的信息
        /// </summary>
        /// <param name="file">单个文件</param>
        /// <param name="key"></param>
        /// <returns></returns>
        public async Task <FileDto> UploadAsync(IFormFile file, int key = 0)
        {
            string md5 = LinCmsUtils.GetHash <MD5>(file.OpenReadStream());

            LinFile linFile = await _fileRepository.Where(r => r.Md5 == md5 && r.Type == 2).FirstAsync();

            if (linFile != null)
            {
                return(new FileDto
                {
                    Id = linFile.Id,
                    Key = "file_" + key,
                    Path = linFile.Path,
                    Url = _fileStorageOption.Qiniu.Host + linFile.Path
                });
            }

            string path = this.QiniuUpload(file);

            LinFile saveLinFile = new LinFile()
            {
                Extension = Path.GetExtension(file.FileName),
                Md5       = md5,
                Name      = file.FileName,
                Path      = path,
                Type      = 2,
                Size      = file.Length,
            };

            long id = (await _fileRepository.InsertAsync(saveLinFile)).Id;

            return(new FileDto
            {
                Id = id,
                Key = "file_" + key,
                Path = path,
                Url = _fileStorageOption.Qiniu.Host + path
            });
        }
        public async Task UpdateLikeQuantity(Guid subjectId, int likesQuantity)
        {
            Article article = await _articleRepository.Where(r => r.Id == subjectId).ToOneAsync();

            if (article.IsAudit == false)
            {
                throw new LinCmsException("该文章因违规被拉黑");
            }

            if (likesQuantity < 0)
            {
                //防止数量一直减,减到小于0
                if (article.LikesQuantity < -likesQuantity)
                {
                    return;
                }
            }

            article.LikesQuantity += likesQuantity;
            await _articleRepository.UpdateAsync(article);

            //_articleRepository.UpdateDiy.Set(r => r.LikesQuantity + likesQuantity).Where(r => r.Id == subjectId).ExecuteAffrows();
        }
        /// <summary>
        /// 根据用户点赞类型:文章、评论,得到消息的NotificationRespUserId的值
        /// </summary>
        /// <param name="createUpdateUserLike"></param>
        /// <returns></returns>
        private async Task PublishUserLikeNotification(CreateUpdateUserLikeDto createUpdateUserLike, bool isCancel)
        {
            var createNotificationDto = new CreateNotificationDto()
            {
                UserInfoId = _currentUser.Id ?? 0,
                CreateTime = DateTime.Now,
                IsCancel   = isCancel
            };

            switch (createUpdateUserLike.SubjectType)
            {
            case UserLikeSubjectType.UserLikeArticle:

                Article subjectArticle = await _articleRepository.Where(r => r.Id == createUpdateUserLike.SubjectId).ToOneAsync();

                createNotificationDto.NotificationRespUserId = subjectArticle.CreateUserId;
                createNotificationDto.NotificationType       = NotificationType.UserLikeArticle;
                createNotificationDto.ArticleId = createUpdateUserLike.SubjectId;
                break;

            case UserLikeSubjectType.UserLikeComment:

                Comment subjectComment = await _commentRepository.Where(r => r.Id == createUpdateUserLike.SubjectId).ToOneAsync();

                createNotificationDto.NotificationRespUserId = subjectComment.CreateUserId;
                createNotificationDto.NotificationType       = NotificationType.UserLikeArticleComment;
                createNotificationDto.ArticleId = subjectComment.SubjectId;
                createNotificationDto.CommentId = createUpdateUserLike.SubjectId;
                break;
            }


            if (createNotificationDto.NotificationRespUserId != 0 && _currentUser.Id != createNotificationDto.NotificationRespUserId)
            {
                await _capBus.PublishAsync("NotificationController.Post", createNotificationDto);
            }
        }
 public List <long> GetUserGroupIdsByUserId(long userId)
 {
     return(_userGroupRepository.Where(r => r.UserId == userId).ToList(r => r.GroupId));
 }
Example #18
0
 public async Task <List <long> > GetGroupIdsByUserIdAsync(long userId)
 {
     return(await _userGroupRepository.Where(r => r.UserId == userId).ToListAsync(r => r.GroupId));
 }
Example #19
0
 public Task DeleteAsync(long userId)
 {
     return(_userIdentityRepository.Where(r => r.CreateUserId == userId).ToDelete().ExecuteAffrowsAsync());
 }
        public async Task <ArticleDraftDto> GetAsync(Guid id)
        {
            ArticleDraft articleDraft = await _articleDraftRepository.Where(r => r.Id == id && r.CreateUserId == _currentUser.Id).ToOneAsync();

            return(_mapper.Map <ArticleDraftDto>(articleDraft));
        }