コード例 #1
0
        private bool ValidatePasswordHashed(UserPart userPart, string password)
        {
            var saltBytes = Convert.FromBase64String(userPart.PasswordSalt);

            bool isValid;

            if (userPart.HashAlgorithm == PBKDF2)
            {
                // We can't reuse ComputeHashBase64 as the internally generated salt repeated calls to Crypto.HashPassword() return different results.
                isValid = Crypto.VerifyHashedPassword(userPart.Password, Encoding.Unicode.GetString(CombineSaltAndPassword(saltBytes, password)));
            }
            else
            {
                isValid = SecureStringEquality(userPart.Password, ComputeHashBase64(userPart.HashAlgorithm, saltBytes, password));
            }

            // Migrating older password hashes to Default algorithm if necessary and enabled.
            if (isValid && userPart.HashAlgorithm != DefaultHashAlgorithm)
            {
                var keepOldConfiguration = _appConfigurationAccessor.GetConfiguration("Orchard.Users.KeepOldPasswordHash");
                if (String.IsNullOrEmpty(keepOldConfiguration) || keepOldConfiguration.Equals("false", StringComparison.OrdinalIgnoreCase))
                {
                    userPart.HashAlgorithm = DefaultHashAlgorithm;
                    userPart.Password      = ComputeHashBase64(userPart.HashAlgorithm, saltBytes, password);
                }
            }

            return(isValid);
        }
コード例 #2
0
        public void Synchronize()
        {
            if (_communicationService != null)
            {
                CommunicationContactPart master = _communicationService.EnsureMasterContact();
                _transactionManager.RequireNew();

                // assegna un contact a ogni device
                int idmaster            = master.Id;
                var notificationrecords = _pushNotificationRepository.Fetch(x => x.Produzione && x.Validated).ToList();
                foreach (PushNotificationRecord rec in notificationrecords)
                {
                    rec.MobileContactPartRecord_Id = EnsureContactId(rec.UUIdentifier, idmaster);
                    _pushNotificationRepository.Update(rec);
                    _transactionManager.RequireNew();
                }
                _pushNotificationRepository.Flush();
                _notifier.Add(NotifyType.Information, T("Linked {0} device To Master contact", notificationrecords.Count().ToString()));
                string message = string.Format("Linked {0} device To Master contact", notificationrecords.Count().ToString());
                Logger.Log(OrchardLogging.LogLevel.Information, null, message, null);

                _transactionManager.RequireNew();

                // elimina gli userDevice riferiti a utenti inesistenti (perché cancellati)
                UserPart user = null;
                List <UserDeviceRecord> elencoUdr = _userDeviceRecord.Fetch(x => x.UserPartRecord.Id > 0).ToList();
                foreach (UserDeviceRecord udr in elencoUdr)
                {
                    user = _orchardServices.ContentManager.Get <UserPart>(udr.UserPartRecord.Id);
                    if (user == null)
                    {
                        _userDeviceRecord.Delete(udr);
                        _transactionManager.RequireNew();
                    }
                }
                _userDeviceRecord.Flush();
                _transactionManager.RequireNew();

                // elimina gli userDevice duplicati (con lo stesso UUIdentifier) e tiene il più recente (in base all'Id del record)
                string uuidPrecedente = "";
                elencoUdr = _userDeviceRecord.Fetch(x => x.UUIdentifier != null).OrderBy(y => y.UUIdentifier).OrderByDescending(z => z.Id).ToList();
                foreach (UserDeviceRecord udr in elencoUdr)
                {
                    if (udr.UUIdentifier == uuidPrecedente)
                    {
                        _userDeviceRecord.Delete(udr);
                        _transactionManager.RequireNew();
                    }
                    else
                    {
                        uuidPrecedente = udr.UUIdentifier;
                    }
                }
                _userDeviceRecord.Flush();
                _transactionManager.RequireNew();
            }
        }
