public async Task <IActionResult> Authenticate([FromBody] AuthenticateDto model)
        {
            try
            {
                var payload = await GoogleJsonWebSignature.ValidateAsync(model.GoogleToken).ConfigureAwait(false);

                if (payload == null)
                {
                    return(Unauthorized());
                }

                var user = await _userService.Authenticate(payload.Email).ConfigureAwait(false);

                if (user == null)
                {
                    return(BadRequest(new { message = "User unidentified" }));
                }

                UserOutputDto userDto = _mapper.Map <UserOutputDto>(user);

                return(Ok(userDto));
            }
            catch (InvalidJwtException ex)
            {
                return(Unauthorized(new { message = ex.Message }));
            }
        }
Exemple #2
0
        public static Token CreateToken(UserOutputDto userOutput)
        {
            var header  = new JwtHeader(new SigningCredentials(SecretKey, SecurityAlgorithms.HmacSha256));
            var payload = new JwtPayload(
                Jwt.Issuer,
                Jwt.Audience,
                userOutput.Roles.Select(role => new Claim(ClaimTypes.Role, role)),
                DateTime.UtcNow,
                DateTime.UtcNow + Jwt.TokenLifetime
                );
            var dict = DictionaryHelper.ToDictionary(userOutput);

            foreach (var(key, value) in dict)
            {
                payload.Add(key, value);
            }

            var token = new JwtSecurityToken(header, payload);

            var refreshToken = Guid.NewGuid().ToString().Replace("-", "") + "." + userOutput.Id;
            var accessToken  = new Token
            {
                AccessToken  = Handler.WriteToken(token),
                Type         = "bearer",
                RefreshToken = refreshToken,
                Expires      = token.ValidTo
            };

            return(accessToken);
        }
Exemple #3
0
        public UserOutputDto CheckLogin(string username, string password)
        {
            User user = userRepository.Find(t => t.UserName == username);

            if (user != null)
            {
                UserOutputDto userOutputDto = new UserOutputDto();
                if (user.EnabledMark == true)
                {
                    string dbPassword = Md5.md5(DESEncrypt.Encrypt(password.ToLower(), user.SecretKey).ToLower(), 32).ToLower();
                    if (dbPassword == user.Password)
                    {
                        user.LastLoginTime = DateTime.Now;
                        userRepository.Update(user);
                        AutoMapper.Mapper.Map <User, UserOutputDto>(user, userOutputDto);
                        return(userOutputDto);
                    }
                    else
                    {
                        throw new Exception("密码不正确,请重新输入。");
                    }
                }
                else
                {
                    throw new Exception("账户被系统锁定,请联系管理员。");
                }
            }
            else
            {
                throw new Exception("账户不存在,请重新输入。");
            }
        }
Exemple #4
0
        public async Task <IActionResult> GetProfileAsync(Guid userId)
        {
            if (User.FindFirst("sub")?.Value != userId.ToString())
            {
                return(new ApiResult(ApiResultType.Error, "验证失败"));
            }

            var user = await _userManager.Users.FirstOrDefaultAsync(u => u.Id == userId && u.IsDeleted == false);

            var dto = new UserOutputDto();

            if (user != null)
            {
                dto.PhoneNumber = user.PhoneNumber;
                dto.Email       = user.Email;
                dto.UserName    = user.UserName;
                dto.Id          = user.Id;
                dto.Sex         = user.Sex;
                dto.Group       = user.Group;
                dto.Title       = user.Title;
                dto.FirstName   = user.FirstName;
                dto.LastName    = user.LastName;
                dto.OfficePhone = user.OfficePhone;
                dto.Level       = user.Level;
                dto.Roles       = string.Join("; ", await _userManager.GetRolesAsync(user));
            }

            return(new ApiResult(dto));
        }
Exemple #5
0
        /// <summary>
        /// 根据用户输入的用户名与密码返回UserInputDto
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="password"></param>
        /// <returns>UserInputDto</returns>
        public virtual async Task <UserOutputDto> Login(string userName, string password)
        {
            User user = await UserManager.FindAsync(userName, password);

            UserOutputDto userDto = null;

            return(user.MapTo(userDto));
        }
