Exemplo n.º 1
0
 IAccessDecider GetDeciderForMessage(UserId userId)
 {
     var combinator = new AccessDecisionCombinator();
       var user = _userRepository.Get(userId);
       user.CombineDecisions(combinator, _roleRepository);
       return combinator.BuildDecider();
 }
Exemplo n.º 2
0
        public AuthenticationResult PerformIdentityAuth(string identity)
        {
            long userId;
            var logins = _webEndpoint.GetSingleton<LoginsIndexView>().Identities;
            if (!logins.TryGetValue(identity, out userId))
            {
                // login not found
                return AuthenticationResult.UnknownIdentity;
            }
            var id = new UserId(userId);

            var maybe = _webEndpoint.GetView<LoginView>(id);

            if (!maybe.HasValue)
            {
                // we haven't created view, yet
                return AuthenticationResult.UnknownIdentity;
            }

            var view = maybe.Value;

            // ok, the view is locked.
            if (view.LockedOutTillUtc > DateTime.UtcNow.AddSeconds(2))
            {
                return new AuthenticationResult(ComposeLockoutMessage(view));
            }

            // direct conversion, will be updated to hashes

            ReportLoginSuccess(id, view);
            return ViewToResult(id, view);
        }
Exemplo n.º 3
0
 public void Authorize(UserId user, object message)
 {
     var decider = GetDeciderForMessage(user);
       if (!decider.AreAllAllowed(_resolver.ResolvePermission(message))) {
     throw new SecurityException(string.Format("Yo bro, u do not have permission to {0}", message.GetType().Name.ToLowerInvariant()));
       }
 }
Exemplo n.º 4
0
            public User GetUser(UserId userId)
            {
                Guard.IsTrue("userId", () => userId.ToString().Length>0);

                var request = AsanaRequest.Get(string.Format("users/{0}", userId));
                return ExecuteRequest<User>(request);
            }
Exemplo n.º 5
0
		public static IObservable<StatusCollection> GetUserTimeline(
			this TwitterAccount account,
			UserId? userId = null,
			int? count = null,
			StatusId? sinceId = null,
			StatusId? maxId = null,
			bool? trimUser = null,
			bool? excludeReplies = null,
			bool? contributorDetails = null,
			bool? includeRts = null,
			bool isStartup = false)
		{
			const string endpoint = "statuses/user_timeline";
			var source = isStartup
				? StatusSource.RestApi | StatusSource.Startup
				: StatusSource.RestApi;
			var client = account.ToOAuthClient(endpoint);

			if (userId.HasValue) client.Parameters.Add("user_id", userId.Value);
			if (count.HasValue) client.Parameters.Add("count", count.Value);
			if (sinceId.HasValue) client.Parameters.Add("since_id", sinceId.Value);
			if (maxId.HasValue) client.Parameters.Add("max_id", maxId.Value);
			if (trimUser.HasValue) client.Parameters.Add("trim_user", trimUser.Value);
			if (excludeReplies.HasValue) client.Parameters.Add("exclude_replies", excludeReplies.Value);
			if (contributorDetails.HasValue) client.Parameters.Add("contributor_details", contributorDetails.Value);
			if (includeRts.HasValue) client.Parameters.Add("include_rts", includeRts.Value);

			return Observable
				.Defer(client.GetResponseText)
				.Select(json => StatusCollection.Parse(json, source))
				.OnErrorRetry(3)
				.WriteLine(endpoint);
		}
Exemplo n.º 6
0
 public Invite(string email, string displayName, UserId userId, string token)
 {
     Email = email;
     DisplayName = displayName;
     FutureUserId = userId;
     FutureToken = token;
 }
Exemplo n.º 7
0
        public void Create(UserId userId, SecurityId securityId)
        {
            if (_state.Version != 0)
                throw new DomainError("User already has non-zero version");

            Apply(new UserCreated(userId, securityId, DefaultLoginActivityThreshold));
        }
Exemplo n.º 8
0
        public ActionResult VkontakteLogin(string uid, string firstName, string lastName, string photo, string returnUrl)
        {
            var userId = new UserId(uid);
            _bus.Send(new ReportUserLoggedIn(userId, firstName + " " + lastName, photo));

            FormsAuthentication.SetAuthCookie(uid, true);
            return SuccessfullLoginRedirect(returnUrl);
        }
Exemplo n.º 9
0
 public void UpdateLogin(UserId id, DateTime timeUtc)
 {
     var item = Items[id.Id];
     if (item.LastLoginUtc < timeUtc)
     {
         item.LastLoginUtc = timeUtc;
     }
 }
Exemplo n.º 10
0
		public void SetFallbackToken(UserId userId, Guid applicationId)
		{
			this.fallbackToken = null;
			this.FallbackUserId = userId;
			this.FallbackApplicationId = applicationId;

			this.RaisePropertyChanged("FallbackToken");
		}
Exemplo n.º 11
0
 public User(InMemoryDomainEvents domainEvents, UserId id, string name, string email)
     : base(domainEvents)
 {
     Id = id;
     Name = name;
     _email = email;
     TryRaiseEvent(new UserCreated() { UserId = Id, UserName = Name, UserEmail = Email, Version = Version });
 }
Exemplo n.º 12
0
		private static IObservable<List> ShowListCore(OAuthClient client, string endpoint, UserId ownerId)
		{
			return Observable
				.Defer(() => client.GetResponseText())
				.Select(json => List.Parse(json, ownerId))
				.OnErrorRetry(3)
				.WriteLine(endpoint, list => list.FullName);
		}
Exemplo n.º 13
0
		public List this[ListId id, UserId ownerId]
		{
			get
			{
				var key = Tuple.Create(id, ownerId);
				return this.DoReadLockAction(() => this.lists.ContainsKey(key) ? this.lists[key] : null);
			}
		}
Exemplo n.º 14
0
 public void AddIdentity(IDomainIdentityService ids, PasswordGenerator pwds, string display, string identity)
 {
     if (_state.ContainsIdentity(identity))
         return;
     var user = new UserId(ids.GetId());
     var token = pwds.CreateToken();
     Apply(new SecurityIdentityAdded(_state.Id, user, display, identity, token));
 }
