Exemple #1
0
        /// <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 _freeSql.Select <LinUserIdentity>().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);

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

            return(userId);
        }
        public async Task <IActionResult> Login([FromForm] LoginViewModel viewModel)
        {
            LinUser user = await userRepository.GetUserAsync(r => r.Username == viewModel.Username || r.Email == viewModel.Username);

            if (user == null)
            {
                ModelState.AddModelError("", "用户不存在");
                viewModel.Password = string.Empty;
                return(View(viewModel));
            }

            bool valid = await userIdentityService.VerifyUserPasswordAsync(user.Id, viewModel.Password);

            if (!valid)
            {
                ModelState.AddModelError("", "Invalid username or password");
                viewModel.Password = string.Empty;
                return(View(viewModel));
            }

            // Use an IdentityServer-compatible ClaimsPrincipal
            var identityServerUser = new IdentityServerUser(user.Id.ToString());

            identityServerUser.DisplayName = viewModel.Username;

            //await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, identityServerUser.CreatePrincipal());
            var props = new AuthenticationProperties
            {
                IsPersistent = true,
                ExpiresUtc   = DateTimeOffset.UtcNow.Add(TimeSpan.FromDays(1))
            };
            await HttpContext.SignInAsync(identityServerUser, props);

            return(Redirect(viewModel.ReturnUrl));
        }
Exemple #3
0
        /// <summary>
        /// 修改指定字段,邮件和组别
        /// </summary>
        /// <param name="id"></param>
        /// <param name="updateUserDto"></param>
        /// <returns></returns>
        public void UpdateUserInfo(int id, UpdateUserDto updateUserDto)
        {
            //此方法适用于更新字段少时
            //_freeSql.Update<LinUser>(id).Set(a => new LinUser()
            //{
            //    Email = updateUserDto.Email,
            //    GroupId = updateUserDto.GroupId
            //}).ExecuteAffrows();

            //需要多查一次
            LinUser linUser = _userRepository.Where(r => r.Id == id).ToOne();

            if (linUser == null)
            {
                throw new LinCmsException("用户不存在", ErrorCode.NotFound);
            }
            //赋值过程可使用AutoMapper简化
            //只更新 Email、GroupId
            // UPDATE `lin_user` SET `email` = ?p_0, `group_id` = ?p_1
            // WHERE(`id` = 1) AND(`is_deleted` = 0)
            //linUser.Email = updateUserDto.Email;
            //linUser.GroupId = updateUserDto.GroupId;

            _mapper.Map(updateUserDto, linUser);

            _userRepository.Update(linUser);
        }
Exemple #4
0
        public void Register(LinUser user)
        {
            bool isExistGroup = _groupRepository.Select.Any(r => r.Id == user.GroupId);

            if (!isExistGroup)
            {
                throw new LinCmsException("分组不存在", ErrorCode.NotFound);
            }

            bool isRepeatNickName = _userRepository.Select.Any(r => r.Nickname == user.Nickname);

            if (isRepeatNickName)
            {
                throw new LinCmsException("用户名重复,请重新输入", ErrorCode.RepeatField);
            }

            if (!string.IsNullOrEmpty(user.Email.Trim()))
            {
                var isRepeatEmail = _userRepository.Select.Any(r => r.Email == user.Email.Trim());
                if (isRepeatEmail)
                {
                    throw new LinCmsException("注册邮箱重复,请重新输入", ErrorCode.RepeatField);
                }
            }

            user.Active   = 1;
            user.Admin    = 1;
            user.Password = LinCmsUtils.Get32Md5(user.Password);

            _userRepository.Insert(user);
        }
        public ResultDto Post([FromBody] CreateMessageBoardDto createMessageBoardDto)
        {
            MessageBoard messageBoard = _mapper.Map <MessageBoard>(createMessageBoardDto);

            messageBoard.Ip       = this.GetIp();
            messageBoard.Agent    = Request.Headers["User-agent"].ToString();
            messageBoard.UserHost = Dns.GetHostName();
            messageBoard.System   = LinCmsUtils.GetOsNameByUserAgent(messageBoard.Agent);
            if (messageBoard.Ip.IsNotNullOrEmpty())
            {
                IpQueryResult ipQueryResult = LinCmsUtils.IpQueryCity(messageBoard.Ip);
                messageBoard.GeoPosition = ipQueryResult.errno == 0 ? ipQueryResult.data : ipQueryResult.errmsg;
            }

            LinUser linUser = _userService.GetCurrentUser();

            if (linUser == null)
            {
                messageBoard.Avatar = "/assets/user/" + new Random().Next(1, 360) + ".png";
            }
            else
            {
                messageBoard.Avatar = _currentUser.GetFileUrl(linUser.Avatar);
            }

            _messageBoardRepository.Insert(messageBoard);
            return(ResultDto.Success("留言成功"));
        }
        public async Task <Tokens> GetRefreshTokenAsync(string refreshToken)
        {
            LinUser user = await _userRepository.GetUserAsync(r => r.RefreshToken == refreshToken);

            if (user.IsNull())
            {
                throw new LinCmsException("该refreshToken无效!");
            }

            if (DateTime.Compare(user.LastLoginTime, DateTime.Now) > new TimeSpan(30, 0, 0, 0).Ticks)
            {
                throw new LinCmsException("请重新登录", ErrorCode.RefreshTokenError);
            }

            List <Claim> claims = new List <Claim>()
            {
                new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()),
                new Claim(ClaimTypes.Email, user.Email ?? ""),
                new Claim(ClaimTypes.GivenName, user.Nickname ?? ""),
                new Claim(ClaimTypes.Name, user.Username ?? ""),
            };

            _logger.LogInformation($"用户{user.Username},JwtRefreshToken 刷新-登录成功,{JsonConvert.SerializeObject(claims)}");

            string token = _jsonWebTokenService.Encode(claims);

            refreshToken = GenerateToken();
            user.AddRefreshToken(refreshToken);
            await _userRepository.UpdateAsync(user);

            return(new Tokens(token, refreshToken));
        }
