public async Task <IActionResult> Login(UserLogin login)
        {
            if (!ModelState.IsValid)
            {   //数据验证失败
                login.UserName = null;
                login.Password = null;
                return(View());
            }
            if (!string.Equals(HttpContext.Session.Get <string>("verCode")
                               , login.VerifyCode, StringComparison.InvariantCultureIgnoreCase))
            {
                ModelState.AddModelError("VerifyCode", "验证码错误");
                return(View());
            }

            login.Password = Md5Encryption.Encrypt(Md5Encryption.Encrypt(login.Password, Md5EncryptionType.Strong));
            UserInfo userInfo = UserInfoServices
                                .LoadFirst(entity => entity.UserName == login.UserName &&
                                           entity.Password == login.Password);

            if (userInfo == null)
            {
                ModelState.AddModelError("Password", "用户名与密码不匹配");
                return(View());
            }
            if (userInfo.IsCanUse == false)
            {
                ModelState.AddModelError("", "当前用户不可用");
                return(View());
            }
            SetUser(userInfo, login.RememberMe);
            return(RedirectToAction("Index", "Home"));
        }
Esempio n. 2
0
        /// <summary>
        /// Load data from config file
        /// </summary>
        private void LoadConfig()
        {
            var appSettings = ConfigurationManager.AppSettings;

            //Ping times
            PingLoopDelayInMilliSeconds = appSettings[WindServConfigConst.PingLoopDelayInMilliSeconds];
            //Mail
            MailSmtpServer        = appSettings[WindServConfigConst.MailSmtpServer];
            MailAlertDestinataire = appSettings[WindServConfigConst.MailAlertDestinataire];
            MailNoReplyAddress    = appSettings[WindServConfigConst.MailNoReplyAddress];
            //user allowed to ping
            UserAllowedToUseServiceLogin = appSettings[WindServConfigConst.UserAllowedToUseServiceLogin];

            //Password management
            var decryptedPw = Md5Encryption.DecryptString(appSettings[WindServConfigConst.UserAllowedToUseServicePassword], Security.ToEncryptEncryptPw);

            UserAllowedToUseServicePassword = decryptedPw; // appSettings[WindServConfigConst.UserAllowedToUseServicePassword];

            //urls to ping
            var listeToCatch = appSettings[WindServConfigConst.WebServiceToPingAsConcatStringPipeSeparated];
            var listIds      = listeToCatch.Split(WindServConfigConst.PipeSep);

            foreach (var key in listIds)
            {
                //get those url to ping
                WebServicesToPing.Add(appSettings[FormatParam(key, WindServConfigConst.WsToPing)]);
            }
        }
Esempio n. 3
0
        public string CheckUser(User userchk, HttpContextBase httpContext)
        {
            var result   = string.Empty;
            var email    = userchk.Email;
            var password = Md5Encryption.Encrypt(userchk.Password);
            var usertype = userchk.UserType;

            var user = _userRepository.Query(u => u.Email == email && u.Password == password && u.UserType == usertype).Select().FirstOrDefault();

            if (user == null)
            {
                result = "invalid";
            }
            else
            {
                if (user.UserType == "Customer" && !user.IsConfirmed)
                {
                    result = "notconfirmed";
                }
                else
                {
                    _formsAuthenticationFactory.SetAuthCookie(httpContext, UserAuthenticationTicketBuilder.CreateAuthenticationTicket(user));
                    result = "valid";
                }
            }
            return(result);
        }
Esempio n. 4
0
        /// <summary>
        ///     This method is used to authenticate a users login
        /// </summary>
        /// <param name="email"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        public AppUser AuthenticateAppUserLogin(string email, string password)
        {
            var hashPassword = new Md5Encryption().ConvertStringToMd5Hash(password.Trim());
            var user         = new AppUserFactory().GetAppUserByLogin(email, hashPassword);

            return(user);
        }
        public ActionResult Add(UserEdit userEdit)
        {
            if (ModelState.IsValid)
            {
                UserInfo user = Mapper.Map <UserInfo>(userEdit);
                user.Password = Md5Encryption.Encrypt(Md5Encryption.Encrypt(user.Password, Md5EncryptionType.Strong));
                user          = UserInfoServices.AddEntity(user);

                //LoggerHelper.Operate(new OperateLog
                //{
                //    CreateUser_Id = UserInfo.ID,
                //    OperateType = (int)OperateType.Add,
                //    Remark = $"{UserInfo.Name}添加了一个用户{userEdit.Name}"
                //});
                return(Json(new Result <int>
                {
                    State = 1,
                    Message = "添加成功",
                    Data = user.ID
                }));
            }
            else
            {
                IEnumerable <object> errors = ModelStateToJson();
                return(Json(new Result <object>
                {
                    State = 0,
                    Message = "错误",
                    Data = errors
                }));
            }
        }
