Пример #1
0
 internal MemberLeftEventArgs(
     CachedGuild guild,
     CachedUser user) : base(guild.Client)
 {
     Guild = guild;
     User  = user;
 }
Пример #2
0
        public Task PresenceAsync(
            [Description("User to check presence.")] CachedUser user = null)
        {
            user ??= Context.User;

            var embed = EmbedHelper.New(Context, $"Displays {user.Mention}'s presences. (`{user.Presence?.Status.ToString() ?? "Offline"}`)");

            if (user.Presence?.Activities is null)
            {
                embed.AddField("Presence", "No presence for that user.");
                return(RespondAsync(embed.Build()));
            }

            foreach (var presence in user.Presence?.Activities)
            {
                switch (presence)
                {
                case RichActivity ra:
                    var content = $"`{presence.Name}`";

                    if (ra.State != null && ra.Details != null)
                    {
                        content = $"`{presence.Name}`, `{ra.State}`: `{ra.Details}`";
                    }
                    else if (ra.Details != null)
                    {
                        content = $"`{presence.Name}`: `{ra.Details}`";
                    }

                    embed.AddField($"{presence.Type}", content);
                    break;

                case CustomActivity ca:
                    embed.AddField("Custom Status", $"{ca.Emoji.MessageFormat} | {(string.IsNullOrWhiteSpace(ca.Text) ? "No custom message." : $"`{ca.Text}`")}");
                    break;
Пример #3
0
        public User GetCurrentAuthenticatedUser()
        {
            var userId = Thread.CurrentPrincipal.Identity.Name;

            if (String.IsNullOrWhiteSpace(userId))
            {
                return null;
            }

            var cached = (CachedUser)this.Session[SessionKey];
            if (cached == null || !userId.ToLower().Equals(cached.UserId))
            {
                var user = this.FindBy(Meta.UserName, userId);

                if (user == null)
                {
                    return null;
                }

                cached = new CachedUser(user);
                this.Session[SessionKey] = cached;
            }

            return cached.GetUser(this.Session);
        }
Пример #4
0
        public async Task <bool> CheckColorAsync(CachedUser user, Color color, int?tier = null)
        {
            if (Credentials.PatreonConfig is null)
            {
                return(true);
            }

            if (user.Id == Credentials.MasterId)
            {
                return(true);
            }

            if (_colors.Any(x => x == color))
            {
                return(true);
            }

            if (tier.HasValue)
            {
                return(tier.Value >= PatreonService.ProfileColorTier);
            }

            using var scope = RiasBot.CreateScope();
            var db = scope.ServiceProvider.GetRequiredService <RiasDbContext>();

            tier = (await db.Patreon.FirstOrDefaultAsync(x => x.UserId == user.Id))?.Tier ?? 0;
            return(tier >= PatreonService.ProfileColorTier);
        }
Пример #5
0
        public async Task <Stream> GenerateProfileBackgroundAsync(CachedUser user, Stream backgroundStream)
        {
            using var image = new MagickImage(_dark, 500, 500);

            using var tempBackgroundImage = new MagickImage(backgroundStream);
            tempBackgroundImage.Resize(new MagickGeometry
            {
                Width             = 500,
                Height            = 250,
                IgnoreAspectRatio = false,
                FillArea          = true
            });

            using var backgroundImageLayer = new MagickImage(MagickColors.Black, 500, 250);
            backgroundImageLayer.Draw(new DrawableComposite(0, 0, CompositeOperator.Over, tempBackgroundImage));

            image.Draw(new DrawableComposite(0, 0, backgroundImageLayer));
            image.Draw(new Drawables().Rectangle(0, 0, 500, 250).FillColor(MagickColor.FromRgba(0, 0, 0, 128)));

            await AddAvatarAndUsernameAsync(image, user);

            var imageStream = new MemoryStream();

            image.Write(imageStream, MagickFormat.Png);
            imageStream.Position = 0;
            return(imageStream);
        }
Пример #6
0
        public User GetCurrentAuthenticatedUser()
        {
            var userId = Thread.CurrentPrincipal.Identity.Name;

            if (string.IsNullOrWhiteSpace(userId))
            {
                return(null);
            }

            var cached = (CachedUser)this.Session[SessionKey];

            if (cached == null || !userId.ToLower().Equals(cached.UserId))
            {
                var user = this.FindBy(this.Meta.UserName, userId);

                if (user == null)
                {
                    return(null);
                }

                cached = new CachedUser(user);
                this.Session[SessionKey] = cached;
            }

            return(cached.GetUser(this.Session));
        }
Пример #7
0
        private CachedUser AllocateUser(UserId userId, bool safe = true)
        {
            if (!safe)
            {
                return(new CachedUser());
            }

            const int cacheSize = 500;
            const int maxTries  = 3;

            for (var cnt = 0; cnt < maxTries; cnt++)
            {
                if (_cache.Count < cacheSize)
                {
                    // There is a place for new user
                    _cache[userId] = new CachedUser();
                    return(_cache[userId]);
                }

                // Cache is full, so remove one user and try again
                var oldest = _cache.Aggregate((l, r) => l.Value.LastLoaded > r.Value.LastLoaded ? l : r);
                Flush(oldest.Value);
            }

            // Something wrong and cache is always full, so return uncached user
            Logger.Warn("Cache is always full. Maybe bot overloaded?");
            return(new CachedUser());
        }
Пример #8
0
        private string ValidateNewUser(CachedUser user)
        {
            if (user == null || !Permissions.CanAddUser(user.RoleId))
            {
                return("Insufficient Permissions.");
            }

            if (string.IsNullOrWhiteSpace(UserEmailInput.Text))
            {
                return("Email cannot be empty.");
            }

            if (string.IsNullOrWhiteSpace(UserPasswordInput.Text))
            {
                return("Password cannot be empty.");
            }

            if (!UserPasswordInput.Text.Equals(UserConfirmInput.Text))
            {
                return("Passwords do not match.");
            }

            if (_userDal.GetByEmail(UserEmailInput.Text) != null)
            {
                return("User already exists.");
            }

            return(string.Empty);
        }
Пример #9
0
        /// <summary>
        /// See interface docs.
        /// </summary>
        public void Refresh()
        {
            var users  = new Dictionary <string, CachedUser>();
            var config = _SharedConfiguration.Get();

            foreach (var user in _UserManager.GetUsers().Where(r => r.Enabled))
            {
                var isAdministrator  = config.WebServerSettings.AdministratorUserIds.Contains(user.UniqueId);
                var isWebContentUser = isAdministrator || config.WebServerSettings.BasicAuthenticationUserIds.Contains(user.UniqueId);

                if (LoadAllUsers || isWebContentUser)
                {
                    var key = NormaliseLoginName(user.LoginName);
                    if (!users.ContainsKey(key))
                    {
                        var cachedUser = new CachedUser(user, isWebContentUser, isAdministrator);
                        if (TagAction != null)
                        {
                            TagAction(cachedUser);
                        }

                        users.Add(key, cachedUser);
                    }
                }
            }

            lock (_SyncLock) {
                _Cache = users;
            }
        }
        private CachedUser AddUserToCache(string loginName = "default", string password = "******", bool isWebContentUser = true, bool isAdministrator = false)
        {
            if (isAdministrator)
            {
                isWebContentUser = true;
            }

            var mockUser = TestUtilities.CreateMockInstance <IUser>();

            mockUser.SetupGet(r => r.LoginName).Returns(loginName);

            var cachedUser = new CachedUser(mockUser.Object, isWebContentUser, isAdministrator);

            _UserCache.Object.TagAction(cachedUser);

            _UserCache.Setup(r => r.GetUser(loginName)).Returns(cachedUser);
            if (isWebContentUser)
            {
                _UserCache.Setup(r => r.GetWebContentUser(loginName)).Returns(cachedUser);
            }
            if (isAdministrator)
            {
                _UserCache.Setup(r => r.GetAdministrator(loginName)).Returns(cachedUser);
            }

            _UserManager.Setup(r => r.PasswordMatches(mockUser.Object, It.IsAny <string>())).Returns((IUser u, string p) => p == password);

            return(cachedUser);
        }
Пример #11
0
        public async Task CleanAsync(
            [Description("Amount of messages to remove")] int count,
            [Description("User affected by the filter.")] CachedUser user)
        {
            var messages = await Context.Channel.GetMessagesAsync(count);

            await PurgeAsync(messages, count, x => x.Author.Id == user.Id);
        }
Пример #12
0
 public static IQueryable <File_Number> GetFileNumber(CachedUser user, EntityContext e)
 {
     return(e.File_Numbers.Where(p =>
                                 p.Project_Numbers.All_Investigators
                                 .Select(q => q.Investigator)
                                 .Contains(user.InvestigatorName)
                                 ));
 }
Пример #13
0
 public RiasCommandContext(CachedUserMessage message, IServiceProvider serviceProvider, string prefix) : base(serviceProvider)
 {
     Guild   = (message.Channel as CachedTextChannel)?.Guild;
     Channel = message.Channel;
     User    = message.Author;
     Message = message;
     Prefix  = prefix;
 }
 /// <summary>
 /// stores new user inot Session
 /// </summary>
 /// <param name="u">CachedUser</param>
 public static void SetSessionUser(CachedUser u)
 {
     if (u == null)
     {
         return;
     }
     HttpContext.Current.Session["userID"]     = u.Username;
     HttpContext.Current.Session["CachedUser"] = u;
 }
Пример #15
0
 public static IQueryable <Family> GetFamilies(CachedUser user, EntityContext e)
 {
     return(e.Families.Where(p =>
                             p.Family_Listings.Where(q =>
                                                     q.File_Numbers.Project_Numbers.All_Investigators
                                                     .Select(y => y.Investigator).Contains(user.InvestigatorName)
                                                     ).Count() > 0
                             ));
 }
Пример #16
0
        public ActionResult ResetPassword(ResetPasswordModel model)
        {
            // clears the errors from the model
            model.ClearToaster();
            // check for simple warnings
            var isValid = true;

            // makes sure we don't have any empty fields
            if (String.IsNullOrEmpty(model.Email))
            {
                model.AddError(GlobalErrors.EmptyFields);
                isValid = false;
            }
            if (!CredentialsHelper.IsEmailValid(model.Email)) // check email is valid
            {
                model.AddError(ResetPasswordErrors.InvalidEmail);
                isValid = false;
            }

            if (isValid)                            // check for more serious warnings
            {
                using (var e = new EntityContext()) // db context
                {
                    // check if email exists in the database, we need the email to register
                    if (!Authorize.EmailExists(model.Email, e))
                    {
                        model.AddError(ResetPasswordErrors.EmailNotAssociatedWithUser);
                        isValid = false;
                    }
                    else if (!Authorize.EmailIsRegistered(model.Email, e)) // if it does check if it is already registered
                    {
                        model.AddError(ResetPasswordErrors.EmailNotRegistered);
                        isValid = false;
                    }

                    if (isValid && !model.HasWarnings()) // we have checked everything we need to check
                    {
                        CachedUser cachedUser = GetCachedUser.UserByEmail(model.Email, e);
                        if (cachedUser == null)
                        {
                            model.AddError(RegistrationErrors.UnknowError);
                        }
                        else
                        {
                            return(RedirectToAction("Send", "ResetPassword", new
                            {
                                email = cachedUser.Email,
                                username = cachedUser.Username,
                                investigatorName = cachedUser.InvestigatorName
                            }));
                        }
                    }
                }
            }
            // if we got here there was an error
            return(View(model));
        }
Пример #17
0
        /// <summary>
        ///     Flushes and removes user from cache
        /// </summary>
        private void Flush(CachedUser user)
        {
            if (user.Lock.CurrentCount == 0)
            {
                return;
            }

            Flush(new[] { user });
            _cache.TryRemove(user.User.Info.UserId, out _);
        }
Пример #18
0
        public static bool IsMicrosoftUser(this PolicyAnalysisContext context, CachedUser user)
        {
            if (context.UserLinks.LinkByGitHubLogin.ContainsKey(user.Login))
            {
                return(true);
            }

            var microsoftBotsTeam = user.Org.GetMicrosoftBotsTeam();

            return(microsoftBotsTeam != null && microsoftBotsTeam.Members.Contains(user));
        }
 /// <summary>
 /// Pulling data from database for FilesFormModel
 /// </summary>
 /// <param UserClass="user"></param>
 /// <param DatabaseContext="context"></param>
 /// <returns>Two list of related information</returns>
 public static FilesData GetFilesForm(CachedUser user, EntityContext context)
 {
     if (user == null)
     {
         return(new FilesData());
     }
     return(new FilesData()
     {
         FileNumbers = ByUser.GetFileNumber(user, context).ToList()
     });
 }
Пример #20
0
 private AdminCommandContext(LocalizedLanguage language, IServiceProvider provider, CachedUser user,
                             CachedGuild guild, CachedUserMessage message, ICachedMessageChannel channel)
     : base(provider)
 {
     User     = user;
     Guild    = guild;
     Message  = message;
     Channel  = channel;
     Database = new AdminDatabaseContext(provider);
     Language = language;
 }
Пример #21
0
        public static bool IsClaimingToBeWorkingForMicrosoft(this CachedUser user)
        {
            var companyContainsMicrosoft = user.Company != null &&
                                           user.Company.IndexOf("Microsoft", StringComparison.OrdinalIgnoreCase) >= 0;

            var emailContainsMicrosoft = user.Email != null &&
                                         user.Email.IndexOf("Microsoft", StringComparison.OrdinalIgnoreCase) >= 0;

            return(companyContainsMicrosoft ||
                   emailContainsMicrosoft);
        }
        //private IEnumerable<Claim> GetClaimsForUserPermissions(CachedUser user)
        //{
        //    //The following ResourceTypes are added via GetClaimsForResourceTypeAndActions
        //    var resourceTypesToExclude = new List<PermissionResourceType>()
        //    {
        //        PermissionResourceType.Organization,
        //        PermissionResourceType.Customer,
        //        PermissionResourceType.Division,
        //        PermissionResourceType.PostingAccount
        //    }; //TODO Get all applicable  Resources

        //    var permissionsList = user.Permissions;
        //    return permissionsList.Select(p => new Claim(DynamicClaimTypes.Permissions, p.Resource + p.Action));
        //}

        private IEnumerable <Claim> GetClaimsForRessourceTypeAndActions(CachedUser user, PermissionResourceType resourceType, ResourceAction[] actions, string claimType)
        {
            var ids = user.Permissions
                      .Where(p => p.Resource == resourceType && actions.Contains(p.Action))
                      .Select(p => p.ReferenceId.ToString())
                      .ToArray();

            return(ids
                   .Select(id => new Claim(claimType, id))
                   .ToList());
        }
Пример #23
0
 public async Task King(CachedUser user)
 {
     if (Data.ImposterKings.Any(x => x.id == user.Id))
     {
         await ReplyAsync($"{user} is already a potential King", null, LocalMentions.None);
     }
     else
     {
         Data.ImposterKings.Add((user.Id, 0));
         await ReplyAsync($"{user} is now a potential King", null, LocalMentions.None);
     }
 }
        public DiscordCommandResult GetUserInfo([Remainder] CachedUser user = null)
        {
            user ??= Context.User;

            return(Success(embed: new LocalEmbedBuilder()
                           .WithColor(Color.Green)
                           .WithThumbnailUrl(user.GetAvatarUrl())
                           .WithTitle($"Information for user {user}")
                           .AddField("ID", user.Id)
                           .AddField("Joined Discord", user.CreatedAt.ToString("g"))
                           .Build()));
        }
 /// <summary>
 /// Pulling data from database for InventionsFormModel
 /// </summary>
 /// <param UserClass="user"></param>
 /// <param DatabaseContext="context"></param>
 /// <returns>Two list of related information</returns>
 public static InventionsData GetInventionsForm(CachedUser user, EntityContext context)
 {
     if (user == null)
     {
         return(new InventionsData());
     }
     return(new InventionsData()
     {
         ProjectNumber = context.Project_Numbers.Where(p =>
                                                       p.All_Investigators.Select(q => q.Investigator).Contains(user.InvestigatorName)
                                                       ).ToList()
     });
 }
        private string ValidateNewDepartment(CachedUser user)
        {
            if (user == null || !Permissions.CanAddDepartment(user.RoleId))
                return "Insufficient Permissions.";

            if (string.IsNullOrWhiteSpace(DepartmentNameInput.Text))
                return "Department name cannot be empty.";

            if (_departmentDal.GetByName(DepartmentNameInput.Text, user.CompanyId) != null)
                return "Department with the same name already exists.";

            return string.Empty;
        }
        /// <summary>
        /// Pulling data from database for FamiliesFormModel
        /// </summary>
        /// <param UserClass="user"></param>
        /// <param DatabaseContext="context"></param>
        /// <returns>family with FileNumbers related to that family</returns>
        public static List <FamiliesDataItem> GetFamiliesForm(CachedUser user, EntityContext context)
        {
            if (user == null)
            {
                return(new List <FamiliesDataItem>());
            }
            var families = ByUser.GetFamilies(user, context);

            return(families.Select(p => new FamiliesDataItem
            {
                Family = p,
                FileNumbers = p.Family_Listings.Select(q => q.File_Numbers).ToList()
            }).ToList());
        }
Пример #28
0
        public void OverlayTest(CachedUser user, MemoryStream output)
        {
            // var player = ContrackerService.GetPlayer(discordId: user.Id.ToString());
            using var profilePictureStream = GetProfilePicture(user);
            profilePictureStream.Position  = 0;

            using var profilePicture = Image.Load(profilePictureStream);
            using var background     = Image.Load("Resources/Images/contracker.jpg");
            profilePicture.Mutate(x => x.Resize(new Size(100, 100)));
            background.Mutate(x => x
                              .Resize(new Size(450, 300))
                              .DrawImage(profilePicture, new Point(30, 30), 1f));

            background.SaveAsJpeg(output);
        }
Пример #29
0
        public void AddCachedTweets(IEnumerable <ITweetModel> tweets)
        {
            lock (locker)
            {
                foreach (var tweet in tweets)
                {
                    #region cache tweets
                    var entity = context.CachedTweets.FirstOrDefault(t => t.Id == tweet.Id);
                    if (entity == null)
                    {
                        entity = new CachedTweet {
                            Id = tweet.Id
                        };
                        context.CachedTweets.InsertOnSubmit(entity);
                    }
                    entity.Data = SerializeObject(tweet);
                    #endregion

                    #region cache users
                    var user = context.CachedUsers.FirstOrDefault(u => u.Id == tweet.User.ScreenName);
                    if (user == null)
                    {
                        user = new CachedUser {
                            Id = tweet.User.ScreenName
                        };
                        context.CachedUsers.InsertOnSubmit(user);
                    }
                    user.Data = SerializeObject(tweet.User);

                    #region retweet users
                    if (tweet.RetweetedStatus != null && tweet.RetweetedStatus.User != null)
                    {
                        var origin = context.CachedUsers.FirstOrDefault(u => u.Id == tweet.RetweetedStatus.User.ScreenName);
                        if (origin == null)
                        {
                            origin = new CachedUser {
                                Id = tweet.RetweetedStatus.User.ScreenName
                            };
                            context.CachedUsers.InsertOnSubmit(origin);
                        }
                        origin.Data = SerializeObject(tweet.RetweetedStatus.User);
                    }
                    #endregion
                    #endregion
                }
                context.SubmitChanges();
            }
        }
Пример #30
0
 public void AddOrUpdateCachedUser(IUserModel user)
 {
     lock (locker)
     {
         var entity = context.CachedUsers.FirstOrDefault(u => u.Id == user.ScreenName);
         if (entity == null)
         {
             entity = new CachedUser {
                 Id = user.ScreenName
             };
             context.CachedUsers.InsertOnSubmit(entity);
         }
         entity.Data = SerializeObject(user);
         context.SubmitChanges();
     }
 }
        /// <summary>
        /// Pulling data from database for RecentActivitiesModel
        /// </summary>
        /// <param UserClass="user"></param>
        /// <param DatabaseContext="context"></param>
        /// <returns>Three list of related information</returns>
        public static List <RecentActivitesDataItem> GetRecentActivites(CachedUser user, EntityContext context)
        {
            if (user == null)
            {
                return(new List <RecentActivitesDataItem>());
            }
            // finds it project number has a investigator that is the same as the CachedUser
            var fileNumbers = ByUser.GetFileNumber(user, context);

            return(fileNumbers.Select(p =>
                                      new RecentActivitesDataItem()
            {
                FileNumber = p,
                Transactions = p.Transactions.ToList()
            }
                                      ).ToList());
        }
        private async Task OnAuthorizationCodeReceivedAsync(AuthorizationCodeReceivedNotification notification)
        {
            var idClient = ConfidentialClientApplicationBuilder.Create(appId)
                           .WithRedirectUri(redirectUri)
                           .WithClientSecret(appSecret)
                           .Build();

            var signedInUserId = notification.AuthenticationTicket.Identity.FindFirst(ClaimTypes.NameIdentifier).Value;
            var tokenStore     = new SessionTokenStore(signedInUserId, HttpContext.Current);

            tokenStore.Initialize(idClient.UserTokenCache);

            try
            {
                string[] scopes = graphScopes.Split(' ');

                var result = await idClient.AcquireTokenByAuthorizationCode(
                    scopes, notification.Code).ExecuteAsync();

                var userDetails = await GraphHelper.GetUserDetailsAsync(result.AccessToken);

                var cachedUser = new CachedUser()
                {
                    DisplayName = userDetails.DisplayName,
                    Email       = string.IsNullOrEmpty(userDetails.Mail) ?
                                  userDetails.UserPrincipalName : userDetails.Mail,
                    Avatar = string.Empty
                };

                tokenStore.SaveUserDetails(cachedUser);
            }
            catch (MsalException ex)
            {
                string message = "AcquireTokenByAuthorizationCodeAsync threw an exception";
                notification.HandleResponse();
                notification.Response.Redirect($"/Home/Error?message={message}&debug={ex.Message}");
            }
            catch (Microsoft.Graph.ServiceException ex)
            {
                string message = "GetUserDetailsAsync threw an exception";
                notification.HandleResponse();
                notification.Response.Redirect($"/Home/Error?message={message}&debug={ex.Message}");
            }
        }
Пример #33
0
        private string ValidateNewUser(CachedUser user)
        {
            if (user == null || !Permissions.CanAddUser(user.RoleId))
                return "Insufficient Permissions.";

            if (string.IsNullOrWhiteSpace(UserEmailInput.Text))
                return "Email cannot be empty.";

            if (string.IsNullOrWhiteSpace(UserPasswordInput.Text))
                return "Password cannot be empty.";

            if (!UserPasswordInput.Text.Equals(UserConfirmInput.Text))
                return "Passwords do not match.";

            if (_userDal.GetByEmail(UserEmailInput.Text) != null)
                return "User already exists.";

            return string.Empty;
        }
Пример #34
0
        private CachedUser GetImpl(string id)
        {
            var user = _cache.GetValue<CachedUser>(id);

            if (user != null)
                return user;

            var dbUser = _userDal.Get(id);
            user = new CachedUser
            {
                RoleId = dbUser?.AspNetRoles?.FirstOrDefault()?.Id,
                CompanyId = dbUser?.Companies?.FirstOrDefault()?.CompanyId ?? 0,
                CompanyName = dbUser?.Companies?.FirstOrDefault()?.CompanyName
            };

            _cache.SetValue(id, user, 60 * 5);

            return user;
        }
        private void ValidateCredentials(HttpActionContext context)
        {
            var userName = GetHeaderValue(context, ApiUserContext);
            var userKey = GetHeaderValue(context, ApiUserKey);

            var cachedUser = _cache.GetValue<CachedUser>(userName);

            if (cachedUser == null)
            {
                var user = _userDac.GetByEmail(userName);

                if (user == null)
                    throw new NotFoundException("User does not exist.");

                cachedUser = new CachedUser(user);
            }

            if (!userKey.Equals(cachedUser.Password))
                    throw new UnauthorizedException("Invalid Password.");

            _cache.SetValue(userName, cachedUser, DateTimeOffset.UtcNow.AddMinutes(10));

            HttpContext.Current.Items.Add(UserContext, cachedUser.Id);
        }
Пример #36
0
        public User GetUser(string userId)
        {
            var cached = (CachedUser)this.Session[SessionKey];
            if (cached == null || !userId.ToLower().Equals(cached.UserId))
            {
                var user = this.FindBy(Meta.UserName, userId);

                if (user == null)
                {
                    return null;
                }

                cached = new CachedUser(user);
                this.Session[SessionKey] = cached;
            }

            return cached.GetUser(this.Session);
        }
Пример #37
0
 private void SetPermissions(CachedUser user)
 {
     ManageDepartments.Visible = Permissions.CanManageDepartments(user?.RoleId);
     ManageServers.Visible = Permissions.CanManageServers(user?.RoleId);
     ManageUsers.Visible = Permissions.CanManageUsers(user?.RoleId);
 }