Exemple #1
0
 public record StoreWithOffersCount(
     Guid Guid,
     string Name,
     DateTime?CloseDate,
     string?Url,
     User?Manager,
     int OffersCount);
Exemple #2
0
 public BuildBuilder WithOwner(Action <UserBuilder>?configure = null)
 {
     _owner        = null;
     _ownerBuilder = new UserBuilder();
     configure?.Invoke(_ownerBuilder);
     return(this);
 }
        private IList <IAuthenticationProvider> GetAuthenticationProviders(User?user)
        {
            var authenticationProviderId = user?.AuthenticationProviderId;

            var providers = _authenticationProviders.Where(i => i.IsEnabled).ToList();

            if (!string.IsNullOrEmpty(authenticationProviderId))
            {
                providers = providers.Where(i => string.Equals(authenticationProviderId, i.GetType().FullName, StringComparison.OrdinalIgnoreCase)).ToList();
            }

            if (providers.Count == 0)
            {
                // Assign the user to the InvalidAuthProvider since no configured auth provider was valid/found
                _logger.LogWarning(
                    "User {Username} was found with invalid/missing Authentication Provider {AuthenticationProviderId}. Assigning user to InvalidAuthProvider until this is corrected",
                    user?.Username,
                    user?.AuthenticationProviderId);
                providers = new List <IAuthenticationProvider>
                {
                    _invalidAuthProvider
                };
            }

            return(providers);
        }
        public async Task OnGetAsync()
        {
            GraphServiceClient graphClient = GetGraphServiceClient(new[] { "user.read", "calendars.read" });

            User?me = await graphClient.Me.Request().GetAsync();

            ViewData["Me"] = me;

            ICalendarEventsCollectionPage?cal = await graphClient.Me.Calendar.Events.Request().GetAsync();

            foreach (Event?evnt in cal)
            {
                Console.WriteLine(evnt.Subject);
            }

            try
            {
                // Get user photo
                using Stream? photoStream = await graphClient.Me.Photo.Content.Request().GetAsync();

                byte[] photoByte = ((MemoryStream)photoStream).ToArray();
                ViewData["Photo"] = Convert.ToBase64String(photoByte);
            }
            catch (Exception)
            {
                ViewData["Photo"] = null;
            }
        }
Exemple #5
0
        public async Task <long> CreateUser(CreateUser createUser)
        {
            bool emailIsTaken = await IsEmailAddressTaken(createUser.EmailAddress);

            if (emailIsTaken)
            {
                throw new DomainException(DomainExceptions.User_with_given_email_address_already_exists);
            }

            User?createdUser = null;

            using (var transaction = await context.Database.BeginTransactionAsync())
            {
                createdUser      = new User(EmailAddress.Create(createUser.EmailAddress), Password.Create(createUser.Password));
                createdUser.Name = createUser.Name;
                context.Users.Add(createdUser);
                await context.SaveChangesAsync();

                context.AddEvent(createdUser.CreateEvent(), correlationIdProvider.TraceId);
                await context.SaveChangesAsync();

                await transaction.CommitAsync();
            }
            return(createdUser !.UserId);
        }
