예제 #1
0
        public InvoiceDto Create(InvoiceDto invoice)
        {
            var insertedEntity = invoiceRepository.Insert(
                invoice.ToInvoice(currentPrincipal.GetUserId()));

            invoiceRepository.Save();

            return(insertedEntity.ToInvoiceDto());
        }
예제 #2
0
 public Task ToggleLibrary(int trackId, bool isInLibrary, IPrincipal principal)
 {
     if (isInLibrary)
     {
         return(context.TrackRepository.AddTrackToUserLibrary(trackId, principal.GetUserId()));
     }
     else
     {
         return(context.TrackRepository.RemoveTrackToUserLibrary(trackId, principal.GetUserId()));
     }
 }
예제 #3
0
        public async Task <ListResult <Track> > SearchTracks(TrackFilter filter, Page <TrackOrderColumn> page, IPrincipal principal)
        {
            var filterDo = mapper.Map <TrackFilterDo>(filter);
            var pageDo   = mapper.Map <PagedQuery <TrackOrderColumnDo> >(page);

            if (filter != null && filter.PlayedByMe)
            {
                filterDo.PlayedByUserId = principal.GetUserId();
            }

            if (filter != null && filter.IsInMyLibrary)
            {
                filterDo.IsInLibraryForUserId = principal.GetUserId();
            }

            var tracks = (await context.TrackRepository.SearchTracks(filterDo, pageDo)).ToList();

            var albumIds = tracks.Select(t => t.AlbumId).Distinct().ToList();
            var trackIds = tracks.Select(t => t.Id).Distinct().ToList();

            var albums  = (await context.AlbumRepository.GetByIdList(albumIds)).ToDictionary(a => a.Id);
            var artists = await context.ArtistRepository.GetArtistsByTrackIdList(trackIds);

            var genres = await context.GenreRepository.GetGenresByTrackIdList(trackIds);

            var userTrackIds = new HashSet <int>(await context.TrackRepository.GetUserTracksByTrackIdList(trackIds, principal.GetUserId()));

            var count = await context.TrackRepository.CountTracks(filterDo);

            var items = tracks
                        .Select(t =>
                                new Track
            {
                Id             = t.Id,
                Album          = mapper.Map <Album>(albums[t.AlbumId]),
                Artists        = mapper.Map <List <Artist> >(artists[t.Id]),
                Genres         = mapper.Map <List <Genre> >(genres[t.Id]),
                DiscNumber     = t.DiscNumber,
                Duration       = t.Duration.TotalSeconds,
                SavedToLibrary = userTrackIds.Contains(t.Id),
                Title          = t.Title,
                TrackNumber    = t.TrackNumber
            })
                        .ToList();

            return(new ListResult <Track>
            {
                Items = items,
                Count = count
            });
        }
예제 #4
0
        public static ApplicationUser GetApplicationUser(this IPrincipal principal, IssuesDb db)
        {
            var userId = principal.GetUserId();
            var user   = db.Users.Find(userId);

            return(user);
        }
예제 #5
0
        public static IQueryable <Author> FilterByOwner(this IQueryable <Author> query, IPrincipal user, string role = Constants.EditorRole)
        {
            var userId = user.GetUserId();

            if (!user.IsInRole(role))
            {
                query = query.Where(a => a.OwnerId == userId);
            }

            return(query);
        }
예제 #6
0
        public User GetBySSOUser(IPrincipal user)
        {
            var u = new User()
            {
                Id = user.GetUserId(),
                UserName = user.GetUserName(),
                Email = user.GetEmail(),
                PhoneNumber = user.GetPhoneNumber().Count > 0 ? user.GetPhoneNumber().First() : string.Empty
            };

            return u;
        }
