/// <summary>
        /// Đăng nhập cho người dùng đã đăng ký, đối với tài khoản guest và system account thì sẽ xử lý ở nơi khác
        /// </summary>
        public virtual void SignIn(Customer customer, bool createPersistentCookie)
        {
            DateTime now = DateTime.Now;

            var ticket = new FormsAuthenticationTicket(
                1,
                _customerSettings.UsernamesEnabled ? customer.Username : customer.Email, // tùy cấu hình mà ghi nhận người dùng đăng nhập theo user name hay email
                now,
                now.Add(_expirationTimeSpan),
                createPersistentCookie,
                // lưu trữ thêm password dùng để phát hiện việc thay đổi password nếu có.
                customer.Password,
                FormsAuthentication.FormsCookiePath
            );

            var encryptedTicket = FormsAuthentication.Encrypt(ticket);
            var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
            cookie.HttpOnly = true;
            if (ticket.IsPersistent) cookie.Expires = ticket.Expiration;
            cookie.Secure = FormsAuthentication.RequireSSL;
            cookie.Path = FormsAuthentication.FormsCookiePath;
            if (FormsAuthentication.CookieDomain != null) cookie.Domain = FormsAuthentication.CookieDomain;

            _httpContext.Response.Cookies.Add(cookie);
            _cachedCustomer = customer; // sau khi đăng nhập cho customer, ghi nhận lại customer vào cache để tiện sử dụng sau này
        }
        /// <summary>
        /// Nhìn chung là hàm thực hiện đọc cookies để lấy ra thông tin người dùng đã đăng nhập, sau đó dùng thông tin đó để truy vấn
        /// CSDL lấy ra thông tin người dùng, kiểm tra nếu thông tin ấy hợp lệ thì sẽ trả về, ngược lại thì sẽ ném ra ngoại lệ 
        /// AuthenticationDangerousException và trả về null
        /// </summary>
        public virtual Customer GetAuthenticatedCustomer()
        {
            if (_cachedCustomer != null) return _cachedCustomer; // nếu đã có cache thì sử dụng, ko cần đi sang những bước sau

            if (_httpContext == null || _httpContext.Request == null || !_httpContext.Request.IsAuthenticated
                || _httpContext.User == null || !(_httpContext.User.Identity is FormsIdentity)) return null;

            var formsIdentity = (FormsIdentity)_httpContext.User.Identity;
            string usernameOrEmail = formsIdentity.Name; //_httpContext.User.Identity.Name
            string password = formsIdentity.Ticket.UserData;
            if (string.IsNullOrWhiteSpace(usernameOrEmail)) return null;

            var customer = _customerSettings.UsernamesEnabled ?
                _customerService.GetCustomerByUsername(usernameOrEmail)
                : _customerService.GetCustomerByEmail(usernameOrEmail);

            // kiểm tra để bảo đảm tài khoản người dùng là loại role Registered, active, ko bị xóa, khớp mật khẩu
            if (customer != null && customer.Active && !customer.Deleted &&
                string.Equals(customer.Password, password, StringComparison.InvariantCulture) &&
                customer.IsRegistered())
                _cachedCustomer = customer;
            else
            {
                if (!(_httpContext is FakeHttpContext)) // chỉ ném ra ngoại lệ nếu request ko phải là fake
                    throw new AuthenticationDangerousException();
            }

            return _cachedCustomer;
        }
Esempio n. 3
0
 private static void FilteredLog(ILogger logger, LogLevel level, string message,
     Exception exception = null, Customer customer = null, bool stopException = true)
 {
     // không log thông điệp khi ngoại lệ là ThreadAbortException
     if (exception is ThreadAbortException) return;
     try
     {
         if (logger.IsEnabled(level)) // nếu cho phép ghi log với kiểu level
         {
             string fullMessage = exception == null ? string.Empty : exception.ToString();
             logger.InsertLog(level, message, fullMessage, customer);
         }
     }
     catch (Exception)
     {
         if (!stopException) throw;
     }
 }
Esempio n. 4
0
 public virtual TimeZoneInfo GetCustomerTimeZone(Customer customer)
 {
     TimeZoneInfo timeZoneInfo = null;
     if (_dateTimeSettings.AllowCustomersToSetTimeZone && customer != null)
     {
         // nếu có thì lấy time zone của customer. Thông tin time zone của customer được lưu trong generic attribute
         string timeZoneId = customer.GetAttribute<string>(SystemCustomerAttributeNames.TimeZoneId, _genericAttributeService);
         if(!string.IsNullOrEmpty(timeZoneId))
             try
             {
                 timeZoneInfo = FindTimeZoneById(timeZoneId);
             }catch(Exception ex)
             {
                 Debug.WriteLine(ex.ToString());
             }
     }
     // nếu ko có, lấy time zone của store
     if (timeZoneInfo == null) timeZoneInfo = DefaultStoreTimeZone;
     return timeZoneInfo;
 }
