コード例 #1
0
        public void AddUser_should_save()
        {
            string username = "******" + Guid.NewGuid();

            var user = new User
            {
                 Email = "*****@*****.**",
                 FirstName = "john",
                 IsActive = true,
                 LastName = "haigh",
                 PasswordHash = "asdf",
                 Username = username
            };

            var svc = new UserService();
            svc.AddUser(user);

            var repo = new UserRepository();

            var repoUser = repo.Find(u => u.Username == username).FirstOrDefault();

            // Test
            repoUser.ShouldNotBeNull();

            // Cleanup user
            repo.Delete(repoUser);
            repo.Save();

            var results2 = repo.Find(u => u.Username == username);
            var userFound2 = results2.FirstOrDefault();

            Assert.IsNull(userFound2, "Tried to get user but the user was found");
        }
コード例 #2
0
        public void AddUserMessage()
        {
            using (var uow = new CapriconContext())
            {
                //retreive an existing user
                var userRepository = new UserRepository(uow);
                var existingUser = userRepository.GetAll().FirstOrDefault();

                Assert.IsNotNull(existingUser);

                //retreive an existing message
                var messageRepository = new MessageRepository(uow);
                var existingMessage = messageRepository.GetAll().FirstOrDefault();

                Assert.IsNotNull(existingMessage);

                //create new user messsage
                var newUserMessage = new UserMessage()
                {
                    User = existingUser,
                    Message = existingMessage
                };

                //add the new user message to the repository
                var userMessageRepository = new UserMessageRepository(uow);
                userMessageRepository.Add(newUserMessage);

                try
                {
                    uow.SaveChanges();
                }
                catch (DbEntityValidationException ex)
                {
                    //Retrieve validation errors
                    ex.EntityValidationErrors.ToList().ForEach
                    (
                        v =>
                        {
                            v.ValidationErrors.ToList().ForEach
                                (
                                    e =>
                                    {
                                        System.Diagnostics.Debug.WriteLine(e.ErrorMessage);
                                    }
                                );
                        }
                    );

                    Assert.Fail("Test failed");
                }

                //retrieve saved object
                var uow1 = new CapriconContext();
                var repository = new UserMessageRepository(uow1);
                var savedUserMessages = repository.GetAll().ToList();

                Assert.AreEqual(savedUserMessages[0].User.FirstName, existingUser.FirstName = "james");
                Assert.AreEqual(savedUserMessages[0].Message.MessageId, existingMessage.MessageId = 1);
            };
        }
コード例 #3
0
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            // Allow CORS on the token middleware provider
            context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });

            //TODO
            // Usually this would be done via dependency injection
            // But I haven't got it to work with the OWIN startup class yet
            AppDBContext _ctx = new AppDBContext();
            UserRepository _repo = new UserRepository(_ctx);

                IdentityUser user = await _repo.FindUser(context.UserName, context.Password);

                if (user == null)
                {
                    context.SetError("invalid_grant", "The user name or password is incorrect.");
                    return;
                }

            var identity = new ClaimsIdentity(context.Options.AuthenticationType);
            identity.AddClaim(new Claim("sub", context.UserName));
            identity.AddClaim(new Claim("role", "user"));

            context.Validated(identity);

        }
コード例 #4
0
        public static BaseActionResult BulkDeleteUserByIds(string idsStr)
        {
            string msg;
            string[] idArr = idsStr.Split(',');
            if (idArr.Length == 0)
            {
                msg = XiaoluResources.ERR_MSG_NO_RECORD_FOR_ACTION;
                return new BaseActionResult(false, msg);
            }
            try
            {
                List<User> list4delete = new List<User>();
                foreach (string id in idArr)
                {
                    var obj4delete = GetUserById(id);
                    list4delete.Add(obj4delete);
                }

                using (var context = new XiaoluEntities())
                {
                    var repository = new UserRepository(context);
                    repository.BulkDelete(list4delete);
                    context.SaveChanges();
                    msg = string.Format(XiaoluResources.MSG_BULK_ACTION_SUCCESS, XiaoluResources.STR_USER, idArr.Length);
                    return new BaseActionResult(true, msg);
                }
            }
            catch (Exception e)
            {
                msg = string.Format(XiaoluResources.MSG_BULK_ACTION_FAIL, XiaoluResources.STR_DELETE, idArr.Length) + string.Format(XiaoluResources.STR_FAIL_RESAON, ExceptionHelper.GetInnerExceptionInfo(e));
                return new BaseActionResult(false, msg, e);
            }
        }
コード例 #5
0
        public void Initialize() {
            session.BeginTransaction();
            userRepository = new UserRepository();
            identityService = new IdentityService<User>(userRepository);

            password = "******";
            
            user = new User
            {
                Name = "John Doe",
                BirthDate = new DateTime(1982, 8, 1),
                Email = "*****@*****.**",
                Username = "******",
                Address = new Address { City = "São paulo", StreetName = "name", Number = "123B", State = "SP", ZipCode = "03423-234" }
            };

            user2 = new User
            {
                Name = "Fulano",
                BirthDate = DateTime.Now,
                Email = "*****@*****.**",
                Password = "******",
                Username = "******",
                Address = new Address { City = "São paulo", StreetName = "name", Number = "123B", State = "SP", ZipCode = "03423-234" }
            };
        }