Exemplo n.º 15
0
        private void SetUserEmailIfNeeded(UserId userId, EmailAddress email)
        {
            UserDetails userDetails = _readModel.GetUserDetails(userId);

            if (String.IsNullOrWhiteSpace(userDetails.Email))
            {
                _bus.Send(new SetUserEmail(userId, email));
            }
        }
Exemplo n.º 16
0
 /// <summary>
 /// Gets the file name of the given user id.
 /// </summary>
 /// <param name="userId">the user id.</param>
 /// <returns>the file name.</returns>
 static string GetFileName(UserId userId)
 {
     if (userId == UserId.User1)
         return @"Assets\Data\User1Contacts.xml";
     else if (userId == UserId.User2)
         return @"Assets\Data\User2Contacts.xml";
     else
         throw new NotSupportedException($"{userId} is not supported");
 }
Exemplo n.º 17
0
		public static IObservable<List> ShowList(this TwitterAccount account, UserId owner, string slug)
		{
			const string endpoint = "lists/show";
			var client = account.ToOAuthClient(endpoint);
			client.Parameters.Add("slug", slug);
			client.Parameters.Add("owner_id", owner);

			return ShowListCore(client, endpoint, account.UserId);
		}
Exemplo n.º 18
0
 public AccountManagement.User GetUser(UserId userId)
 {
     using (var db = new THCard()) {
         Guid userIdAsGuid = userId.ToGuid();
         User dbUser = db.Users.SingleOrDefault(u => u.UserId == userIdAsGuid);
         AccountManagement.User user = MapToUser(dbUser);
         return user;
     }
 }
Exemplo n.º 19
0
        public void UpdateDisplayName(UserId userId, string displayName)
        {
            var user = _state.GetUser(userId);

            if (user.DisplayName == displayName)
                return;

            Apply(new SecurityItemDisplayNameUpdated(_state.Id, userId, displayName));
        }
Exemplo n.º 20
0
 public void AddItem(UserId userId, SecurityItemType type, string displayName, string value)
 {
     Items[userId.Id] = new SecurityItem
         {
             Display = displayName,
             Type = type,
             Value = value,
             UserId = userId.Id
         };
 }
Exemplo n.º 21
0
 public void RemoveSecurityItem(UserId userId)
 {
     SecurityState.User user;
     if (!_state.TryGetUser(userId, out user))
     {
         throw new InvalidOperationException("User not found");
     }
     var s = user.Kind.ToString().ToLowerInvariant();
     Apply(new SecurityItemRemoved(_state.Id, user.Id, user.Lookup, s));
 }
        public void CreatingNewUser()
        {
            var id = new UserId(Guid.NewGuid());
            var email = "*****@*****.**";
            var metroId = 11;
            var command = new CreateBasicUser {EmailAddress = email, GlobalPersonId = id.Gpid, MetroId = metroId};

            new ConstructorScenarioFor<User>(() => User.CreateBasicUser(id, email, metroId)).
                Then(UserEvents.Created(email, id, metroId, false)).
                Assert();
        }
Exemplo n.º 23
0
        public ActionResult FacebookLogin(string token, string returnUrl)
        {
            FacebookUserDetals userDetails = FacebookAuth.LoadUserDetails(token);

            var userId = new UserId(userDetails.Email);
            _bus.Send(new ReportUserLoggedIn(userId, userDetails.Name, userDetails.PictureUrl));
            SetUserEmailIfNeeded(userId, new EmailAddress(userDetails.Email));

            FormsAuthentication.SetAuthCookie(userDetails.Email, true);
            return SuccessfullLoginRedirect(returnUrl);
        }
Exemplo n.º 24
0
        public static void Main(string[] args)
        {
            AbstractSerializer.RegisterKnownType(typeof(UserCreatedEvent));

              // Create serializers after registering known types
              ISerializer[] Serializers =
              {
            new DataContractSerializer(),
            new ProtoBufSerializer(),
            new BsonNetSerializer(),
            new JsonNetSerializer()
              };

              foreach (Func<IAppendOnlyStore> aStoreBuilder in AppendOnlyStores)
              {
            foreach (ISerializer serializer in Serializers)
            {
              UserId id = new UserId(1);
              List<IEvent> events = new List<IEvent>() { new UserCreatedEvent(id, "John") };

              IAppendOnlyStore aStore = aStoreBuilder();
              try
              {
            EventStoreDB eStore = new EventStoreDB(aStore, serializer);
            eStore.Append(id, 0, events);

            // Warm up various caches
            for (int i = 0; i < 10; ++i)
            {
              EventStream s = eStore.Load(id);
              eStore.Append(id, s.Version, events);
            }

            int count = 0;
            DateTime t1 = DateTime.Now;
            do
            {
              id = new UserId(100 + count);
              //EventStream s = eStore.Load(id);
              eStore.Append(id, 0, new IEvent[] { new UserCreatedEvent(id, "John") });
              ++count;
            }
            while ((DateTime.Now - t1) < TimeSpan.FromMilliseconds(1000));

            Console.WriteLine("{0} + {1}: {2}", aStore, serializer, count);
              }
              finally
              {
            aStore.Dispose();
              }
            }
              }
        }
Exemplo n.º 25
0
		public static IObservable<ICollection<List>> GetLists(this TwitterAccount account, UserId? userId = null)
		{
			const string endpoint = "lists/list";
			var client = account.ToOAuthClient(endpoint);
			client.Parameters.Add("user_id", userId ?? account.UserId);

			return Observable
				.Defer(() => client.GetResponseText())
				.Select(res => ListCollection.Parse(res, account.UserId))
				.OnErrorRetry(3)
				.WriteLine(endpoint, lists => lists.Count);
		}