예제 #7
0
        public async Task AddToCollection(int bookId, IPrincipal user)
        {
            var userId = user.GetUserId();

            if (userId != null)
            {
                var sql = $"IF NOT EXISTS (SELECT * FROM UserBooks WHERE UserId = @{nameof(userId)} AND BookId = @{nameof(bookId)})"
                          + " INSERT INTO UserBooks (UserId, BookId)"
                          + $" VALUES (@{nameof(userId)}, @{nameof(bookId)})";
                var cmd = new CommandDefinition(sql, new { bookId, userId });
                await db.ExecuteAsync(cmd);
            }
        }
예제 #8
0
        /// <summary>
        /// Get information about the context in which the current user is currently working.
        /// </summary>
        /// <returns></returns>
        public static UserContext GetContext(this IPrincipal principal)
        {
            if (!principal.IsAuthenticated())
            {
                return(null);
            }

            return(new UserContext
            {
                UserId = principal.GetUserId(),
                EventId = principal.GetEventId()
            });
        }
예제 #9
0
        public static UserOrganisation FindUserOrganisation(this IRepository repository, IPrincipal principal)
        {
            //GEt the logged in users identifier
            var userId = principal.GetUserId();

            //If internal user the load it using the identifier as the UserID
            if (userId > 0)
            {
                return(repository.GetAll <UserOrganisation>().FirstOrDefault(uo => uo.UserId == userId));
            }

            return(null);
        }
예제 #10
0
        public static User FindUser(this IDataRepository repository, IPrincipal principal)
        {
            if (principal == null)
            {
                return(null);
            }

            //GEt the logged in users identifier
            var userId = principal.GetUserId();

            //If internal user the load it using the identifier as the UserID
            if (userId > 0)
            {
                return(repository.Get <User>(userId));
            }

            return(null);
        }
예제 #11
0
        public async Task <Book?> GetBookAsync(int bookId, IPrincipal user)
        {
            var userId = user.GetUserId();

            var sql = "SELECT b.*, CASE WHEN ub.UserId IS NULL THEN CAST(0 as bit) ELSE CAST(1 as bit) END AS HasBook"
                      + " FROM Books b"
                      + $" LEFT JOIN UserBooks ub ON ub.BookId = b.BookId AND ub.UserId = @{nameof(userId)}"
                      + $" WHERE b.BookId = @{nameof(bookId)}";
            var cmd    = new CommandDefinition(sql, new { bookId, userId });
            var result = await db.QuerySingleOrDefaultAsync <Book>(cmd);

            if (result != null)
            {
                sql = "SELECT ISNULL(ba.Name, p.Name) AS Name, ba.RoleDesc FROM BookAuthors ba"
                      + " JOIN People p ON p.PersonId = ba.PersonId"
                      + $" WHERE ba.BookId = @{nameof(bookId)}"
                      + " ORDER BY ba.SortOrder";
                cmd            = new CommandDefinition(sql, new { bookId });
                result.Authors = await db.QueryAsync <Person>(cmd);

                sql = "SELECT ISNULL(bi.Name, p.Name) AS Name, bi.RoleDesc FROM BookIllustrators bi"
                      + " JOIN People p ON p.PersonId = bi.PersonId"
                      + $" WHERE bi.BookId = @{nameof(bookId)}"
                      + " ORDER BY bi.SortOrder";
                cmd = new CommandDefinition(sql, new { bookId });
                result.Illustrators = await db.QueryAsync <Person>(cmd);

                sql = "SELECT ISNULL(bt.Name, p.Name) AS Name, bt.RoleDesc FROM BookTranslators bt"
                      + " JOIN People p ON p.PersonId = bt.PersonId"
                      + $" WHERE bt.BookId = @{nameof(bookId)}"
                      + " ORDER BY bt.SortOrder";
                cmd = new CommandDefinition(sql, new { bookId });
                result.Translators = await db.QueryAsync <Person>(cmd);

                sql = "SELECT * FROM SeriesBooks sb"
                      + " JOIN Series s ON s.SeriesId = sb.SeriesId"
                      + $" WHERE sb.BookId = @{nameof(bookId)}";
                cmd = new CommandDefinition(sql, new { bookId });
                result.SeriesBooks = await db.QueryAsync <SeriesBook, Series, SeriesBook>(cmd, (sb, s) => { sb.Series = s; return(sb); }, "SeriesId");
            }

            return(result);
        }