コード例 #6
0
ファイル: UnitTest2.cs プロジェクト: diegotrujillor/SMCL
        public void CanCreateAlarmTypeAndLog()
        {
            IRepository<AlarmType> repoA = new AlarmTypeRepository();
            AlarmType alarm = new AlarmType();
            alarm.NameAlarmType = "PruebaAlarma";
            alarm.Description = "Prueba descriptiva alarma";

            repoA.Save(alarm);

            IRepository<User> repoB = new UserRepository();
            User user = new User();
            user = repoB.GetById(1);
            IRepository<Event> repoC = new EventRepository();
            Event eventt = new Event();
            eventt = repoC.GetById(2);

            IRepository<Log> repoD = new LogRepository();
            Log log = new Log();
            log.DateTime = DateTime.Now;
            log.Text = "Prueba descriptiva log";
            log.Event = eventt;
            log.User = user;

            repoD.Save(log);
        }
コード例 #7
0
ファイル: UnitOfWork.cs プロジェクト: rMb93/BasteleiApp
 public UnitOfWork(bastelei_ws context)
 {
     _context = context;
     Probes = new ProbeRepository(_context);
     Measurements = new MeasurementRepository(_context);
       Users = new UserRepository(_context);
 }
コード例 #8
0
		private void GetPostService(UnitOfWork uow, out ICategoryService categoryService, out IForumService forumService, out ITopicService topicService, out IPostService postService) {
			ICategoryRepository cateRepo = new CategoryRepository(uow);
			IForumRepository forumRepo = new ForumRepository(uow);
			ITopicRepository topicRepo = new TopicRepository(uow);
			IPostRepository postRepo = new PostRepository(uow);
			IForumConfigurationRepository configRepo = new ForumConfigurationRepository(uow);

			IState request = new DummyRequest();

			ILogger logger = new ConsoleLogger();

			IUserRepository userRepo = new UserRepository(uow);
			User user = userRepo.Create(new User {
				Name = "D. Ummy",
				ProviderId = "12345678",
				FullName = "Mr. Doh Ummy",
				EmailAddress = "[email protected]",
				Culture = "th-TH",
				TimeZone = "GMT Standard Time"
			});

			List<IEventSubscriber> subscribers = new List<IEventSubscriber>();

			IEventPublisher eventPublisher = new EventPublisher(subscribers, logger, request);
			IUserProvider userProvider = new DummyUserProvider(user);
			IPermissionService permService = new PermissionService();
			IForumConfigurationService confService = new ForumConfigurationService(configRepo);

			categoryService = new CategoryService(userProvider, cateRepo, eventPublisher, logger, permService);
			forumService = new ForumService(userProvider, cateRepo, forumRepo, topicRepo, postRepo, eventPublisher, logger, permService);
			topicService = new TopicService(userProvider, forumRepo, topicRepo, postRepo, eventPublisher, logger, permService, confService);
			postService = new PostService(userProvider, forumRepo, topicRepo, postRepo, eventPublisher, logger, permService, confService);
		}
コード例 #9
0
        public void UserExample()
        {
            var interests = new HashSet<string> { "distributed systems", "Erlang" };
            var joe = new User("Joe", "Armstrong", interests);

            var entityManager = new EntityManager(client);
            entityManager.Add(joe);
            var repo = new UserRepository(client);
            repo.Save(joe);

            joe.VisitPage();

            joe.AddInterest("riak");

            repo.UpgradeAccount(joe);

            var joeFetched = repo.Get(joe.ID);

            Assert.GreaterOrEqual(joe.PageVisits, 0);
            Assert.Contains("riak", joeFetched.Interests.ToArray());

            PrintObject(joeFetched);

            repo.DowngradeAccount(joe);

            joeFetched = repo.Get(joe.ID);
            PrintObject(joeFetched);
        }
コード例 #10
0
        public void TestAdd()
        {
            try
            {
                var userEntiry = new UserEntity()
                    {
                        Password = "******",
                        CreatedAt = DateTime.UtcNow,
                        UserName = "******",
                        Emails = new List<string>()
                            {
                                "*****@*****.**",
                                "*****@*****.**"
                            },
                        Options = new Dictionary<string, string>()
                            {
                                {"city", "Zhuhai"},
                                {"language", "cn"}
                            }
                    };

                var userRepo = new UserRepository();
                var task = userRepo.Add(userEntiry);
                task.Wait();

                Assert.IsNotNull(userEntiry.Id);
                Assert.IsFalse(string.IsNullOrWhiteSpace(task.Result));
            }
            catch (Exception e)
            {
                Assert.Fail(e.Message);
            }
            
        }
コード例 #11
0
        public void GetByLogin_LoginExists()
        {
            var userRepository = new UserRepository(_contextFactory);
            var authenticationRepository = new LoginAuthenticationRepository(_contextFactory);

            var user = new User { Name = "name", Email = "email" };
            var userId = userRepository.Create(user);

            var initalLoginAuth = new LoginAuthentication
            {
                UserId = userId,
                LoginName = "login",
                PasswordHash = Enumerable.Range(0, 32).Select(i => (byte)i).ToArray(),
                Salt = Enumerable.Range(0, 16).Select(i => (byte)i).ToArray()
            };

            authenticationRepository.Save(initalLoginAuth);

            var restoredLoginAuthentication = authenticationRepository.GetByLogin(initalLoginAuth.LoginName);

            Assert.NotNull(restoredLoginAuthentication);
            Assert.AreEqual(initalLoginAuth.UserId, restoredLoginAuthentication.UserId);
            Assert.AreEqual(initalLoginAuth.LoginName, restoredLoginAuthentication.LoginName);
            CollectionAssert.AreEqual(initalLoginAuth.Salt, restoredLoginAuthentication.Salt);
            CollectionAssert.AreEqual(initalLoginAuth.PasswordHash, restoredLoginAuthentication.PasswordHash);
        }
