Esempio n. 1
0
        public virtual LoginState ChangePassword(PasswordChangeModel model)
        {
            var _context = new ModelContext();

            // var user = _context.UserProfiles.Find(2);
            MemberShip member = _context.Set <MemberShip>().FirstOrDefault(m => m.UserName.Equals(
                                                                               Thread.CurrentPrincipal.Identity.Name,
                                                                               StringComparison.OrdinalIgnoreCase));

            if (member == null)
            {
                return(LoginState.UserNotExist);
            }

            if (model.Password != model.ConfirmPassword)
            {
                return(LoginState.PasswordError);
            }

            if (EncryptPassword(model.OldPassword, member.PasswordSalt) != member.Password)
            {
                return(LoginState.OldPasswordError);
            }

            member.PasswordSalt        = CommOp.NewId();
            member.Password            = Encryption.MD5(model.Password + member.PasswordSalt);
            member.PasswordChangedDate = DateTime.Now;
            _context.SaveChanges();
            return(LoginState.OK);
        }
Esempio n. 2
0
        public int Add(AppUser user)
        {
            //WebSecurity.CreateUserAndAccount(user.Name, "123456", new { Email = ((AppUserEx)user).Email });
            MemberShip member = new MemberShip()
            {
                UserName     = user.Name,
                CreateDate   = DateTime.Now,
                IsConfirmed  = true,
                Email        = user.Email,
                PhoneNumber  = user.PhoneNumber,
                PasswordSalt = CommOp.NewId(),
            };

            member.Password = MyStateProvider.EncryptPassword("123456", member.PasswordSalt);

            foreach (string roleId in user.RoleIds)
            {
                UserInRole uir = new UserInRole
                {
                    RoleId = roleId.ToInt(),
                };
                member.UserInRoles.Add(uir);
            }
            using (var _context = new ModelContext())
            {
                _context.Set <MemberShip>().Add(member);
                _context.SaveChanges();
            }
            user.Id = member.UserId.ToString();
            return(1);
        }
Esempio n. 3
0
        public virtual LoginState ResetPassword(PasswordResetModel model)
        {
            var _context = new ModelContext();

            // var user = _context.UserProfiles.Find(2);
            MemberShip member = _context.Set <MemberShip>().FirstOrDefault(m => m.UserName.Equals(model.UserName, StringComparison.OrdinalIgnoreCase));

            if (member == null)
            {
                return(LoginState.UserNotExist);
            }

            if (model.Password != model.ConfirmPassword && model.IsResetPass != 1)
            {
                return(LoginState.PasswordError);
            }

            if (model.ConfirmToken != member.ConfirmationToken && model.IsResetPass != 1)
            {
                return(LoginState.TokenError);
            }
            member.PasswordSalt        = CommOp.NewId();
            member.Password            = Encryption.MD5(model.Password + member.PasswordSalt);
            member.PasswordChangedDate = DateTime.Now;
            //对于系统重置的密码,强制吧修改密码日期移除让用户登陆重新修改面貌
            if (model.IsResetPass == 1)
            {
                member.PasswordChangedDate = null;
            }
            _context.SaveChanges();
            return(LoginState.OK);
        }
Esempio n. 4
0
        public async Task <bool> ChangePassword(string p)
        {
            var userSession = _session.Get(Token);

            var user = await _user.GetAsync(userSession.Account);

            //  ps["Password"] = Encryption.MD5("123456" + ps["PasswordSalt"]);
            user.PasswordSalt = CommOp.NewId();
            user.Password     = Encryption.MD5(p + user.PasswordSalt);
            await _user.UpdateAsync(user);

            return(true);
        }
Esempio n. 5
0
        async Task <AppUser> CreateTempUser(string tempId)
        {
            DataGateService dataSvc = Consts.Get <DataGateService>();
            var             newUser = new AppUser
            {
                Id       = tempId,
                Account  = tempId,
                Name     = tempId,
                Password = CommOp.NewId().Substring(8, 16)
            };

            await dataSvc.SubmitAsync("SaveUser", new
            {
                Added = new object[] { newUser }
            });

            return(newUser);
        }