コード例 #3
0
        public void UnboundFromUser(UserPart userPart)
        {
            var contacts = _orchardServices.ContentManager.Query <CommunicationContactPart, CommunicationContactPartRecord>().Where(x => x.UserPartRecord_Id == userPart.Id).List();

            foreach (var contact in contacts)
            {
                contact.UserIdentifier                = 0;
                contact.As <CommonPart>().Owner       = _orchardServices.WorkContext.CurrentUser;
                contact.As <CommonPart>().ModifiedUtc = DateTime.UtcNow;
            }
        }
コード例 #4
0
        public static string GetThumbnailImageOfUser(UserPart userPart)
        {
            if (userPart == null)
            {
                return(string.Empty);
            }

            var user = userPart.ContentItem.Parts.FirstOrDefault(d => d.PartDefinition.Name.ToLower(CultureInfo.InvariantCulture) == "user");

            return(CRMHelper.ReteriveField(user, FieldNames.UserThumbnailImageField));
        }
コード例 #5
0
        private static void SetPasswordHashed(UserPart userPart, string password)
        {
            var saltBytes = new byte[0x10];

            using (var random = new RNGCryptoServiceProvider()) {
                random.GetBytes(saltBytes);
            }

            userPart.PasswordFormat = MembershipPasswordFormat.Hashed;
            userPart.Password       = ComputeHashBase64(userPart.HashAlgorithm, saltBytes, password);
            userPart.PasswordSalt   = Convert.ToBase64String(saltBytes);
        }
コード例 #6
0
        public static string GetFullNameOfUser(UserPart userPart)
        {
            if (userPart == null)
            {
                return(string.Empty);
            }

            var    user     = userPart.ContentItem.Parts.FirstOrDefault(d => d.PartDefinition.Name.ToLower(CultureInfo.InvariantCulture) == "user");
            string fullName = CRMHelper.ReteriveField(user, "FullName");

            return(string.IsNullOrEmpty(fullName) ? userPart.UserName : fullName);
        }
コード例 #7
0
        private void DisableUser(GDPRContentContext context, UserPart userPart)
        {
            // for all versions, make sure the user is amrked as disabled
            var partVersions = PartVersions(context);

            foreach (var uPart in partVersions)
            {
                // disable the user.
                uPart.RegistrationStatus = UserStatus.Pending;
                uPart.EmailStatus        = UserStatus.Pending;
            }
        }
コード例 #8
0
        public static string GetUserField(UserPart userPart, string field)
        {
            if (userPart == null)
            {
                return(string.Empty);
            }

            var    user  = userPart.ContentItem.Parts.FirstOrDefault(d => d.PartDefinition.Name.ToLower(CultureInfo.InvariantCulture) == "user");
            string value = CRMHelper.ReteriveField(user, field);

            return(value);
        }
        private DateTime GetDate(UserPart part) {
            // CreatedUTC should never require a default value to fallback to.
            var created = DateOrDefault(part.CreatedUtc);
            // LastPasswordChangeUtc may require a value to fallback to for users that have not changed their
            // password since migration UpdateFrom4()
            var changed = DateOrDefault(part.LastPasswordChangeUtc);

            // Return the most recent of the two dates
            return created > changed
                ? created
                : changed;
        }
コード例 #10
0
        public QuickLogOnResponse Auth(WorkContext wc, string code, string returnUrl)
        {
            string error = null;

            if (string.IsNullOrEmpty(code))
            {
                error = "无效的code";
            }
            else
            {
                var token = GetAccessToken(wc, code);
                if (!string.IsNullOrEmpty(token.access_token))
                {
                    var request = new QuickLogOnRequest
                    {
                        UserName   = token.openid,
                        RememberMe = false,
                        ReturnUrl  = returnUrl
                    };
                    var lowerEmail = request.Email == null ? "" : request.Email.ToLowerInvariant();
                    return(_quickLogOnService.LogOn(request, () =>
                    {
                        UserPart user = _membershipService.CreateUser(new CreateUserParams(request.UserName, Guid.NewGuid().ToString(), lowerEmail, null, null, true)) as UserPart;

                        var model = GetUserInfo(token.access_token, token.openid);

                        var record = new WinXinUserInfoPartRecord
                        {
                            UserId = user.Id,
                            openid = model.openid,
                            nickname = model.nickname,
                            sex = model.sex,
                            province = model.province,
                            city = model.city,
                            country = model.country,
                            headimgurl = model.headimgurl,
                            privilege = string.Join(",", model.privilege),
                        };
                        _winXinUserInfoPartRecordRepository.Create(record);

                        return user;
                    }));
                }
                else
                {
                    error = string.Format("[{0}]{1}", token.errcode, token.errmsg);
                }
            }
            return(new QuickLogOnResponse {
                Error = T("微信登录失败: {0}", error), ReturnUrl = returnUrl
            });
        }
