示例#1
0
        public UserLoginResult LoginUser(string userCode, string password)
        {
            UserLoginResult ulr = new UserLoginResult();

            ulr.LoginUser(userCode, password);
            return(ulr);
        }
示例#2
0
        /// <inheritdoc />
        /// <summary>
        /// 登入帳密檢查
        /// </summary>
        /// <param name="email">會員帳號(email)</param>
        /// <param name="userPass">會員密碼</param>
        /// <returns>返回會員登入結果</returns>
        public virtual UserLoginResult CheckUserPassword(string email, string userPass)
        {
            var result = new UserLoginResult();

            var user = _userRepo.GetUserByMail(_conn, email);

            if (user == null)
            {
                return(result);
            }

            var password = _passwordRepo.FindPasswordByUserId(_conn, user.Id);

            if (password == null)
            {
                return(result);
            }

            var hashPassword = HashService.GetMemberHashPw(user.Guid, userPass);

            result.Auth = password.HashPw == hashPassword && user.IsDel.Equals(false);
            if (result.Auth)
            {
                result.User = ConvertToUserViewModel(user);
            }
            return(result);
        }
示例#3
0
文件: Users.cs 项目: hieuhan/HanCMS3
        //--------------------------------------------------------------
        public UserLoginResult Login(string userName, string password)
        {
            UserLoginResult retVal = new UserLoginResult();

            try
            {
                SqlCommand cmd = new SqlCommand("User_Login")
                {
                    CommandType = CommandType.StoredProcedure
                };
                cmd.Parameters.Add(new SqlParameter("@UserName", StringUtil.InjectionString(userName)));
                cmd.Parameters.Add(new SqlParameter("@Password", StringUtil.InjectionString(password)));
                cmd.Parameters.Add("@LoginStatus", SqlDbType.NVarChar, 50).Direction   = ParameterDirection.Output;
                cmd.Parameters.Add("@LoginMessage", SqlDbType.NVarChar, 500).Direction = ParameterDirection.Output;
                List <Users> listUsers = Init(cmd);
                retVal.User = listUsers.Count == 0 ? new Users() : listUsers[0];
                if (cmd.Parameters["@LoginStatus"].Value != DBNull.Value)
                {
                    retVal.ActionStatus = cmd.Parameters["@LoginStatus"].Value.ToString();
                }
                if (cmd.Parameters["@LoginMessage"].Value != DBNull.Value)
                {
                    retVal.ActionMessage = cmd.Parameters["@LoginMessage"].Value.ToString();
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return(retVal);
        }
示例#4
0
        protected string CheckStatus(string qq, string pwd)
        {
            UserLoginResult userLoginResult = _accountService.ValidateLogin(qq, pwd);

            switch (userLoginResult)
            {
            case UserLoginResult.StopUse:
                HttpContext.Response.StatusCode = 214;
                return("用户已停用");

            case UserLoginResult.CustomerNoExist:
                HttpContext.Response.StatusCode = 214;
                return("用户不存在");

            case UserLoginResult.Deleted:
                HttpContext.Response.StatusCode = 214;
                return("用户已删除");

            case UserLoginResult.Successful:
                var    user = _accountService.GetUserByQQ(qq);
                string res  = TokenHelper.CreateToken(user.Id, Convert.ToInt32(_configuration["ExpTime"]));
                return(res);

            case UserLoginResult.WrongPassword:
                HttpContext.Response.StatusCode = 214;
                return("用户密码不正确");

            default:
                HttpContext.Response.StatusCode = 214;
                return("用户不存在");
            }
        }
示例#5
0
        public UserLoginResult Login(string username, string password)
        {
            UserLoginResult result = new UserLoginResult();

            try
            {
                using (SqlConnection sqlConn = new SqlConnection(GlobalBLL.GetConnectionString()))
                {
                    Users user = sqlConn.QueryFirstOrDefault <Users>("SELECT UserName, PasswordHash FROM vx.Users WHERE UserName=@UserName AND PasswordHash=@PasswordHash",
                                                                     new
                    {
                        UserName     = username,
                        PasswordHash = new SHA256Crypto().GetHashBase64String(password)
                    });
                    if (user == null)
                    {
                        result.Error   = "Invalid credentials";
                        result.Granted = false;
                    }
                    else
                    {
                        result.UserName = username;
                        result.Granted  = true;
                    }
                }
            }
            catch (Exception ex)
            {
                result.Granted = false;
                result.Error   = ex.ToString();
            }
            return(result);
        }
        public async Task HandleRegisterPostSuccess(
            ISiteContext site,
            RegisterViewModel viewModel,
            HttpContext httpContext,
            UserLoginResult loginResult,
            CancellationToken cancellationToken = default(CancellationToken)
            )
        {
            // just testing that on success the user can be updated with custom data
            if (loginResult.User != null)
            {
                var siteUser = await userManager.FindByIdAsync(loginResult.User.Id.ToString());

                if (siteUser != null)
                {
                    siteUser.FirstName = httpContext.Request.Form["FirstName"];
                    siteUser.LastName  = httpContext.Request.Form["LastName"];

                    var dobString = httpContext.Request.Form["DateOfBirth"];

                    DateTime dob;
                    var      dobParsed = DateTime.TryParse(dobString, out dob);
                    if (!dobParsed)
                    {
                        siteUser.DateOfBirth = dob.Date;
                    }

                    await userManager.UpdateAsync(siteUser);
                }
            }
            else
            {
                log.LogError("user was null in HandleRegisterPostSuccess, unable to update user with custom data");
            }
        }
示例#7
0
        /// <summary>
        /// 用户登陆
        /// </summary>
        /// <param name="userLogin">登陆信息</param>
        /// <returns></returns>
        public UserLoginResult Login(UserLogin userLogin)
        {
            LoginModel = userLogin;
            UserLoginResult result = new UserLoginResult();

            //获取登陆信息
            var token = GetLoginToken();

            if (null != token)
            {
                //登陆网关
                token = LoginGateway(token);
                if (null != token)
                {
                    this.LoginToken  = token;
                    result.Successed = true;
                }
                else
                {
                    result.Successed = false;
                    result.Message   = "登录网关失败";
                    result.LoginTime = DateTime.Now.Ticks;
                }
            }
            else
            {
                result.Successed = false;
                result.Message   = "登录失败";
                result.LoginTime = DateTime.Now.Ticks;
            }

            return(result);
        }
示例#8
0
        protected async Task <IActionResult> HandleLoginSuccess(UserLoginResult result, string returnUrl)
        {
            Analytics.HandleLoginSuccess(result).Forget();

            if (result.User != null)
            {
                await IpAddressTracker.TackUserIpAddress(CurrentSite.Id, result.User.Id);
            }

            if (!string.IsNullOrEmpty(returnUrl))
            {
                // when site is closed login is still allowed
                // but don't redirect to closed paged
                if (
                    (!returnUrl.Contains("/closed")) &&
                    (!returnUrl.Contains("/oops/error")) &&
                    (!returnUrl.Contains("/account/logout"))
                    )
                {
                    return(LocalRedirect(returnUrl));
                }
            }

            return(this.RedirectToSiteRoot(CurrentSite));
        }
示例#9
0
        public Task HandleLockout(UserLoginResult result)
        {
            if (!string.IsNullOrEmpty(_currentSite.GoogleAnalyticsProfileId))
            {
                var e = new GoogleAnalyticsEvent();
                e.Category = _options.LoginRegisterEventCategory;
                e.Action   = _options.LoginFailEventAction;
                var source = "Onsite";
                if (result.ExternalLoginInfo != null)
                {
                    source = result.ExternalLoginInfo.LoginProvider;
                }
                e.Label = source;
                e.Value = "Account lockout";
                if (_options.TrackUserId && result.User != null)
                {
                    e.Fields.Add(new KeyValuePair <string, string>("dimension" + _options.UserIdDimensionIndex.ToInvariantString(), result.User.Id.ToString()));
                }
                e.Fields.Add(new KeyValuePair <string, string>("dimension" + _options.LoginRegisterSourceDimenstionIdex.ToInvariantString(), source));
                e.Fields.Add(new KeyValuePair <string, string>("metric" + _options.LoginFailMetricIndex.ToInvariantString(), "1"));

                AddGoogleAnalyticsEvent(e);
            }

            return(Task.FromResult(0));
        }
示例#10
0
        private IActionResult HandleRequiresTwoFactor(UserLoginResult result, string returnUrl, bool rememberMe)
        {
            if (result.User != null)
            {
                log.LogWarning($"redirecting from login for {result.User.Email} because 2 factor not configured yet for account");
            }

            return(RedirectToAction(nameof(SendCode), new { ReturnUrl = returnUrl, RememberMe = rememberMe }));
        }
 public Task HandleRegisterPostSuccess(
     ISiteContext site,
     RegisterViewModel viewModel,
     HttpContext httpContext,
     UserLoginResult loginResult,
     CancellationToken cancellationToken = default(CancellationToken)
     )
 {
     return(Task.FromResult(0));
 }
示例#12
0
        private IActionResult HandleLockout(UserLoginResult result = null)
        {
            ViewData["Title"] = sr["Locked out"];

            if (result != null && result.User != null)
            {
                log.LogWarning($"redirecting to lockout page for {result.User.Email} because account is locked");
            }

            return(View("Lockout"));
        }
示例#13
0
        private async Task HandleRegisterSuccess(UserLoginResult result)
        {
            var source = "Onsite";

            if (result.ExternalLoginInfo != null)
            {
                source = result.ExternalLoginInfo.LoginProvider;
            }

            if (_options.TrackSocialLoginServerSide && result.ExternalLoginInfo != null)
            {
                var props = _analyticsApi.GetStandardProps(_contextAccessor.HttpContext);
                var dimensionAndMetrics = new List <KeyValuePair <string, string> >();
                if (_options.TrackUserId && result.User != null)
                {
                    dimensionAndMetrics.Add(new KeyValuePair <string, string>("cd" + _options.UserIdDimensionIndex.ToInvariantString(), result.User.Id.ToString()));
                }
                dimensionAndMetrics.Add(new KeyValuePair <string, string>("cd" + _options.RegisteredUserDimensionIdex.ToInvariantString(), "Yes"));
                dimensionAndMetrics.Add(new KeyValuePair <string, string>("cd" + _options.LoginRegisterSourceDimenstionIdex.ToInvariantString(), source));
                dimensionAndMetrics.Add(new KeyValuePair <string, string>("cm" + _options.RegisterSuccessMetricIndex.ToInvariantString(), "1"));

                await _analyticsApi.TrackEvent(
                    _currentSite.GoogleAnalyticsProfileId,
                    props.ClientId,
                    null,
                    props.Host,
                    _options.LoginRegisterEventCategory,
                    _options.RegisterSuccessEventAction,
                    source,
                    null,
                    props.IpAddress,
                    props.UserAgent,
                    dimensionAndMetrics
                    );
            }
            else
            {
                var e = new GoogleAnalyticsEvent();
                e.Category = _options.LoginRegisterEventCategory;
                e.Action   = _options.RegisterSuccessEventAction;
                e.Label    = source;
                if (_options.TrackUserId && result.User != null)
                {
                    e.Fields.Add(new KeyValuePair <string, string>("dimension" + _options.UserIdDimensionIndex.ToInvariantString(), result.User.Id.ToString()));
                }
                e.Fields.Add(new KeyValuePair <string, string>("dimension" + _options.RegisteredUserDimensionIdex.ToInvariantString(), "Yes"));
                e.Fields.Add(new KeyValuePair <string, string>("dimension" + _options.LoginRegisterSourceDimenstionIdex.ToInvariantString(), source));
                e.Fields.Add(new KeyValuePair <string, string>("metric" + _options.RegisterSuccessMetricIndex.ToInvariantString(), "1"));

                AddGoogleAnalyticsEvent(e);
            }
        }
 private ValidationResult ValidateLogin(UserLoginResult result)
 {
     return(Enum.GetValues(typeof(UserLoginResultEnum))
            .Cast <UserLoginResultEnum>()
            .Where((n, x) => x == result.Result)
            .DefaultIfEmpty(UserLoginResultEnum.Other)
            .Select(e => new ValidationResult()
     {
         IsValid = e == UserLoginResultEnum.Ok,
         ErrorMsg = e.GetEnumDescription()
     })
            .FirstOrDefault());
 }
示例#15
0
        public void TestLocalUserPassword()
        {
            bool actual           = false;
            bool expected         = true;
            UserAuthenticator ua  = new UserAuthenticator(AuthenticationMode.UserPassword);
            UserLoginResult   res = ua.Login("Administrator", "admin", string.Empty);

            if (res == UserLoginResult.Ok)
            {
                actual = true;
            }
            Assert.AreEqual(actual, expected);
        }
示例#16
0
        public void TestLocalBadgeCode()
        {
            bool actual           = false;
            bool expected         = true;
            UserAuthenticator ua  = new UserAuthenticator(AuthenticationMode.BadgeCode);
            UserLoginResult   res = ua.Login(string.Empty, string.Empty, "12345");

            if (ua.CurrentUser.LoginName == "Administrator" && res == UserLoginResult.Ok)
            {
                actual = true;
            }
            Assert.AreEqual(actual, expected);
        }
示例#17
0
        public JsonResult LoginUser(FormCollection formCollection)
        {
            UserLoginResult ulr = sm.LoginUser(formCollection["usrname"], formCollection["psw"]);

            if (ulr.ulResult == ULResult.Valid)
            {
                Session["UserID"]     = ulr.UserID;
                Session["EmployeeID"] = ulr.EmployeeID;
            }
            JsonResult result = Json(ulr);

            return(result);
        }
示例#18
0
        public void TestRemoteBadgeCode()
        {
            bool              actual           = false;
            bool              expected         = true;
            string            connectionString = "Data Source=192.168.100.250;Initial Catalog=TraMa4_520-334;User ID=TraMa;Password=trama";
            UserAuthenticator ua  = new UserAuthenticator(AuthenticationMode.BadgeCode, connectionString);
            UserLoginResult   res = ua.Login(string.Empty, string.Empty, ";80380000100118208054?");

            if (ua.CurrentUser.LoginName == "marco.dallera" && res == UserLoginResult.Ok)
            {
                actual = true;
            }
            Assert.AreEqual(actual, expected);
        }
示例#19
0
        protected async Task <IActionResult> HandleLoginNotAllowed(UserLoginResult result, string returnUrl)
        {
            Analytics.HandleLoginNotAllowed(result).Forget();

            if (result.User != null)
            {
                await IpAddressTracker.TackUserIpAddress(CurrentSite.Id, result.User.Id);

                if (result.NeedsEmailConfirmation)
                {
                    if (ShouldSendConfirmation(result.User))
                    {
                        var callbackUrl = Url.Action(new UrlActionContext
                        {
                            Action     = "ConfirmEmail",
                            Controller = "Account",
                            Values     = new { userId = result.User.Id.ToString(), code = result.EmailConfirmationToken, returnUrl },
                            Protocol   = HttpContext.Request.Scheme
                        });

                        EmailSender.SendAccountConfirmationEmailAsync(
                            CurrentSite,
                            result.User.Email,
                            StringLocalizer["Confirm your account"],
                            callbackUrl,
                            result.EmailConfirmationToken
                            ).Forget();


                        this.AlertSuccess(StringLocalizer["Please check your email inbox, we just sent you a link that you need to click to confirm your account"], true);
                    }

                    return(RedirectToAction("EmailConfirmationRequired", new { userId = result.User.Id, didSend = true, returnUrl }));
                }

                if (result.NeedsAccountApproval)
                {
                    var timeSpan = DateTime.UtcNow - result.User.CreatedUtc;
                    if (timeSpan.TotalDays < 1)
                    {
                        // account was just created so send notification to approver
                        EmailSender.AccountPendingApprovalAdminNotification(CurrentSite, result.User).Forget();
                    }

                    return(RedirectToAction("PendingApproval", new { userId = result.User.Id, didSend = true }));
                }
            }

            return(this.RedirectToSiteRoot(CurrentSite));
        }
示例#20
0
        protected async Task <IActionResult> HandleRequiresTwoFactor(UserLoginResult result, string returnUrl, bool rememberMe)
        {
            Analytics.HandleRequiresTwoFactor(result).Forget();

            if (result.User != null)
            {
                await IpAddressTracker.TackUserIpAddress(CurrentSite.Id, result.User.Id);

                Log.LogWarning($"redirecting from login for {result.User.Email} because 2 factor not configured yet for account");
            }

            return(RedirectToAction(nameof(LoginWith2fa), new { returnUrl, rememberMe }));

            //return RedirectToAction(nameof(SendCode), new { ReturnUrl = returnUrl, RememberMe = rememberMe });
        }
示例#21
0
        protected async Task <IActionResult> HandleLockout(UserLoginResult result = null)
        {
            Analytics.HandleLockout(result).Forget();

            ViewData["Title"] = StringLocalizer["Locked out"];

            if (result != null && result.User != null)
            {
                await IpAddressTracker.TackUserIpAddress(CurrentSite.Id, result.User.Id);

                Log.LogWarning($"redirecting to lockout page for {result.User.Email} because account is locked");
            }

            return(View("Lockout"));
        }
示例#22
0
        public void TestRemoteUserPassword()
        {
            bool actual   = false;
            bool expected = true;
            //string connectionString = "Data Source=192.168.100.250;Initial Catalog=TraMa4_520-334;User ID=TraMa;Password=trama";
            string            connectionString = "Data Source=192.168.153.250;Initial Catalog=TraMa4_SLight;User ID=TraMa;Password=trama";
            UserAuthenticator ua  = new UserAuthenticator(AuthenticationMode.UserPassword, connectionString);
            UserLoginResult   res = ua.Login("md", "md", string.Empty);

            //UserLoginResult res = ua.Login("marco.dallera", "md", string.Empty);
            if (res == UserLoginResult.Ok)
            {
                actual = true;
            }
            Assert.AreEqual(actual, expected);
        }
        public UserLoginResult Authenticate(string username, string password)
        {
            var user = Search(f => f.Username == username && f.Password == password).FirstOrDefault();

            // return null if user not found
            if (user == null)
            {
                return(null);
            }

            // authentication successful so generate jwt token
            var tokenHandler = new JwtSecurityTokenHandler();
            var key          = Encoding.ASCII.GetBytes(_configuration["appSecret"]);
            var claims       = new List <Claim>()
            {
                new Claim(ClaimTypes.Name, user.Id.ToString())
            };

            foreach (var right in user?.Role?.Rights)
            {
                claims.Add(new Claim(right.Name, "true"));
            }

            var identity        = new ClaimsIdentity(claims);
            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject            = identity,
                Expires            = DateTime.UtcNow.AddHours(6),
                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
            };
            var token      = tokenHandler.CreateToken(tokenDescriptor);
            var userResult = new UserLoginResult()
            {
                Id          = user.Id,
                DisplayName = user.DisplayName,
                Email       = user.Email,
                Username    = user.Username,
                Role        = user.Role,
                CreatedOn   = user.CreatedOn,
                ModifiedOn  = user.ModifiedOn,
                AccessToken = tokenHandler.WriteToken(token)
            };

            return(userResult);
        }
示例#24
0
        public ActionResult Login(LoginModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                if (model.UserName != null)
                {
                    model.UserName = model.UserName.Trim();
                }
                UserLoginResult loginResult = _userService.ValidateUser(model.UserName, model.Password);

                switch (loginResult)
                {
                case UserLoginResult.Successful:
                {
                    User user = _userService.GetUserByUserNameOrEmail(model.UserName);
                    //sign in new customer
                    AuthenticationService.SignIn(user, model.RememberMe);

                    if (String.IsNullOrEmpty(returnUrl) || !Url.IsLocalUrl(returnUrl))
                    {
                        return(RedirectToAction("Index", "Home"));
                    }
                    return(Redirect(returnUrl));
                }

                case UserLoginResult.UserNotExist:
                    ModelState.AddModelError("", "用户不存在");
                    break;

                case UserLoginResult.Locked:
                    ModelState.AddModelError("", "用户已锁定");
                    break;

                case UserLoginResult.NotActive:
                    ModelState.AddModelError("", "用户没有激活");
                    break;

                case UserLoginResult.WrongPassword:
                default:
                    ModelState.AddModelError("", "密码错误");
                    break;
                }
            }
            return(View(model));
        }