Esempio n. 5
0
 public Log InsertLog(LogLevel logLevel, string shortMessage, string fullMessage = "", Customer customer = null)
 {
     return null;
 }
 public virtual void SignOut()
 {
     _cachedCustomer = null;
     FormsAuthentication.SignOut();
 }
Esempio n. 7
0
 public static void Warning(this ILogger logger, string message, Exception ex = null,
     Customer customer = null, bool stopException = true)
 {
     FilteredLog(logger, LogLevel.Warning, message, ex, customer);
 }
 protected virtual void SetPasswordValue(Customer customer, string password)
 {
     switch (customer.PasswordFormat)
     {
         case PasswordFormat.Hashed:
             customer.PasswordSalt = _encryptionService.CreateSaltKey(5);
             customer.Password = _encryptionService.CreatePasswordHash(password, customer.PasswordSalt,
                 _customerSettings.HashedPasswordFormat);
             break;
         case PasswordFormat.Encrypted:
             customer.Password = _encryptionService.EncryptText(password, _securitySettings);
             break;
         case PasswordFormat.Clear:
             customer.Password = password;
             break;
     }
 }
        public virtual void SetUsername(Customer customer, string newUsername)
        {
            if (customer == null) throw new ArgumentNullException("customer");
            if (string.IsNullOrWhiteSpace(newUsername)) throw new ArgumentNullException("newUsername");
            if (!_customerSettings.UsernamesEnabled) throw new ResearchException("Usernames are disabled");
            if (!_customerSettings.AllowUsersToChangeUsernames) throw new ResearchException("Changing usernames is not allowed");

            newUsername = newUsername.Trim();
            if (newUsername.Length > _customerSettings.UsernameMaxLength)
                throw new ResearchException(_localizationService.GetResource("Account.EmailUsernameErrors.UsernameTooLong", false));

            var another = _customerService.GetCustomerByUsername(newUsername);
            if(another != null && another.Id != customer.Id)
                throw new ResearchException(_localizationService.GetResource("Account.EmailUsernameErrors.UsernameAlreadyExists", false));

            if (newUsername.Equals(customer.Username, StringComparison.InvariantCulture))
                return;

            customer.Username = newUsername;
            _customerService.UpdateCustomer(customer);
        }
        public virtual void SetEmail(Customer customer, string newEmail)
        {
            if (customer == null) throw new ArgumentNullException("customer");
            if (string.IsNullOrWhiteSpace(newEmail)) throw new ArgumentNullException("newEmail");

            newEmail = newEmail.Trim();
            if (newEmail.Length > _customerSettings.EmailMaxLength)
                throw new ResearchException(_localizationService.GetResource("Account.EmailUsernameErrors.EmailTooLong", false));
            if(!CommonHelper.IsValidEmail(newEmail))
                throw new ResearchException(_localizationService.GetResource("Account.EmailUsernameErrors.NewEmailIsNotValid", false));

            var another = _customerService.GetCustomerByEmail(newEmail);
            if (another != null && another.Id != customer.Id)
                throw new ResearchException(_localizationService.GetResource("Account.EmailUsernameErrors.EmailAlreadyExists", false));

            if (newEmail.Equals(customer.Email, StringComparison.InvariantCulture))
                return;

            string oldEmail = customer.Email;
            customer.Email = newEmail;
            _customerService.UpdateCustomer(customer);

            //update newsletter subscription (if required)
            // điều kiện để update là email cũ khác null, và email mới khác email cũ
            if(!string.IsNullOrEmpty(oldEmail) && !newEmail.Equals(oldEmail, StringComparison.InvariantCultureIgnoreCase))
            {
                foreach(var store in _storeService.GetAllStores())
                {
                    var subscriptionOld = _newsLetterSubscriptionService.GetNewsLetterSubscriptionByEmailAndStoreId(oldEmail, store.Id);
                    if(subscriptionOld != null)
                    {
                        subscriptionOld.Email = newEmail;
                        _newsLetterSubscriptionService.UpdateNewsLetterSubscription(subscriptionOld);
                        // xem lại vấn đề publish event ở chỗ này và publish event cho cútomer
                    }
                }
            }
        }