Esempio n. 6
0
        //在新增记录时,对于单一主键的记录,检查主键字段是否自增或是guid,是否值为空,
        //如果是自增,则去掉传过来的值,由库自动生成,如果是guid并且为空,则生成一个guid
        private void CheckPrimaryKey(TableMeta tableMeta, IDictionary <string, object> psin, out string id, out string getMaxIdSql)
        {
            id          = null;
            getMaxIdSql = null;
            var pKeyField = tableMeta.PrimaryKey;

            if (pKeyField == null)
            {
                return;
            }

            if (pKeyField.DataType == "Number")
            {
                getMaxIdSql = $"select max({pKeyField.FixDbName}) from {tableMeta.FixDbName}";
            }

            var pkey = psin.Keys.FirstOrDefault(k => k.Equals(pKeyField.Name, StringComparison.OrdinalIgnoreCase));

            //没有传主键字段过来
            if (pkey == null)
            {
                pkey = pKeyField.Name;
                psin.Add(pkey, null);
            }

            //当主键为Number型时,认为是自增字段,为空时从参数中去掉,让数据库自动生成
            if (pKeyField.DataType == "Number")
            {
                psin.Remove(pkey);
            }
            //非number型,并且为空,则认为是32位的guid字符串,为它自动生成
            else if (CommOp.IsEmpty(psin[pkey]))
            {
                id         = CommOp.NewId();
                psin[pkey] = id;
            }
            else
            {
                id = CommOp.ToStr(psin[pkey]);
            }
        }
Esempio n. 7
0
        public void OnChanged(DataGateKey gkey, IDictionary <string, object> ps)
        {
            string pwdKey = GetLUKey(ps, "password");

            if (pwdKey.IsEmpty())
            {
                return;
            }

            string   pwd          = (string)ps[pwdKey];
            string   passwordSalt = CommOp.NewId();
            string   password     = Encryption.MD5(pwd + passwordSalt);
            DateTime createDate   = DateTime.Now;
            string   id           = (string)ps[GetLUKey(ps, "id")];

            gkey.DataService.DB.ExecNonQuery(@"UPDATE APP_USER SET PASSWORD=@password, PASSWORD_SALT=@passwordSalt WHERE ID=@id", gkey.DataService.DB.GetParameter(new
            {
                password,
                passwordSalt,
                id
            }).ToArray());
        }
Esempio n. 8
0
        public virtual LoginState SendPasswordResetMessage(string userName, string email, string resetUrl)
        {
            var _context = new ModelContext();

            MemberShip member = _context.Set <MemberShip>().FirstOrDefault(m => m.UserName.Equals(userName, StringComparison.OrdinalIgnoreCase) && m.IsConfirmed == true);

            if (member == null)
            {
                return(LoginState.UserNotExist);
            }
            if (!member.Email.Equals(email, StringComparison.OrdinalIgnoreCase))
            {
                return(LoginState.EmailError);
            }
            member.ConfirmationToken = CommOp.NewId();
            string url     = resetUrl + "?username="******"&confirmToken=" + member.ConfirmationToken;
            string subject = ResHelper.GetStr("Password+Reset");
            string body    = "<p>" + ResHelper.GetStr("Click the link below to reset your password") + "</p>"
                             + "<p>" + "<a href='" + url + "' target='_blank'>" + url + "</a></p>";
            SMTPMail mail = new SMTPMail(member.Email, subject, body);

            _context.SaveChanges();
            mail.Send();
            if (mail.ErrorMessage.IsEmpty())
            {
                return(LoginState.OK);
            }
            else
            {
#if DEBUG
                if (HttpContext.Current != null)
                {
                    HttpContext.Current.Session["ResetPasswordEmailBody"] = body;
                }
#endif
                return(LoginState.EmailSendError);
            }
        }