Exemplo n.º 26
0
        public void AddPassword(IDomainIdentityService ids, PasswordGenerator pwds,
            string display, string login, string password)
        {
            if (_state.ContainsLogin(login))
                throw DomainError.Named("duplicate-login", "Login {0} is already taken", login);

            var user = new UserId(ids.GetId());
            var salt = pwds.CreateSalt();
            var token = pwds.CreateToken();
            var hash = pwds.HashPassword(password, salt);
            Apply(new SecurityPasswordAdded(_state.Id, user, display, login, hash, salt, token));
        }
Exemplo n.º 27
0
		public static IObservable<User> GetUser(this TwitterAccount account, UserId userId)
		{
			const string endpoint = "users/show";
			var client = account.ToOAuthClient(endpoint);
			client.Parameters.Add("user_id", userId);

			return Observable
				.Defer(() => client.GetResponseText())
				.Select(res => User.Parse(res))
				.OnErrorRetry(3)
				.WriteLine(endpoint, u => u.ScreenName + " / " + u.Name);
		}
Exemplo n.º 28
0
        public ActionResult GoogleLogin(string code, string state)
        {
            string accessToken = GoogleAuth.ObtainAccessToken(code, state);
            GoogleUserDetals userDetails = GoogleAuth.LoadUserDetails(accessToken);

            var userId = new UserId(userDetails.Email);
            _bus.Send(new ReportUserLoggedIn(userId, userDetails.Name, userDetails.PictureUrl));
            SetUserEmailIfNeeded(userId, new EmailAddress(userDetails.Email));

            FormsAuthentication.SetAuthCookie(userDetails.Email, true);
            return SuccessfullLoginRedirect(null);
        }
Exemplo n.º 29
0
        public void AddPermissionToSecurityItem(UserId userId, string permission)
        {
            if (string.IsNullOrEmpty(permission))
                throw DomainError.Named("empty", "Permission can't be empty");

            if (!_state.ContainsUser(userId))
            {
                throw DomainError.Named("invalid-user", "User {0} does not exist", userId.Id);
            }

            var user = _state.GetUser(userId);
            if (!user.Permissions.Contains(permission))
                Apply(new PermissionAddedToSecurityItem(_state.Id, user.Id, user.DisplayName, permission, user.Token));
        }
        public void AddWishListItemToUser()
        {
            var id = new UserId(Guid.NewGuid());
            var email = "*****@*****.**";
            var metroId = 11;
            var wishlistItemId = new WishListItemId(Guid.NewGuid());
            var restoId = new RestaurantId(Guid.NewGuid());

            new CommandScenarioFor<User>(User.Factory)
            .Given(UserEvents.Created(email, id, metroId, false))
            .When(user => user.AddWishListItem(id, wishlistItemId, restoId, "some notes"))
            .Then(UserEvents.WishListItemAdded(id, wishlistItemId, restoId, "some notes"))
            .Assert();
        }
Exemplo n.º 31
0
 public override int GetHashCode()
 {
     return(UserId.GetHashCode() * 37 + BackgroundId.GetHashCode());
 }
        internal async Task <string> PostAsync(UserId userId, string url)
        {
            CheckAndAddUserId(userId);

            return(await MakeRequestAsync(HttpMethod.POST, InternalHttpClient, url));
        }
Exemplo n.º 33
0
 public override int GetHashCode()
 {
     return(UserId.GetHashCode() ^ GroupId.GetHashCode() ^ Tenant.GetHashCode() ^ RefType.GetHashCode());
 }
Exemplo n.º 34
0
 public void Authorize(UserId authorizedByUserId)
 {
     RaiseEvent(new BookingRequestAuthorized(authorizedByUserId));
 }
Exemplo n.º 35
0
 internal static MeetingGroupProposalDecision AcceptDecision(DateTime date, UserId userId)
 {
     return(new MeetingGroupProposalDecision(date, userId, "Accept", null));
 }
Exemplo n.º 36
0
        public int CompareTo(AddAction other)
        {
            var timestampComparison = base.CompareTo(other);

            return(timestampComparison != 0 ? timestampComparison : UserId.CompareTo(other.UserId) * -1);
        }
Exemplo n.º 37
0
 public PlayerBuilder WithUserId(UserId userId)
 {
     _userId = userId;
     return(this);
 }
Exemplo n.º 38
0
 string DebuggerDisplay() => $"{ImagesId}, {Type}, {User?.NickName ?? (UserId?.ToString())}";
        public static async Task PublishUserProfileChangedIntegrationEventAsync(this IServiceBusPublisher publisher, UserId userId, UserProfile profile)
        {
            var integrationEvent = new UserProfileChangedIntegrationEvent
            {
                UserId  = userId,
                Profile = new ProfileDto
                {
                    FirstName = profile.FirstName,
                    LastName  = profile.LastName,
                    Gender    = profile.Gender.ToEnum <EnumGender>()
                }
            };

            await publisher.PublishAsync(integrationEvent);
        }
        public static async Task PublishUserPasswordResetTokenGeneratedIntegrationEventAsync(this IServiceBusPublisher publisher, UserId userId, string code)
        {
            var integrationEvent = new UserPasswordResetTokenGeneratedIntegrationEvent
            {
                UserId = userId.ToString(),
                Code   = code
            };

            await publisher.PublishAsync(integrationEvent);
        }
        public static async Task PublishUserAddressChangedIntegrationEventAsync(this IServiceBusPublisher publisher, UserId userId, Address address)
        {
            var integrationEvent = new UserAddressChangedIntegrationEvent
            {
                UserId  = userId,
                Address = new AddressDto
                {
                    Id             = address.Id,
                    Type           = address.Type.ToEnumOrDefault <EnumAddressType>(),
                    CountryIsoCode = address.Country.ToEnum <EnumCountryIsoCode>(),
                    Line1          = address.Line1,
                    Line2          = address.Line2,
                    State          = address.State,
                    City           = address.City,
                    PostalCode     = address.PostalCode
                }
            };

            await publisher.PublishAsync(integrationEvent);
        }