コード例 #11
0
        private static bool ValidatePasswordHashed(UserPart userPart, string password)
        {
            var saltBytes = Convert.FromBase64String(userPart.PasswordSalt);

            var passwordBytes = Encoding.Unicode.GetBytes(password);

            var combinedBytes = saltBytes.Concat(passwordBytes).ToArray();

            byte[] hashBytes;
            using (var hashAlgorithm = HashAlgorithm.Create(userPart.HashAlgorithm)) {
                hashBytes = hashAlgorithm.ComputeHash(combinedBytes);
            }

            return(userPart.Password == Convert.ToBase64String(hashBytes));
        }
コード例 #12
0
ファイル: QuickLogOnService.cs プロジェクト: YSRE/SuperRocket
        public QuickLogOnResponse LogOn(QuickLogOnRequest request)
        {
            var currentUser = _authenticationService.GetAuthenticatedUser();

            if (currentUser != null)
            {
                _authenticationService.SignOut();
            }

            var userName   = request.UserName;
            var lowerEmail = request.Email == null ? "" : request.Email.ToLowerInvariant();

            //var user = _orchardServices.ContentManager.Query<UserPart, UserPartRecord>().Where(u => u.NormalizedUserName == lowerName).List().FirstOrDefault();
            UserPart user = null;

            if (!string.IsNullOrWhiteSpace(userName))
            {
                user = _orchardServices.ContentManager.Query <UserPart, UserPartRecord>().Where(u => u.UserName == userName).List().FirstOrDefault();
            }
            else if (!string.IsNullOrWhiteSpace(lowerEmail))
            {
                user = _orchardServices.ContentManager.Query <UserPart, UserPartRecord>().Where(u => u.Email == lowerEmail).List().FirstOrDefault();
            }

            if (user == null)
            {
                user = _membershipService.CreateUser(new CreateUserParams(userName, Guid.NewGuid().ToString(), lowerEmail, null, null, true)) as UserPart;
                if (user == null)
                {
                    return(new QuickLogOnResponse {
                        User = null, Error = T("User can not be created to assign to Quick LogOn credentials")
                    });
                }
            }

            if (user.RegistrationStatus != UserStatus.Approved)
            {
                return(new QuickLogOnResponse {
                    User = null, Error = T("User was disabled by site administrator"), ReturnUrl = request.ReturnUrl
                });
            }

            _authenticationService.SignIn(user, request.RememberMe);

            return(new QuickLogOnResponse {
                User = user, ReturnUrl = request.ReturnUrl
            });
        }
コード例 #13
0
        private void HandleLatestUUID(GDPRContentContext context, UserPart part)
        {
            // the record may not exist
            var userRecord = part.Record;

            if (userRecord != null)   // sanity check
            {
                var latestRecord = _latestUUIDForUserRepository
                                   .Fetch(luu => luu.UserPartRecord == userRecord)
                                   .FirstOrDefault();
                if (latestRecord != null)
                {
                    // we had recorded the UUID, so now we clear it
                    latestRecord.UUID = latestRecord.UUID.GenerateUniqueString();
                    _latestUUIDForUserRepository.Update(latestRecord);
                }
            }
        }