예제 #12
0
        public string GetStreamingToken(int trackId, IPrincipal principal, string clientAddress)
        {
            var userId = principal.GetUserId();

            var tokenHandler    = new JwtSecurityTokenHandler();
            var key             = Encoding.ASCII.GetBytes(tokenSecret);
            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(new Claim[]
                {
                    new Claim(RequestorUserIdClaimType, userId.ToString("D")),
                    new Claim(TrackIdClaimType, trackId.ToString("D")),
                    new Claim(ClientAddressClaimType, clientAddress)
                }),
                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature),
                Expires            = DateTime.Now.AddDays(1)
            };
            var token = tokenHandler.CreateToken(tokenDescriptor);

            return(tokenHandler.WriteToken(token));
        }
        private async Task <HttpRequestMessage> CreateHttpRequestMessage(HttpMethod method, string uri, IPrincipal principal, object requestBodyData = null)
        {
            if (uri.StartsWith("/"))
            {
                throw new Exception($"{nameof(uri)} parameter value starts with a forward-slash.  You didn't want to do that.");
            }

            var requestMessage = new HttpRequestMessage(method, uri);

            requestMessage.Headers.Add(HEADER_SA_USER_ID, principal.GetUserId() ?? string.Empty);
            if (requestBodyData != null)
            {
                requestMessage.Content = new ObjectContent <object>(requestBodyData, _formatter);
                requestMessage.Properties[REQ_BODY_JSON_PAYLOAD] = await requestMessage.Content.ReadAsStringAsync();
            }
            else
            {
                requestMessage.Properties[REQ_BODY_JSON_PAYLOAD] = string.Empty;
            }

            return(requestMessage);
        }
예제 #14
0
        public static bool IsLoggedIn(this IPrincipal principal)
        {
            string UserID = principal.GetUserId();

            return(!String.IsNullOrEmpty(UserID));
        }
예제 #15
0
 /// <summary>
 /// Gets the user identificator.
 /// This method works with authorized requests only!!!
 /// </summary>
 /// <param name="user">The user.</param>
 /// <returns>The user identificator</returns>
 public static Int64 GetUserIdValue(this IPrincipal user)
 {
     return(user.GetUserId().Value);
 }
 public static bool CanDelete(this IApprovableEntity entityV, IPrincipal user)
 {
     return((entityV.ModifiedUserId == user.GetUserId()) || user.IsAdmin());
 }
 public static string GetNotificationTag(this IPrincipal user)
 => NotificationHubExtensions.GetNotificationTagFor(user.GetUserId());