Exemple #7
0
        public async Task <string> JwtLogin(LoginInputDto loginInputDto)
        {
            LinUser user = await _userRepository.GetUserAsync(r => r.Username == loginInputDto.Username);

            if (user == null)
            {
                throw new LinCmsException("用户不存在", ErrorCode.NotFound);
            }

            bool valid = await _userIdentityService.VerifyUserPasswordAsync(user.Id, loginInputDto.Password);

            if (!valid)
            {
                throw new LinCmsException("请输入正确密码", ErrorCode.ParameterError);
            }

            await _userRepository.UpdateLastLoginTimeAsync(user.Id);

            List <Claim> claims = new List <Claim>()
            {
                new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()),
                new Claim(ClaimTypes.Email, user.Email ?? ""),
                new Claim(ClaimTypes.GivenName, user.Nickname ?? ""),
                new Claim(ClaimTypes.Name, user.Username ?? ""),
            };
            string token = _jsonWebTokenService.Encode(claims);

            return(token);
        }
Exemple #8
0
        public async Task <IActionResult> Login([FromForm] LoginViewModel viewModel)
        {
            LinUser user = await userRepository.GetUserAsync(r => r.Username == viewModel.Username || r.Email == viewModel.Username);

            if (user == null)
            {
                ModelState.AddModelError("", "用户不存在");
                viewModel.Password = string.Empty;
                return(View("/Views/Login.cshtml", viewModel));
            }

            bool valid = await userIdentityService.VerifyUserPasswordAsync(user.Id, viewModel.Password);

            if (!valid)
            {
                ModelState.AddModelError("", "Invalid username or password");
                viewModel.Password = string.Empty;
                return(View("/Views/Login.cshtml", viewModel));
            }

            // Use an IdentityServer-compatible ClaimsPrincipal
            var identityServerUser = new IdentityServerUser(viewModel.Username);

            identityServerUser.DisplayName = viewModel.Username;
            await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, identityServerUser.CreatePrincipal());

            return(Redirect(viewModel.ReturnUrl));
        }