Exemple #6
0
        /// <summary>
        /// 分页查询用户列表
        /// </summary>
        /// <param name="pagination">分页类</param>
        /// <param name="keyword">查询关键字</param>
        /// <returns></returns>
        public UserOutputDto GetUserList(Pagination pagination, string keyword)
        {
            List <SysUserEntity> userEntityList = _sysUserRepository.GetUserListByPage(pagination, keyword);
            List <UserDto>       userDtoList    = AutoMapper.Mapper.Map <List <UserDto> >(userEntityList);
            UserOutputDto        outputDto      = new UserOutputDto();

            outputDto.UserDtoList = userDtoList;
            return(outputDto);
        }
Exemple #7
0
        private static IEnumerable <Claim> CreateClaims(UserOutputDto profile)
        {
            yield return(new Claim(ClaimTypes.Sid, profile.Id));

            foreach (var role in profile.Roles)
            {
                yield return(new Claim(ClaimTypes.Role, role.RoleName));
            }
        }
Exemple #8
0
        public UserOutputDto GetForm(string keyword)
        {
            SysUserEntity userEntityList = _sysUserRepository.Get(keyword);
            UserDto       userDtoList    = AutoMapper.Mapper.Map <UserDto>(userEntityList);
            UserOutputDto outputDto      = new UserOutputDto();

            outputDto.UserDtoSingle = userDtoList;
            return(outputDto);
        }
Exemple #9
0
        public async Task <IActionResult> OnGetAsync(int id)
        {
            inputDto = await userService.Get(id);

            if (inputDto == null)
            {
                return(RedirectToPage("/NotFound"));
            }

            return(Page());
        }
Exemple #10
0
        public UserOutputDto GetForm(string keyValue)
        {
            var           id            = Convert.ToInt64(keyValue);
            UserOutputDto userOutputDto = new UserOutputDto();

            string[] includePath = { "Company", "Department", "Duty", "UserRoles.Role", "UserRoles.User" };
            User     user        = userRepository.Get(id, includePath);

            AutoMapper.Mapper.Map <User, UserOutputDto>(user, userOutputDto);
            return(userOutputDto);
        }
        public UserOutputDto GetUser(string Domain, string UserEmail)
        {
            UserOutputDto output = new UserOutputDto {
                IsSuccessful = false
            };
            string resource = ProofPointEndpoints.GetUserEndpoint(Domain, UserEmail);

            try
            {
                _log.Info($"INITIATING GetUser: {resource}");

                if (Domain.IsNullOrEmpty())
                {
                    throw new Exception("Domain was not provided");
                }

                if (UserEmail.IsNullOrEmpty())
                {
                    throw new Exception("UserEmail was not provided");
                }

                var request = new RestRequest(resource, Method.GET).AddAuthenticationHeaders();

                var response = _client.Execute <UserOutputDto>(request);

                if (response.Data == null)
                {
                    response.Data = new UserOutputDto();
                }
                response.Data.IsSuccessful = response.IsSuccessful;

                _log.Info($"RESPONSE GetUser: {response.IsSuccessful}");
                if (!response.IsSuccessful)
                {
                    _log.Error($"ERROR GetUser: {JsonConvert.SerializeObject(response.Data?.errors)}");
                }

                output = response.Data;
            }
            catch (Exception ex)
            {
                _log.Fatal("EXCEPTION GetUser", ex);
            }
            finally
            {
                _log.Info($"ENDED GetUser: {resource}");
            }

            return(output);
        }
        public UserOutputDto UpdateUser(string Domain, ProofPointUserModal updateUser)
        {
            UserOutputDto output = new UserOutputDto {
                IsSuccessful = false
            };
            string resource = ProofPointEndpoints.UpdateUserEndpoint(Domain, updateUser.primary_email);

            try
            {
                _log.Info($"INITIATING UpdateUser: {resource} | {updateUser.primary_email}");

                if (Domain.IsNullOrEmpty())
                {
                    throw new Exception("Domain was not provided");
                }

                if (updateUser.primary_email.IsNullOrEmpty())
                {
                    throw new Exception("UserEmail was not provided");
                }

                var request = new RestRequest(resource, Method.PUT).AddAuthenticationHeaders();
                request.AddJsonBody(updateUser);

                IRestResponse <UserOutputDto> response = _client.Execute <UserOutputDto>(request);
                if (response.Data == null)
                {
                    response.Data = new UserOutputDto();
                }
                response.Data.IsSuccessful = response.IsSuccessful;

                _log.Info($"RESPONSE UpdateUser: {response.IsSuccessful}");
                if (!response.IsSuccessful)
                {
                    _log.Error($"ERROR UpdateUser: {JsonConvert.SerializeObject(response.Data?.errors)}");
                }

                output = response.Data;
            }
            catch (Exception ex)
            {
                _log.Fatal("EXCEPTION UpdateUser: "******"ENDED UpdateUser: {resource}");
            }

            return(output);
        }