Esempio n. 6
0
        public ActionResult Create([Bind(Include = "AppUserId,FirstName,LastName,MiddleName,Email,Mobile,Password,ComfirmPassword,RestaurantId,Create_dby,DateCreated,DateLastModified,LastModifie_dby")] AppUser appUser, FormCollection collectedValues)
        {
            var loggedinuser = Session["odarmsloggedinuser"] as AppUser;
            var restaurant   = Session["restaurant"] as Restaurant;

            if (ModelState.IsValid)
            {
                if (loggedinuser != null && restaurant != null)
                {
                    appUser.EmployeeId       = loggedinuser.EmployeeId;
                    appUser.RestaurantId     = loggedinuser.RestaurantId;
                    appUser.DateLastModified = DateTime.Now;
                    appUser.DateCreated      = DateTime.Now;
                    appUser.LastModifiedBy   = loggedinuser.AppUserId;
                    appUser.CreatedBy        = loggedinuser.AppUserId;

                    //generate password and convert to md5 hash
                    var password     = Membership.GeneratePassword(8, 1);
                    var hashPassword = new Md5Encryption().ConvertStringToMd5Hash(password.Trim());
                    appUser.Password        = new RemoveCharacters().RemoveSpecialCharacters(hashPassword);
                    appUser.ComfirmPassword = appUser.Password;
                }
                _db.AppUsers.Add(appUser);
                _db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            return(View(appUser));
        }
Esempio n. 7
0
        public bool ProfileUpdate(User user, string action, int vid)
        {
            bool isSuccess = true;

            try
            {
                user.Password = Md5Encryption.Encrypt(user.Password);



                if (action == "I")
                {
                    Insert(user);
                }
                else if (action == "U")
                {
                    Update(user);
                }
                else if (action == "D")
                {
                    Delete(user);
                }
                _unitOfWork.SaveChanges();
            }
            catch (Exception ex)
            {
                isSuccess = false;
                throw ex;
            }
            return(isSuccess);
        }
Esempio n. 8
0
        public IActionResult Login([FromBody] JObject jobj)
        {
            //if (!string.Equals(HttpContext.Session.Get<string>("verCode")
            //    , login.VerifyCode, StringComparison.InvariantCultureIgnoreCase))
            //{
            //    return BadRequest(new Result
            //    {
            //         State = 0,
            //         Message = "验证码错误"
            //    });
            //}
            //string s = jobj["fsfsf"].ToString();
            string username = jobj["username"]?.ToString(),
                   password = jobj["password"]?.ToString();

            if (IsValidUserAndPasswordCombination(username, password))
            {
                return(BadRequest(new Result
                {
                    State = 0,
                    Message = "用户名或密码不能为空"
                }));
            }

            password = Md5Encryption.Encrypt(Md5Encryption.Encrypt(password, Md5EncryptionType.Strong));
            UserInfo userInfo = UserInfoServices
                                .LoadFirst(entity => entity.UserName == username &&
                                           entity.Password == password);

            if (userInfo == null)
            {
                return(BadRequest(new Result
                {
                    State = 0,
                    Message = "用户名或密码不正确"
                }));
            }
            if (userInfo.IsCanUse == false)
            {
                return(BadRequest(new Result
                {
                    State = 0,
                    Message = "当前用户不可用"
                }));
            }

            string token = GenerateToken(username);

            Cache.SetString(token, userInfo.UserName);
            return(Ok(new Result <string>
            {
                State = 1,
                Message = "登陆成功",
                Data = token
            }));
        }
Esempio n. 9
0
        /// <summary>
        ///     This method is used to reset a user password
        /// </summary>
        /// <param name="newPassword"></param>
        /// <param name="userId"></param>
        public void ResetUserPassword(string newPassword, int userId)
        {
            var user = _db.AppUsers.Find(userId);

            user.Password = newPassword;
            var hashPasword = new Md5Encryption().ConvertStringToMd5Hash(newPassword);

            _db.Entry(user).State = EntityState.Modified;
            user.Password         = hashPasword;
            _db.SaveChanges();
        }
Esempio n. 10
0
        public KeyValuePair <bool, string> ValidatePassword(User userchk, string oldPassword, string newPassword)
        {
            if (oldPassword == newPassword)
            {
                return(new KeyValuePair <bool, string>(false, "Existing password and the new password are same, please change the password."));
            }

            if (userchk.Password != Md5Encryption.Encrypt(oldPassword))
            {
                return(new KeyValuePair <bool, string>(false, "Entered old password is not valid."));
            }
            return(new KeyValuePair <bool, string>(true, "valid"));
        }
Esempio n. 11
0
        public ActionResult Create(UserViewModel userViewModel)
        {
            userViewModel.genderList = _userBusiness.GetGenderList();
            if (ModelState.IsValid)
            {
                Mapper.CreateMap <UserViewModel, User>();
                User user   = Mapper.Map <UserViewModel, User>(userViewModel);
                var  result = _userBusiness.ValidateUser(user, "I");
                if (!string.IsNullOrEmpty(result))
                {
                    TempData["Success"]   = result;
                    TempData["isSuccess"] = "false";
                    return(View(userViewModel));
                }

                //saving profile image
                user.TokenKey = GlobalMethods.GetToken();
                user.UserType = "Admin";
                user.Password = Md5Encryption.Encrypt(userViewModel.Password);
                FileOperations.CreateDirectory(Server.MapPath("~/ProfileImage"));
                if (userViewModel.ProfileImageUpload != null)
                {
                    string ext      = Path.GetExtension(userViewModel.ProfileImageUpload.FileName).ToLower();
                    string filename = user.TokenKey + ext;

                    string filePath = Server.MapPath("~/ProfileImage/") + filename;
                    userViewModel.ProfileImageUpload.SaveAs(filePath);
                    user.ProfileImage = filename;
                }
                user.IsBlocked = false;
                bool isSuccess = _userBusiness.AddUpdateDeleteUser(user, "I");
                if (isSuccess)
                {
                    TempData["Success"]   = "User Created Successfully!!";
                    TempData["isSuccess"] = "true";
                    return(RedirectToAction("Index"));
                }
                else
                {
                    TempData["Success"]   = "Failed to create User!!";
                    TempData["isSuccess"] = "false";
                }
            }
            else
            {
                TempData["Success"]   = ModelState.Values.SelectMany(m => m.Errors).FirstOrDefault().ErrorMessage;
                TempData["isSuccess"] = "false";
            }

            return(View(userViewModel));
        }
Esempio n. 12
0
        public ActionResult Add(UserEdit userEdit)
        {
            UserInfo user = Mapper.Map <UserInfo>(userEdit);

            user.Password = Md5Encryption.Encrypt(Md5Encryption.Encrypt(user.Password, Md5EncryptionType.Strong));
            user          = UserInfoServices.AddEntity(user);

            //LoggerHelper.Operate(new OperateLog
            //{
            //    CreateUser_Id = UserInfo.ID,
            //    OperateType = (int)OperateType.Add,
            //    Remark = $"{UserInfo.Name}添加了一个用户{userEdit.Name}"
            //});
            return(Ok(new Result <int>
            {
                State = 1,
                Message = "添加成功",
                Data = user.ID
            }));
        }
Esempio n. 13
0
        public static void Initialize(NdcContext context)
        {
            context.Database.EnsureCreated();

            if (context.Users.Any())
            {
                return;   // DB has been seeded
            }

            var users = new User[]
            {
                new User {
                    UserId = Guid.NewGuid(), UserName = "******", Password = Md5Encryption.EncryptMd5("123456"), Email = "*****@*****.**", FirstName = "Châu", LastName = "Nguyễn"
                },
            };

            foreach (var user in users)
            {
                context.Users.Add(user);
            }
            context.SaveChanges();
        }
Esempio n. 14
0
        public ActionResult ChangePassword(ChangePasswordViewModel changePassword)
        {
            string JsonStr   = "";
            bool   isSuccess = true;
            string message   = "Password changed successfully!!";

            if (ModelState.IsValid)
            {
                try
                {
                    var user          = _userBusiness.GetListWT(c => c.TokenKey == changePassword.TokenKey).FirstOrDefault();
                    var validpassword = _userBusiness.ValidatePassword(user, changePassword.OldPassword, changePassword.Password);
                    if (validpassword.Key)
                    {
                        user.Password = Md5Encryption.Encrypt(changePassword.Password);
                        _userBusiness.Update(user);
                        _unitOfWork.SaveChanges();
                    }
                    else
                    {
                        isSuccess = false;
                        message   = validpassword.Value;
                    }
                }
                catch (Exception ex)
                {
                    message   = "Failed to change password!!";
                    isSuccess = false;
                    _unitOfWork.Dispose();
                }
            }

            TempData["Success"]   = message;
            TempData["isSuccess"] = isSuccess.ToString();

            JsonStr = "{\"message\":\"" + message + "\",\"isSuccess\":\"" + isSuccess + "\"}";
            return(Json(JsonStr, JsonRequestBehavior.AllowGet));
        }
Esempio n. 15
0
        public ActionResult Index()
        {
            bool IsUsedLocalLoginPage = bool.Parse(System.Configuration.ConfigurationManager.AppSettings["UserLocalLoginPage"]);


            if (!IsUsedLocalLoginPage)
            {
                #region IntergartionCode
                if (Request.QueryString["uid"] == null)
                {
                    string LoginUrl = System.Configuration.ConfigurationManager.AppSettings["LoginPageUrl"];
                    return(Redirect(LoginUrl));
                }
                else
                {
                    string Fname = Request.QueryString["first"];
                    string Lname = Request.QueryString["last"];
                    string Email = Request.QueryString["email"];

                    db = new EcommerceContext();
                    this._unitOfWork = new UnitOfWork(_df);

                    UsersList = new UserBusiness(_df, _unitOfWork);

                    User CurrentUserInfo = new User()
                    {
                        FirstName = Fname, LastName = Lname, Email = Email
                    };


                    var IsUserExist = UsersList.GetUserByemail(CurrentUserInfo.Email);

                    if (IsUserExist == null)
                    {
                        User newUser = new User();
                        newUser.TokenKey = GlobalMethods.GetToken();

                        newUser.FirstName   = CurrentUserInfo.FirstName;
                        newUser.LastName    = CurrentUserInfo.LastName;
                        newUser.Email       = CurrentUserInfo.Email;
                        newUser.Password    = Md5Encryption.Encrypt(System.Configuration.ConfigurationManager.AppSettings["UserPassword"]);
                        newUser.UserType    = "Customer";
                        newUser.IsBlocked   = false;
                        newUser.IsConfirmed = true;

                        UsersList.Insert(newUser);
                        _unitOfWork.SaveChanges();

                        Session["CurrentUserInfo"] = newUser;
                    }
                    else
                    {
                        Session["CurrentUserInfo"] = IsUserExist;
                    }
                }

                #endregion
            }
            else
            {
            }

            return(View());
        }
Esempio n. 16
0
        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="loginInfo">登录条件</param>
        /// <returns>是否成功</returns>
        public ResponseBase <CurrentUserDto> Login(LoginDto model)
        {
            var rp = new ResponseBase <CurrentUserDto>();

            rp.IsLogin = false;
            if (null != model)
            {
                var userName  = model.UserName;
                var loginUser = SystemRepo.GetUserByName(userName);
                if (null == loginUser)
                {
                    rp.IsSuccess     = false;
                    rp.OperationDesc = "用户不存在";
                }
                else if (loginUser.UserStatus == StatusCode.锁定)
                {
                    rp.IsSuccess     = false;
                    rp.OperationDesc = "该用户已被锁定";
                }
                else if (loginUser.RoleIDs == null || loginUser.RoleIDs.Count() <= 0)
                {
                    rp.IsSuccess     = false;
                    rp.OperationDesc = "该用户无角色";
                }
                else
                {
                    var password = Md5Encryption.Encrypt(model.UserPassword);
                    if (password == loginUser.UserPassword)
                    {
                        CurrentUserDto currentUser = new CurrentUserDto();
                        currentUser.UserID   = loginUser.SysUserId;
                        currentUser.UserName = loginUser.UserName;
                        //currentUser.Actions = loginUser.Actions;
                        currentUser.RealName  = loginUser.RealName;
                        currentUser.RoleIDs   = loginUser.RoleIDs;
                        currentUser.RoleNames = loginUser.RoleNames;
                        currentUser.MenuIds   = loginUser.MenuIds;
                        rp.Result             = currentUser;
                        rp.IsLogin            = true;
                        rp.IsSuccess          = true;
                        rp.OperationDesc      = "登录成功";
                        WriteLogInfo("用户:" + model.UserName + ", 登录系统");
                        var dto = new SysOperationLogDto
                        {
                            UserName          = loginUser.UserName,
                            OperationTypeCode = OperationTypeCode.操作,
                            OperationUrl      = "/Account/Login",
                            OperationContent  = "登录成功",
                        };
                        CreateSysOperationLog(dto);
                    }
                    else
                    {
                        rp.IsSuccess     = false;
                        rp.OperationDesc = "登录失败,密码错误";
                    }
                }
            }
            else
            {
                rp.IsSuccess     = false;
                rp.OperationDesc = "登录失败,提交数据为空";
            }
            return(rp);
        }
Esempio n. 17
0
        public async Task <IActionResult> AddEmployee(PreEmployee preEmployee)
        {
            var userId       = _session.GetInt32("loggedinusersessionid");
            var restaurantid = _session.GetInt32("restaurantsessionid");
            var restaurant   = _db.Restaurants.Find(restaurantid);

            try
            {
                if (_db.EmployeePersonalDatas.Any(n => n.Email == preEmployee.Email) == false &&
                    _db.AppUsers.Any(n => n.Email == preEmployee.Email) == false)
                {
                    var _employee = new Employee
                    {
                        RestaurantId     = Convert.ToInt32(restaurantid),
                        CreatedBy        = userId,
                        LastModifiedBy   = Convert.ToInt32(userId),
                        DateCreated      = DateTime.Now,
                        DateLastModified = DateTime.Now
                    };

                    _db.Employees.Add(_employee);
                    await _db.SaveChangesAsync();

                    if (_employee.EmployeeId > 0)
                    {
                        //Popluate the personal data object
                        var _employeePersonalData = new EmployeePersonalData
                        {
                            RestaurantId     = Convert.ToInt32(restaurantid),
                            CreatedBy        = userId,
                            LastModifiedBy   = Convert.ToInt32(userId),
                            DateCreated      = DateTime.Now,
                            DateLastModified = DateTime.Now,
                            FirstName        = preEmployee.Firstname,
                            LastName         = preEmployee.Lastname,
                            Email            = preEmployee.Email,
                            PrimaryAddress   = preEmployee.PrimaryAddress,
                            SecondaryAddress = "N/A",
                            State            = "N/A",
                            MiddleName       = "N/A",
                            LGA           = "N/A",
                            HomePhone     = preEmployee.HomePhoneNumber,
                            WorkPhone     = "N/A",
                            DOB           = DateTime.Now,
                            Title         = 0.ToString(),
                            MaritalStatus = 0.ToString(),
                            Gender        = 0.ToString(),
                            POB           = "N/A",
                            EmployeeId    = _employee.EmployeeId
                        };

                        _db.EmployeePersonalDatas.Add(_employeePersonalData);
                        await _db.SaveChangesAsync();

                        var password = new Md5Encryption().RandomString(7);
                        var _appUser = new AppUser
                        {
                            EmployeeId       = _employee.EmployeeId,
                            Email            = _employeePersonalData.Email,
                            Name             = _employeePersonalData.DisplayName,
                            RestaurantId     = Convert.ToInt32(restaurantid),
                            CreatedBy        = userId,
                            LastModifiedBy   = Convert.ToInt32(userId),
                            DateCreated      = DateTime.Now,
                            DateLastModified = DateTime.Now,
                            Password         = new Hashing().HashPassword(password),
                            ConfirmPassword  = new Hashing().HashPassword(password),
                            Status           = UserStatus.Inactive.ToString()
                        };

                        _db.AppUsers.Add(_appUser);
                        await _db.SaveChangesAsync();

                        if (_appUser.AppUserId > 0)
                        {
                            //define acceskeys and save transactions
                            var accesskey = new AppUserAccessKey
                            {
                                PasswordAccessCode          = new Md5Encryption().RandomString(15),
                                AccountActivationAccessCode = new Md5Encryption().RandomString(20),
                                CreatedBy        = _appUser.AppUserId,
                                LastModifiedBy   = _appUser.AppUserId,
                                DateCreated      = DateTime.Now,
                                DateLastModified = DateTime.Now,
                                ExpiryDate       = DateTime.Now.AddDays(1),
                                AppUserId        = _appUser.AppUserId
                            };

                            _db.AppUserAccessKeys.Add(accesskey);
                            await _db.SaveChangesAsync();

                            //new Mailer()
                        }

                        TempData["display"]          = "You have successfully added a new employee!";
                        TempData["notificationType"] = NotificationType.Success.ToString();
                        return(View());
                    }

                    TempData["display"]          = "There is an error performing this action. Try again!";
                    TempData["notificationType"] = NotificationType.Error.ToString();
                    return(View(preEmployee));
                }

                TempData["display"]          = "The employee already exist, try a different email!";
                TempData["notificationtype"] = NotificationType.Error.ToString();
                return(View(preEmployee));
            }
            catch (Exception ex)
            {
                TempData["display"]          = ex.Message;
                TempData["notificationtype"] = NotificationType.Error.ToString();
                return(View());
            }
        }