コード例 #14
0
        public QuickLogOnResponse LogOn(QuickLogOnRequest request, Func <UserPart> createUser, Func <UserPart> findUser)
        {
            var currentUser = _authenticationService.GetAuthenticatedUser();

            if (currentUser != null)
            {
                _authenticationService.SignOut();
            }

            UserPart user = findUser();

            if (user == null)
            {
                try
                {
                    user = createUser();
                    if (user == null)
                    {
                        return(new QuickLogOnResponse {
                            User = null, Error = T("用户无法被指定的快速登录凭据创建!")
                        });
                    }
                }
                catch (Exception ex)
                {
                    return(new QuickLogOnResponse {
                        User = null, Error = T("{0}", ex.Message)
                    });
                }
            }

            if (user.RegistrationStatus != UserStatus.Approved)
            {
                return(new QuickLogOnResponse {
                    User = null, Error = T("用户已被管理员禁用!"), ReturnUrl = request.ReturnUrl
                });
            }

            _authenticationService.SignIn(user, request.RememberMe);

            return(new QuickLogOnResponse {
                User = user, ReturnUrl = request.ReturnUrl
            });
        }
コード例 #15
0
        private void ClearUser(GDPRContentContext context, UserPart userPart)
        {
            // for all versions, clear username and email address. We make them into unique
            // strings.
            var partVersions = PartVersions(context);

            foreach (var uPart in partVersions)
            {
                // UserName
                uPart.UserName           = uPart.UserName.GenerateUniqueString();
                uPart.NormalizedUserName = uPart.UserName.ToLowerInvariant();
                // Email
                uPart.Email = uPart.Email.GenerateUniqueString();

                // then disable the user (again, just in case).
                uPart.RegistrationStatus = UserStatus.Pending;
                uPart.EmailStatus        = UserStatus.Pending;
            }
        }
コード例 #16
0
        private void HandleUser(GDPRContentContext context, UserPart userPart)
        {
            // Given the user, we should process every MobilePushPart ever, including
            // eventually deleted ones. We should check whether in its RecipientList there
            // is either the username or the email of the current user, and remove it if
            // that is the case.
            var comparisonArray = new string[] {
                userPart.UserName?.Trim(),
                userPart.Email?.Trim()
            }.Where(str => !string.IsNullOrWhiteSpace(str));

            if (comparisonArray.Any())   // sanity check
            {
                var mpParts = _contentManager.Query <MobilePushPart>(VersionOptions.AllVersions)
                              .Where <MobilePushPartRecord>(mppr => // this predicate replaces
                                                            mppr.RecipientList != null && // !string.IsNullOrWhiteSpace(str)
                                                            mppr.RecipientList != "")
                              .List()         // here the IContentQuery ends and the IEnumerable begins
                              .Where(mpp => { // only those that may contain either username or email
                    foreach (var compare in comparisonArray)
                    {
                        if (mpp.RecipientList
                            .Contains(compare, StringComparison.OrdinalIgnoreCase))
                        {
                            return(true);
                        }
                    }
                    return(false);
                });

                foreach (var mpPart in mpParts)
                {
                    // RecipientList is a string of usernames or email addresses separated by
                    // a new line.
                    var split = mpPart.RecipientList
                                .Split(new string[] { "\r", "\n" }, StringSplitOptions.RemoveEmptyEntries);
                    mpPart.RecipientList = string.Join(Environment.NewLine,
                                                       split.Select(str => str.Trim()) // get rid of spare whitespace
                                                       .Except(comparisonArray, StringComparer.OrdinalIgnoreCase));
                }
            }
        }
コード例 #17
0
        public static T Convert <T>(IUser user)
            where T : UserViewModel, new()
        {
            UserPart userPart = user.As <UserPart>();

            var userModel = new T
            {
                UserId    = user.Id,
                Username  = user.UserName,
                Email     = user.Email,
                Fullname  = CRMHelper.GetFullNameOfUser(user),
                Thumbnail = ProjectHelper.GetThumbnailImageOfUser(user),
                SkypeId   = GetUserField(userPart, FieldNames.UserSkypeIdField),
                Tel       = GetUserField(userPart, FieldNames.UserTelField),
                Tags      = GetUserField(userPart, FieldNames.UserTags),
                Mobile    = GetUserField(userPart, FieldNames.UserMobileField)
            };

            return(userModel);
        }
