public async Task <IActionResult> GetCurrentUserId()
        {
            if (!_userManager.Users.Any())
            {
                return(Ok(ApiModel.AsError <string>("setup", "no users in DB")));
            }
            var username = HttpContext.User.Identity.Name;

            if (string.IsNullOrEmpty(username))
            {
                return(Ok(ApiModel.AsError <AccountDto>(null, "no user claims in request, did you forget to set the auth header ?")));
            }

            var user = await _userManager.FindByNameAsync(username);

            if (user == null)
            {
                return(Ok(ApiModel.AsError <AccountDto>(null, $"impossible to find a user with the username '{username}'")));
            }

            var resultDto = _mapper.Map <AccountDto>(user);

            resultDto.IsAuthenticated = true;

            return(Ok(ApiModel.AsSuccess(resultDto)));
        }
Exemplo n.º 2
0
        public async Task <IActionResult> Register([FromBody] RegisterViewModel model, string returnUrl = null)
        {
            ViewData["ReturnUrl"] = returnUrl;
            if (ModelState.IsValid)
            {
                var user = new ApplicationUser {
                    UserName = model.Email, Email = model.Email
                };
                var result = await _userManager.CreateAsync(user, model.Password);

                if (result.Succeeded)
                {
                    // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=532713
                    // Send an email with this link
                    //var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);
                    //var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: HttpContext.Request.Scheme);
                    //await _emailSender.SendEmailAsync(model.Email, "Confirm your account",
                    //    $"Please confirm your account by clicking this link: <a href='{callbackUrl}'>link</a>");
                    await _signInManager.SignInAsync(user, isPersistent : true);

                    _logger.LogInformation(3, "User created a new account with password.");
                    return(Ok(ApiModel.AsSuccess())); // RedirectToLocal(returnUrl);
                }
                AddErrors(result);
            }

            // If we got this far, something failed, redisplay form
            return(BadRequest(ApiModel.AsError("Error"))); // TODO: map modelerrors
        }
Exemplo n.º 3
0
        public async Task <IActionResult> Login([FromBody] LoginInputModel model)
        {
            // Hack to work around rc1 bug
            await HttpContext.SignOutAsync(IdentityConstants.ExternalScheme);

            if (ModelState.IsValid)
            {
                var result = await this.signInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberLogin, lockoutOnFailure : true);

                if (result.Succeeded)
                {
                    this.logger.LogInformation(1, "User logged in.");
                    return(Ok(new LoginResponseModel {
                        Result = ApiResult.AsSuccess()
                    }));
                }
                else
                {
                    this.logger.LogWarning(2, "User login failed.");
                    var response = new LoginResponseModel
                    {
                        IsLockedOut       = result.IsLockedOut,
                        IsNotAllowed      = result.IsNotAllowed,
                        RequiresTwoFactor = result.RequiresTwoFactor,
                        Result            = ApiResult.AsError("Login Failed")
                    };
                    return(BadRequest(response));
                }
            }
            else
            {
                return(BadRequest(ApiModel.AsError("model validation failed (TODO add the errors)")));
            }
        }
Exemplo n.º 4
0
        public async Task <IActionResult> Login([FromBody] LoginInputModel model)
        {
            if (ModelState.IsValid)
            {
                // This doesn't count login failures towards account lockout
                // To enable password failures to trigger account lockout, set lockoutOnFailure: true
                var result = await signInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberLogin, lockoutOnFailure : true);

                if (result.Succeeded)
                {
                    logger.LogInformation(1, "User logged in.");
                    // because we are logging in through an api, we need to generate and send back a new XsrfToken

                    return(Ok(new LoginResponseModel()));
                }
                else
                {
                    logger.LogWarning(2, "User login failed.");
                    var response = new LoginResponseModel
                    {
                        IsLockedOut       = result.IsLockedOut,
                        IsNotAllowed      = result.IsNotAllowed,
                        RequiresTwoFactor = result.RequiresTwoFactor,
                        Result            = ApiResult.AsError("Login Failed")
                    };
                    return(BadRequest(response));
                }
            }
            else
            {
                return(BadRequest(ApiModel.AsError("model validation failed (TODO add the errors)")));
            }
        }
