public override async Task OnConnectedAsync()
        {
            try
            {
                var feature = Context.Features.Get <IConnectionHeartbeatFeature>();
                if (feature == null)
                {
                    await _usersService.AddUserAsync(Context.ConnectionId, Context.User.SubId(),
                                                     Context.User.UserName());

                    await base.OnConnectedAsync();

                    return;
                }

                var context = Context.GetHttpContext();
                if (context == null)
                {
                    throw new InvalidOperationException("The HTTP context cannot be resolved.");
                }

                var result = await context.AuthenticateAsync(IdentityServerAuthenticationDefaults.AuthenticationScheme);

                if (result.Ticket == null)
                {
                    Context.Abort();
                    return;
                }

                var expiresClaim = result.Ticket.Principal.FindFirst(JwtClaimTypes.Expiration);
                if (!long.TryParse(expiresClaim.Value, out var expiresValue))
                {
                    Context.Abort();
                    return;
                }

                var expires = DateTimeOffset.FromUnixTimeSeconds(expiresValue);

                feature.OnHeartbeat(state =>
                {
                    var(innerExpires, connection) = ((DateTimeOffset, HubCallerContext))state;
                    if (innerExpires < DateTimeOffset.UtcNow)
                    {
                        connection.Abort();
                    }
                }, (expires, Context));

                await _usersService.AddUserAsync(Context.ConnectionId, Context.User.SubId(), Context.User.UserName());

                await base.OnConnectedAsync();
            }
            catch (Exception e)
            {
                Console.WriteLine($"Add user failed. Error: {e.Message}");
            }
        }
        private async void OnSave()
        {
            var editingCustomer = Mapper.Map <EditableUser, User>(User);

            try
            {
                if (EditMode)
                {
                    await _usersService.UpdateUserAsync(editingCustomer);
                }
                else
                {
                    await _usersService.AddUserAsync(editingCustomer);
                }
                Done?.Invoke();
            }
            catch (Exception ex)
            {
                Failed(ex);
            }
            finally
            {
                User = null;
            }
        }
Example #3
0
        public async Task <ActionResult <AuthenticatedUser> > Register([FromBody] RegisterCredentials credentials)
        {
            var isAdded = await _users.AddUserAsync(credentials);

            if (isAdded)
            {
                var user = await _authenticateService.Authenticate(new LoginCredentials()
                {
                    Email = credentials.Email, Password = credentials.Password
                });

                if (user != null)
                {
                    var transaction = await _transactions.CreateTransactionAsync(null, user.Id, REGISTRATION_BONUS, DateTime.Now);

                    if (transaction != null)
                    {
                        var result = await _transactions.CommitTransactionAsync(transaction);

                        if (result != null)
                        {
                            return(Ok(user));
                        }
                    }
                }
                return(BadRequest(new { message = "Registration failed" }));
            }
            else
            {
                return(BadRequest(new { message = "User already registered" }));
            }
        }
        public async Task <IActionResult> AddUser([FromForm] UserDTO userDTO)
        {
            if (userDTO == null)
            {
                return(BadRequest("User Object is null"));
            }

            if (!ModelState.IsValid)
            {
                return(BadRequest("Invalid model object"));
            }

            var user = new User
            {
                DisplayName  = userDTO.DisplayName,
                UserName     = userDTO.DisplayName,
                Email        = userDTO.Email,
                PasswordHash = userDTO.Password
            };

            //var userEntity = _mapper
            string errors = await _usersService.AddUserAsync(user);

            if (errors == string.Empty)
            {
                return(Ok(userDTO));
            }
            else
            {
                throw new HttpResponseException(500, errors);
            }
        }
Example #5
0
        public async Task <IActionResult> CreateUser(
            [HttpTrigger(AuthorizationLevel.Function, "post", Route = "users")] CreateUserRequest request)
        {
            var user = request.User.MapToUser();
            await _usersService.AddUserAsync(user);

            return(new CreatedResult($"/{user.DogeId}", user));
        }
        public async Task <IActionResult> Post([FromBody] User user)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }
            await _usersService.AddUserAsync(user);

            return(Created("", user));
        }
        public async Task <ActionResult> CreateAsync([Bind("Id,FirstName,LastName,Email,Gender,Mobile,Pin,Password,Address,Image,CustomField1,CustomField2,CustomField3")] Users user)
        {
            if (ModelState.IsValid)
            {
                user.Id = Guid.NewGuid().ToString();
                await _usersService.AddUserAsync(user);

                return(RedirectToAction("Index"));
            }

            return(View(user));
        }
        public async Task <IActionResult> Add(string username, string fullname)
        {
            try
            {
                await _usersService.AddUserAsync(username, fullname);

                return(Ok());
            }
            catch (Exception ex)
            {
                return(new BadRequestObjectResult($"Unable to add a user: {ex.Message}"));
            }
        }
        public async Task HandleAsync(SynchronizeUserCommand command)
        {
            var dataStructure = _mapper.Map <UserDataStructure>(command);

            if (await _usersService.UserExists(dataStructure.Id))
            {
                await _usersService.UpdateUserAsync(dataStructure);
            }
            else
            {
                await _usersService.AddUserAsync(dataStructure);
            }
        }