コード例 #12
0
 public void Base_Inheritance_Save()
 {
     var repository = new UserRepository();
     var user = new User {Name = "Base_Inheritance_Save"};
     repository.Add(user);
     repository._collectionName.Should().Be("User");
 }
コード例 #13
0
ファイル: AccountController.cs プロジェクト: bearing09/Jspm
 public AccountController(IUnitOfWork unitOfWork)
     : base(unitOfWork)
 {
     _repository = new UserRepository(unitOfWork);
     _departRepository= new DepartRepository(unitOfWork);
     _roleRepository = new RoleRepository(unitOfWork);
 }
コード例 #14
0
ファイル: ChatController.cs プロジェクト: amwtke/bkwecaht
        public async Task<HttpResponseMessage> PostChatCenterInitialize([FromBody]BaseParameter postParameter)
        {
            string openid = postParameter.openID;
            if(string.IsNullOrEmpty(openid))
            {
                return WebApiHelper.HttpRMtoJson(null, HttpStatusCode.OK, customStatus.InvalidArguments);
            }
            using(UserRepository userRepository = new UserRepository())
            {
                var uuid = await userRepository.GetUserUuidByOpenid(openid);
                var sessions = await MessageRedisOp.GetSessionsTimeStampByUuid(uuid.ToString().ToUpper(), Order.Descending, 0, -1);
                List<Tuple<double, UserInfo, string>> ChatCenterList = new List<Tuple<double, UserInfo, string>>();
                foreach(var s in sessions)
                {
                    double unreadNum = await MessageRedisOp.GetUnreadScore(uuid.ToString().ToUpper(), s.Key);
                    List<string> uuidPair = await MessageRedisOp.GetUUidsBySessionId(s.Key);
                    string userUuid = uuidPair[0] == uuid.ToString().ToUpper() ? uuidPair[1] : uuidPair[0];

                    Guid userGUID;
                    if(!Guid.TryParse(userUuid, out userGUID) || userGUID.Equals(Guid.Empty))
                        continue;
                    UserInfo toUser = await userRepository.GetUserInfoByUuidAsync(userGUID);

                    var latestMessage = await WeChatReceiveHelper.GetFirstMessagesFromRedis(uuid.ToString().ToUpper(), userUuid.ToUpper());
                    ChatCenterList.Add(Tuple.Create(unreadNum, toUser, latestMessage));
                }
                return WebApiHelper.HttpRMtoJson(ChatCenterList, HttpStatusCode.OK, customStatus.Success);
            }
        }
コード例 #15
0
        public override Task OnActionExecutedAsync(HttpActionExecutedContext actionExecutedContext, CancellationToken cancellationToken)
        {
            //加入访问次数
            foreach (var v in getActionArgumentsValues(actionExecutedContext))
            {
                if (v is DualParameter)
                {
                    var u = v as DualParameter;
                    NameCardAccessCountOP.AddScore(u.uuid.ToString(), 1);
                    using (UserRepository repo = new UserRepository())
                    {
                        UserInfo user = repo.GetUserInfoByUuid_TB(u.uuid);
                        if(user!=null)
                        {
                            if(user.IsBusiness!= null)
                            {
                                if (user.IsBusiness == 0)
                                    new RedisManager2<WeChatRedisConfig>().AddScoreAsync<NameCardRedis, NameCardPCountZsetAttribute>(u.uuid.ToString(), 1);
                                else if(user.IsBusiness==2)
                                    new RedisManager2<WeChatRedisConfig>().AddScoreAsync<NameCardRedis, NameCardSCountZsetAttribute>(u.uuid.ToString(), 1);
                            }

                        }
                    }
                    break;
                }
            }
            return base.OnActionExecutedAsync(actionExecutedContext, cancellationToken);
        }
コード例 #16
0
        public List<Guid> GetUCError()
        {
            List<Guid> ret = new List<Guid>();
            using (UserRepository repo = new UserRepository())
            {
                foreach(var v in repo.GetAllUserAcadmic())
                {
                    if(!string.IsNullOrEmpty(v.Association) && string.IsNullOrEmpty(v.AssociationPost))
                    {
                        if (!ret.Contains(v.AccountEmail_uuid))
                            ret.Add(v.AccountEmail_uuid);
                    }

                    if (!string.IsNullOrEmpty(v.Magazine) && string.IsNullOrEmpty(v.MagazinePost))
                    {
                        if (!ret.Contains(v.AccountEmail_uuid))
                            ret.Add(v.AccountEmail_uuid);
                    }


                    if (!string.IsNullOrEmpty(v.Fund) && string.IsNullOrEmpty(v.FundPost))
                    {
                        if (!ret.Contains(v.AccountEmail_uuid))
                            ret.Add(v.AccountEmail_uuid);
                    }
                }
            }
            return ret;
        }