예제 #18
0
        protected async Task ProcessMatch(string lookupId, DateTime matchDate, CompetitionV competitionV, Guid?venueGuid, int?attendance, Guid team1Guid, short?team1Ht, short?team1Ft, Guid team2Guid, short?team2Ht, short?team2Ft, Guid campaignStageKey)
        {
            if (campaignStageKey == null)
            {
                return;
            }

            var lookupMatchSearch = await Provider.GetLookupMatch(ImportSite, lookupId);

            var startOfDay = matchDate.Date;
            var endOfDay   = matchDate.ToEndOfDay();

            var matchSearch = await Provider.GetMatchByTeams(team1Guid, team2Guid, matchDate);

            var campaign = await Provider.FindCampaignAsync(competitionV.HeaderKey, matchDate);

            if (campaign == null)
            {
                var startDate = Date.LowDate;
                var endDate   = Date.HighDate;

                if (!competitionV.GetCampaignDates(matchDate, ref startDate, ref endDate))
                {
                    return;
                }

                var newCampaign = Campaign.CreateNew(competitionV.HeaderKey, startDate, endDate);
                campaign = newCampaign;

                Provider.Add(newCampaign);
                Provider.SaveChanges();
            }

            if (lookupMatchSearch != null || matchSearch != null)
            {
                MatchV matchV = null;

                if (lookupMatchSearch != null)
                {
                    var lookupMatch = lookupMatchSearch;
                    matchV = (await Provider.GetMatch(lookupMatch.MatchGuid, DateTime.Now));
                }
                else if (matchSearch != null)
                {
                    matchV = matchSearch;
                }

                if (matchV == null || matchV.MatchImportType == MatchImportType.ManualResult)
                {
                    return;
                }

                matchV.MatchDate        = matchDate.Date;
                matchV.MatchTimeTicks   = (matchDate - matchDate.Date).Ticks;
                matchV.VenueGuid        = venueGuid;
                matchV.Attendance       = attendance;
                matchV.Team1Guid        = team1Guid;
                matchV.Team1HT          = team1Ht;
                matchV.Team1FT          = team1Ft;
                matchV.Team2Guid        = team2Guid;
                matchV.Team2HT          = team2Ht;
                matchV.Team2FT          = team2Ft;
                matchV.MatchImportType  = matchV.GetMatchImportType(true);
                matchV.CampaignStageKey = campaignStageKey;
            }
            else
            {
                if (matchDate < DateTime.Now && team1Ft == null && team2Ft == null)
                {
                    return;
                }

                var matchGuid = Guid.NewGuid();

                Provider.Add(new Match()
                {
                    PrimaryKey = matchGuid
                });

                var matchV = MatchV.CreateNew <MatchV>(User.GetUserId());
                matchV.HeaderKey        = matchGuid;
                matchV.MatchDate        = matchDate.Date;
                matchV.MatchTimeTicks   = (matchDate - matchDate.Date).Ticks;
                matchV.VenueGuid        = venueGuid;
                matchV.Attendance       = attendance;
                matchV.Team1Guid        = team1Guid;
                matchV.Team1HT          = team1Ht;
                matchV.Team1FT          = team1Ft;
                matchV.Team2Guid        = team2Guid;
                matchV.Team2HT          = team2Ht;
                matchV.Team2FT          = team2Ft;
                matchV.EffectiveFrom    = Date.LowDate;
                matchV.EffectiveTo      = Date.HighDate;
                matchV.MatchImportType  = matchV.GetMatchImportType(true);
                matchV.CampaignStageKey = campaignStageKey;

                Provider.Add(matchV);

                if (lookupId != string.Empty)
                {
                    Provider.Add(new LookupMatch()
                    {
                        PrimaryKey = Guid.NewGuid(),
                        ImportSite = ImportSite,
                        MatchGuid  = matchGuid,
                        LookupId   = lookupId
                    });
                }
            }

            Provider.SaveChanges();
        }
예제 #19
0
        public async Task <Track> GetById(int id, IPrincipal principal)
        {
            var track = await context.TrackRepository.GetById(id);

            var album = await context.AlbumRepository.GetById(track.AlbumId);

            var idAsList = new List <int> {
                id
            };
            var artists = await context.ArtistRepository.GetArtistsByTrackIdList(idAsList);

            var genres = await context.GenreRepository.GetGenresByTrackIdList(idAsList);

            var userTrackIds = new HashSet <int>(await context.TrackRepository.GetUserTracksByTrackIdList(idAsList, principal.GetUserId()));

            return(new Track()
            {
                Id = track.Id,
                Album = mapper.Map <Album>(album),
                Artists = mapper.Map <List <Artist> >(artists[id]),
                Genres = mapper.Map <List <Genre> >(genres[id]),
                DiscNumber = track.DiscNumber,
                Duration = track.Duration.TotalSeconds,
                SavedToLibrary = userTrackIds.Contains(track.Id),
                Title = track.Title,
                TrackNumber = track.TrackNumber
            });
        }