Esempio n. 9
0
        async Task TestCUDRole()
        {
            var    rand  = new Random();
            string pk    = CommOp.NewId();
            var    menus = await Get <DBCrud <AppMenu> >().GetListAsync();

            if (menus.Count < 2)
            {
                throw new Exception("要完成本次测试,菜单表中至少要有2个菜单。");
            }
            var roleMenu = new
            {
                menuId = menus[0].Id,
                roleId = pk
            };

            var role = new
            {
                id   = pk,
                name = "测试角色" + rand.Next(),
                //这个子表数据应该被忽略掉,在前端json传值时也应该不传
                menus = new object[] { }
            };

            var task = new
            {
                added   = new object[] { role },
                details = new object[]
                {
                    new
                    {
                        key   = "SaveRoleMenu",
                        added = new object[] { roleMenu }
                    }
                }
            };

            var result = await SubmitAsync("SaveRole", task);

            Assert.True(1 == result.Length);

            var role1 = new
            {
                id    = pk,
                name  = "测试角色" + rand.Next(),
                menus = new object[] { roleMenu }
            };

            var roleMenu1 = new
            {
                menuId = menus[1].Id,
                roleId = pk
            };

            var task1 = new
            {
                changed = new object[] { role1 },
                details = new object[]
                {
                    new
                    {
                        key     = "SaveRoleMenu",
                        removed = new object[] { roleMenu },
                        added   = new object[] { roleMenu1 }
                    }
                }
            };

            result = await SubmitAsync("SaveRole", task1);

            Assert.True(0 == result.Length);

            var task2 = new
            {
                removed = new object[] { role1 },
                details = new object[]
                {
                    new
                    {
                        key     = "SaveRoleMenu",
                        removed = new object[] { roleMenu1 }
                    }
                }
            };

            result = await SubmitAsync("SaveRole", task2);

            Assert.True(0 == result.Length);
        }
Esempio n. 10
0
        async Task TestCUDUser()
        {
            var    rand  = new Random();
            string pk    = CommOp.NewId();
            var    roles = await Get <DBCrud <AppRole> >().GetListAsync();

            if (roles.Count < 1)
            {
                throw new Exception("要完成本次测试,角色表中至少要有1个角色。");
            }
            var userRole = new
            {
                roleId = roles[0].Id,
                userId = pk
            };

            var user = new
            {
                id      = pk,
                name    = "测试用户" + rand.Next(),
                account = "TEST_USER" + rand.Next(),
                email   = DateTime.Now.Ticks + "@abc.com",
                tel     = DateTime.Now.Ticks,
                //这个子表数据应该被忽略掉,在前端json传值时也应该不传
                roles = new object[] { userRole }
            };

            var task = new
            {
                added   = new object[] { user },
                details = new object[]
                {
                    new
                    {
                        key   = "SaveUserRole",
                        added = new object[] { userRole }
                    }
                }
            };

            var result = await SubmitAsync("SaveUser", task);

            Assert.True(1 == result.Length);

            var user1 = new
            {
                id      = pk,
                name    = "测试用户U" + rand.Next(),
                account = "USER_" + rand.Next(),
                email   = rand.Next() + "@update.com",
                tel     = new Random().Next(),
                roles   = new object[] { userRole }
            };

            var userRole1 = new
            {
                roleId = roles[1].Id,
                userId = pk
            };

            var task1 = new
            {
                changed = new object[] { user1 },
                details = new object[]
                {
                    new
                    {
                        key     = "SaveUserRole",
                        removed = new object[] { userRole },
                        added   = new object[] { userRole1 }
                    }
                }
            };

            result = await SubmitAsync("SaveUser", task1);

            Assert.True(0 == result.Length);

            var task2 = new
            {
                removed = new object[] { user1 },
                details = new object[]
                {
                    new
                    {
                        key     = "SaveUserRole",
                        removed = new object[] { userRole1 }
                    }
                }
            };

            result = await SubmitAsync("SaveUser", task2);

            Assert.True(0 == result.Length);
        }