示例#25
0
        private async Task <IActionResult> HandleLoginSuccess(UserLoginResult result, string returnUrl)
        {
            if (result.User != null)
            {
                await ipAddressTracker.TackUserIpAddress(Site.Id, result.User.Id);
            }

            if (!string.IsNullOrEmpty(returnUrl))
            {
                // when site is closed login is still allowed
                // but don't redirect to closed paged
                if (!returnUrl.Contains("/closed"))
                {
                    return(LocalRedirect(returnUrl));
                }
            }

            return(this.RedirectToSiteRoot(Site));
        }
示例#26
0
        public virtual async Task HandleRegisterPostSuccess(
            ISiteContext site,
            RegisterViewModel viewModel,
            HttpContext httpContext,
            UserLoginResult loginResult,
            CancellationToken cancellationToken = default(CancellationToken)
            )
        {
            await EnsureProps();

            // we "could" re-validate here but
            // the method above gets called just before this in the same postback
            // so we know there were no validation errors or this method would not be invoked
            SiteUser siteUser = null;

            if (_userPropertyService.HasAnyNativeProps(_props.Properties))
            {
                siteUser = await _userPropertyService.GetUser(loginResult.User.Id.ToString());
            }
            if (loginResult.User != null)
            {
                foreach (var p in _props.Properties)
                {
                    if (p.VisibleOnRegistration)
                    {
                        if (!_userPropertyService.IsNativeUserProperty(p.Key))
                        {
                            var postedValue = httpContext.Request.Form[p.Key];
                            // persist to kvp storage
                            await _userPropertyService.CreateOrUpdate(
                                site.Id.ToString(),
                                loginResult.User.Id.ToString(),
                                p.Key,
                                postedValue);
                        }
                    }
                }
            }
            else
            {
                _log.LogError("user was null in HandleRegisterPostSuccess, unable to update user with custom data");
            }
        }