Exemple #13
0
        public ActionResult GetFormJson(string keyValue)
        {
            UserOutputDto data = _sysUserApp.GetForm(keyValue);
            UserDto       dto  = data.UserDtoSingle;

            if (!string.IsNullOrEmpty(keyValue))
            {
                Role2UserInputDto inputDto = new Role2UserInputDto();
                inputDto.SysUserId = keyValue;
                if (_sysRole2UserApp.GetRole2UserByUserId(inputDto).Role2UserDto != null)
                {
                    dto.RoleId = _sysRole2UserApp.GetRole2UserByUserId(inputDto).Role2UserDto.SysRoleId;
                }
            }
            return(Content(JsonConvert.SerializeObject(dto)));
        }
        public IActionResult CheckLogin(string username, string password, string verifycode)
        {
            LoginLogInputDto loginLogInputDto = new LoginLogInputDto();

            loginLogInputDto.UserName          = username;
            loginLogInputDto.OperateType       = "Login";
            loginLogInputDto.OperateTime       = System.DateTime.Now;
            loginLogInputDto.IpAddress         = HttpContext.Connection.RemoteIpAddress.ToString();
            loginLogInputDto.IpAddressLocation = NetHelper.GetLocation(loginLogInputDto.IpAddress);
            try
            {
                var SessionVerifyCode = HttpContext.Session.GetString("nfinecore_session_verifycode");
                var Md5VerifyCode     = Md5.md5(verifycode.ToLower(), 16);
                if (SessionVerifyCode != Md5VerifyCode)
                {
                    throw new Exception("验证码错误,请重新输入。");
                }
                UserOutputDto userOutputDto = userService.CheckLogin(username, password);
                if (userOutputDto != null)
                {
                    loginLogInputDto.UserId        = userOutputDto.Id;
                    loginLogInputDto.OperateResult = true;
                    loginLogInputDto.Description   = "系统登录,登录成功。";
                    loginLogService.SubmitForm(loginLogInputDto, null);

                    OperatorModel operatorModel = new OperatorModel();
                    operatorModel.Id          = userOutputDto.Id;
                    operatorModel.UserName    = userOutputDto.UserName;
                    operatorModel.MobilePhone = userOutputDto.MobilePhone;
                    operatorModel.Email       = userOutputDto.Email;
                    OperatorProvider.Provider.AddCurrent(operatorModel);
                }
                return(Content(new AjaxResult {
                    state = ResultType.success.ToString(), message = "登录成功。"
                }.ToJson()));
            }
            catch (Exception ex)
            {
                loginLogInputDto.OperateResult = false;
                loginLogInputDto.Description   = "系统登录," + ex.Message;
                loginLogService.SubmitForm(loginLogInputDto, null);
                return(Content(new AjaxResult {
                    state = ResultType.error.ToString(), message = ex.Message
                }.ToJson()));
            }
        }
        public async Task <IActionResult> OnGetAsync(int?id)
        {
            if (id == null)
            {
                return(NotFound());
            }

            var tempUserOutput = await userService.Get(id.Value);

            userOutputDto = mapper.Map <UserOutputDto>(tempUserOutput);

            if (userOutputDto == null)
            {
                return(NotFound());
            }
            return(Page());
        }