Exemplo n.º 5
0
        public async Task <IActionResult> Login([FromBody] LoginModel model)
        {
            // Hack to work around rc1 bug
            await HttpContext.SignOutAsync(IdentityConstants.ExternalScheme);

            if (!ModelState.IsValid)
            {
                return(BadRequest(this.ModelState.AsApiModel(model)));
            }

            var result = await this.signInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberLogin, lockoutOnFailure : true);

            if (result.Succeeded)
            {
                this.logger.LogInformation(1, "User logged in.");
                return(Ok(ApiModel.AsSuccess(model)));
            }
            else
            {
                this.logger.LogWarning(2, "User login failed.");
                model.IsLockedOut       = result.IsLockedOut;
                model.IsNotAllowed      = result.IsNotAllowed;
                model.RequiresTwoFactor = result.RequiresTwoFactor;
                return(this.BadRequest(ApiModel.AsError(model, "Login failed")));
            }
        }
        // [ValidateAntiForgeryToken]
        public async Task <IActionResult> PatchAsync([FromBody] JsonPatchDocument <UserDto> patch, CancellationToken cancellationToken = default(CancellationToken))
        {
            var patched = _mapper.Map <JsonPatchDocument <User> >(patch);

            var username = HttpContext.User.Identity.Name;

            if (string.IsNullOrEmpty(username))
            {
                return(Ok(ApiModel.AsError <AccountDto>(null, "no user claims in request, did you forget to set the auth header ?")));
            }

            var user = await _userManager.FindByNameAsync(username);

            if (user == null)
            {
                return(Ok(ApiModel.AsError <AccountDto>(null, $"impossible to find a user with the username '{username}'")));
            }

            patched.ApplyTo(user);
            await _userManager.UpdateAsync(user);

            var dto = _mapper.Map <UserDto>(user);

            return(Ok(ApiModel.AsSuccess(dto)));
        }
        public async Task <IActionResult> ChargeAsync([FromServices] PayPalPaymentProvider provider, [FromBody] PayPalChargeBindings bindings, CancellationToken cancellationToken = default(CancellationToken))
        {
            try
            {
                var order = await provider.ChargeAsync(bindings, cancellationToken);

                return(Ok(ApiModel.AsSuccess(order.Payments)));
            }
            catch (AppException AppException)
            {
                return(Ok(ApiModel.AsError(AppException)));
            }
        }
Exemplo n.º 8
0
        public ActionResult XsrfRefresh()
        {
            var tokens = this.antiForgery.GetAndStoreTokens(this.HttpContext);

            if (string.IsNullOrWhiteSpace(tokens.RequestToken))
            {
                return(BadRequest(ApiModel.AsError(new XsrfModel {
                    XsrfToken = null
                }, "Error getting XSRF token")));
            }

            return(Ok(ApiModel.AsSuccess(new XsrfModel {
                XsrfToken = tokens.RequestToken
            })));
        }
Exemplo n.º 9
0
        public async Task <ActionResult> Action([FromBody] dynamic actionData)
        {
            var action = ActionHelper.ConstructTypedAction(actionData);

            if (action != null)
            {
                // We can send the action directly, or send it via a stream
                var grain = this.grainClient.GetGrain <ICounterGrain>(this.sessionId);
                await grain.Process(action);

                return(this.Ok());
            }

            return(this.BadRequest(ApiModel.AsError("invalid action")));
        }