コード例 #17
0
 private static UserService GetService()
 {
     IServiceLocator serviceLocator = new DummyServiceLocator();
     IUserRepository userRepository = new UserRepository(serviceLocator);
     IUnitOfWork uow = new EfUnitOfWork<SampleDataContext>(serviceLocator);
     return new UserService(uow, userRepository);
 }
コード例 #18
0
ファイル: UserService.cs プロジェクト: tahtarov/gspd-chat
        public UserService()
        {
            _userManager = _userManager ?? new ApplicationUserManager(new UserStore<ApplicationUserEntity>());
            _userRepository = _userRepository ?? new UserRepository<ApplicationUserEntity>();

            UserMappingConfig.RegisterMappings();
        }
コード例 #19
0
        public void TestMethod1()
        {
            var dbContext = new DanwuDbContext();
            var context = new EntityFrameworkRepositoryContext();
            var unitOfWork = new EntityFrameworkUnitOfWork(dbContext);
            IUserRepository userRepository = new UserRepository(context);
            userRepository.Create(new User()
            {
                UserName = "******",
                NickName = "坏坏男孩",
                RealName = "吴丹",
                PhoneNum = "18916765826",
                Email = "*****@*****.**",
                Status = UserStatus.Enabled,
                PassWord = "******",
                RegisterTime = DateTime.Now,
                LastLogonTime = DateTime.Now
            });
            userRepository.Create(new User()
            {
                UserName = "******",
                NickName = "坏坏男孩1",
                RealName = "吴丹1",
                PhoneNum = "18916765000",
                Email = "*****@*****.**",
                Status = UserStatus.Disabled,
                PassWord = "******",
                RegisterTime = DateTime.Now,
                LastLogonTime = DateTime.Now
            });

            var result = context.Commit();
            //var result = unitOfWork.Commit();
        }
コード例 #20
0
 public GroupMemberService(
         UserRepository userRepository,
         GroupRepository groupRepository)
 {
     this.GroupRepository = groupRepository;
     this.UserRepository = userRepository;
 }
コード例 #21
0
ファイル: MyRoleProvider.cs プロジェクト: na2sia/CheckPoint
        public override string[] GetRolesForUser(string login)
        {
            string[] role = new string[] { };
            using (IModelRepository<User> _user = new UserRepository())
            {
                try
                {
                    IModelRepository<Role> _role = new RoleRepository();
                    // Get User
                    var user = (from u in _user.Items
                                 where u.Login == login
                                 select u).FirstOrDefault();
                    if (user != null)
                    {
                        // Get role
                        var userRole = _role.Items.FirstOrDefault(x=>x.Id==user.RoleId);

                        if (userRole != null)
                        {
                            role = new string[] { userRole.Name };
                        }
                    }
                }
                catch
                {
                    role = new string[] { };
                }
            }
            return role;
        }
コード例 #22
0
        public ActionResult Delete(int id)
        {
            UserRepository userRep = new UserRepository();
            userRep.Delete(id);

            return RedirectToAction("List");
        }
コード例 #23
0
        protected override IUserRepository GetUserRepository()
        {
            var userRepository = new UserRepository(this.repositoryStrategy);
            userRepository.RepositoryGlass = new UserRepositoryGlass();

            return userRepository;
        }
コード例 #24
0
        public static Boolean IsAdmin(this IPrincipal principal)
        {
            UserRepository userRepository = new UserRepository();

            User user = userRepository.GetBy(x => x.Email == principal.Identity.Name);
            return user != null && user.Role == Role.Admin;
        }
コード例 #25
0
 public void ReturnsTrueIfEmailExistsForDifferentUser()
 {
     var repository = new UserRepository(null, SessionSource.CreateSession());
     var user = new User { Name = "test", Credentials = new Credentials("*****@*****.**", "pass") };
     repository.Save(new User {Name = "test", Credentials = new Credentials("*****@*****.**", "pass")});
     Assert.True(repository.EmailExists(user));
 }
コード例 #26
0
        public override bool Execute(string input)
        {
            if (String.IsNullOrEmpty(input)) return false;

            var repository = new UserRepository();
            int userId;
            if (!Int32.TryParse(input, out userId))
            {
                return false;
            }

            var user = repository.GetById(userId);
            if (user != null)
            {
                repository.Delete(user);
            }
            try
            {
                repository.SaveChanges();
                Success = true;
            }
            catch
            {
                Success = false;
            }
            return Success;
        }
コード例 #27
0
        public ActionResult Edit(int? id)
        {
            User user;
            UserRepository userRep = new UserRepository();

            if (!id.HasValue)
            {
                user = new User();
            }
            else
            {
                user = userRep.GetByID(id.Value);
                if (user == null)
                {
                    return RedirectToAction("List");
                }
            }

            UsersEditVM model = new UsersEditVM();
            model.ID = user.ID;
            model.Username = user.Username;
            model.FirstName = user.FirstName;
            model.LastName = user.LastName;
            model.Email = user.Email;
            model.Groups = PopulateAssignedGroups(user);

            return View(model);
        }