Exemple #6
0
        public ActionResult Login(LoginPageModel model) //TODO: Move all of this to a UserService class
        {
            if (model is null)
            {
                throw new ArgumentNullException(nameof(model));
            }

            //We want to wait a specified amount of time for the response regardless of the results, to avoid
            //Exposing any information to the client
            StaticLogger.Log($"{model.Login}: Login attempt", StaticLogger.LoggingLevel.Call);
            DateTime startLogin = DateTime.Now;

            void WaitForRedirect()
            {
                const double LoginTime = 3000;

                double toWait = LoginTime - (DateTime.Now - startLogin).TotalMilliseconds;

                StaticLogger.Log($"{model.Login}: Waiting for {toWait}", StaticLogger.LoggingLevel.Call);
                if (toWait > 0)
                {
                    System.Threading.Thread.Sleep((int)toWait);
                }
            }

            StaticLogger.Log($"{model.Login}: Calling user service...", StaticLogger.LoggingLevel.Call);
            User?user = this.UserService.Login(model.Login, model.Password);

            if (user != null)
            {
                StaticLogger.Log($"{model.Login}: User not null", StaticLogger.LoggingLevel.Call);
                if (this.ConfigurationService.GetBool(ConfigurationNames.REQUIRE_EMAIL_VALIDATION))
                {
                    if (!this.EmailValidationRepository.IsValidated(user))
                    {
                        return(this.RedirectToAction(nameof(EmailValidationRequired), new { Id = user.Guid.ToString(), area = "" }));
                    }
                }

                if (!string.IsNullOrWhiteSpace(model.ReturnUrl) && model.ReturnUrl != this.Request.Path.Value)
                {
                    WaitForRedirect();
                    StaticLogger.Log($"{model.Login}: Returning to {model.ReturnUrl}", StaticLogger.LoggingLevel.Call);
                    return(this.Redirect(model.ReturnUrl));
                }
                else
                {
                    WaitForRedirect();
                    StaticLogger.Log($"{model.Login}: Returning Home", StaticLogger.LoggingLevel.Call);
                    return(this.Redirect("/Home/Index"));
                }
            }
            else
            {
                StaticLogger.Log($"{model.Login}: User is null", StaticLogger.LoggingLevel.Call);
                this.ModelState.AddModelError(string.Empty, "Invalid Login or Password" + System.Environment.NewLine);
                WaitForRedirect();
                return(this.View(model));
            }
        }
Exemple #7
0
        public async Task <CommentReadView?> FindById(int id, User?user = null)
        {
            var comments = await Connection.QueryAsync <CommentRecord>(
                @"WITH RECURSIVE commenttree AS (
                    SELECT r.* FROM comment r WHERE id = @Id AND was_deleted = FALSE
                    UNION ALL
                    SELECT c.* FROM comment c
                    INNER JOIN commenttree ct ON ct.id = c.parent_id
                    WHERE c.was_deleted = FALSE
                    ) SELECT * FROM commenttree
                    ORDER BY parent_id, creation_date ASC;",
                new { Id = id }
                );

            IUserReader userReader = GetReader <IUserReader>();
            IVoteReader voteReader = GetReader <IVoteReader>();

            List <CommentReadView> views = new List <CommentReadView>();

            foreach (CommentRecord comment in comments)
            {
                CommentReadView view = Map(comment);
                view.User = (await userReader.FindById(comment.UserId)) !;

                if (user != null)
                {
                    view.Vote = await voteReader.FindByCommentAndUser(comment.Id, user.Id);
                }

                views.Add(view);
            }

            // We're assuming there will always be one top level comment.
            return(BuildCommentTree(views)[0]);
        }
        public Task <User> Update(User update)
        {
            this.Update_InputUser = update;
            this.Update_Output    = update;

            return(Task.FromResult(this.Update_Output));
        }
Exemple #9
0
        public async override Task <ServiceView> Execute(UpdateServiceCommand input, User?user)
        {
            var service = await this.service.GetById(input.Id);

            if (!service.IsOwner(user !))
            {
                throw new AuthorizationException();
            }

            await this.service.Update(
                service,
                new ServiceUpdate(
                    input.Name,
                    input.Description,
                    input.PricingMethod,
                    input.Configurations.Select(c => new ServiceConfigurationUpdate(
                                                    c.VehicleCategoryId,
                                                    c.Price,
                                                    c.Duration
                                                    )).ToList()
                    )
                );

            throw new NotImplementedException();
            // return mapper.Map<Service, ServiceView>(service);
        }
Exemple #10
0
        public async Task <IActionResult> ProcessSendActivationUserMailTopic([FromBody] TopicData <User> topicData)
        {
            User?user = topicData.Data;

            if (!string.IsNullOrWhiteSpace(user?.Id))
            {
                _logger.LogInformation($"Receive send activation user mail topic, user id: {user.Id}");
                // TODO Add api key ADMIN from global tenant and add tenant Id to header
                await _daprClient.InvokeMethodAsync("userapi", $"UserMail/activation",
                                                    data : user,
                                                    httpExtension : new HTTPExtension()
                {
                    Verb    = HTTPVerb.Post,
                    Headers = new Dictionary <string, string>()
                    {
                        { "tenantId", topicData.TenantId }
                    }
                }
                                                    );
            }
            else
            {
                _logger.LogWarning($"Receive user topic without id");
            }
            return(Ok());
        }
        public Task <User> Create(User create)
        {
            this.Create_InputUser = create;
            this.Create_Output    = create;

            return(Task.FromResult(this.Create_Output));
        }