コード例 #18
0
        public QuickLogOnResponse LogOn(QuickLogOnRequest request, Func <UserPart> createUser)
        {
            var userName   = request.UserName;
            var lowerEmail = request.Email == null ? "" : request.Email.ToLowerInvariant();

            return(LogOn(request, createUser, () =>
            {
                UserPart user = null;
                //var user = _orchardServices.ContentManager.Query<UserPart, UserPartRecord>().Where(u => u.NormalizedUserName == lowerName).List().FirstOrDefault();
                if (!string.IsNullOrWhiteSpace(userName))
                {
                    user = _orchardServices.ContentManager.Query <UserPart, UserPartRecord>().Where(u => u.UserName == userName).List().FirstOrDefault();
                }
                else if (!string.IsNullOrWhiteSpace(lowerEmail))
                {
                    user = _orchardServices.ContentManager.Query <UserPart, UserPartRecord>().Where(u => u.Email == lowerEmail).List().FirstOrDefault();
                }
                return user;
            }));
        }
コード例 #19
0
        private bool ValidatePassword(UserPart userPart, string password)
        {
            // Note - the password format stored with the record is used
            // otherwise changing the password format on the site would invalidate
            // all logins
            switch (userPart.PasswordFormat)
            {
            case MembershipPasswordFormat.Clear:
                return(ValidatePasswordClear(userPart, password));

            case MembershipPasswordFormat.Hashed:
                return(ValidatePasswordHashed(userPart, password));

            case MembershipPasswordFormat.Encrypted:
                return(ValidatePasswordEncrypted(userPart, password));

            default:
                throw new ApplicationException("Unexpected password format value");
            }
        }
コード例 #20
0
        private static void SetPasswordHashed(UserPart userPart, string password)
        {
            var saltBytes = new byte[0x10];

            using (var random = new RNGCryptoServiceProvider()) {
                random.GetBytes(saltBytes);
            }

            var passwordBytes = Encoding.Unicode.GetBytes(password);

            var combinedBytes = saltBytes.Concat(passwordBytes).ToArray();

            byte[] hashBytes;
            using (var hashAlgorithm = HashAlgorithm.Create(userPart.HashAlgorithm)) {
                hashBytes = hashAlgorithm.ComputeHash(combinedBytes);
            }

            userPart.PasswordFormat = MembershipPasswordFormat.Hashed;
            userPart.Password       = Convert.ToBase64String(hashBytes);
            userPart.PasswordSalt   = Convert.ToBase64String(saltBytes);
        }
コード例 #21
0
        private void HandleDeviceRecords(GDPRContentContext context, UserPart part)
        {
            var userRecord = part.Record;

            if (userRecord != null)   // sanity check
            {
                var deviceRecords = _userDeviceRepository
                                    .Fetch(ud => ud.UserPartRecord == userRecord)
                                    .ToList();
                foreach (var deviceRecord in deviceRecords)
                {
                    // clear this UUID
                    deviceRecord.UUIdentifier = deviceRecord.UUIdentifier.GenerateUniqueString();
                    _userDeviceRepository.Update(deviceRecord);
                    // These records we are processing here will be deleted elsewhere if
                    // the user is deleted. However, here we cannot know if the user is going
                    // to be deleted, and we cannot assume it will be. For this reason we
                    // are putting the unique string there.
                }
            }
        }