コード例 #28
0
        public static BaseActionResult CreateUser(User obj4create)
        {
            string msg;
            if (obj4create == null)
            {
                msg = string.Format(XiaoluResources.MSG_CREATE_SUCCESS, XiaoluResources.STR_USER) + string.Format(XiaoluResources.STR_FAIL_RESAON, XiaoluResources.MSG_OBJECT_IS_NULL);
                return new BaseActionResult(false, msg);
            }

            try
            {
                using (var context = new XiaoluEntities())
                {
                    var repository = new UserRepository(context);
                    string newId = Guid.NewGuid().ToString();
                    obj4create.Id = newId;
                    repository.Create(obj4create);
                    context.SaveChanges();
                    msg = string.Format(XiaoluResources.MSG_CREATE_SUCCESS, obj4create.Name);
                    return new BaseActionResult(true, msg);
                }
            }
            catch (Exception e)
            {
                msg = string.Format(XiaoluResources.MSG_CREATE_FAIL, obj4create.Name) + string.Format(XiaoluResources.STR_FAIL_RESAON, ExceptionHelper.GetInnerExceptionInfo(e));
                return new BaseActionResult(false, msg);
            }
        }
コード例 #29
0
        public void GetById_UserDoesNotExist()
        {
            var repository = new UserRepository(_contextFactory);

            var retrievedUser = repository.GetById(123);
            Assert.IsNull(retrievedUser);
        }
コード例 #30
0
 public MatchCreator(UserRepository userRepository)
 {
     this.userRepository = userRepository;
 }
コード例 #31
0
 public UsersControl()
 {
     InitializeComponent();
     repository = new UserRepository();
     refresh();
 }
コード例 #32
0
 public void TearDown()
 {
     adminService = guestService.SuccessfulAdminLogin(UserRepository.Get().Admin());
     adminService.UpdateTokenlifetime(LifetimeRepository.GetDefault());
     adminService.RemoveUser(UserRepository.Get().TestUser());
 }
コード例 #33
0
 public void SetUp()
 {
     guestService = new GuestService();
     adminService = guestService.SuccessfulAdminLogin(UserRepository.Get().Admin());
 }
コード例 #34
0
 public DocumentController(CurrentUserProvider currentUserProvider, UserRepository userRepository, DocumentRepository documentRepository)
 {
     _currentUserProvider = currentUserProvider ?? throw new ArgumentNullException(nameof(currentUserProvider));
     _userRepository      = userRepository ?? throw new ArgumentNullException(nameof(userRepository));
     _documentRepository  = documentRepository ?? throw new ArgumentNullException(nameof(documentRepository));
 }
コード例 #35
0
 public GetUserByIdQuery(UserRepository userRepository, string userId)
 {
     this.userRepository = userRepository;
     this.userId         = userId;
 }
コード例 #36
0
 public ChatHub()
 {
     repo = new UserRepository();
 }
コード例 #37
0
        public Result <ServiceResponse> SignUp(SignUpRequest request)
        {
            return(this.UseConnection("Default", connection =>
            {
                request.CheckNotNull();

                Check.NotNullOrWhiteSpace(request.Email, "email");
                Check.NotNullOrEmpty(request.Password, "password");
                UserRepository.ValidatePassword(request.Email, request.Password, true);
                Check.NotNullOrWhiteSpace(request.DisplayName, "displayName");

                if (connection.Exists <UserRow>(
                        UserRow.Fields.Username == request.Email |
                        UserRow.Fields.Email == request.Email))
                {
                    throw new ValidationError("EmailInUse", Texts.Validation.EmailInUse);
                }

                using (var uow = new UnitOfWork(connection))
                {
                    string salt = null;
                    var hash = UserRepository.GenerateHash(request.Password, ref salt);
                    var displayName = request.DisplayName.TrimToEmpty();
                    var email = request.Email;
                    var username = request.Email;

                    var fld = UserRow.Fields;
                    var userId = (int)connection.InsertAndGetID(new UserRow
                    {
                        Username = username,
                        Source = "sign",
                        DisplayName = displayName,
                        Email = email,
                        PasswordHash = hash,
                        PasswordSalt = salt,
                        IsActive = 0,
                        InsertDate = DateTime.Now,
                        InsertUserId = 1,
                        LastDirectoryUpdate = DateTime.Now
                    });

                    byte[] bytes;
                    using (var ms = new MemoryStream())
                        using (var bw = new BinaryWriter(ms))
                        {
                            bw.Write(DateTime.UtcNow.AddHours(3).ToBinary());
                            bw.Write(userId);
                            bw.Flush();
                            bytes = ms.ToArray();
                        }

                    var token = Convert.ToBase64String(HttpContext.RequestServices
                                                       .GetDataProtector("Activate").Protect(bytes));

                    var externalUrl = Config.Get <EnvironmentSettings>().SiteExternalUrl ??
                                      Request.GetBaseUri().ToString();

                    var activateLink = UriHelper.Combine(externalUrl, "Account/Activate?t=");
                    activateLink = activateLink + Uri.EscapeDataString(token);

                    var emailModel = new ActivateEmailModel();
                    emailModel.Username = username;
                    emailModel.DisplayName = displayName;
                    emailModel.ActivateLink = activateLink;

                    var emailSubject = Texts.Forms.Membership.SignUp.ActivateEmailSubject.ToString();
                    var emailBody = TemplateHelper.RenderViewToString(HttpContext.RequestServices,
                                                                      MVC.Views.Membership.Account.SignUp.AccountActivateEmail, emailModel);

                    Common.EmailHelper.Send(emailSubject, emailBody, email);

                    uow.Commit();
                    UserRetrieveService.RemoveCachedUser(userId, username);

                    return new ServiceResponse();
                }
            }));
        }