Exemplo n.º 10
0
        // [ValidateAntiForgeryToken]
        public virtual async Task <IActionResult> PatchAsync(string id, [FromBody] JsonPatchDocument <TModelDto> patch, CancellationToken cancellationToken = default(CancellationToken))
        {
            var patched = _mapper.Map <JsonPatchDocument <TModel> >(patch);
            var result  = await service.GetByIdAsync(id, cancellationToken);

            if (result == null)
            {
                return(Ok(ApiModel.AsError(id, $"impossible to find ${typeof(TModel).Name} width id: ${id}")));
            }

            patched.ApplyTo(result);

            await service.UpdateAsync(result, cancellationToken);

            var dto = _mapper.Map <TModelDto>(result);

            return(Ok(ApiModel.AsSuccess(dto)));
        }
        // [ValidateAntiForgeryToken]
        public async Task <IActionResult> BalanceAsync([FromRoute] string id, CancellationToken cancellationToken = default(CancellationToken))
        {
            var username = HttpContext.User.Identity.Name;

            if (string.IsNullOrEmpty(username))
            {
                return(Ok(ApiModel.AsError <AccountDto>(null, "no user claims in request, did you forget to set the auth header ?")));
            }

            var user = await userManager.FindByNameAsync(username);

            if (user == null)
            {
                return(Ok(ApiModel.AsError <AccountDto>(null, $"impossible to find a user with the username '{username}'")));
            }
            var filter  = Filter.And(Filter.Eq("Archived", false), Filter.Eq("ShopId", id));
            var results = await service.FindAsync(filter, cancellationToken : cancellationToken);

            foreach (var group in results.GroupBy(m => m.Currency))
            {
                var amount = -group.Sum(m => m.Amount);
                if (amount == 0)
                {
                    continue;
                }

                var result = await service.NewAsync(cancellationToken);

                result.UserId   = user.Id;
                result.User     = user.Preview();
                result.Currency = group.Key;
                result.ShopId   = id;
                result.Amount   = -group.Sum(m => m.Amount);
                result.Archived = true;
                await service.CreateAsync(result, cancellationToken);

                foreach (var m in group)
                {
                    m.Archived = true;
                    await service.UpdateAsync(m, cancellationToken);
                }
            }
            return(Ok(ApiModel.AsSuccess(new { archived = results.Count() })));
        }
Exemplo n.º 12
0
        public async Task <IActionResult> SetupAsync([FromServices] User user, [FromBody] SetupBindings bindings, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (_userManager.Users.Any())
            {
                return(Ok(ApiModel.AsError <string>("setup", "setup only available when no users in DB")));
            }
            user.UserName = bindings.UserName;
            user.Roles    = new string[] { RoleStore.ADMIN };
            if (bindings.Patch != null)
            {
                var patched = _mapper.Map <JsonPatchDocument <User> >(bindings.Patch);
                patched.ApplyTo(user);
            }


            var result = await _userManager.CreateAsync(user, bindings.Password);

            // TODO: do we have to log ?
            return(Ok(ApiModel.FromIdentityResult <UserDto>(result.Succeeded ? _mapper.Map <UserDto>(user) : null, result)));
        }
        // [ValidateAntiForgeryToken]
        public override async Task <IActionResult> PostAsync([FromBody] MovementDto modelDto, CancellationToken cancellationToken = default(CancellationToken))
        {
            var username = HttpContext.User.Identity.Name;

            if (string.IsNullOrEmpty(username))
            {
                return(Ok(ApiModel.AsError <AccountDto>(null, "no user claims in request, did you forget to set the auth header ?")));
            }

            var user = await userManager.FindByNameAsync(username);

            if (user == null)
            {
                return(Ok(ApiModel.AsError <AccountDto>(null, $"impossible to find a user with the username '{username}'")));
            }

            modelDto.UserId = user.Id;
            modelDto.User   = user.Preview();
            return(await base.PostAsync(modelDto, cancellationToken));
        }
Exemplo n.º 14
0
        // [ValidateAntiForgeryToken]
        public async Task <IActionResult> AuthenticateAsync([FromBody] AuthenticateBindings userDto, string returnUrl = null)
        {
            var username = _userManager.NormalizeKey(userDto.UserName);

            var result = await _signInManager.PasswordSignInAsync(username,
                                                                  userDto.Password, userDto.RememberMe, lockoutOnFailure : false);

            if (result.Succeeded)
            {
                var user = await _userManager.FindByNameAsync(username);

                if (user == null)
                {
                    throw new AppException($"impossible to find the user {userDto.UserName} after successfull login using this username");
                }

                _logger.LogInformation("User logged in.");

                var resultDto = _mapper.Map <AccountDto>(user);
                resultDto.Token = await _GenerateTokenAsync(user);

                resultDto.IsAuthenticated = true;

                return(Ok(ApiModel.AsSuccess(resultDto)));
            }
            if (result.RequiresTwoFactor)
            {
                return(RedirectToAction(nameof(LoginWith2fa), new { returnUrl, userDto.RememberMe }));
            }
            if (result.IsLockedOut)
            {
                _logger.LogWarning("User account locked out.");

                return(Ok(ApiModel.AsError(userDto, "User account locked out.")));
            }
            else
            {
                ModelState.AddModelError(string.Empty, "Invalid login attempt.");
                return(Ok(ApiModel.AsError(userDto, "Invalid login attempt.")));
            }
        }