コード例 #22
0
        private void SetShippingAddress(PaypalRequest pr, OrderPart order)
        {
            bool         addrOverride = true;
            CustomerPart customer     = _customerService.GetCustomer(order.CustomerId);

            // determine which address to use
            var address = _customerService.GetShippingAddress(order.CustomerId, order.Id);

            if (address == null || String.IsNullOrWhiteSpace(address.Address))
            {
                address = _customerService.GetInvoiceAddress(order.CustomerId);
            }
            if (address == null || String.IsNullOrWhiteSpace(address.Address))
            {
                addrOverride = false;
            }

            pr.Add("ADDROVERRIDE", addrOverride ? "1" : "0");
            pr.Add("NOSHIPPING", "0");
            if (addrOverride)
            {
                if (string.IsNullOrWhiteSpace(address.Name))
                {
                    pr.Add("PAYMENTREQUEST_0_SHIPTONAME", customer.FirstName + " " + customer.LastName);
                }
                else
                {
                    pr.Add("PAYMENTREQUEST_0_SHIPTONAME", address.Name);
                }
                pr.Add("PAYMENTREQUEST_0_SHIPTOSTREET", address.Address);
                pr.Add("PAYMENTREQUEST_0_SHIPTOCITY", address.City);
                pr.Add("PAYMENTREQUEST_0_SHIPTOSTATE", address.State);
                pr.Add("PAYMENTREQUEST_0_SHIPTOZIP", address.Postcode);
                pr.Add("PAYMENTREQUEST_0_SHIPTOCOUNTRYCODE", address.CountryCode);

                // Set email
                UserPart user = customer.As <UserPart>();
                pr.Add("PAYMENTREQUEST_0_EMAIL", user.Email);
            }
        }
コード例 #23
0
        private OTPRecord NewOTP(UserPart user, Dictionary <string, string> additionalInformation)
        {
            if (user == null)
            {
                throw new ArgumentNullException("user");
            }

            // use the base nonce from the IUserServices
            var      nonce = _userService.CreateNonce(user, new TimeSpan(0, ValidityTime(), 0));
            string   userName;
            DateTime expiration;

            // get the expiration actually assigned on the nonce
            _userService.DecryptNonce(nonce, out userName, out expiration);
            // create the OTP
            var otp = new OTPRecord {
                UserRecord        = user.As <UserPart>().Record,
                Password          = nonce,
                PasswordType      = PasswordType.Nonce.ToString(),
                ExpirationUTCDate = expiration,
                AdditionalData    = additionalInformation != null
                    ? JsonConvert.SerializeObject(additionalInformation, Formatting.Indented)
                    : string.Empty
            };
            // delete all old nonces that match the one we are creating
            var oldOtps = _otpRepositoryService.Get(user, PasswordType.Nonce.ToString());

            foreach (var old in oldOtps
                     .Where(or =>
                            CompareDictionaries(
                                JsonConvert.DeserializeObject <Dictionary <string, string> >(or.AdditionalData),
                                additionalInformation)))
            {
                _otpRepositoryService.Delete(old);
            }
            // save the OTP
            return(_otpRepositoryService.AddOTP(otp));
        }
コード例 #24
0
        public override IEnumerable <LocalizedString> Execute(WorkflowContext workflowContext, ActivityContext activityContext)
        {
            LocalizedString messageout = T("Success");

            try {
                var newowner = activityContext.GetState <string>("allusers");
                if (String.IsNullOrEmpty(newowner))
                {
                    messageout = T("Error");
                }
                var content = workflowContext.Content;

                UserPart userpart = _contentManager
                                    .Query <UserPart, UserPartRecord>()
                                    .Where(x => x.Id == Convert.ToInt32(newowner)).List().FirstOrDefault();



                ((dynamic)content.ContentItem).CommonPart.Owner = userpart;
            }
            catch { messageout = T("Error"); }
            yield return(messageout);
        }
コード例 #25
0
 // MIGRATION copied from Orchard.Users.Services.MembershipService
 private static bool ValidatePasswordClear(UserPart partRecord, string password)
 {
     return partRecord.Password == password;
 }
コード例 #26
0
 private static void SetPasswordClear(UserPart userPart, string password)
 {
     userPart.PasswordFormat = MembershipPasswordFormat.Clear;
     userPart.Password       = password;
     userPart.PasswordSalt   = null;
 }
コード例 #27
0
 private static bool ValidatePasswordClear(UserPart userPart, string password)
 {
     return(userPart.Password == password);
 }
