Пример #1
0
        public async Task <ActionResult> GetUserByEmail([FromBody] EmailAddressRequest emailAddress)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var user = await _userService.GetUserByEmail(emailAddress.EmailAddress);

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

            return(Ok(user));
        }
        public EmailStatusList checkEmails(EmailAddressRequest request)
        {
            var emailStatusList = new EmailStatusList
            {
                deleted = new List <string> {
                    "*****@*****.**", "*****@*****.**"
                },
                existing = new List <string> {
                    "*****@*****.**", "*****@*****.**"
                },
                pending = new List <string> {
                    "*****@*****.**", "*****@*****.**"
                }
            };

            return(emailStatusList);
        }
        /// <summary>
        /// Sends email to create credentials (new/reset)
        /// </summary>
        /// <param name="args">Call arguments</param>
        /// <param name="appToken">Application token to access mail-service api</param>
        /// <param name="cancellationToken">A System.Threading.CancellationToken to observe while waiting for the task to complete</param>
        private async Task <SimpleOperationResult> SendMailTokenPasswordAsync(SendMailArgs args, string appToken, CancellationToken cancellationToken = default)
        {
            //TODO: Create libraty to consuming rsoft apis

            HttpClient client = new()
            {
                BaseAddress = new Uri(_apiOptions.Uri)
            };

            client.DefaultRequestHeaders.Add("User-Agent", "RSoft.Auth");
            client.DefaultRequestHeaders.Add("Authorization", $"bearer {appToken}");
            client.DefaultRequestHeaders.Add("Accepted-Language", CultureInfo.CurrentCulture.Name);

            RsMailRequest request = new()
            {
                From       = new EmailAddressRequest("*****@*****.**", "RSoft.Auth"),
                Subject    = args.FirstAccess ? _localizer["CREDENTIAL_FIRST_ACCESS_SUBJECT"] : _localizer["CREDENTIAL_RECOVERY_ACCESS_SUBJECT"],
                Content    = GetEmailBody(args.Name, "RSoft System", args.Token, args.ExpireOn, args.FirstAccess, args.UrlCredential),
                EnableHtml = true
            };

            request.To.Add(new EmailAddressRequest(args.Email, args.Name));

            StringContent content = new(JsonSerializer.Serialize(request, _jsonOptions), Encoding.UTF8, "application/json");
            IDictionary <string, string> errors = new Dictionary <string, string>();
            Guid requestId = Guid.Empty;

            HttpResponseMessage response = await client.PostAsync(_apiOptions.MailService, content, cancellationToken);

            bool success = response.IsSuccessStatusCode;

            if (!success)
            {
                string body = await response.Content.ReadAsStringAsync(cancellationToken);

                if (response.StatusCode == HttpStatusCode.BadRequest)
                {
                    IEnumerable <GenericNotification> notifications = JsonSerializer.Deserialize <IEnumerable <GenericNotification> >(body, _jsonOptions);
                    errors = notifications.ToDictionary(k => k.Property, v => v.Message);
                }
                else if (response.StatusCode == HttpStatusCode.Unauthorized)
                {
                    errors.Add("API SendMail", $"API SendMail | Unauthorized - {body}");
                }
                else if (response.StatusCode == HttpStatusCode.NotFound)
                {
                    errors.Add("API SendMail", $"API SendMail | Not Found");
                }
                else
                {
                    errors.Add("API SendMail", $"API SendMail | {response.StatusCode} - {body}");
                }
            }

            return(new SimpleOperationResult(success, errors));
        }

        /// <summary>
        /// Get e-mail body with action data and links
        /// </summary>
        /// <param name="userName">user name</param>
        /// <param name="serviceName">Client service name</param>
        /// <param name="token">Recovery token</param>
        /// <param name="tokenDeadLine">Token dead limte date/time</param>
        /// <param name="firstAccess">Is first access flag</param>
        /// <param name="urlCredential">Url to create/recovery credential pass by header parameter</param>
        private string GetEmailBody(string userName, string serviceName, Guid token, DateTime tokenDeadLine, bool firstAccess, string urlCredential)
        {
            string file            = Path.Combine(AppContext.BaseDirectory, "wwwroot", "assets", "credential-template.html");
            string templateContent = File.OpenText(file).ReadToEnd();

            string urlBase = string.IsNullOrWhiteSpace(urlCredential) ? new Uri(_pagesOptions.InputPassword).AbsoluteUri : urlCredential;

            string url = $"{urlBase}?type={(firstAccess ? "create" : "recovery")}&token={token}";

            string credentialAction = firstAccess ? _localizer["CREDENTIAL_CREATE"] : _localizer["CREDENTIAL_RECOVERY"];

            templateContent = templateContent.Replace("{CREDENTIAL_ACTION}", credentialAction);
            templateContent = templateContent.Replace("{CREDENTIAL_MAIL_BODY_OPEN_TEXT}", _localizer["CREDENTIAL_MAIL_BODY_OPEN_TEXT"]);
            templateContent = templateContent.Replace("{SERVICE_NAME}", serviceName);
            templateContent = templateContent.Replace("{USERNAME}", userName);
            templateContent = templateContent.Replace("{ACTION}", firstAccess ? _localizer["CREDENTIAL_ACTION_CREATE"] : _localizer["CREDENTIAL_ACTION_RECOVERY"]);
            templateContent = templateContent.Replace("{ACTION_PASSWORD}", firstAccess ? _localizer["CREDENTIAL_ACTION_CREATE_PASSWORD"] : _localizer["CREDENTIAL_ACTION_RECOVERY_PASSWORD"]);
            templateContent = templateContent.Replace("{CREDENTIAL_OR_ELSE_LINK}", _localizer["CREDENTIAL_OR_ELSE_LINK"]);
            templateContent = templateContent.Replace("{URL_CLIENT}", url);
            templateContent = templateContent.Replace("{BUTTON_LABEL}", firstAccess ? _localizer["CREDENTIAL_BUTTONL_LABEL_CREATE"] : _localizer["CREDENTIAL_BUTTONL_LABEL_RECOVERY"]);
            templateContent = templateContent.Replace("{CREDENTIAL_TOKEN_DEADLINE}", _localizer["CREDENTIAL_TOKEN_DEADLINE"]);

            //TODO: Need future manage DateTimeOffset
            templateContent = templateContent.Replace("{TOKEN_DEADLINE}", $"{tokenDeadLine.ToLocalTime().ToShortDateString()} {tokenDeadLine.ToLocalTime().ToShortTimeString()}");

            templateContent = templateContent.Replace("{CREDENTIAL_DISCARD_MESSAGE}", _localizer["CREDENTIAL_DISCARD_MESSAGE"]);

            return(templateContent);
        }