internal User FindByCriteria(string email, List <int> userStatusEnums = null, UserTypeEnum?userTypeEnums = null)
        {
            User result = null;

            userStatusEnums = (userStatusEnums == null || userStatusEnums.Count == 0)
                ? new List <int> {
                (int)UserStatusEnum.Active, (int)UserStatusEnum.Blocked
            }
                : userStatusEnums;

            try
            {
                using (CraveatsDbContext craveatsDbContext = new CraveatsDbContext())
                {
                    List <User> results = craveatsDbContext.User.Where(u => (u.UserStatus.HasValue &&
                                                                             userStatusEnums.Contains(u.UserStatus.Value) &&
                                                                             (u.EmailAddress == email))).OrderBy(u => u.UserStatus).ThenBy(v => v.Id).ToList();

                    result = results.Any()
                        ? (userTypeEnums == null)
                            ? results.FirstOrDefault()
                            : results.Where(u =>
                                            u.UserTypeFlag.HasValue &&
                                            ((UserTypeEnum)u.UserTypeFlag.Value).HasFlag(
                                                userTypeEnums.Value)).FirstOrDefault()
                        : null
                    ;
                }
            }
            catch (Exception e)
            {
                throw e;
            }
            return(result);
        }
        internal async Task <IdentityResult> ChangePasswordAsync(int loggedUserId, string oldPassword, string newPassword)
        {
            bool returnSuccess = false;

            try
            {
                SHA1HashProvider sHA1HashProvider = new SHA1HashProvider();

                using (CraveatsDbContext craveatsDbContext = new CraveatsDbContext()) {
                    User thisUser = craveatsDbContext.User.FirstOrDefault(u => u.Id == loggedUserId);
                    if (thisUser != null && sHA1HashProvider.CheckHashSHA1(oldPassword, thisUser.Password, 8))
                    {
                        thisUser.Password    = sHA1HashProvider.SecureSHA1(newPassword);
                        thisUser.LastUpdated = DateTime.Now;

                        await craveatsDbContext.SaveChangesAsync();

                        returnSuccess = true;
                    }
                }
            }
            catch (Exception e) {
                Trace.WriteLine(e);
            }

            return(returnSuccess ? IdentityResult.Success : IdentityResult.Failed("Change password failed"));
        }
        public User GetSigningUserByEmail(string emailAddress)
        {
            try
            {
                using (CraveatsDbContext craveatsDbContext = new CraveatsDbContext())
                {
                    DBCommonUtility dBCommonUtility   = new DBCommonUtility();
                    string          sqlCmdParamString = "";
                    SqlParameter[]  sqlParameters     = dBCommonUtility.GetSqlParameters(
                        new object[] {
                        emailAddress
                    },
                        out sqlCmdParamString
                        , true);
                    StringBuilder sbRawSQL = new StringBuilder("exec GetSigningUserByEmail");
                    sbRawSQL.AppendFormat(" {0}", sqlCmdParamString.Trim());

                    User newUser = craveatsDbContext.User.SqlQuery(
                        sql: sbRawSQL.ToString(),
                        parameters: sqlParameters
                        ).FirstOrDefault();

                    return(newUser);
                }
            }
            catch (Exception e) {
                throw e;
            }
        }
        public ActionResult ForgotPassword(ForgotPasswordViewModel model)
        {
            SessionManager.RegisterSessionActivity();

            if (ModelState.IsValid)
            {
                User          anActiveOrBlockedUser = null;
                CEUserManager ceUserManager         = new CEUserManager();
                anActiveOrBlockedUser = ceUserManager.GetSigningUserByEmail(model.Email);

                if (anActiveOrBlockedUser == null)
                {
                    // Don't reveal that the user does not exist or is not confirmed
                    return(View("ForgotPasswordConfirmation"));
                }

                // For more information on how to enable account confirmation and password reset please visit https://go.microsoft.com/fwlink/?LinkID=320771
                // Send an email with this link
                string longTicks = DateTime.Now.Ticks.ToString(),
                       code      = DataSecurityTripleDES.GetEncryptedText(longTicks);

                using (CraveatsDbContext craveatsDbContext = new CraveatsDbContext())
                {
                    User anUser = craveatsDbContext.User.First(u => u.Id == anActiveOrBlockedUser.Id);

                    anUser.ResetCode       = longTicks;
                    anUser.ResetCodeExpiry = DateTime.Now.AddDays(1);
                    anUser.ResetCodeSentAt = DateTime.Now;

                    anUser.LastUpdated = DateTime.Now;

                    craveatsDbContext.SaveChanges();
                }

                var callbackUrl = Url.Action("ResetPassword", "Login", new { userId = DataSecurityTripleDES.GetEncryptedText(anActiveOrBlockedUser.Id), code = code }, protocol: Request.Url.Scheme);

                StringBuilder sbSubject   = new StringBuilder("Craveats reset password request"),
                              sbEmailBody = new StringBuilder("<p>Dear [FullName],</p><p>We have received a request that you would like to reset your account password with us." +
                                                              "Please reset your password by clicking <a href=\"" + callbackUrl + "\">here</a></p><p>Thank you.</p><p>Craveats</p>");

                CommunicationServiceProvider.SendOutgoingNotification(
                    new MailAddress(
                        anActiveOrBlockedUser.EmailAddress,
                        string.Format("{0}{1}{2}", anActiveOrBlockedUser?.FirstName, " ", anActiveOrBlockedUser?.Surname).Trim()),
                    sbSubject.ToString(),
                    sbEmailBody.Replace("[FullName]",
                                        string.Format("{0}{1}{2}", anActiveOrBlockedUser?.FirstName, " ", anActiveOrBlockedUser?.Surname).Trim()).ToString());

                return(RedirectToAction("ForgotPasswordConfirmation", "Login"));
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
 public void GetCountry()
 {
     using (CraveatsDbContext craveatsDbContext = new CraveatsDbContext())
     {
         var iso2Param = new SqlParameter {
             ParameterName = "@iso2",
             Value         = "CA"
         };
         //var country = craveatsContext.Database.SqlQuery<object>("select c.* from [Country] c where c.iso2 = @iso2", iso2Param).SingleOrDefaultAsync();
         var country = craveatsDbContext.Database.SqlQuery <Country>("select c.* from [Country] c where c.iso2 = @iso2", iso2Param).SingleOrDefaultAsync().Result;
     }
 }
 private bool UserExistsForEmail(string emailAddress)
 {
     try
     {
         using (CraveatsDbContext craveatsDbContext = new CraveatsDbContext())
         {
             return(craveatsDbContext.GetUserByEmail(emailAddress).Count() > 0);
         }
     }
     catch (Exception e)
     {
         throw e;
     }
 }
Exemple #7
0
 public DAL.Country FindCountryById(int id)
 {
     DAL.Country result = null;
     try
     {
         using (CraveatsDbContext craveatsDbContext = new CraveatsDbContext())
         {
             result = craveatsDbContext.Country.Find(id);
         }
     }
     catch (Exception e)
     {
         Trace.WriteLine(e);
     }
     return(result);
 }
Exemple #8
0
        public Address FindAddressById(int id)
        {
            Address result = null;

            try
            {
                using (CraveatsDbContext craveatsDbContext = new CraveatsDbContext())
                {
                    result = craveatsDbContext.Address.Find(id);
                }
            }
            catch (Exception e)
            {
                Trace.WriteLine(e);
            }
            return(result);
        }
        public User FindById(int id)
        {
            User user = null;

            try
            {
                using (CraveatsDbContext craveatsDbContext = new CraveatsDbContext())
                {
                    user = craveatsDbContext.User.Find(id);
                }
            }
            catch (Exception e)
            {
                Trace.WriteLine(e);
            }
            return(user);
        }
Exemple #10
0
        public DAL.Region FindRegionById(int id)
        {
            Region result = null;

            try
            {
                using (CraveatsDbContext craveatsDbContext = new CraveatsDbContext())
                {
                    result = craveatsDbContext.Region.Find(id);
                }
            }
            catch (Exception e)
            {
                Trace.WriteLine(e);
            }
            return(result);
        }
        internal async Task <UserDTO> FindByIdAsync(int loggedUserId)
        {
            UserDTO userDTO = null;

            try
            {
                using (CraveatsDbContext craveatsDbContext = new CraveatsDbContext())
                {
                    User user = await craveatsDbContext.User.FindAsync(loggedUserId);

                    userDTO = EntityDTOHelper.GetEntityDTO <User, UserDTO>(user);
                }
            }
            catch (Exception e)
            {
                Trace.WriteLine(e);
            }
            return(userDTO);
        }
        internal void SaveUserDetail(UserDTO userDTO)
        {
            try
            {
                using (CraveatsDbContext craveatsDbContext = new CraveatsDbContext())
                {
                    int  userId = int.Parse(DataSecurityTripleDES.GetPlainText(userDTO.Id));
                    User anUser = craveatsDbContext.User.FirstOrDefault(u => u.Id == userId);

                    anUser = EntityDTOHelper.MapToEntity <UserDTO, User>(userDTO, anUser);

                    anUser.LastUpdated = DateTime.Now;
                    craveatsDbContext.SaveChanges();
                }
            }
            catch (Exception e)
            {
                throw e;
            }
        }
Exemple #13
0
        internal Address FindActiveByCriteria(int ownerId, int ownerType)
        {
            Address result = null;

            try
            {
                using (CraveatsDbContext craveatsDbContext = new CraveatsDbContext())
                {
                    result = craveatsDbContext.Address.Where(u => (u.AddressStatus.HasValue &&
                                                                   u.AddressStatus.Value == (int)Common.AddressStatusEnum.Active) &&
                                                             (u.OwnerType.HasValue && u.OwnerType.Value == ownerType) &&
                                                             (u.OwnerId.HasValue && u.OwnerId == ownerId)).OrderBy(u => u.Id).ThenBy(v => v.Id).FirstOrDefault();
                }
            }
            catch (Exception e)
            {
                throw e;
            }
            return(result);
        }
        public ActionResult ResetPassword(ResetPasswordViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            User          anActiveOrBlockedUser = null;
            CEUserManager ceUserManager = new CEUserManager();
            int           userIDFromRequest = 0;
            string        plainCode = null, errorInTranslation = string.Empty;

            try
            {
                userIDFromRequest = int.Parse(DataSecurityTripleDES.GetPlainText(model.UserId));
                plainCode         = DataSecurityTripleDES.GetPlainText(model.Code);

                DateTime minExpiry = DateTime.Now;

                using (CraveatsDbContext craveatsDbContext = new CraveatsDbContext())
                {
                    anActiveOrBlockedUser = craveatsDbContext.User.First(u => u.Id == userIDFromRequest && u.ResetCode == plainCode && (!u.ResetCodeExpiry.HasValue || u.ResetCodeExpiry >= minExpiry));
                    anActiveOrBlockedUser.ResetCodeExpiry = DateTime.Now;
                    anActiveOrBlockedUser.ResetCode       = null;

                    anActiveOrBlockedUser.Password = new SHA1HashProvider().SecureSHA1(model.Password.Trim());

                    anActiveOrBlockedUser.LastUpdated = DateTime.Now;

                    craveatsDbContext.SaveChanges();
                }
            }
            catch (Exception e)
            {
                Trace.WriteLine(e);
            }

            return(RedirectToAction("ResetPasswordConfirmation", "Account"));
        }
Exemple #15
0
        public static string GetContextSessionID()
        {
            object xLock  = new object();
            int?   UserId = (int?)int.Parse(DataSecurityTripleDES.GetPlainText(GetContextSessionLoggedUserID()));

            lock (xLock)
            {
                string SessionID = HttpContext.Current.Session.SessionID,
                       IPAddress = (HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] ?? string.Empty).Trim() == string.Empty
                ? HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"]?.Trim()
                : HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"]?.Trim();

                SessionTracking result = null;


                using (CraveatsDbContext craveatsDbContext = new CraveatsDbContext())
                {
                    result = craveatsDbContext.SessionTracking.FirstOrDefault(u => u.IPAddress == IPAddress && u.SessionID == SessionID && u.UserId == UserId);
                }

                return(DataSecurityTripleDES.GetEncryptedText(result?.Id ?? 0));
            }
        }
        internal int?RegisterNew(string email, string hashedPassword, string role)
        {
            try {
                Common.UserTypeEnum registeringRole = Common.CommonUtility.GetEnumValueFromDescription <Common.UserTypeEnum>(role);

                if (!(registeringRole.HasFlag(Common.UserTypeEnum.CraveatsDiner) ||
                      registeringRole.HasFlag(Common.UserTypeEnum.PartnerRestaurant)))
                {
                    throw new InvalidOperationException("Requested role could not be used in this context.");
                }

                using (CraveatsDbContext craveatsDbContext = new CraveatsDbContext()) {
                    DBCommonUtility dBCommonUtility   = new DBCommonUtility();
                    string          sqlCmdParamString = "";
                    SqlParameter[]  sqlParameters     = dBCommonUtility.GetSqlParameters(
                        new object[] {
                        email,
                        hashedPassword,
                        (int)registeringRole
                    },
                        out sqlCmdParamString
                        , true);
                    StringBuilder sbRawSQL = new StringBuilder("exec RegisterNewActiveUser");
                    sbRawSQL.AppendFormat(" {0}", sqlCmdParamString.Trim());

                    User newUser = craveatsDbContext.User.SqlQuery(
                        sql: sbRawSQL.ToString(),
                        parameters: sqlParameters
                        ).FirstOrDefault();

                    return(newUser?.Id);
                }
            }
            catch (Exception e) {
                throw e;
            }
        }
Exemple #17
0
        private static SessionTracking EditSessionTracking(SessionTracking sessionTracking)
        {
            SessionTracking savedSessionTracking = null;

            try
            {
                using (CraveatsDbContext craveatsDbContext = new CraveatsDbContext()) {
                    DBCommonUtility dBCommonUtility   = new DBCommonUtility();
                    string          sqlCmdParamString = "";
                    SqlParameter[]  sqlParameters     = dBCommonUtility.GetSqlParameters(
                        new object[] {
                        sessionTracking.SessionID,
                        sessionTracking.IPAddress,
                        sessionTracking.UserId,
                        null,
                        sessionTracking.LoggedInAt,
                        sessionTracking.LoggedOutAt
                    },
                        out sqlCmdParamString
                        , true);
                    StringBuilder sbRawSQL = new StringBuilder("exec EditSessionTracking");
                    sbRawSQL.AppendFormat(" {0}", sqlCmdParamString.Trim());

                    savedSessionTracking = craveatsDbContext.Database.SqlQuery <SessionTracking>(
                        sql: sbRawSQL.ToString(),
                        parameters: sqlParameters
                        ).FirstOrDefault();
                }
            }
            catch (Exception exception)
            {
                throw exception;
            }

            return(savedSessionTracking);
        }