コード例 #28
0
        private bool ValidatePasswordHashed(UserPart userPart, string password) {
            var saltBytes = Convert.FromBase64String(userPart.PasswordSalt);

            bool isValid;
            if (userPart.HashAlgorithm == PBKDF2) {
                // We can't reuse ComputeHashBase64 as the internally generated salt repeated calls to Crypto.HashPassword() return different results.
                isValid = Crypto.VerifyHashedPassword(userPart.Password, Encoding.Unicode.GetString(CombineSaltAndPassword(saltBytes, password)));
            }
            else {
                isValid = SecureStringEquality(userPart.Password, ComputeHashBase64(userPart.HashAlgorithm, saltBytes, password)); 
            }

            // Migrating older password hashes to Default algorithm if necessary and enabled.
            if (isValid && userPart.HashAlgorithm != DefaultHashAlgorithm) {
                var keepOldConfiguration = _appConfigurationAccessor.GetConfiguration("Orchard.Users.KeepOldPasswordHash");
                if (String.IsNullOrEmpty(keepOldConfiguration) || keepOldConfiguration.Equals("false", StringComparison.OrdinalIgnoreCase)) {
                    userPart.HashAlgorithm = DefaultHashAlgorithm;
                    userPart.Password = ComputeHashBase64(userPart.HashAlgorithm, saltBytes, password); 
                }
            }

            return isValid;
        }
コード例 #29
0
        private static void SetPasswordHashed(UserPart userPart, string password) {
            var saltBytes = new byte[0x10];
            using (var random = new RNGCryptoServiceProvider()) {
                random.GetBytes(saltBytes);
            }

            userPart.PasswordFormat = MembershipPasswordFormat.Hashed;
            userPart.Password = ComputeHashBase64(userPart.HashAlgorithm, saltBytes, password);
            userPart.PasswordSalt = Convert.ToBase64String(saltBytes);
        }
コード例 #30
0
        public QuickLogOnResponse Auth(WorkContext wc, string code, string error, string returnUrl)
        {
            if (string.IsNullOrEmpty(code))
            {
                error = "无效的code";
            }
            else
            {
                var token = GetAccessToken(wc, code);
                if (!string.IsNullOrEmpty(token))
                {
                    var openId = GetOpenId(token);
                    if (!string.IsNullOrEmpty(openId))
                    {
                        var request = new QuickLogOnRequest
                        {
                            UserName   = openId,
                            RememberMe = false,
                            ReturnUrl  = returnUrl
                        };
                        var lowerEmail = request.Email == null ? "" : request.Email.ToLowerInvariant();
                        return(_quickLogOnService.LogOn(request, () =>
                        {
                            var model = GetUserInfo(token, openId);

                            if (model.ret < 0)
                            {
                                throw new Exception(string.Format("[{0}]{1}", model.ret, model.msg));
                            }

                            UserPart user = _membershipService.CreateUser(new CreateUserParams(request.UserName, Guid.NewGuid().ToString(), lowerEmail, null, null, true)) as UserPart;

                            var record = new QQUserInfoPartRecord
                            {
                                UserId = user.Id,
                                nickname = model.nickname,
                                figureurl = model.figureurl,
                                figureurl_1 = model.figureurl_1,
                                figureurl_2 = model.figureurl_2,
                                figureurl_qq_1 = model.figureurl_qq_1,
                                figureurl_qq_2 = model.figureurl_qq_2,
                                gender = model.gender,
                                is_yellow_vip = model.is_yellow_vip,
                                vip = model.vip,
                                yellow_vip_level = model.yellow_vip_level,
                                level = model.level,
                                is_yellow_year_vip = model.is_yellow_year_vip,
                            };
                            _QQRepository.Create(record);

                            return user;
                        }));
                    }
                    error = "无效的OpenID";
                }
                else
                {
                    error = "无效的访问令牌";
                }
            }
            return(new QuickLogOnResponse {
                Error = T("QQ登录失败: {0}", error), ReturnUrl = returnUrl
            });
        }