Exemplo n.º 42
0
        private static void MessageHandler(RecivedMessage message)
        {
            if (message == null)
            {
                return;
            }

#if DEBUG
            Logger.Debug($"Message from {message.UserId}@{message.ChatId}");
#endif
            using (var context = new UserContext(message.UserId, message.ChatId))
            {
                User.User user = context;

                try
                {
                    user.MessageManager.RecievedMessage = message;
                    message.Action?.Invoke(message, user);

                    switch (message.Text.Split('@')[0].Split(' ')[0])
                    {
                    case "/start":
                    {
                        user.RoomManager.Go("_root", false);
                        break;
                    }

                    case "/debug":
                    {
                        var serialized = MessageManager.Escape(MessagePackSerializer.ToJson(
                                                                   new PublicUser(user)
                                                                   ));
                        user.MessageManager.SendImmediately(new SentMessage
                            {
                                Text   = $"Всё про вас:\n```\n{serialized}\n```",
                                Intent = "command-debug"
                            });
                        break;
                    }

                    case "/lag":
                    {
                        user.MessageManager.SendImmediately(new SentMessage
                            {
                                Text =
                                    @"Если бот долго отвечает, то создайте беседу и обязательно пригласите туда @AdventureTownBot.
После этого пригласите туда @PocketTownBot и @MonsterTownBot",
                                Intent = "command-lag"
                            });
                        break;
                    }

                    case "/repeat":
                    {
                        user.MessageManager.SendImmediately(user.MessageManager.LastMessages.Last());
                        break;
                    }

                    case "/token":
                    {
                        user.MessageManager.SendImmediately(new SentMessage
                            {
                                Text   = $@"Ваш токен: `{user.Token}`.
Используйте его чтобы связать другой аккаунт с этим персонажем (`/link {user.Info.UserId.Messenger} {user.Info.UserId.Id} {user.Token}`).
Чтобы сгенерировать новый токен используйте `/revoke`",
                                Intent = "command-token"
                            });
                        break;
                    }

                    case "/revoke":
                    {
                        user.Token = Guid.NewGuid();
                        user.MessageManager.SendImmediately(new SentMessage
                            {
                                Text   = $"Ваш новый токен: `{user.Token}`.",
                                Intent = "command-revoke"
                            });
                        break;
                    }

                    case "/link":
                    {
                        var splitted = message.Text.Split(' ');
                        if (splitted.Length != 4 ||
                            !int.TryParse(splitted[1], out var messenger) ||
                            !long.TryParse(splitted[2], out var id) ||
                            !Guid.TryParse(splitted[3], out var token))
                        {
                            user.MessageManager.SendImmediately(new SentMessage
                                {
                                    Text =
                                        @"Чтобы связвть этот аккаунт с другим игровым персонажем используйте `/link <messenger_id> <user_id> <token>`",
                                    Intent = "command-link-error"
                                });
                            break;
                        }

                        var uid = new UserId(messenger, id);

                        if (uid.Equals(user.Info.UserId))
                        {
                            user.MessageManager.SendImmediately(new SentMessage
                                {
                                    Text   = @"К сожалению, нельзя связаться с самим собой",
                                    Intent = "command-link-self"
                                });
                            break;
                        }

                        using (var linkTo = new UserContext(uid))
                        {
                            if (linkTo.User.Token != token)
                            {
                                user.MessageManager.SendImmediately(new SentMessage
                                    {
                                        Text   = @"Не удалось связать аккаунты. Проверьте, всё ли правильно вы ввели",
                                        Intent = "command-link-forbidden"
                                    });
                                break;
                            }
                        }

                        user.LinkedTo = new Tuple <UserId, Guid>(uid, token);
                        user.MessageManager.SendImmediately(new SentMessage
                            {
                                Text   = @"Отлично! Чтобы отвязать аккаунт используйте `/unlink`",
                                Intent = "command-link"
                            });
                        break;
                    }

                    case "/unlink":
                    {
                        context.Unlink();
                        user.MessageManager.SendImmediately(new SentMessage
                            {
                                Text   = @"Готово!",
                                Intent = "command-unlink"
                            });
                        break;
                    }

                    default:
                    {
                        user.MessageManager.OnRecieved(message);
                        break;
                    }
                    }

                    user.MessageManager.Finish();
                }
                catch (Exception e)
                {
                    YandexMetrica.ReportError($"Error for user {message.UserId}@{message.ChatId}", e);
                    Logger.Error(e, $"Error for user {message.UserId}@{message.ChatId}");
                    var error = MessageManager.Escape(e.ToString());
                    user.MessageManager.SendImmediately(new SentMessage
                    {
                        Text   = $"Вы пошатнули мироздание и произошла ошибка:\n```{error}```",
                        Intent = "error"
                    });
                }
            }
        }
 public UserCreatedDomainEvent(UserId id)
 {
     Id = id;
 }
Exemplo n.º 44
0
        public string GetUserNameByUid(UserId userId)
        {
            OsuUser userObj = GetUserList(userId).FirstOrDefault(k => k.UserId.ToString() == userId.IdOrName);

            return(userObj?.UserName);
        }