Exemple #12
0
        protected override async Task <UserLogin> HandleInput(UserRegisterParams input)
        {
            using (var connection = database.GetConnection()) {
                using (var transaction = connection.BeginTransaction()) {
                    IUserRepo         userRepo  = database.GetRepo <IUserRepo>(connection);
                    ISpaceRepo        spaceRepo = database.GetRepo <ISpaceRepo>(connection);
                    ISubscriptionRepo subRepo   = database.GetRepo <ISubscriptionRepo>(connection);

                    // Check that the email is free first.
                    if (!String.IsNullOrWhiteSpace(input.Email))
                    {
                        User?emailInUse = await userRepo.FindByEmail(input.Email);

                        if (emailInUse != null)
                        {
                            throw new CollisionException("Email is already in use");
                        }
                    }

                    User?usernameInUse = await userRepo.FindByUsername(input.Username);

                    if (usernameInUse != null)
                    {
                        throw new CollisionException("Username is unavailable");
                    }

                    User user = new User()
                    {
                        Username     = input.Username,
                        PasswordHash = passwordHasher.Hash(input.Password),
                        Email        = StringUtils.NullifyWhiteSpace(input.Email),
                        JoinedDate   = System.DateTime.UtcNow
                    };

                    await userRepo.Add(user);

                    // Subscribe the user to the default spaces.
                    IEnumerable <Space> defaultSpaces = await spaceRepo.FindDefault();

                    IEnumerable <Subscription> defaultSubscriptions = defaultSpaces.Select(space => new Subscription()
                    {
                        User = user, Space = space
                    });

                    foreach (Subscription s in defaultSubscriptions)
                    {
                        await subRepo.Add(s);

                        s.Space.SubscriptionCount++;
                        await spaceRepo.Update(s.Space);
                    }

                    UserView userView  = userMapper.Map(user);
                    string   authToken = tokenHandler.IssueToken(user);

                    transaction.Commit();
                    return(new UserLogin(userView, authToken));
                }
            }
        }
        /// <summary>
        /// ログインする。
        /// </summary>
        /// <param name="mailAddress">メールアドレス</param>
        /// <param name="password">パスワード</param>
        /// <returns>ログインに成功したかどうか</returns>
        public static bool LogIn(string mailAddress, string password)
        {
            bool ret;
            var  userDAO = new UserDAO();

            // メールアドレスが一致するユーザ取得
            var dt    = userDAO.Select(mailAddress);
            var users = User.ConvertFrom(dt);

            if (users.Count == 0)
            {
                return(false);
            }

            // 認証
            var user = Authenticate(users, mailAddress, password);

            ret = (user != null);

            // オンラインフラグ更新
            ret = ret && user !.LogIn();

            if (ret)
            {
                // 認証成功した場合はログイン中ユーザを保持
                CurrentUser = user;
            }

            return(ret);
        }
        public async Task <User?> AuthenticateUser(string name, string password)
        {
            User?user = null;

            byte[] hash = pool.Rent(64);
            try /// Arraypool example from https://adamsitnik.com/Array-Pool/
            {
                user = await _context.Users.Where(u => u.Name == name).AsNoTracking().SingleOrDefaultAsync();

                if (user == null)
                {
                    return(null);
                }
                Hash(password, user.PasswordSalt, hash);
                if (!user.PasswordSha512Hash.SequenceEqual(hash))
                {
                    return(null);
                }
            }
            catch
            { }
            finally
            {
                pool.Return(hash);
            }
            return(user);
        }