示例#27
0
        public async Task <ResponseEntity> Login(UserLogin modelVm)
        {
            try
            {
                // Lấy ra thông tin người dùng từ database dựa vào email
                AppUser entity = await _userRepository.GetSingleByConditionAsync("email", modelVm.email);

                if (entity == null)// Nếu email sai
                {
                    return(new ResponseEntity(StatusCodeConstants.NOT_FOUND, modelVm, MessageConstants.SIGNIN_WRONG));
                }
                // Kiểm tra mật khẩu có khớp không
                //if (!BCrypt.Net.BCrypt.Verify(modelVm.MatKhau, entity.MatKhau))
                //    // Nếu password không khớp
                //    return new ResponseEntity(StatusCodeConstants.NOT_FOUND, modelVm, MessageConstants.SIGNIN_WRONG);

                List <KeyValuePair <string, dynamic> > columns = new List <KeyValuePair <string, dynamic> >();
                columns.Add(new KeyValuePair <string, dynamic>("email", modelVm.email));
                columns.Add(new KeyValuePair <string, dynamic>("password", modelVm.password));
                if (entity == null)// Nếu email sai
                {
                    return(new ResponseEntity(StatusCodeConstants.NOT_FOUND, modelVm, MessageConstants.SIGNIN_WRONG));
                }
                entity = await _userRepository.GetSingleByListConditionAsync(columns);

                // Tạo token
                string token = await GenerateToken(entity);

                if (token == string.Empty)
                {
                    return(new ResponseEntity(StatusCodeConstants.BAD_REQUEST, modelVm, MessageConstants.TOKEN_GENERATE_ERROR));
                }
                UserLoginResult userLogin = new UserLoginResult();
                userLogin.email       = modelVm.email;
                userLogin.accessToken = token;
                return(new ResponseEntity(StatusCodeConstants.OK, userLogin, MessageConstants.SIGNIN_SUCCESS));
            }
            catch (Exception ex)
            {
                return(new ResponseEntity(StatusCodeConstants.BAD_REQUEST, modelVm, MessageConstants.SIGNIN_ERROR));
            }
        }
        public Task HandleRegisterPostSuccess(
            ISiteContext site,
            RegisterViewModel viewModel,
            HttpContext httpContext,
            UserLoginResult loginResult,
            CancellationToken cancellationToken = default(CancellationToken)
            )
        {
            if (loginResult.User != null)
            {
                // here is where you could process additional custom fields into your own custom data storage
                // if only updating native properties of siteuser use the method above
            }
            else
            {
                log.LogError("user was null in HandleRegisterPostSuccess, unable to update user with custom data");
            }

            return(Task.FromResult(0));
        }