Exemplo n.º 45
0
        public override bool TakeAction()
        {
            var cacheSetUserPack   = new GameDataCacheSet <UserPack>();
            var cacheSetBackPack   = new ConfigCacheSet <BackpackConfigInfo>();
            var backpackConfigInfo = cacheSetBackPack.FindKey(1);


            var userPack = cacheSetUserPack.FindKey(UserId.ToString());
            var packType = userPack != null && userPack.PackTypeList != null?userPack.PackTypeList.Find(s => s.BackpackType.ToInt() == 1) : null;

            if (backpackConfigInfo == null)
            {
                ErrorCode = LanguageManager.GetLang().ErrorCode;
                ErrorInfo = LanguageManager.GetLang().LoadDataError;
                return(false);
            }
            if (ContextUser.GoldNum < backpackConfigInfo.RequiredGoldNum)
            {
                ErrorCode = LanguageManager.GetLang().ErrorCode;
                ErrorInfo = LanguageManager.GetLang().St_GoldNotEnough;
                return(false);
            }
            if (packType != null && packType.OpenNum >= backpackConfigInfo.MaxOpenNum)
            {
                ErrorCode = LanguageManager.GetLang().ErrorCode;
                ErrorInfo = LanguageManager.GetLang().St1110_OverExpansion;
                return(false);
            }
            if (userPack == null)
            {
                userPack              = new UserPack(UserId);
                packType              = new PackType();
                userPack.CreateDate   = DateTime.Now;
                packType.OpenNum      = 1;
                packType.BackpackType = BackpackType.HunJi;
                packType.OpenNum      = MathUtils.Addition(backpackConfigInfo.DefaultNum, backpackConfigInfo.EveryAddNum);
                userPack.PackTypeList.AddChildrenListener(packType);
                cacheSetUserPack.Add(userPack, UserId);
            }
            else
            {
                if (packType == null)
                {
                    packType              = new PackType();
                    userPack.CreateDate   = DateTime.Now;
                    packType.OpenNum      = 1;
                    packType.BackpackType = BackpackType.HunJi;
                    packType.OpenNum      = MathUtils.Addition(backpackConfigInfo.DefaultNum, backpackConfigInfo.EveryAddNum); cacheSetUserPack.Add(userPack, UserId);
                }
                else
                {
                    userPack.UpdateNotify(obj =>
                    {
                        packType.OpenNum = MathUtils.Subtraction(packType.OpenNum, 1);
                        packType.OpenNum = MathUtils.Addition(packType.OpenNum, backpackConfigInfo.EveryAddNum);
                        return(true);
                    });
                }
            }
            MathUtils.DiffDate(DateTime.Now.Date).TotalDays.ToInt();
            return(true);
        }
Exemplo n.º 46
0
 public UserNotFoundException(UserId id)
 {
     Id = id.Value;
 }
Exemplo n.º 47
0
 public override string ToString()
 {
     return(UserId.ToString() + " " + Name);
 }
Exemplo n.º 48
0
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity <Clan>(
                builder =>
            {
                builder.ToTable("Clan");

                builder.Property(clan => clan.Id).HasConversion(clanId => clanId.ToGuid(), value => ClanId.FromGuid(value)).IsRequired().ValueGeneratedNever();

                builder.Property(clan => clan.Name).IsRequired();

                builder.Property(clan => clan.Summary).IsRequired(false);

                builder.Property(clan => clan.OwnerId).HasConversion(invitationId => invitationId.ToGuid(), value => UserId.FromGuid(value)).IsRequired();

                builder.Ignore(clan => clan.Deleted);

                builder.HasMany(clan => clan.Members).WithOne().HasForeignKey(member => member.ClanId);

                builder.HasKey(clan => clan.Id);
            });

            modelBuilder.Entity <Clan>(
                builder =>
            {
                builder.ToTable("Clan");

                builder.Property(clan => clan.Id).HasConversion(clanId => clanId.ToGuid(), value => ClanId.FromGuid(value)).IsRequired().ValueGeneratedNever();

                builder.Property(clan => clan.Name).IsRequired();

                builder.Property(clan => clan.Summary).IsRequired(false);

                builder.Property(clan => clan.OwnerId).HasConversion(invitationId => invitationId.ToGuid(), value => UserId.FromGuid(value)).IsRequired();

                builder.HasMany(clan => clan.Members).WithOne().HasForeignKey(member => member.ClanId);

                builder.HasKey(clan => clan.Id);
            });

            modelBuilder.Entity <Member>(
                builder =>
            {
                builder.ToTable("Member");

                builder.Property(member => member.Id).HasConversion(memberId => memberId.ToGuid(), value => MemberId.FromGuid(value)).IsRequired().ValueGeneratedNever();

                builder.Property(member => member.UserId).HasConversion(userId => userId.ToGuid(), value => UserId.FromGuid(value)).IsRequired();
                builder.Property(member => member.ClanId).HasConversion(clanId => clanId.ToGuid(), value => ClanId.FromGuid(value)).IsRequired();

                builder.HasKey(member => member.Id);
            });

            modelBuilder.Entity <Candidature>(
                builder =>
            {
                builder.ToTable("Candidature");

                builder.Property(candidature => candidature.Id)
                .HasConversion(candidatureId => candidatureId.ToGuid(), value => CandidatureId.FromGuid(value))
                .IsRequired().ValueGeneratedNever();

                builder.Property(candidature => candidature.UserId).HasConversion(userId => userId.ToGuid(), value => UserId.FromGuid(value)).IsRequired();
                builder.Property(candidature => candidature.ClanId).HasConversion(clanId => clanId.ToGuid(), value => ClanId.FromGuid(value)).IsRequired();
                builder.HasKey(candidature => candidature.Id);
            });

            modelBuilder.Entity <Invitation>(
                builder =>
            {
                builder.ToTable("Invitation");

                builder.Property(invitation => invitation.Id)
                .HasConversion(invitationId => invitationId.ToGuid(), value => InvitationId.FromGuid(value))
                .IsRequired().ValueGeneratedNever();

                builder.Property(invitation => invitation.UserId).HasConversion(userId => userId.ToGuid(), value => UserId.FromGuid(value)).IsRequired();
                builder.Property(invitation => invitation.ClanId).HasConversion(clanId => clanId.ToGuid(), value => ClanId.FromGuid(value)).IsRequired();
                builder.HasKey(invitation => invitation.Id);
            });

            modelBuilder.Entity <Division>(
                builder =>
            {
                builder.ToTable("Division");

                builder.Property(division => division.Id)
                .HasConversion(divisionId => divisionId.ToGuid(), value => DivisionId.FromGuid(value))
                .IsRequired().ValueGeneratedNever();

                builder.Property(division => division.Name).IsRequired();

                builder.Property(division => division.Description).IsRequired(false);

                builder.Property(division => division.ClanId).HasConversion(clanId => clanId.ToGuid(), value => ClanId.FromGuid(value)).IsRequired();

                builder.Ignore(division => division.Members);

                builder.HasKey(division => division.Id);
            });
        }
Exemplo n.º 49
0
 public override int GetHashCode()
 {
     return(UserId.GetHashCode());
 }
 public ConfirmUserRegistrationCommand(UserId userId)
 {
     UserId = userId;
 }