Exemplo n.º 15
0
        // [AllowAnonymous]
        // [ValidateAntiForgeryToken]
        public async Task <IActionResult> ResetPassword([FromBody] ResetPasswordBindings bindings)
        {
            var id           = bindings.Id;
            var resetFormURL = bindings.resetFormURL ?? "";
            // TODO: validate model here or with a filter ?
            // TODO: do we really need the email confirmation ?
            var user = await _userManager.FindByIdAsync(id);

            if (user == null) // || !(await _userManager.IsEmailConfirmedAsync(user))
            {
                _logger.LogWarning("Invalid forgot password attempt.");

                // Don't reveal that the user does not exist or is not confirmed
                return(Ok(ApiModel.AsError <string>(null, "user does not exist")));
            }

            // For more information on how to enable account confirmation and password reset please
            // visit https://go.microsoft.com/fwlink/?LinkID=532713
            var code = await _userManager.GeneratePasswordResetTokenAsync(user);

            var values = new { id = user.Id, code = code };

            var callbackUrl = Url.Action(
                action: nameof(AccountController.ResetPassword),
                controller: nameof(AccountController).ToLowerInvariant().Replace("controller", ""),
                values: values,
                protocol: Request.Scheme,
                host: Request.Host.Value);

            var encodedCallback = WebUtility.UrlEncode(callbackUrl);
            var link            = $"{resetFormURL}?action={encodedCallback}";
            var result          = new ResetPasswordResult {
                Id = id, Code = code, Link = link, Username = user.UserName
            };

            result.sent = bindings.email && await _emailSender.SendEmailAsync(user.Email, "Reset Password",
                                                                              $"Please reset your password by clicking here: <a href='{link}'>link</a>");

            return(Ok(ApiModel.AsSuccess <ResetPasswordResult>(result)));
        }
Exemplo n.º 16
0
        // [ValidateAntiForgeryToken]
        public async Task <IActionResult> ForgotPassword([FromBody] ForgotPasswordBindings bindings, [FromQuery] string resetFormURL = "")
        {
            // TODO: validate model here or with a filter ?
            // TODO: do we really need the email confirmation ?
            var user = await _userManager.FindByNameAsync(bindings.UserName);

            if (user == null) // || !(await _userManager.IsEmailConfirmedAsync(user))
            {
                _logger.LogWarning("Invalid forgot password attempt.");

                // Don't reveal that the user does not exist or is not confirmed
                return(Ok(ApiModel.AsSuccess <UserDto>(null)));
            }

            // For more information on how to enable account confirmation and password reset please
            // visit https://go.microsoft.com/fwlink/?LinkID=532713
            var code = await _userManager.GeneratePasswordResetTokenAsync(user);

            var callbackUrl = Url.Action(
                action: nameof(AccountController.ResetPassword),
                controller: nameof(AccountController).ToLowerInvariant().Replace("controller", ""),
                values: new { id = user.Id, code = code },
                protocol: Request.Scheme,
                host: Request.Host.Value);

            var encodedCallback = WebUtility.UrlEncode(callbackUrl);

            var sendResult = await _emailSender.SendEmailAsync(user.Email, "Reset Password",
                                                               $"Please reset your password by clicking here: <a href='{resetFormURL}?action={encodedCallback}'>link</a>");

            if (sendResult)
            {
                return(Ok(ApiModel.AsSuccess <UserDto>(null)));
            }
            else
            {
                return(Ok(ApiModel.AsError <UserDto>(null, "impossible to send reset password link by email")));
            }
        }