Exemple #16
0
        public async Task <UserOutputDto> GetUserInfo()
        {
            UserOutputDto userInfo = new UserOutputDto();

            var user = _defaultDbContext.MbpUsers.Where(u => u.LoginName == _currentUser.LoginName).FirstOrDefault();

            userInfo.Email       = _currentUser.Email;
            userInfo.Code        = user.Code;
            userInfo.Id          = _currentUser.Id;
            userInfo.IsAdmin     = user.IsAdmin;
            userInfo.LoginName   = _currentUser.LoginName;
            userInfo.PhoneNumber = "";
            userInfo.UserAvatar  = "";
            userInfo.UserName    = _currentUser.UserName;
            userInfo.UserStatus  = user.UserStatus;

            return(userInfo);
        }
Exemple #17
0
        public static Token CreateToken(UserOutputDto profile)
        {
            var header  = new JwtHeader(new SigningCredentials(SecretKey, SecurityAlgorithms.HmacSha256));
            var payload = new JwtPayload(
                Jwt.Issuer,
                Jwt.Audience,
                CreateClaims(profile),
                DateTime.UtcNow,
                DateTime.UtcNow + Jwt.TokenLifetime
                );
            var token        = new JwtSecurityToken(header, payload);
            var refreshToken = Guid.NewGuid().ToString().Replace("-", "") + "." + profile.Id;
            var accessToken  = new Token
            {
                AccessToken  = Handler.WriteToken(token),
                Type         = "bearer",
                RefreshToken = refreshToken,
                Expires      = token.ValidTo
            };

            return(accessToken);
        }
Exemple #18
0
        public async Task <ActionResult> Login(string UserName, string Password, string Code)
        {
            if (Session[OSharp.Core.Constants.VerifyCodeSession] == null)
            {
                return(Json(new OperationResult(OperationResultType.ValidError, "请重新刷新验证码").ToAjaxResult(), JsonRequestBehavior.AllowGet));
            }

            if (!SecurityHelper.CheckVerify(Code))
            {
                return(Json(new OperationResult(OperationResultType.ValidError, "验证码错误").ToAjaxResult(), JsonRequestBehavior.AllowGet));
            }

            UserOutputDto user = await IdentityContract.Login(UserName, Password);

            if (user == null)
            {
                Logger.Info("用户:" + UserName + "在" + Utils.NowTime + "登录系统,IP:" + this.Request.GetIpAddress() + "账户或密码错误");
                return(Json(new OperationResult(OperationResultType.ValidError, "用户名或密码错误").ToAjaxResult(), JsonRequestBehavior.AllowGet));
            }
            else if (Convert.ToBoolean(user.IsLocked))//被禁用
            {
                return(Json(new OperationResult(OperationResultType.ValidError, "账户被系统禁用").ToAjaxResult(), JsonRequestBehavior.AllowGet));
            }

            AccountModel account = new AccountModel();

            account.Id       = user.Id.ToString();
            account.NickName = user.NickName;
            //account.Photo = string.IsNullOrEmpty(user.Photo) ? "/Images/Photo.jpg" : user.Photo;
            Session["Account"] = account;
            GetThemes(user.Id.ToString());

            //LoginUserManage.Add(Session.SessionID, account.Id);

            //在线用户统计
            //OnlineHttpModule.ProcessRequest();
            Logger.Info("用户:" + UserName + "在" + Utils.NowTime + "登录系统,IP:" + this.Request.GetIpAddress() + "登录成功");
            return(Json(new OperationResult(OperationResultType.Success, "登录成功").ToAjaxResult(), JsonRequestBehavior.AllowGet));
        }
 public ProofPointUserModal(UserOutputDto userOutputDto)
 {
     Mapper.Map(userOutputDto, this, typeof(UserOutputDto), typeof(ProofPointUserModal));
 }