Exemplo n.º 51
0
 public UserNotFoundException(UserId id, string message) : base(message)
 {
     Id = id.Value;
 }
Exemplo n.º 52
0
 public string GetPersonIdForCurrentUser()
 {
     UserId.IsNullOrWhiteSpaceThrowException("User not logged in.");
     return(GetPersonIdFor(UserId));
 }
Exemplo n.º 53
0
        public override bool TakeAction()
        {
            if (ContextUser.UserStatus == UserStatus.CountryCombat)
            {
                CountryCombat countryCombat = new CountryCombat(ContextUser);
                if (countryCombat.GameActive != null && countryCombat.GameActive.RefreshStatus() == CombatStatus.Combat)
                {
                    countryCombat.Exit();
                }
            }

            if (ContextUser.EnergyNum <= 0 && ContextUser.SurplusEnergy <= 0)
            {
                ErrorCode = 3;
                ErrorInfo = LanguageManager.GetLang().St_EnergyNotEnough;
                return(false);
            }
            //if (_ops != 1 && UserHelper.IsPromptBlood(ContextUser.UserID))
            //{
            //    ErrorCode = 1;
            //    ErrorInfo = LanguageManager.GetLang().St4002_PromptBlood;
            //    return false;
            //}
            //if (_ops != 1 && UserItemHelper.CheckItemOut(ContextUser, ItemStatus.BeiBao))
            //{
            //    ErrorCode = 1;
            //    ErrorInfo = LanguageManager.GetLang().St_User_BeiBaoMsg;
            //    return false;
            //}

            UserHelper.UserGeneralPromptBlood(ContextUser);//佣兵自动使用绷带补血

            plotInfo = new ConfigCacheSet <PlotInfo>().FindKey(plotID);

            if (plotInfo == null)
            {
                ErrorCode = LanguageManager.GetLang().ErrorCode;
                ErrorInfo = LanguageManager.GetLang().LoadDataError;
                return(false);
            }
            int challengeNum = PlotHelper.GetPlotChallengeNum(UserId.ToString(), plotInfo.PlotID);

            if (plotInfo.PlotType == PlotType.Elite && challengeNum >= plotInfo.ChallengeNum)
            {
                ErrorCode = 4;
                ErrorInfo = LanguageManager.GetLang().St4002_IsPlotEliteNotChallengeNum;
                return(false);
            }

            if ((challengeNum >= plotInfo.ChallengeNum && ContextUser.VipLv < 3))
            {
                ErrorCode = LanguageManager.GetLang().ErrorCode;
                ErrorInfo = LanguageManager.GetLang().St4002_NotChallengeNum;
                return(false);
            }

            int num = challengeNum;
            int challengeDefSoldNum    = ConfigEnvSet.GetInt("UserPlot.ChallengeDefSoldNum");
            int challengeDoubleSoldNum = ConfigEnvSet.GetInt("UserPlot.ChallengeDoubleSoldNum");

            if (_ops != 1 && num >= plotInfo.ChallengeNum && PlotHelper.GetPlotIsOne(UserId.ToString(), plotInfo.PlotID))
            {
                ErrorCode = 1;
                _plotNum  = challengeDefSoldNum;
                return(false);
            }
            else
            {
                if (_ops != 1 && num >= plotInfo.ChallengeNum && PlotHelper.GetPlotIsOne(UserId.ToString(), plotInfo.PlotID) == false)
                {
                    int openNum = num - plotInfo.ChallengeNum + 1;
                    _plotNum = challengeDoubleSoldNum * openNum + challengeDefSoldNum;
                }
            }

            if (_ops != 1 && num >= plotInfo.ChallengeNum)
            {
                ErrorCode = 1;
                ErrorInfo = string.Format(LanguageManager.GetLang().St4002_IsPlotNum, _plotNum);
                return(false);
            }
            if (_ops == 1 && num >= plotInfo.ChallengeNum)
            {
                if (ContextUser.GoldNum < _plotNum)
                {
                    ErrorCode = LanguageManager.GetLang().ErrorCode;
                    ErrorInfo = LanguageManager.GetLang().St_GoldNotEnough;
                    return(false);
                }
                ContextUser.UseGold = MathUtils.Subtraction(ContextUser.UseGold, _plotNum);
            }
            if (_ops == 1 && num >= plotInfo.ChallengeNum && PlotHelper.GetPlotIsOne(UserId.ToString(), plotInfo.PlotID) == false)
            {
                int openNum = num - plotInfo.ChallengeNum + 1;
                _plotNum = challengeDoubleSoldNum * openNum + challengeDefSoldNum;;
                if (ContextUser.GoldNum < _plotNum)
                {
                    ErrorCode = 2;
                    ErrorInfo = LanguageManager.GetLang().St_GoldNotEnough;
                    return(false);
                }
                ContextUser.UseGold = MathUtils.Addition(ContextUser.UseGold, _plotNum);
            }
            if (_ops != 1 && !string.IsNullOrEmpty(plotInfo.EnchantID) && plotInfo.EnchantProbability > 0 && EnchantHelper.IsEnchantPackage(ContextUser.UserID))
            {
                ErrorCode = 1;
                ErrorInfo = LanguageManager.GetLang().St4002_EnchantPackageFull;
                return(false);
            }
            //var cacheSetUserPlot = new GameDataCacheSet<UserPlotPackage>();
            //var userPlotPack = cacheSetUserPlot.FindKey(ContextUser.UserID);
            //var userPlot = userPlotPack != null ? userPlotPack.PlotPackage.Find(s => s.PlotID == npcInfo.PlotID) : null;
            var userPlot = UserPlotHelper.GetUserPlotInfo(ContextUser.UserID, plotID);

            if (userPlot != null && userPlot.PlotNum >= plotInfo.ChallengeNum)
            {
                if (plotInfo.PlotType == PlotType.Elite)
                {
                    ErrorCode = LanguageManager.GetLang().ErrorCode;
                    ErrorInfo = LanguageManager.GetLang().St4002_EliteUsed;
                    return(false);
                }
                else if (plotInfo.PlotType == PlotType.HeroPlot)
                {
                    ErrorCode = LanguageManager.GetLang().ErrorCode;
                    ErrorInfo = LanguageManager.GetLang().St4002_HeroPlotNum;
                    return(false);
                }
            }
            npcList = new ConfigCacheSet <PlotNPCInfo>().FindAll(m => m.PlotID == plotID);
            //if (ContextUser.EnergyNum < (npcList.Count * PlotInfo.BattleEnergyNum))
            //{
            //    ErrorCode = 3;
            //    ErrorInfo = LanguageManager.GetLang().St_EnergyNotEnough;
            //    return false;
            //}
            ContextUser.InPlotDate = DateTime.Now;
            //if (ContextUser.UserExtend == null || ContextUser.UserExtend.PlotStatusID == 0 || ContextUser.UserExtend.MercenarySeq == 0)
            //{
            //    ContextUser.TempEnergyNum = PlotInfo.BattleEnergyNum;
            //    //ContextUser.RemoveEnergyNum(PlotInfo.BattleEnergyNum);
            //}
            //ContextUser.Update();
            if (ContextUser.UserExtend != null && ContextUser.UserExtend.PlotStatusID <= 0)
            {
                ContextUser.UserExtend.UpdateNotify(obj =>
                {
                    ContextUser.UserExtend.PlotStatusID = plotID;
                    ContextUser.UserExtend.PlotNpcID    = -1;
                    ContextUser.UserExtend.MercenarySeq = 1;
                    ContextUser.UserExtend.IsBoss       = false;
                    return(true);
                });
            }

            _isOverCombat             = userPlot != null && userPlot.PlotStatus == PlotStatus.Completed;
            ContextUser.TempEnergyNum = PlotInfo.BattleEnergyNum;
            return(true);
        }