コード例 #38
0
 public UserController(UserRepository repository)
 {
     _repository = repository;
 }
コード例 #39
0
 public UserController(UserRepository repo, CommentRepository repocmt, TokenManager tokenManager)
 {
     _repo         = repo;
     _repoCmt      = repocmt;
     _tokenManager = tokenManager;
 }
コード例 #40
0
 public UserController(UserRepository user)
 {
     _user = user;
 }
コード例 #41
0
ファイル: LdapSync.cs プロジェクト: hugaohhh/JinCreek.Server
 public LdapSync(IConfiguration configuration, ILogger <Deauthentication> logger, UserRepository userRepository, AuthenticationRepository authenticationRepository)
 {
     _configuration = configuration;
     //_ldapSyncSettings = ldapSyncSettings;
     _logger                   = logger;
     _userRepository           = userRepository;
     _authenticationRepository = authenticationRepository;
 }
コード例 #42
0
        private bool ValidateFirstTimeUser(ref string username, string password)
        {
            var throttler = new Throttler("ValidateUser:"******"Error on directory first time authentication", ex, this.GetType());
                return(false);
            }

            try
            {
                string salt        = null;
                var    hash        = UserRepository.GenerateHash(password, ref salt);
                var    displayName = entry.FirstName + " " + entry.LastName;
                var    email       = entry.Email.TrimToNull() ?? (username + "@yourdefaultdomain.com");
                username = entry.Username.TrimToNull() ?? username;

                using (var connection = SqlConnections.NewFor <UserRow>())
                    using (var uow = new UnitOfWork(connection))
                    {
                        var userId = (int)connection.InsertAndGetID(new UserRow
                        {
                            Username            = username,
                            Source              = "ldap",
                            DisplayName         = displayName,
                            Email               = email,
                            PasswordHash        = hash,
                            PasswordSalt        = salt,
                            IsActive            = 1,
                            InsertDate          = DateTime.Now,
                            InsertUserId        = 1,
                            LastDirectoryUpdate = DateTime.Now
                        });

                        uow.Commit();

                        UserRetrieveService.RemoveCachedUser(userId, username);
                    }

                return(true);
            }
            catch (Exception ex)
            {
                Log.Error("Error while importing directory user", ex, this.GetType());
                return(false);
            }
        }
コード例 #43
0
        public IHttpActionResult GetModule(string module)
        {
            //var model = new ResponseContentModel<List<T>>();

            string token  = Request.Headers.GetValues("Authorization").FirstOrDefault();
            var    result = CommonMethods.AuthenticateWebAPI(token);

            if (result != WebAPIEnums.AuthenticationStatus.OK)
            {
                return(Json(CommonMethods.GetAutheticationError(result)));
            }
            else
            {
                if (module == WebAPIEnums.Module.inventory.ToString())
                {
                    var model = new ResponseContentModel <List <ProductAPIModel> >();
                    IProductRepository productRepo = new ProductRepository();

                    model.rows    = productRepo.GetProductsMobile();
                    model.total   = model.rows.Count.ToString();
                    model.key     = "id";
                    model.control = new Control {
                        page = "1", order = "asc", sort = "", limit = ""
                    };
                    return(Json(model));
                }
                else if (module == WebAPIEnums.Module.location.ToString())
                {
                    var model = new ResponseContentModel <List <LocationAPIModel> >();
                    ILocationRepository locRepo = new LocationRepository();
                    model.rows    = locRepo.GetLocationsMobile();
                    model.total   = model.rows.Count.ToString();
                    model.key     = "id";
                    model.control = new Control {
                        page = "1", order = "asc", sort = "", limit = ""
                    };
                    return(Json(model));
                }
                else if (module == WebAPIEnums.Module.supplier.ToString())
                {
                    var model = new ResponseContentModel <List <SupplierAPIModel> >();
                    IClientRepository clientRepo = new ClientRepository();
                    model.rows    = clientRepo.GetSuppliersMobile();
                    model.total   = model.rows.Count.ToString();
                    model.key     = "id";
                    model.control = new Control {
                        page = "1", order = "asc", sort = "", limit = ""
                    };
                    return(Json(model));
                }
                else if (module == WebAPIEnums.Module.users.ToString())
                {
                    var             model    = new ResponseContentModel <List <UserAPIModel> >();
                    IUserRepository userRepo = new UserRepository();
                    model.rows    = userRepo.GetUsersMobile();
                    model.total   = model.rows.Count.ToString();
                    model.key     = "id";
                    model.control = new Control {
                        page = "1", order = "asc", sort = "", limit = ""
                    };
                    return(Json(model));
                }
            }

            return(Json(CommonMethods.GetAutheticationError(WebAPIEnums.AuthenticationStatus.FAILED)));
        }
コード例 #44
0
 public UserController(IConfiguration configuration)
 {
     _userRepository = new UserRepository(configuration);
 }