示例#29
0
        // Build a claims principal from authenticated user
        private ClaimsPrincipal BuildClaimsPrincipal(UserLoginResult user)
        {
            if (user.UserAccountDetails == null || string.IsNullOrEmpty(user.UserAccountDetails.Username) || user.UserAccountDetails.Id < 1 ||
                user.UserAccountDetails.JobDescription == null || user.UserAccountDetails.JobDescription.Role == UserRole.Unknown)
            {
                return(null);
            }

            // define user claims including a custom claim for user Id
            // this would be useful if any future queries/actions required
            // user Id to be submitted with requests
            var claims = new ClaimsIdentity(new[]
            {
                new Claim(ClaimTypes.Name, user.UserAccountDetails.Username),
                new Claim("Id", user.UserAccountDetails.Id.ToString(CultureInfo.InvariantCulture)),
                new Claim("PatientId", user.PatientAccountPatientId.ToString(CultureInfo.InvariantCulture)),
                new Claim(ClaimTypes.Role, user.UserAccountDetails.JobDescription.Role.ToString())
            }, CookieAuthenticationDefaults.AuthenticationScheme);

            // build principal using claims
            return(new ClaimsPrincipal(claims));
        }
示例#30
0
        public void CheckUserPasswordTest()
        {
            var email      = "*****@*****.**";
            var userPass   = "******";
            var fakeUserVm = GetFakeUser(email);
            var fakeUser   = GetFakeUserViewModel(email);
            var expected   = new UserLoginResult()
            {
                Auth = true,
                User = fakeUserVm
            };

            var fakeConn    = new SqlConnection();
            var connFactory = Substitute.For <IConnectionFactory>();

            connFactory.GetConnection().Returns(fakeConn);

            var sut = new MemberService(connFactory);

            var userRepo = Substitute.For <IUserRepository>();

            userRepo.GetUserByMail(fakeConn, fakeUserVm.Mail).Returns(fakeUser);
            sut.SetUserRepository(userRepo);

            var passRepo = Substitute.For <IPasswordRepository>();

            passRepo.FindPasswordByUserId(fakeConn, fakeUserVm.Id).Returns(GetFakePassword());
            sut.SetPasswordRepository(passRepo);

            var hashTool = new HashService();

            hashTool.SetAlgList("SHA512,SHA256");
            hashTool.SetHashKey("i_am_security_key");
            sut.SetHashTool(hashTool);

            var actual = sut.CheckUserPassword(email, userPass);

            expected.ToExpectedObject().ShouldEqual(actual);
        }