Exemple #9
0
        public UserInformation Auths()
        {
            LinUser linUser = _freeSql.Select <LinUser>().Where(r => r.Id == _currentUser.Id).First();

            UserInformation user = _mapper.Map <UserInformation>(linUser);

            user.Avatar    = _currentUser.GetFileUrl(linUser.Avatar);
            user.GroupName = user.GroupId != null?_freeSql.Select <LinGroup>().Where(r => r.Id == user.GroupId).First()?.Info : "";

            if (linUser.IsAdmin())
            {
                user.Auths = new List <IDictionary <string, object> >();
            }
            else
            {
                if (linUser.GroupId != 0)
                {
                    List <LinAuth> listAuths = _freeSql.Select <LinAuth>().Where(r => r.GroupId == linUser.GroupId).ToList();

                    user.Auths = ReflexHelper.AuthsConvertToTree(listAuths);;
                }
            }

            return(user);
        }
        public void Post(long subscribeUserId)
        {
            if (subscribeUserId == _currentUser.Id)
            {
                throw new LinCmsException("您无法关注自己");
            }
            LinUser linUser = _userRepository.Select.Where(r => r.Id == subscribeUserId).ToOne();

            if (linUser == null)
            {
                throw new LinCmsException("该用户不存在");
            }

            if (!linUser.IsActive())
            {
                throw new LinCmsException("该用户已被拉黑");
            }

            bool any = _userSubscribeRepository.Select.Any(r =>
                                                           r.CreateUserId == _currentUser.Id && r.SubscribeUserId == subscribeUserId);

            if (any)
            {
                throw new LinCmsException("您已关注该用户");
            }

            UserSubscribe userSubscribe = new UserSubscribe()
            {
                SubscribeUserId = subscribeUserId
            };

            _userSubscribeRepository.Insert(userSubscribe);
        }
Exemple #11
0
        public UnifyResponseDto Post([FromBody] RegisterDto registerDto)
        {
            LinUser user = _mapper.Map <LinUser>(registerDto);

            _userSevice.CreateAsync(user, new List <long>(), registerDto.Password);
            return(UnifyResponseDto.Success("注册成功"));
        }
Exemple #12
0
        public async Task CreateAsync(CreateMessageBoardDto createMessageBoardDto)
        {
            MessageBoard messageBoard = _mapper.Map <MessageBoard>(createMessageBoardDto);

            messageBoard.Ip       = this.GetIp();
            messageBoard.Agent    = _httpContextAccessor.HttpContext.Request.Headers["User-agent"].ToString();
            messageBoard.UserHost = Dns.GetHostName();
            messageBoard.System   = LinCmsUtils.GetOsNameByUserAgent(messageBoard.Agent);
            if (messageBoard.Ip.IsNotNullOrEmpty())
            {
                IpQueryResult ipQueryResult = LinCmsUtils.IpQueryCity(messageBoard.Ip);
                messageBoard.GeoPosition = ipQueryResult.errno == 0 ? ipQueryResult.data : ipQueryResult.errmsg;
            }

            LinUser linUser = await _userService.GetCurrentUserAsync();

            if (linUser == null)
            {
                messageBoard.Avatar = "/assets/user/" + new Random().Next(1, 360) + ".png";
            }
            else
            {
                messageBoard.Avatar = _currentUser.GetFileUrl(linUser.Avatar);
            }

            await _messageBoardRepository.InsertAsync(messageBoard);
        }
Exemple #13
0
        /// <summary>
        /// 验证密码是否正确,生成Claims,返回用户身份信息
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public async Task ValidateAsync(ResourceOwnerPasswordValidationContext context)
        {
            LinUser user = await _userRepository.Select.Where(r => r.Username == context.UserName || r.Email == context.UserName).ToOneAsync();

            if (user == null)
            {
                context.Result = new GrantValidationResult(TokenRequestErrors.InvalidGrant, "用户不存在");
                return;
            }

            bool valid = await _userIdentityService.VerifyUserPasswordAsync(user.Id, context.Password, user.Salt);

            if (!valid)
            {
                context.Result = new GrantValidationResult(TokenRequestErrors.InvalidGrant, "请输入正确密码!");
                return;
            }

            user.LastLoginTime = DateTime.Now;
            await _userRepository.UpdateAsync(user);

            //subjectId 为用户唯一标识 一般为用户id
            //authenticationMethod 描述自定义授权类型的认证方法
            //authTime 授权时间
            //claims 需要返回的用户身份信息单元
            context.Result = new GrantValidationResult(user.Id.ToString(), OidcConstants.AuthenticationMethods.Password);
        }