コード例 #45
0
        private bool ValidateExistingUser(ref string username, string password, UserDefinition user)
        {
            username = user.Username;

            if (user.IsActive != 1)
            {
                if (Log.IsInfoEnabled)
                {
                    Log.Error(String.Format("Inactive user login attempt: {0}", username), this.GetType());
                }

                return(false);
            }

            // prevent more than 50 invalid login attempts in 30 minutes
            var throttler = new Throttler("ValidateUser:"******"site" || user.Source == "sign" || directoryService == null)
            {
                if (validatePassword())
                {
                    throttler.Reset();
                    return(true);
                }

                return(false);
            }

            if (user.Source != "ldap")
            {
                throw new ArgumentOutOfRangeException("userSource");
            }

            if (!string.IsNullOrEmpty(user.PasswordHash) &&
                user.LastDirectoryUpdate != null &&
                user.LastDirectoryUpdate.Value.AddHours(1) >= DateTime.Now)
            {
                if (validatePassword())
                {
                    throttler.Reset();
                    return(true);
                }

                return(false);
            }

            DirectoryEntry entry;

            try
            {
                entry = directoryService.Validate(username, password);
                if (entry == null)
                {
                    return(false);
                }

                throttler.Reset();
            }
            catch (Exception ex)
            {
                Log.Error("Error on directory access", ex, this.GetType());

                // couldn't access directory. allow user to login with cached password
                if (!user.PasswordHash.IsTrimmedEmpty())
                {
                    if (validatePassword())
                    {
                        throttler.Reset();
                        return(true);
                    }

                    return(false);
                }

                throw;
            }

            try
            {
                string salt        = user.PasswordSalt.TrimToNull();
                var    hash        = UserRepository.GenerateHash(password, ref salt);
                var    displayName = entry.FirstName + " " + entry.LastName;
                var    email       = entry.Email.TrimToNull() ?? user.Email ?? (username + "@yourdefaultdomain.com");

                using (var connection = SqlConnections.NewFor <UserRow>())
                    using (var uow = new UnitOfWork(connection))
                    {
                        var fld = UserRow.Fields;
                        new SqlUpdate(fld.TableName)
                        .Set(fld.DisplayName, displayName)
                        .Set(fld.PasswordHash, hash)
                        .Set(fld.PasswordSalt, salt)
                        .Set(fld.Email, email)
                        .Set(fld.LastDirectoryUpdate, DateTime.Now)
                        .WhereEqual(fld.UserId, user.UserId)
                        .Execute(connection, ExpectedRows.One);

                        uow.Commit();

                        UserRetrieveService.RemoveCachedUser(user.UserId, username);
                    }

                return(true);
            }
            catch (Exception ex)
            {
                Log.Error("Error while updating directory user", ex, this.GetType());
                return(true);
            }
        }
コード例 #46
0
        public WalletRecord WithdrawNotify(WalletRecord walletRecord, bool success, string failReason = null)
        {
            using (CurrentUnitOfWork.SetTenantId(walletRecord.TenantId))
            {
                string openid = WechatUserManager.GetOpenid(walletRecord.GetUserIdentifier());
                User   user   = walletRecord.User;

                if (user == null)
                {
                    user = UserRepository.Get(walletRecord.UserId);
                }

                if (success)
                {
                    walletRecord.FetchStatus = FetchStatus.Success;
                    walletRecord.FailReason  = "";
                    WalletRecordRepository.Update(walletRecord);
                    CurrentUnitOfWork.SaveChanges();

                    if (!string.IsNullOrEmpty(openid))
                    {
                        Task.Run(async() =>
                        {
                            WalletWithdrawTemplateMessageData data = new WalletWithdrawTemplateMessageData(
                                new TemplateDataItem(L("WithdrawSuccessfully")),
                                new TemplateDataItem(user.NickName),
                                new TemplateDataItem((-walletRecord.Money).ToString()),
                                new TemplateDataItem(L("ThankYouForYourPatronage"))
                                );
                            await TemplateMessageManager.SendTemplateMessageOfWalletWithdrawAsync(walletRecord.TenantId, openid, null, data);
                        });
                    }
                }
                else
                {
                    if (string.IsNullOrEmpty(failReason))
                    {
                        failReason = L("UnKnowFail");
                    }
                    walletRecord.FetchStatus = FetchStatus.Fail;
                    walletRecord.FailReason  = failReason;
                    WalletRecordRepository.Update(walletRecord);
                    CurrentUnitOfWork.SaveChanges();

                    if (!string.IsNullOrEmpty(openid))
                    {
                        Task.Run(async() =>
                        {
                            WalletWithdrawTemplateMessageData data = new WalletWithdrawTemplateMessageData(
                                new TemplateDataItem(L("WithdrawFailed") + ":" + failReason),
                                new TemplateDataItem(user.NickName),
                                new TemplateDataItem((-walletRecord.Money).ToString()),
                                new TemplateDataItem(L("ThankYouForYourPatronage"))
                                );
                            await TemplateMessageManager.SendTemplateMessageOfWalletWithdrawAsync(walletRecord.TenantId, openid, null, data);
                        });
                    }
                }
                return(walletRecord);
            }
        }
コード例 #47
0
 public async Task AdminModsUser(string username)
 {
     UserRepository.ModUser(Context.ConnectionId, username);
 }