Exemple #15
0
    /// <summary>
    /// Creates a character in the database with the given settings.
    /// </summary>
    /// <param name="owner">The owner. Defaults to <see cref="DefaultOwner"/>.</param>
    /// <param name="server">The server. Defaults <see cref="DefaultServer"/>.</param>
    /// <param name="name">The name.</param>
    /// <param name="avatarUrl">The avatar.</param>
    /// <param name="nickname">The nickname.</param>
    /// <param name="summary">The summary.</param>
    /// <param name="description">The description.</param>
    /// <param name="pronouns">The pronouns.</param>
    /// <param name="isNSFW">Whether the character is NSFW.</param>
    /// <returns>The character.</returns>
    protected Character CreateCharacter
    (
        User?owner         = null,
        Server?server      = null,
        string?name        = null,
        string?avatarUrl   = null,
        string?nickname    = null,
        string?summary     = null,
        string?description = null,
        string?pronouns    = null,
        bool?isNSFW        = null
    )
    {
        var character = this.Database.CreateProxy <Character>
                        (
            owner ?? this.DefaultOwner,
            server ?? this.DefaultServer,
            name ?? string.Empty,
            avatarUrl ?? string.Empty,
            nickname ?? string.Empty,
            summary ?? string.Empty,
            description ?? string.Empty,
            pronouns ?? "They" // a real value is used here to avoid having to set it in the majority of cases
                        );

        if (isNSFW is not null)
        {
            character.IsNSFW = isNSFW.Value;
        }

        this.Database.Characters.Update(character);
        this.Database.SaveChanges();

        return(character);
    }
Exemple #16
0
        protected override async Task <UserLogin?> HandleInput(UserCredentials input)
        {
            using (var connection = database.GetConnection()) {
                IUserRepo userRepo = database.GetRepo <IUserRepo>(connection);

                User?user = await userRepo.FindByUsername(input.Username);

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

                if (passwordHasher.Verify(input.Password, user.PasswordHash))
                {
                    UserView userView  = userMapper.Map(user);
                    string   authToken = tokenHandler.IssueToken(user);

                    return(new UserLogin(userView, authToken));
                }
                else
                {
                    return(null);
                }
            }
        }
Exemple #17
0
        public override Task Login(User user, AuthenticationProperties properties)
        {
            this.Login_InputUser       = user;
            this.Login_InputProperties = properties;

            return(base.Login(user, properties));
        }
Exemple #18
0
        public async Task CreateUserOfUserNotInSystemShouldWork(string userName, string userRole, string userEmail)
        {
            User?enteredUser  = null;
            User?returnedUser = null;

            await using (var ctx = new TestKitchenRpContext(_options))
            {
                ctx.Database.EnsureCreated();
                var users = new UserRepository(ctx, new RolesRepository(ctx));
                enteredUser = await users.CreateNewUser(userName, userRole, userEmail);
            }

            await using (var ctx = new TestKitchenRpContext(_options))
            {
                var users = new UserRepository(ctx, new RolesRepository(ctx));
                Assert.NotNull(enteredUser.Id);
                returnedUser = await users.FindById(enteredUser.Id.Value);
            }

            Assert.NotNull(returnedUser);

            Assert.Equal(returnedUser.Id, enteredUser.Id);
            Assert.Equal(returnedUser.Email, enteredUser.Email);
            Assert.Equal(returnedUser.Sub, enteredUser.Sub);
            Assert.Equal(returnedUser.AllowNotifications, enteredUser.AllowNotifications);
            Assert.Equal(returnedUser.Role?.Id, enteredUser.Role?.Id);

            Assert.Equal(returnedUser.Email, userEmail);
            Assert.Equal(returnedUser.Sub, userName);
            Assert.Equal(returnedUser.Role?.RoleName, userRole);
        }
        /// <inheritdoc />
        public async Task <RetrieveEntityResult <Character> > GetBestMatchingCharacterAsync
        (
            Server server,
            User?user,
            string?name,
            CancellationToken ct = default
        )
        {
            server = _database.NormalizeReference(server);
            if (!(user is null))
            {
                user = _database.NormalizeReference(user);
            }

            if (user is null && name is null)
            {
                return(RetrieveEntityResult <Character> .FromError("No user and no name specified."));
            }

            if (user is null)
            {
                return(await GetCharacterByNameAsync(server, name !, ct));
            }

            if (name.IsNullOrWhitespace())
            {
                return(await GetCurrentCharacterAsync(user, server, ct));
            }

            return(await GetUserCharacterByNameAsync(user, server, name, ct));
        }