Exemplo n.º 54
0
 internal static MeetingGroupProposalDecision RejectDecision(DateTime date, UserId userId, string rejectReason)
 {
     return(new MeetingGroupProposalDecision(date, userId, "Reject", rejectReason));
 }
Exemplo n.º 55
0
 public void Publish(UserId userId) =>
 Apply(new Events.ClassifiedAdPublished
 {
     Id = Id, ApprovedBy = userId
 }
       );
 public virtual async Task GetAsync(UserId userId)
 {
     await GetAsync(userId, GoogleEndpointAddresses.Collect);
 }
Exemplo n.º 57
0
 public void Create(BookingRequestId id, UserId userId, ResourceId resourceId, BookingInterval interval)
 {
     RaiseEvent(new BookingRequestCreated(id, userId, resourceId, interval));
 }
Exemplo n.º 58
0
 public override int GetHashCode() =>
 UserId.GetHashCode();
Exemplo n.º 59
0
        public static Result MountSaveDataReadOnly(this FileSystemClient fs, U8Span mountName, TitleId titleId, UserId userId)
        {
            Result rc;

            if (fs.IsEnabledAccessLog(LocalAccessLogMode.Application))
            {
                TimeSpan startTime = fs.Time.GetCurrent();
                rc = MountSaveDataImpl(fs, mountName, SaveDataSpaceId.User, titleId, userId, SaveDataType.SaveData, true, 0);
                TimeSpan endTime = fs.Time.GetCurrent();

                fs.OutputAccessLog(rc, startTime, endTime, $", name: \"{mountName.ToString()}\", applicationid: 0x{titleId}, userid: 0x{userId}");
            }
            else
            {
                rc = MountSaveDataImpl(fs, mountName, SaveDataSpaceId.User, titleId, userId, SaveDataType.SaveData, false, 0);
            }

            if (rc.IsSuccess() && fs.IsEnabledAccessLog(LocalAccessLogMode.Application))
            {
                fs.EnableFileSystemAccessorAccessLog(mountName);
            }

            return(rc);
        }