コード例 #48
0
 public AdminController()
 {
     this.userRepository = UserRepository.Instance;
     ActionInvoker       = new CustomActionInvoker();
 }
コード例 #49
0
 public CustomResolver(UserRepository userRepository)
 {
     _userRepository = userRepository;
 }
コード例 #50
0
 public static void UpdateUserPasswordHandler(int id, string newPassword)
 {
     UserRepository.UpdateUserPassword(id, newPassword);
 }
コード例 #51
0
 public MessageController()
 {
     _userRepository    = new UserRepository();
     _messageRepository = new MessageRepository();
 }
コード例 #52
0
 public UserController()
 {
     uow  = new UnitOfWork();
     repo = new UserRepository(uow);
 }
コード例 #53
0
 public void Delete(long id)
 {
     UserRepository.Delete(id);
 }
コード例 #54
0
        public UserLibraryCrudController()
        {
            Get("/api/v1/me/library/projects/get", _ => {
                var me = UserRepository.Find(CurrentRequest.UserId);

                var items = UserLibraryItemRepository.Get(me);

                return(HttpResponse.Item("library_projects", new UserLibraryItemTransformer().Many(items)));
            });

            Get("/api/v1/me/library/project/status/get", _ => {
                var errors = ValidationProcessor.Process(Request, new IValidatorRule[] {
                    new ExistsInTable("project_guid", "projects", "guid")
                });
                if (errors.Count > 0)
                {
                    return(HttpResponse.Errors(errors));
                }

                var me      = UserRepository.Find(CurrentRequest.UserId);
                var project = ProjectRepository.FindByGuid(GetRequestStr("project_guid"));

                return(HttpResponse.Data(new JObject()
                {
                    ["status"] = new JObject()
                    {
                        ["in_library"] = project.InLibrary(me)
                    }
                }));
            });

            Get("/api/v1/me/library/project/get", _ => {
                var errors = ValidationProcessor.Process(Request, new IValidatorRule[] {
                    new ShouldHaveParameters(new[] { "project_guid" }),
                    new ExistsInTable("project_guid", "projects", "guid")
                }, true);
                if (errors.Count > 0)
                {
                    return(HttpResponse.Errors(errors));
                }

                var me      = UserRepository.Find(CurrentRequest.UserId);
                var project = ProjectRepository.FindByGuid(GetRequestStr("project_guid"));
                var item    = UserLibraryItemRepository.Find(me, project);

                if (item == null)
                {
                    return(HttpResponse.Error(HttpStatusCode.NotFound, "Project does not exist in your library"));
                }

                return(HttpResponse.Item("library_project", new UserLibraryItemTransformer().Transform(item)));
            });

            Post("/api/v1/me/library/project/add", _ => {
                var errors = ValidationProcessor.Process(Request, new IValidatorRule[] {
                    new ShouldHaveParameters(new[] { "project_guid" }),
                    new ExistsInTable("project_guid", "projects", "guid"),
                }, true);
                if (errors.Count > 0)
                {
                    return(HttpResponse.Errors(errors));
                }

                var me      = UserRepository.Find(CurrentRequest.UserId);
                var project = ProjectRepository.FindByGuid(GetRequestStr("project_guid"));

                var item = UserLibraryItemRepository.FindOrCreate(me, project);

                return(HttpResponse.Item(
                           "library_project", new UserLibraryItemTransformer().Transform(item), HttpStatusCode.Created
                           ));
            });

            Delete("/api/v1/me/library/project/remove", _ => {
                var errors = ValidationProcessor.Process(Request, new IValidatorRule[] {
                    new ShouldHaveParameters(new[] { "project_guid" }),
                    new ExistsInTable("project_guid", "projects", "guid")
                }, true);
                if (errors.Count > 0)
                {
                    return(HttpResponse.Errors(errors));
                }

                var me = UserRepository.Find(CurrentRequest.UserId);

                var project = ProjectRepository.FindByGuid(GetRequestStr("project_guid"));

                var item = UserLibraryItemRepository.Find(me, project);
                if (item == null)
                {
                    return(HttpResponse.Error(HttpStatusCode.NotFound, "Project does not exist in your library"));
                }
                item.Delete();

                return(HttpResponse.Item("library_project", new UserLibraryItemTransformer().Transform(item)));
            });
        }
コード例 #55
0
 public static User GetUserHandler(string email, string password)
 {
     return(UserRepository.GetUser(email, password));
 }
コード例 #56
0
 public void viewData()
 {
     userGridView.DataSource = UserRepository.getMember();
     userGridView.DataBind();
 }
コード例 #57
0
 public RedditService(PostRepository postRepo, UserRepository userRepo)
 {
     this.postRepo = postRepo;
     this.userRepo = userRepo;
 }
コード例 #58
0
 static void Main(string[] args)
 {
     UserRepository ur    = new UserRepository();
     IList <User>   users = ur.GetAllUsers();
 }
コード例 #59
0
 public AccountController()
 {
     Repository = new UserRepository();
 }
コード例 #60
-1
ファイル: BaseController.cs プロジェクト: amwtke/bkwecaht
 protected async Task<Guid> getUUidByOpenIdAsync(string openId)
 {
     using (UserRepository r = new UserRepository())
     {
         return await r.GetUserUuidByOpenid(openId);
     }
 }