Exemple #20
0
        /// <summary>
        /// Get user by email without Discrminator
        /// </summary>
        /// <param name="email"></param>
        /// <returns>User as its found</returns>
        public async Task <User?> GetUserByEmail(string email)
        {
            User?user = null;

            FullAPIUri = new Uri(BaseAPIUri, $"{nameof(GetUserByEmail)}/{email}");
            string stringResult = string.Empty;

            await Policy.Handle <Exception>()
            .WaitAndRetryAsync(
                retryCount: 5,
                sleepDurationProvider: retryAttemp => TimeSpan.FromSeconds(Math.Pow(1.5, retryAttemp)),
                onRetry: (exception, timeSpan, retryCount, context) =>
            {
                // Add logic to be executed before each retry, such as logging
                System.Diagnostics.Debug.WriteLine($"Retry #{retryCount} due to exception '{(exception.InnerException ?? exception).Message}'");
                HttpClient.CancelPendingRequests();
            }
                ).ExecuteAsync(async() =>
            {
                var response = await HttpClient.GetStringAsync(FullAPIUri);

                user = JsonConvert.DeserializeObject <User>(response,
                                                            new JsonSerializerSettings
                {
                    ContractResolver    = new JsonPrivateResolver(),
                    ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor
                });;
            });

            return(user);
        }
Exemple #21
0
        public async Task <IEnumerable <CommentReadView> > FindByPost(int postId, User?user = null)
        {
            var comments = (await Connection.QueryAsync <CommentRecord>(
                                @"WITH RECURSIVE commenttree AS (
                    SELECT r.* FROM comment r WHERE post_id = @PostId AND parent_id = 0 AND was_deleted = FALSE 
                    UNION ALL
                    SELECT c.* FROM comment c
                    INNER JOIN commenttree ct ON ct.id = c.parent_id
                    WHERE c.was_deleted = FALSE
                    ) SELECT * FROM commenttree
                    ORDER BY parent_id, creation_date DESC;",
                                new { PostId = postId }
                                ));

            IUserReader userReader = GetReader <IUserReader>();
            IVoteReader voteReader = GetReader <IVoteReader>();

            List <CommentReadView> views = new List <CommentReadView>();

            foreach (CommentRecord comment in comments)
            {
                CommentReadView view = Map(comment);
                view.User = (await userReader.FindById(comment.UserId)) !;

                if (user != null)
                {
                    view.Vote = await voteReader.FindByCommentAndUser(comment.Id, user.Id);
                }

                views.Add(view);
            }

            return(BuildCommentTree(views));
        }
Exemple #22
0
        public async Task <int> Handle(CreatePersistedURLCommand request,
                                       CancellationToken cancellationToken)
        {
            User?user = null;

            if (request?.UserId != null)
            {
                user = await _ctx.Users.FindAsync(request.UserId);

                if (user == null)
                {
                    throw new BadRequestException("The specified user is unknown.");
                }
            }

            var shortURL = await GetShortURL(request?.DesiredShortURL);

            var persistedURL = new PersistedURL
            {
                URL      = request.URL, // request cannot be null, but I still get a warning for that it might be :(
                ShortURL = shortURL,
                User     = user
            };

            await _ctx.PersistedURLs.AddAsync(persistedURL);

            await _ctx.SaveChangesAsync(cancellationToken);

            return(persistedURL.Id);
        }