Exemple #14
0
        public async Task <UnifyResponseDto> Register([FromBody] RegisterDto registerDto, [FromServices] IMapper _mapper, [FromServices] IUserService _userSevice)
        {
            LinUser user = _mapper.Map <LinUser>(registerDto);
            await _userSevice.CreateAsync(user, new List <long>(), registerDto.Password);

            return(UnifyResponseDto.Success("注册成功"));
        }
        /// <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>
        /// <exception cref="NotImplementedException"></exception>
        public async Task <long> SaveQQAsync(ClaimsPrincipal principal, string openId)
        {
            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 avatar         = principal.FindFirst(QQAuthenticationConstants.Claims.AvatarUrl)?.Value;
            string avatar_full    = principal.FindFirst(QQAuthenticationConstants.Claims.AvatarFullUrl)?.Value;

            Expression <Func <LinUserIdentity, bool> > expression = r =>
                                                                    r.IdentityType == LinUserIdentity.QQ && 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        = avatar_full,
                    CreateTime    = DateTime.Now,
                    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
                        {
                            CreateTime   = DateTime.Now,
                            Credential   = openId,
                            IdentityType = LinUserIdentity.GitHub,
                            Identifier   = nickname,
                        }
                    }
                };
                await _userRepository.InsertAsync(user);

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

            return(userId);
        }
        private async Task <Tokens> CreateTokenAsync(LinUser user)
        {
            List <Claim> claims = new List <Claim>()
            {
                new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()),
                new Claim(ClaimTypes.Email, user.Email ?? ""),
                new Claim(ClaimTypes.GivenName, user.Nickname ?? ""),
                new Claim(ClaimTypes.Name, user.Username ?? ""),
            };

            user.LinGroups?.ForEach(r =>
            {
                claims.Add(new Claim(ClaimTypes.Role, r.Name));
                claims.Add(new Claim(LinCmsClaimTypes.Groups, r.Id.ToString()));
            });

            string token = _jsonWebTokenService.Encode(claims);

            string refreshToken = GenerateToken();

            user.AddRefreshToken(refreshToken);
            await _userRepository.UpdateAsync(user);

            return(new Tokens(token, refreshToken));
        }
Exemple #17
0
        public UserInformation GetInformation()
        {
            LinUser linUser = _freeSql.Select <LinUser>().Where(r => r.Id == _currentUser.Id).First();

            linUser.Avatar = _currentUser.GetFileUrl(linUser.Avatar);

            return(_mapper.Map <UserInformation>(linUser));
        }
Exemple #18
0
        public UnifyResponseDto Post([FromBody] RegisterDto registerDto)
        {
            LinUser user = _mapper.Map <LinUser>(registerDto);

            user.Username = Guid.NewGuid().ToString().Substring(0, 24);
            _userSevice.CreateAsync(user, new List <long>(), registerDto.Password);

            return(UnifyResponseDto.Success("注册成功"));
        }
Exemple #19
0
        public ResultDto Post([FromBody] RegisterDto registerDto)
        {
            LinUser user = _mapper.Map <LinUser>(registerDto);

            user.GroupId = LinConsts.Group.User;
            _userSevice.Register(user);

            return(ResultDto.Success("注册成功"));
        }
Exemple #20
0
        public async Task ResetPasswordAsync(long id, ResetPasswordDto resetPasswordDto)
        {
            LinUser user = await _userRepository.Where(r => r.Id == id).FirstAsync();

            if (user == null)
            {
                throw new LinCmsException("用户不存在", ErrorCode.NotFound);
            }

            await _userIdentityService.ChangePasswordAsync(id, resetPasswordDto.ConfirmPassword, user.Salt);
        }
        /// <summary>
        /// 查找用户搜索分组,查找分组下的所有权限
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public async Task <List <LinPermission> > GetUserPermissions(long userId)
        {
            LinUser linUser = await _userRepository.GetUserAsync(r => r.Id == userId);

            List <long> groupIds = linUser.LinGroups.Select(r => r.Id).ToList();

            if (linUser.LinGroups == null || linUser.LinGroups.Count == 0)
            {
                return(new List <LinPermission>());
            }
            return(await _permissionService.GetPermissionByGroupIds(groupIds));
        }
        public async Task <long> SaveGiteeAsync(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);
        }