Exemplo n.º 17
0
        // [ValidateAntiForgeryToken]
        public async Task <IActionResult> ChangePassword([FromBody] ChangePasswordBindings bindings)
        {
            var username = HttpContext.User.Identity.Name;

            if (string.IsNullOrEmpty(username))
            {
                return(Ok(ApiModel.AsError <AccountDto>(null, "no user claims in request, did you forget to set the auth header ?")));
            }

            var user = await _userManager.FindByNameAsync(username);

            if (user == null)
            {
                return(Ok(ApiModel.AsError <AccountDto>(null, $"impossible to find a user with the username '{username}'")));
            }

            var result = await _userManager.ChangePasswordAsync(user, bindings.currentPassword, bindings.newPassword);

            var userDto = _mapper.Map <AccountDto>(user);

            return(Ok(ApiModel.FromIdentityResult <AccountDto>(userDto, result)));
        }
Exemplo n.º 18
0
        // [ValidateAntiForgeryToken]
        public async Task <IActionResult> ResetPassword(
            [FromQuery] string id,
            [FromQuery] string code,
            [FromQuery] string password
            )
        {
            // TODO: validate model here or with a filter ?

            var user = await _userManager.FindByIdAsync(id);

            if (user == null)
            {
                _logger.LogWarning("Invalid reset password attempt.");

                // Don't reveal that the user does not exist or is not confirmed
                return(Ok(ApiModel.AsError <UserDto>(null)));
            }

            var result = await _userManager.ResetPasswordAsync(user, code, password);

            return(Ok(ApiModel.FromIdentityResult <UserDto>(result.Succeeded ? _mapper.Map <UserDto>(user) : null, result)));
        }
        public async Task <IActionResult> RegisterAsync([FromServices] UserManager userManager, [FromBody] RegisterBindings bindings, CancellationToken cancellationToken = default(CancellationToken))
        {
            var order = await this.orderService.GetByIdAsync(bindings.OrderID, cancellationToken);

            var toPay      = order.Total - order.PaidAmount;
            var rateAmount = order.Currency == bindings.AmountCurrency ? 1 : configuration.GetRate(bindings.AmountCurrency, order.Currency);
            var rateChange = order.Currency == bindings.ChangeCurrency ? 1 : configuration.GetRate(bindings.ChangeCurrency, order.Currency);
            var amount     = bindings.Amount * rateAmount;
            var change     = bindings.Change * rateChange;

            var payment = new Payment()
            {
                Title     = "Cash Payment",
                Provider  = Name,
                Reference = $"{User.Identity.Name}",
                Status    = PaymentStatus.Paid,
                Date      = DateTime.UtcNow,
                Method    = PaymentMethod.Cash,
                Details   = $"Payment Order #{order.Reference}",
                Currency  = bindings.AmountCurrency,
                Amount    = amount - change
            };

            var username = HttpContext.User.Identity.Name;

            if (string.IsNullOrEmpty(username))
            {
                return(Ok(ApiModel.AsError <ChangeResponse>(null, "no user claims in request, did you forget to set the auth header ?")));
            }

            var user = await userManager.FindByNameAsync(username);

            if (user == null)
            {
                return(Ok(ApiModel.AsError <ChangeResponse>(null, $"impossible to find a user with the username '{username}'")));
            }

            await orderService.AddPayment(order, payment, cancellationToken);

            if (bindings.Change != 0)
            {
                await movementService.CreateAsync(new Movement()
                {
                    Currency = bindings.ChangeCurrency,
                    Amount   = -1 * bindings.Change,
                    User     = user.Preview(),
                    UserId   = user.Id,
                    Date     = DateTime.UtcNow,
                    ShopId   = order.ShopId
                },
                                                  cancellationToken);
            }

            if (bindings.Amount != 0)
            {
                await movementService.CreateAsync(new Movement()
                {
                    Currency = bindings.AmountCurrency,
                    Amount   = bindings.Amount,
                    User     = user.Preview(),
                    UserId   = user.Id,
                    Date     = DateTime.UtcNow,
                    ShopId   = order.ShopId
                },
                                                  cancellationToken);
            }


            return(Ok(ApiModel.AsSuccess(
                          payment
                          )));
        }