Esempio n. 11
0
        /// <summary>
        /// 登录,根据用户名,手机,邮箱来登录,当同一手机,邮箱不止一个用户使用时,将登录不成功
        /// </summary>
        /// <param name="request"></param>
        /// <param name="validate">验证密码</param>
        /// <returns></returns>
        public async Task <LoginResult> Login(LoginRequest request, bool validate = true)
        {
            LoginResult result      = new LoginResult();
            string      requestPass = null;

            //登录时回传的记住我的信息,从记住我的信息恢复用户的登录用户名密码
            if (request.Remember?.Length > 10)
            {
                RestoreFormRemember(request);
                requestPass = request.Password;
            }
            AppUser user = null;

            request.Account = request.Account.ToLower();
            if (user == null && CommOp.IsEmail(request.Account))
            {
                user = await _user.GetByEmailAsync(request.Account);
            }
            if (user == null && CommOp.IsPhoneNumber(request.Account))
            {
                user = await _user.GetByTelAsync(request.Account);
            }
            if (user == null)
            {
                user = await _user.GetAsync(request.Account);
            }
            if (user == null)
            {
                return(MSG.UserNotExists);
            }

            if (requestPass == null)
            {
                requestPass = Encryption.MD5(request.Password + user.PasswordSalt);
            }
            if (user.Password != requestPass && validate)
            {
                return(MSG.PasswordError);
            }
            UserSession session = new UserSession
            {
                Token      = CommOp.NewId(),
                Account    = user.Account,
                Id         = user.Id,
                LastOpTime = DateTime.Now
            };
            var cacheKey     = GetCacheKey(session.Token);
            var sessionBytes = Encoding.UTF8.GetBytes(session.ToJson(false));

            await this.DistributedCache.SetAsync(cacheKey, sessionBytes, new DistributedCacheEntryOptions()
            {
                AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(this.Expires)
            });

            this.MemoryCache.Set(cacheKey, session);

            DataGateService ds = Consts.Get <DataGateService>();

            //写最后登录时间,并进一步判断用户是否存在
            await ds.UpdateAsync("UpdateLastLoginTime", new
            {
                id            = user.Id,
                LastLoginDate = session.LastOpTime
            });

            //要求“记住我”时,将登录信息加密回传,根据服务端的加密
            if (request.Remember == "1")
            {
                request.Remember = Encryption.Encrypt(String.Join("|", user.Account, user.Password));
            }
            return(new LoginResult
            {
                ExpireIn = Expires,
                Token = session.Token,
                Remember = request.Remember
            });
        }
Esempio n. 12
0
        /// <summary>
        /// 登录,根据用户名,手机,邮箱来登录,当同一手机,邮箱不止一个用户使用时,将不成登录成功
        /// </summary>
        /// <param name="request"></param>
        /// <param name="validate">验证密码</param>
        /// <returns></returns>
        public async Task <LoginResult> Login(LoginRequest request, bool validate = true)
        {
            LoginResult result      = new LoginResult();
            string      requestPass = null;

            //登录时回传的记住我的信息,从记住我的信息恢复用户的登录用户名密码
            if (request.Remember?.Length > 10)
            {
                RestoreFormRemember(request);
                requestPass = request.Password;
            }
            AppUser user = null;

            if (user == null && CommOp.IsEmail(request.Account))
            {
                user = await _user.GetByEmailAsync(request.Account);
            }
            if (user == null && CommOp.IsPhoneNumber(request.Account))
            {
                user = await _user.GetByTelAsync(request.Account);
            }
            if (user == null)
            {
                user = await _user.GetAsync(request.Account);
            }
            if (user == null)
            {
                return(MSG.UserNotExists);
            }

            if (requestPass == null)
            {
                requestPass = Encryption.MD5(request.Password + user.PasswordSalt);
            }
            if (user.Password != requestPass && validate)
            {
                return(MSG.PasswordError);
            }
            UserSession session = new UserSession
            {
                Token      = CommOp.NewId(),
                Account    = user.Account,
                Id         = user.Id,
                LastOpTime = DateTime.Now
            };

            _sessionDict.TryAdd(session.Token, session);

            DataGateService ds = Consts.Get <DataGateService>();
            await ds.UpdateAsync("UpdateLastLoginTime", new
            {
                id            = user.Id,
                LastLoginDate = session.LastOpTime
            });

            //要求“记住我”时,将登录信息加密回传,根据服务端的加密
            if (request.Remember == "1")
            {
                request.Remember = Encryption.Encrypt(String.Join("|", user.Account, user.Password));
            }
            return(new LoginResult
            {
                ExpireIn = Expires,
                Token = session.Token,
                Remember = request.Remember
            });
        }