Exemple #23
0
        public async Task <OpenUserDto> GetUserByUserId(long userId)
        {
            LinUser linUser = await _freeSql.Select <LinUser>().WhereCascade(r => r.IsDeleted == false).Where(r => r.Id == userId).FirstAsync();

            OpenUserDto openUser = _mapper.Map <LinUser, OpenUserDto>(linUser);

            if (openUser == null)
            {
                return(null);
            }
            openUser.Avatar = _fileRepository.GetFileUrl(openUser.Avatar);
            return(openUser);
        }
        public OpenUserDto GetUserByUserId(long userId)
        {
            LinUser     linUser  = _freeSql.Select <LinUser>().WhereCascade(r => r.IsDeleted == false).Where(r => r.Id == userId).First();
            OpenUserDto openUser = _mapper.Map <LinUser, OpenUserDto>(linUser);

            if (openUser == null)
            {
                return(null);
            }
            openUser.Avatar = _currentUser.GetFileUrl(openUser.Avatar);

            return(openUser);
        }
Exemple #25
0
        public async Task <OpenUserDto?> GetUserByUserId(long userId)
        {
            LinUser linUser = await _userRepository.Where(r => r.Id == userId).FirstAsync();

            OpenUserDto openUser = _mapper.Map <LinUser, OpenUserDto>(linUser);

            if (openUser == null)
            {
                return(null);
            }
            openUser.Avatar = _fileRepository.GetFileUrl(openUser.Avatar);
            return(openUser);
        }
        private void Init(LinUser user)
        {
            Id       = user.Id;
            Username = user.Username;
            Nickname = user.Nickname;
            Avatar   = user.Avatar;
            Email    = user.Email;
            IsAdmin  = user.Admin == (short)UserAdmin.Admin;
            IsActive = user.Active == (short)UserActive.Active;

            SetRole(user.GroupId);
            SetGroupAndAuth(user.LinGroup);
        }
Exemple #27
0
        public async Task ChangePasswordAsync(ChangePasswordDto passwordDto)
        {
            long    currentUserId = CurrentUser.Id ?? 0;
            LinUser user          = await _userRepository.Where(r => r.Id == currentUserId).FirstAsync();

            bool valid = await _userIdentityService.VerifyUserPasswordAsync(currentUserId, passwordDto.OldPassword, user.Salt);

            if (!valid)
            {
                throw new LinCmsException("旧密码不正确");
            }

            await _userIdentityService.ChangePasswordAsync(user.Id, passwordDto.NewPassword, user.Salt);
        }
        /// <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);
        }
Exemple #29
0
        public async Task Post(long subscribeUserId)
        {
            if (subscribeUserId == _currentUser.Id)
            {
                throw new LinCmsException("您无法关注自己");
            }

            LinUser linUser = _userRepository.Select.Where(r => r.Id == subscribeUserId).ToOne();

            if (linUser == null)
            {
                throw new LinCmsException("该用户不存在");
            }

            if (!linUser.IsActive())
            {
                throw new LinCmsException("该用户已被拉黑");
            }

            bool any = _userSubscribeRepository.Select.Any(r =>
                                                           r.CreateUserId == _currentUser.Id && r.SubscribeUserId == subscribeUserId);

            if (any)
            {
                throw new LinCmsException("您已关注该用户");
            }

            using (IUnitOfWork unitOfWork = _unitOfWorkManager.Begin())
            {
                using ICapTransaction capTransaction = unitOfWork.BeginTransaction(_capBus, false);

                UserSubscribe userSubscribe = new UserSubscribe()
                {
                    SubscribeUserId = subscribeUserId
                };
                await _userSubscribeRepository.InsertAsync(userSubscribe);

                await _capBus.PublishAsync("NotificationController.Post", new CreateNotificationDto()
                {
                    NotificationType       = NotificationType.UserLikeUser,
                    NotificationRespUserId = subscribeUserId,
                    UserInfoId             = _currentUser.Id ?? 0,
                    CreateTime             = DateTime.Now,
                });

                await capTransaction.CommitAsync();
            }
        }
        public async Task <UserInformation> GetInformationAsync(long userId)
        {
            LinUser linUser = await _userRepository.GetUserAsync(r => r.Id == userId);

            if (linUser == null)
            {
                return(null);
            }
            linUser.Avatar = _currentUser.GetFileUrl(linUser.Avatar);

            UserInformation userInformation = _mapper.Map <UserInformation>(linUser);

            userInformation.Groups = linUser.LinGroups.Select(r => _mapper.Map <GroupDto>(r)).ToList();
            userInformation.Admin  = _currentUser.IsInGroup(LinConsts.Group.Admin);

            return(userInformation);
        }