Exemple #23
0
        private static void InitializeUser()
        {
            Console.WriteLine("Username:"******"";

            user = users.FirstOrDefault(u => u.UserName.Equals(userName, StringComparison.OrdinalIgnoreCase));
            if (user == null)
            {
                Console.WriteLine("Ip:");
                var ip = Console.ReadLine() ?? "";

                int port;
                do
                {
                    Console.WriteLine("Your port:");
                } while (!int.TryParse(Console.ReadLine(), out port));

                Console.WriteLine("Recipient ip");
                var recipientIp = Console.ReadLine() ?? "";

                int recipientPort;
                do
                {
                    Console.WriteLine("Recipient port:");
                } while (!int.TryParse(Console.ReadLine(), out recipientPort));

                user = new User(userName, ip, port, recipientPort, recipientIp);

                configHelper.WriteUsers(users.Concat(new User[] { user }));
            }

            Console.Clear();
        }
        public async Task ReceiveSyncMessage(int roomId, string authToken, VideoSyncMessage videoSyncMessage)
        {
            AuthUser?authUser = await _authService.GetUser(authToken);

            if (authUser == null)
            {
                return;
            }

            User?user = await _userService.CreateOrGetByAuthUser(authUser);

            if (user == null)
            {
                return;
            }

            Room?room = await _roomService.Get(roomId);

            if (room == null || room.CreatedByUserId != user.UserId)
            {
                return;
            }

            await Clients.OthersInGroup(roomId.ToString()).SendAsync("VideoSyncMessage", videoSyncMessage);
        }
Exemple #25
0
        public async void OnSaveButtonClick(object sender, RoutedEventArgs args)
        {
            this.FindControl <TextBlock>("ErrorTextBlock").IsVisible = false;
            this.FindControl <TextBlock>("SavedTextBlock").IsVisible = false;
            this.FindControl <TextBlock>("WaitTextBlock").IsVisible  = true;
            UserID       = this.FindControl <TextBox>("UserID").Text;
            ClientID     = this.FindControl <TextBox>("ClientID").Text;
            ClientSecret = this.FindControl <TextBox>("ClientSecret").Text;
            User?user = await RunAPIRequest(UserID, ClientID, ClientSecret);

            if (user != null)
            {
                StartUser = user;
                SaveConfig();
                this.FindControl <TabItem>("TabUser").Header             = StartUser.Username;
                this.FindControl <TextBlock>("SavedTextBlock").IsVisible = true;
                this.FindControl <TabItem>("TabCustomization").IsVisible = true;
                UpdateValues(StartUser);
                UpdateDiffValues(StartUser);
                InitTimer();
            }
            else
            {
                this.FindControl <TextBlock>("ErrorTextBlock").IsVisible = true;
            }

            this.FindControl <TextBlock>("WaitTextBlock").IsVisible = false;
        }
        public ActionResult <QueryResult <BaseItemDto> > GetMusicGenres(
            [FromQuery] int?startIndex,
            [FromQuery] int?limit,
            [FromQuery] string?searchTerm,
            [FromQuery] string?parentId,
            [FromQuery] string?fields,
            [FromQuery] string?excludeItemTypes,
            [FromQuery] string?includeItemTypes,
            [FromQuery] bool?isFavorite,
            [FromQuery] int?imageTypeLimit,
            [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ImageType[] enableImageTypes,
            [FromQuery] Guid?userId,
            [FromQuery] string?nameStartsWithOrGreater,
            [FromQuery] string?nameStartsWith,
            [FromQuery] string?nameLessThan,
            [FromQuery] bool?enableImages           = true,
            [FromQuery] bool enableTotalRecordCount = true)
        {
            var dtoOptions = new DtoOptions()
                             .AddItemFields(fields)
                             .AddClientFields(Request)
                             .AddAdditionalDtoOptions(enableImages, false, imageTypeLimit, enableImageTypes);

            User?user = userId.HasValue && userId != Guid.Empty ? _userManager.GetUserById(userId.Value) : null;

            var parentItem = _libraryManager.GetParentItem(parentId, userId);

            var query = new InternalItemsQuery(user)
            {
                ExcludeItemTypes        = RequestHelpers.Split(excludeItemTypes, ',', true),
                IncludeItemTypes        = RequestHelpers.Split(includeItemTypes, ',', true),
                StartIndex              = startIndex,
                Limit                   = limit,
                IsFavorite              = isFavorite,
                NameLessThan            = nameLessThan,
                NameStartsWith          = nameStartsWith,
                NameStartsWithOrGreater = nameStartsWithOrGreater,
                DtoOptions              = dtoOptions,
                SearchTerm              = searchTerm,
                EnableTotalRecordCount  = enableTotalRecordCount
            };

            if (!string.IsNullOrWhiteSpace(parentId))
            {
                if (parentItem is Folder)
                {
                    query.AncestorIds = new[] { new Guid(parentId) };
                }
                else
                {
                    query.ItemIds = new[] { new Guid(parentId) };
                }
            }

            var result = _libraryManager.GetMusicGenres(query);

            var shouldIncludeItemTypes = !string.IsNullOrWhiteSpace(includeItemTypes);

            return(RequestHelpers.CreateQueryResult(result, dtoOptions, _dtoService, shouldIncludeItemTypes, user));
        }
Exemple #27
0
        public async Task <UserLogin> Register(UserRegistration registration)
        {
            // If registration provided an email, check to see if it's available.
            if (!String.IsNullOrWhiteSpace(registration.Email))
            {
                User?emailInUse = await userRepo.FindByEmail(registration.Email !);

                if (emailInUse != null)
                {
                    throw new EmailAlreadyInUseException();
                }
            }

            // Check to see if the username is unique.
            User?usernameInUse = await userRepo.FindByUsername(registration.Username);

            if (usernameInUse != null)
            {
                throw new UsernameAlreadyInUseException();
            }

            User user = factory.CreateFromRegistration(registration);
            await userRepo.Add(user);

            UserLogin login = new UserLogin(user.Id);
            await loginRepo.Add(login);

            await bus.Dispatch(new UserRegisterEvent(user, login));

            return(login);
        }
Exemple #28
0
        public static AccessReason GetProfileAccess([NotNull] this User user, [CanBeNull] User?currentUser)
        {
            if (user == null)
            {
                throw new ArgumentNullException(nameof(user));
            }

            if (currentUser == null)
            {
                return(AccessReason.NoAccess);
            }
            if (user.UserId == currentUser.UserId)
            {
                return(AccessReason.ItsMe);
            }
            if (user.Claims.Any(claim => claim.HasAccess(currentUser.UserId) && claim.ClaimStatus != Claim.Status.AddedByMaster))
            {
                return(AccessReason.Master);
            }
            if (user.ProjectAcls.Any(acl => acl.Project.HasMasterAccess(currentUser.UserId)))
            {
                return(AccessReason.CoMaster);
            }
            if (currentUser.Auth.IsAdmin == true)
            {
                return(AccessReason.Administrator);
            }
            return(AccessReason.NoAccess);
        }
Exemple #29
0
        private async Task <(string username, bool success)> AuthenticateWithProvider(
            IAuthenticationProvider provider,
            string username,
            string password,
            User?resolvedUser)
        {
            try
            {
                var authenticationResult = provider is IRequiresResolvedUser requiresResolvedUser
                    ? await requiresResolvedUser.Authenticate(username, password, resolvedUser).ConfigureAwait(false)
                    : await provider.Authenticate(username, password).ConfigureAwait(false);

                if (authenticationResult.Username != username)
                {
                    _logger.LogDebug("Authentication provider provided updated username {1}", authenticationResult.Username);
                    username = authenticationResult.Username;
                }

                return(username, true);
            }
            catch (AuthenticationException ex)
            {
                _logger.LogError(ex, "Error authenticating with provider {Provider}", provider.Name);

                return(username, false);
            }
        }
Exemple #30
0
        public async Task <TokenAuthorizationResult?> RefreshToken()
        {
            var cookies = _httpContextAccessor.HttpContext?.Request.Cookies;

            if (cookies == null || !cookies.TryGetValue(RefreshTokenCookieKey, out var value) || string.IsNullOrEmpty(value))
            {
                return(null);
            }

            var model = JsonSerializer.Deserialize <RefreshTokenModel>(value);

            if (model == null || string.IsNullOrEmpty(model.Username) || string.IsNullOrEmpty(model.RefreshToken))
            {
                return(null);
            }

            User?user = await _userService.FindByNameAsync(model.Username);

            if (user == null || !_userService.IsValidRefreshToken(user, model.RefreshToken))
            {
                return(null);
            }

            await _userService.RemoveRefreshToken(user, model.RefreshToken);

            user = (await _userService.FindByNameAsync(model.Username)) !;
            await SetRefreshTokenCookie(user);

            return(GetAccessToken(user.UserName));
        }