Exemplo n.º 60
0
 public MinerStudioSessionSet(IWsSessionsAdapter wsSessions) : base(wsSessions)
 {
     VirtualRoot.BuildEventPath <UserPasswordChangedMqEvent>("群控用户密码变更后通知群控客户端重新登录", LogEnum.None, path: message => {
         SendToMinerStudioAsync(message.LoginName, new WsMessage(message.MessageId, WsMessage.ReLogin));
     }, this.GetType());
     VirtualRoot.BuildEventPath <ConsoleOutLinesMqEvent>("收到ConsoleOutLinesMq消息后检查对应的用户是否登录着本节点,如果是则处理,否则忽略", LogEnum.None, path: message => {
         #region
         if (IsTooOld(message.Timestamp))
         {
             return;
         }
         if (ServerRoot.IsMinerClientTestId(message.ClientId))
         {
             Logger.Debug($"{nameof(NTMinerAppType.MinerClient)} {message.ClientId.ToString()} {nameof(ConsoleOutLinesMqEvent)}");
         }
         SendToMinerStudioAsync(message.LoginName, new WsMessage(message.MessageId, WsMessage.ConsoleOutLines)
         {
             Data = new WrapperClientIdData {
                 ClientId = message.ClientId,
                 Data     = message.Data
             }
         });
         #endregion
     }, this.GetType());
     VirtualRoot.BuildEventPath <LocalMessagesMqEvent>("收到LocalMessagesMq消息后检查对应的用户是否登录着本节点,如果是则处理,否则忽略", LogEnum.None, path: message => {
         #region
         if (IsTooOld(message.Timestamp))
         {
             return;
         }
         if (ServerRoot.IsMinerClientTestId(message.ClientId))
         {
             Logger.Debug($"{nameof(NTMinerAppType.MinerClient)} {message.ClientId.ToString()} {nameof(LocalMessagesMqEvent)}");
         }
         SendToMinerStudioAsync(message.LoginName, new WsMessage(message.MessageId, WsMessage.LocalMessages)
         {
             Data = new WrapperClientIdData {
                 ClientId = message.ClientId,
                 Data     = message.Data
             }
         });
         #endregion
     }, this.GetType());
     VirtualRoot.BuildEventPath <DrivesMqEvent>("收到DrivesMq消息后检查对应的用户是否登录着本节点,如果是则处理,否则忽略", LogEnum.None, path: message => {
         #region
         if (IsTooOld(message.Timestamp))
         {
             return;
         }
         if (ServerRoot.IsMinerClientTestId(message.ClientId))
         {
             Logger.Debug($"{nameof(NTMinerAppType.MinerClient)} {message.ClientId.ToString()} {nameof(DrivesMqEvent)}");
         }
         SendToMinerStudioAsync(message.LoginName, new WsMessage(message.MessageId, WsMessage.Drives)
         {
             Data = new WrapperClientIdData {
                 ClientId = message.ClientId,
                 Data     = message.Data
             }
         });
         #endregion
     }, this.GetType());
     VirtualRoot.BuildEventPath <LocalIpsMqEvent>("收到LocalIpsMq消息后检查对应的用户是否登录着本节点,如果是则处理,否则忽略", LogEnum.None, path: message => {
         #region
         if (IsTooOld(message.Timestamp))
         {
             return;
         }
         if (ServerRoot.IsMinerClientTestId(message.ClientId))
         {
             Logger.Debug($"{nameof(NTMinerAppType.MinerClient)} {message.ClientId.ToString()} {nameof(LocalIpsMqEvent)}");
         }
         SendToMinerStudioAsync(message.LoginName, new WsMessage(message.MessageId, WsMessage.LocalIps)
         {
             Data = new WrapperClientIdData {
                 ClientId = message.ClientId,
                 Data     = message.Data
             }
         });
         #endregion
     }, this.GetType());
     VirtualRoot.BuildEventPath <OperationResultsMqEvent>("收到OperationResultsMq消息后检查对应的用户是否登录着本节点,如果是则处理,否则忽略", LogEnum.None, path: message => {
         #region
         if (IsTooOld(message.Timestamp))
         {
             return;
         }
         if (ServerRoot.IsMinerClientTestId(message.ClientId))
         {
             Logger.Debug($"{nameof(NTMinerAppType.MinerClient)} {message.ClientId.ToString()} {nameof(OperationResultsMqEvent)}");
         }
         SendToMinerStudioAsync(message.LoginName, new WsMessage(message.MessageId, WsMessage.OperationResults)
         {
             Data = new WrapperClientIdData {
                 ClientId = message.ClientId,
                 Data     = message.Data
             }
         });
         #endregion
     }, this.GetType());
     VirtualRoot.BuildEventPath <OperationReceivedMqEvent>("收到OperationReceivedMq消息后检查对应的用户是否登录着本节点,如果是则处理,否则忽略", LogEnum.None, path: message => {
         #region
         if (IsTooOld(message.Timestamp))
         {
             return;
         }
         if (ServerRoot.IsMinerClientTestId(message.ClientId))
         {
             Logger.Debug($"{nameof(NTMinerAppType.MinerClient)} {message.ClientId.ToString()} {nameof(OperationReceivedMqEvent)}");
         }
         SendToMinerStudioAsync(message.LoginName, new WsMessage(message.MessageId, WsMessage.OperationReceived)
         {
             Data = new WrapperClientId {
                 ClientId = message.ClientId
             }
         });
         #endregion
     }, this.GetType());
     VirtualRoot.BuildEventPath <LocalJsonMqEvent>("收到LocalJsonMq消息后检查对应的用户是否登录着本节点,如果是则处理,否则忽略", LogEnum.None, path: message => {
         #region
         if (IsTooOld(message.Timestamp))
         {
             return;
         }
         if (ServerRoot.IsMinerClientTestId(message.ClientId))
         {
             Logger.Debug($"{nameof(NTMinerAppType.MinerClient)} {message.ClientId.ToString()} {nameof(LocalJsonMqEvent)}");
         }
         SendToMinerStudioAsync(message.LoginName, new WsMessage(message.MessageId, WsMessage.SelfWorkLocalJson)
         {
             Data = new WrapperClientIdData {
                 ClientId = message.ClientId,
                 Data     = message.Data
             }
         });
         #endregion
     }, this.GetType());
     VirtualRoot.BuildEventPath <GpuProfilesJsonMqEvent>("收到GpuProfilesJsonMq消息后检查对应的用户是否登录着本节点,如果是则处理,否则忽略", LogEnum.None, path: message => {
         #region
         if (IsTooOld(message.Timestamp))
         {
             return;
         }
         if (ServerRoot.IsMinerClientTestId(message.ClientId))
         {
             Logger.Debug($"{nameof(NTMinerAppType.MinerClient)} {message.ClientId.ToString()} {nameof(GpuProfilesJsonMqEvent)}");
         }
         SendToMinerStudioAsync(message.LoginName, new WsMessage(message.MessageId, WsMessage.GpuProfilesJson)
         {
             Data = new WrapperClientIdData {
                 ClientId = message.ClientId,
                 Data     = message.Data
             }
         });
         #endregion
     }, this.GetType());
     VirtualRoot.BuildEventPath <QueryClientsForWsResponseMqEvent>("收到QueryClientsResponseMq消息后通过Ws通道发送给群控客户端", LogEnum.None, path: message => {
         #region
         if (IsTooOld(message.Timestamp))
         {
             return;
         }
         if (ServerRoot.IsMinerClientTestId(message.StudioId))
         {
             Logger.Debug($"{nameof(NTMinerAppType.MinerClient)} {message.StudioId.ToString()} {nameof(QueryClientsForWsResponseMqEvent)}");
         }
         var userData = AppRoot.UserSet.GetUser(UserId.CreateLoginNameUserId(message.LoginName));
         if (userData != null && wsSessions.TryGetSession(message.SessionId, out IWsSessionAdapter session))
         {
             session.SendAsync(new WsMessage(Guid.NewGuid(), WsMessage.ClientDatas)
             {
                 Data = message.Response
             }.SignToBytes(userData.Password));
         }
         #endregion
     }, this.GetType());
 }