コード例 #31
0
        private static void SetPasswordHashed(UserPart userPart, string password)
        {
            var saltBytes = new byte[0x10];
            using (var random = new RNGCryptoServiceProvider()) {
                random.GetBytes(saltBytes);
            }

            var passwordBytes = Encoding.Unicode.GetBytes(password);

            var combinedBytes = saltBytes.Concat(passwordBytes).ToArray();

            byte[] hashBytes;
            using (var hashAlgorithm = HashAlgorithm.Create(userPart.HashAlgorithm)) {
                hashBytes = hashAlgorithm.ComputeHash(combinedBytes);
            }

            userPart.PasswordFormat = MembershipPasswordFormat.Hashed;
            userPart.Password = Convert.ToBase64String(hashBytes);
            userPart.PasswordSalt = Convert.ToBase64String(saltBytes);
        }
コード例 #32
0
 private bool ValidatePassword(UserPart userPart, string password)
 {
     // Note - the password format stored with the record is used
     // otherwise changing the password format on the site would invalidate
     // all logins
     switch (userPart.PasswordFormat) {
         case MembershipPasswordFormat.Clear:
             return ValidatePasswordClear(userPart, password);
         case MembershipPasswordFormat.Hashed:
             return ValidatePasswordHashed(userPart, password);
         case MembershipPasswordFormat.Encrypted:
             return ValidatePasswordEncrypted(userPart, password);
         default:
             throw new ApplicationException("Unexpected password format value");
     }
 }
コード例 #33
0
 private bool ValidatePasswordEncrypted(UserPart userPart, string password)
 {
     return String.Equals(password, Encoding.UTF8.GetString(_encryptionService.Decode(Convert.FromBase64String(userPart.Password))), StringComparison.Ordinal);
 }
コード例 #34
0
 private void SetPasswordEncrypted(UserPart userPart, string password)
 {
     userPart.Password = Convert.ToBase64String(_encryptionService.Encode(Encoding.UTF8.GetBytes(password)));
     userPart.PasswordSalt = null;
     userPart.PasswordFormat = MembershipPasswordFormat.Encrypted;
 }
コード例 #35
0
        private static bool ValidatePasswordHashed(UserPart userPart, string password)
        {
            var saltBytes = Convert.FromBase64String(userPart.PasswordSalt);

            var passwordBytes = Encoding.Unicode.GetBytes(password);

            var combinedBytes = saltBytes.Concat(passwordBytes).ToArray();

            byte[] hashBytes;
            using (var hashAlgorithm = HashAlgorithm.Create(userPart.HashAlgorithm)) {
                hashBytes = hashAlgorithm.ComputeHash(combinedBytes);
            }

            return userPart.Password == Convert.ToBase64String(hashBytes);
        }
コード例 #36
0
 private static bool ValidatePasswordClear(UserPart userPart, string password)
 {
     return userPart.Password == password;
 }
コード例 #37
0
 private void SetPasswordEncrypted(UserPart userPart, string password)
 {
     userPart.Password       = Convert.ToBase64String(_encryptionService.Encode(Encoding.UTF8.GetBytes(password)));
     userPart.PasswordSalt   = null;
     userPart.PasswordFormat = MembershipPasswordFormat.Encrypted;
 }
コード例 #38
0
 public bool ValidateEqualFor(UserPart leftPassword, string rightPassword)
 {
     return(ValidatePassword(leftPassword, rightPassword));
 }
コード例 #39
0
 private bool ValidatePasswordEncrypted(UserPart userPart, string password)
 {
     return(String.Equals(password, Encoding.UTF8.GetString(_encryptionService.Decode(Convert.FromBase64String(userPart.Password))), StringComparison.Ordinal));
 }
コード例 #40
0
 private static void SetPasswordClear(UserPart userPart, string password)
 {
     userPart.PasswordFormat = MembershipPasswordFormat.Clear;
     userPart.Password = password;
     userPart.PasswordSalt = null;
 }