Example #10
0
        public async Task <IActionResult> AddUserAsync([FromBody] User userModel)
        {
            try
            {
                var user = await service.AddUserAsync(userModel);

                return(Ok(user));
            }
            catch (Exception ex)
            {
                var exceptionResponse = GetExceptionResponse(ex, Request);
                return(exceptionResponse);
            }
        }
Example #11
0
        public async Task <ActionResult> AddNewUser(UsersViewModel _userViewModel, string redirectUrl)
        {
            if (!ModelState.IsValid)
            {
                return(View(_userViewModel));
            }

            var user = new Users.User
            {
                userName = _userViewModel.userName,
                role     = _userViewModel.role,
                login    = _userViewModel.login
            };

            await userService.AddUserAsync(user);

            return(RedirectToLocal(redirectUrl));
        }
        public IActionResult Register(RegisterViewModel model)
        {
            if (!ModelState.IsValid)
            {
                ViewData[ErrorKey] = InvalidModelSateError;
                return(View(model));
            }
            var userRegistrationTask = usersService
                                       .AddUserAsync(model.Username, model.Password, model.Email, model.FullName);

            if (!userRegistrationTask.Result.Succeeded)
            {
                ViewData[ErrorKey] = string.Join(Environment.NewLine,
                                                 userRegistrationTask.Result.Errors.Select(e => e.Description));
                return(View());
            }
            return(RedirectToAction("Login", "Users"));
        }
Example #13
0
        public async Task <IActionResult> AddUser([FromBody] AddUserFormModel userForm)
        {
            var user = await _usersService.AddUserAsync(HttpContext.GetUser(), userForm);

            return(Ok(GetRequestResult(user)));
        }
Example #14
0
 public void AddUser(UserAddModel model)
 {
     _userService.AddUserAsync(model);
     return;
 }
Example #15
0
        public async Task <IActionResult> RegisterUser(RegisterUserViewModel model)
        {
            if (!ModelState.IsValid)
            {
                // ModelState invalid, return the view with the passed-in model
                // so changes can be made
                return(View(model));
            }

            // create user + claims
            var userToCreate = model.IsProvisioningFromExternal
                    ? new User
            {
                Username = model.Username,
                IsActive = true
            }
                    : new User
            {
                Password = model.Password.GetSha256Hash(),
                Username = model.Username,
                IsActive = true
            };

            userToCreate.UserClaims.Add(new UserClaim("country", model.Country));
            userToCreate.UserClaims.Add(new UserClaim("address", model.Address));
            userToCreate.UserClaims.Add(new UserClaim("given_name", model.Firstname));
            userToCreate.UserClaims.Add(new UserClaim("family_name", model.Lastname));
            userToCreate.UserClaims.Add(new UserClaim("email", model.Email));
            userToCreate.UserClaims.Add(new UserClaim("subscriptionlevel", "FreeUser"));

            if (model.IsProvisioningFromExternal)
            {
                userToCreate.UserLogins.Add(new UserLogin
                {
                    LoginProvider = model.Provider,
                    ProviderKey   = model.ProviderUserId
                });
            }

            // add it through the repository
            await _usersService.AddUserAsync(userToCreate);

            if (!model.IsProvisioningFromExternal)
            {
                // log the user in
                // issue authentication cookie with subject ID and username
                var props = new AuthenticationProperties
                {
                    IsPersistent = false,
                    ExpiresUtc   = DateTimeOffset.UtcNow.Add(AccountOptions.RememberMeLoginDuration)
                };
                await HttpContext.SignInAsync(userToCreate.SubjectId, userToCreate.Username, props);
            }

            // continue with the flow
            if (_interaction.IsValidReturnUrl(model.ReturnUrl) || Url.IsLocalUrl(model.ReturnUrl))
            {
                return(Redirect(model.ReturnUrl));
            }

            return(Redirect("~/"));
        }
        public async Task HandleAsync(CreateUserCommand command)
        {
            var dataStructure = _mapper.Map <UserDataStructure>(command);

            await _usersService.AddUserAsync(dataStructure);
        }