Ejemplo n.º 1
0
        public async Task <Response <string> > Registration(RegistrationDto registrationDto)
        {
            var response = new Response <string>();

            if (_context.Users.Any(u => u.UserName == registrationDto.UserName))
            {
                response.Error = new Error($"User with email {registrationDto.Email} already exist. Please sign in");
                return(response);
            }

            if (_context.Users.Any(u => u.UserName == registrationDto.UserName))
            {
                response.Error = new Error($"User with username {registrationDto.UserName} already exist");
                return(response);
            }



            var user = new ApplicationUser()
            {
                Email     = registrationDto.Email,
                FirstName = registrationDto.FirstName,
                LastName  = registrationDto.LastName,
                UserName  = registrationDto.UserName
            };

            if (!await _context.Users.AnyAsync())
            {
                registrationDto.Role = Role.Admin;
            }

            if (!await _roleManager.RoleExistsAsync(registrationDto.Role.ToString()))
            {
                await _roleManager.CreateAsync(new IdentityRole(registrationDto.Role.ToString()));
            }

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

            if (result.Errors != null && result.Errors.Any())
            {
                response.Error = new Error(result.Errors.Select(e => e.Description).Aggregate((a, b) => a + b));
                return(response);
            }
            await _userManager.AddToRoleAsync(user, registrationDto.Role.ToString());

            var token = new EmailToken()
            {
                UserId = user.Id,
                Token  = Guid.NewGuid()
            };

            await _context.EmailTokens.AddAsync(token);

            await _context.SaveChangesAsync();

            await _emailService.SendConfirmLetter(token.Token.ToString(), user.Id, user.Email);

            response.Data = user.Id;
            return(response);
        }
Ejemplo n.º 2
0
        ////////////////////////////////////////////////////////////////////////////////
        // New method of validating email verification token
        ////////////////////////////////////////////////////////////////////////////////
        private bool isConfirmedUsingNewMethod(EmailToken emailToken, ApplicationUser appUser, string tokenValue)
        {
            Console.WriteLine("[" + DateTime.Now.ToString("MM/dd/yyyy HH:mm:ss") + "][ConfirmEmailService][isConfirmedUsingNewMethod] => BEGIN tokenValue: ");
            Console.WriteLine("'" + tokenValue + "'");
            Console.WriteLine("[" + DateTime.Now.ToString("MM/dd/yyyy HH:mm:ss") + "][ConfirmEmailService][isConfirmedUsingNewMethod] => :END tokenValue");

            Console.WriteLine("");

            Console.WriteLine("[" + DateTime.Now.ToString("MM/dd/yyyy HH:mm:ss") + "][ConfirmEmailService][isConfirmedUsingNewMethod] => BEGIN EmailToken.TokenValue: ");
            Console.WriteLine("'" + emailToken.TokenValue + "'");
            Console.WriteLine("[" + DateTime.Now.ToString("MM/dd/yyyy HH:mm:ss") + "][ConfirmEmailService][isConfirmedUsingNewMethod] => :END EmailToken.TokenValue");

            if (emailToken.TokenValue.Equals(tokenValue))
            {
                Console.WriteLine("[" + DateTime.Now.ToString("MM/dd/yyyy HH:mm:ss")
                                  + "][ConfirmEmailService][isConfirmedUsingNewMethod] => Email tokens ARE EQUAL - setting EmailConfirmed column to TRUE in AspNetUsers table.");

                appUser.EmailConfirmed = true;
                _dbContext.ApplicationUsers.Update(appUser);
                _dbContext.SaveChanges();

                Console.WriteLine("[" + DateTime.Now.ToString("MM/dd/yyyy HH:mm:ss")
                                  + "][ConfirmEmailService][isConfirmedUsingNewMethod] => Email tokens ARE EQUAL - returning TRUE");
                return(true);
            }

            Console.WriteLine("[" + DateTime.Now.ToString("MM/dd/yyyy HH:mm:ss")
                              + "][ConfirmEmailService][isConfirmedUsingNewMethod] => Email tokens ARE NOT EQUAL - returning FALSE");

            return(false);
        }
Ejemplo n.º 3
0
        public async Task SendRegisterEmail(Account account)
        {
            if (_registerRequest == null)
            {
                return;
            }

            var emailToken = new EmailToken(Guid.NewGuid().ToString(), false, DateTime.Now.AddMinutes(10), account);

            _context.emailtokens.Add(emailToken);
            _context.SaveChanges();

            var    client           = new SendGridClient(_configuration.GetValue <string>("SendGridAPI_KEY"));
            var    from             = new EmailAddress("*****@*****.**", "AuthAPI Oblonsek");
            var    to               = new EmailAddress(_registerRequest.Email);
            string subject          = "AuthAPI confirmation email";
            string plainTextContent = $"Welcome to AuthAPI, please click on the following link to confirm your email - http://localhost:5000/api/auth/confirm/{emailToken.ConfirmationToken}";
            string htmlContent      = $"Welcome to AuthAPI, please click on the following link to confirm your email - <a href='http://localhost:5000/api/auth/confirm/{emailToken.ConfirmationToken}' target='_blank'>LINK</a>";
            var    message          = MailHelper.CreateSingleEmail(
                from: from,
                to: to,
                subject: subject,
                plainTextContent: plainTextContent,
                htmlContent: htmlContent
                );

            var response = await client.SendEmailAsync(message);
        }
Ejemplo n.º 4
0
    /// <summary>
    /// Asynchronously sends an e-mail through the SMTP server.
    /// </summary>
    /// <param name="siteName">Site name</param>
    /// <param name="message">E-mail message</param>
    /// <param name="smtpServer">SMTP server</param>
    /// <param name="emailToken">E-mail token that represents the message being sent</param>
    protected override void SendEmailAsyncInternal(string siteName, MailMessage message, SMTPServerInfo smtpServer, EmailToken emailToken)
    {
        base.SendEmailAsyncInternal(siteName, message, smtpServer, emailToken);

        string detail = string.Format("E-mail from {0} through {1} was dispatched (asynchronously)", message.From.Address, smtpServer.ServerName);

        EventLogProvider.LogInformation("CMSCustom", "MyCustomEmailProvider", detail);
    }
Ejemplo n.º 5
0
    /// <summary>
    /// Asynchronously sends an email through the SMTP server.
    /// </summary>
    /// <param name="siteName">Site name</param>
    /// <param name="message">Email message</param>
    /// <param name="smtpServer">SMTP server</param>
    /// <param name="emailToken">Email token that represents the message being sent</param>   
    protected override void SendEmailAsyncInternal(string siteName, MailMessage message, SMTPServerInfo smtpServer, EmailToken emailToken)
    {
        //Send the email via SendGrid
        SendSendGridEmail(message);

        CustomCompletedEventArgs args = new CustomCompletedEventArgs(null, false, emailToken);
        OnSendCompleted(args);
    }
 protected override void SendEmailAsyncInternal(string siteName, MailMessage message, SMTPServerInfo smtpServer,
                                                EmailToken emailToken)
 {
     ThreadPool.QueueUserWorkItem(userData =>
     {
         CMSThread.AllowEmptyContext();
         DispatchSendGridEmail(message, true, emailToken);
     });
 }
Ejemplo n.º 7
0
        public void ClientEvent_OnSubmitNewVerificationEmail(Client client, string newEmail)
        {
            if (!client.IsLoggedIn(true))
            {
                client.TriggerEvent(Events.ServerToClient.Authentication.DisplayError, AccountStrings.ErrorPlayerNotLoggedIn);
                return;
            }

            if (!ValidateString(ValidationStrings.EmailAddress, newEmail))
            {
                client.TriggerEvent(Events.ServerToClient.Authentication.DisplayError, AccountStrings.ErrorEmailInvalid);
                return;
            }

            if (client.GetAccount().HasVerifiedEmail())
            {
                client.TriggerEvent(Events.ServerToClient.Authentication.DisplayError, AccountStrings.ErrorEmailAlreadyVerified);
                return;
            }
            TaskManager.Run(client, async() =>
            {
                if (await AccountModel.IsEmailTakenAsync(newEmail))
                {
                    client.TriggerEvent(Events.ServerToClient.Authentication.DisplayError, AccountStrings.ErrorEmailTaken);
                    return;
                }
                if (await EmailToken.IsEmailTakenAsync(newEmail))
                {
                    client.TriggerEvent(Events.ServerToClient.Authentication.DisplayError, AccountStrings.ErrorEmailTokenAddressTaken);
                    return;
                }

                var accData = client.GetAccount();
                var accTok  = await EmailToken.FetchAsync(accData);

                if (accTok != null)
                {
                    if (accTok.EmailAddress == newEmail)
                    {
                        client.TriggerEvent(Events.ServerToClient.Authentication.ShowChangeEmailAddress);
                        client.TriggerEvent(Events.ServerToClient.Authentication.DisplayError, AccountStrings.ErrorChangeVerificationEmailDuplicate);
                        return;
                    }
                    await EmailToken.ChangeEmailAsync(client.GetAccount(), newEmail);
                    await EmailToken.SendEmail(client.GetAccount());
                }
                else
                { // Handles the case where there's no token entry in the database
                    await EmailToken.CreateAsync(accData, newEmail);
                    await EmailToken.SendEmail(accData);
                }
                client.TriggerEvent(Events.ServerToClient.Authentication.ShowInitialEmailVerification);
                client.SendChatMessage(AccountStrings.SuccessChangeVerificationEmailAddress);
            });
        }
Ejemplo n.º 8
0
        public void ClientEvent_OnSubmitRegisterAccount(Client client, string username, string emailAddress, string password)
        {
            if (client.IsLoggedIn(true))
            {
                client.TriggerEvent(Events.ServerToClient.Authentication.DisplayError, AccountStrings.ErrorPlayerAlreadyLoggedIn);
                return;
            }
            if (!ValidateString(ValidationStrings.Username, username))
            {
                client.TriggerEvent(Events.ServerToClient.Authentication.DisplayError, AccountStrings.ErrorUsernameInvalid);
                return;
            }
            if (!ValidateString(ValidationStrings.Password, password))
            {
                client.TriggerEvent(Events.ServerToClient.Authentication.DisplayError, AccountStrings.ErrorPasswordInvalid);
                return;
            }
            if (!ValidateString(ValidationStrings.EmailAddress, emailAddress))
            {
                client.TriggerEvent(Events.ServerToClient.Authentication.DisplayError, AccountStrings.ErrorEmailInvalid);
                return;
            }
            TaskManager.Run(client, async() =>
            {
                if (await AccountModel.ExistsAsync(username))
                {
                    client.TriggerEvent(Events.ServerToClient.Authentication.DisplayError, AccountStrings.ErrorUsernameTaken);
                    return;
                }
                if (await AccountModel.IsEmailTakenAsync(emailAddress))
                { // Another account with the that email address
                    client.TriggerEvent(Events.ServerToClient.Authentication.DisplayError, AccountStrings.ErrorEmailTaken);
                    return;
                }
                if (await EmailToken.IsEmailTakenAsync(emailAddress))
                { // Another account in the list of email tokens with that address
                    client.TriggerEvent(Events.ServerToClient.Authentication.DisplayError, AccountStrings.ErrorEmailTokenAddressTaken);
                    return;
                }

                await AccountModel.CreateAsync(username, password, client.SocialClubName);
                var newAcc = await AccountModel.FetchAsync(username);
                await EmailToken.CreateAsync(newAcc, emailAddress);
                await EmailToken.SendEmail(newAcc);

                client.TriggerEvent(Events.ServerToClient.Authentication.RegistrationSuccess, AccountStrings.SuccessRegistration);
            });
        }
Ejemplo n.º 9
0
        public void ClientEvent_OnSubmitEmailToken(Client client, string token)
        {
            if (!client.IsLoggedIn(true))
            {
                client.TriggerEvent(Events.ServerToClient.Authentication.DisplayError, AccountStrings.ErrorPlayerNotLoggedIn);
                return;
            }

            if (!ValidateString(ValidationStrings.EmailVerificationCode, token))
            {
                client.TriggerEvent(Events.ServerToClient.Authentication.DisplayError, AccountStrings.ErrorInvalidVerificationCode);
                return;
            }
            TaskManager.Run(client, async() =>
            {
                var accData = client.GetAccount();

                if (!accData.HasVerifiedEmail())
                {
                    return;
                }

                if (!accData.Is2FAbyEmailEnabled())
                {
                    client.TriggerEvent(Events.ServerToClient.Authentication.DisplayError, AccountStrings.TwoFactorByEmailIsNotEnabled);
                    return;
                }

                if (!await EmailToken.ValidateAsync(accData, token))
                {
                    client.TriggerEvent(Events.ServerToClient.Authentication.DisplayError, AccountStrings.ErrorInvalidVerificationCode);
                    return;
                }

                accData.HasPassedTwoStepByEmail = true;

                if (accData.Is2FAbyGAEnabled() && !accData.HasPassedTwoStepByGA)
                {
                    client.TriggerEvent(Events.ServerToClient.Authentication.Show2FAbyGoogleAuth, AccountStrings.VerifyTwoFactorByGA);
                    return;
                }
                SetLoginState(client, false);
            });
        }
Ejemplo n.º 10
0
        public void ClientEvent_OnSubmitResendEmail(Client client)
        {
            if (!client.IsLoggedIn(true))
            {
                client.TriggerEvent(Events.ServerToClient.Authentication.DisplayError, AccountStrings.ErrorPlayerNotLoggedIn);
                return;
            }

            TaskManager.Run(client, async() =>
            {
                if (!await EmailToken.ExistsAsync(client.GetAccount()))
                {
                    client.TriggerEvent(Events.ServerToClient.Authentication.DisplayError, "Error No Token for that Account");
                    return;
                }
                await EmailToken.SendEmail(client.GetAccount());
                client.SendChatMessage(AccountStrings.SuccessResendVerificationEmail);
            });
        }
Ejemplo n.º 11
0
        public bool IsConfirmed(ApplicationUser appUser, string tokenValue)
        {
            Console.WriteLine("[" + DateTime.Now.ToString("MM/dd/yyyy HH:mm:ss") + "][ConfirmEmailService][IsConfirmed] => ApplicationUser.Id: "
                              + (appUser.Id));
            Console.WriteLine("[" + DateTime.Now.ToString("MM/dd/yyyy HH:mm:ss") + "][ConfirmEmailService][IsConfirmed] => ApplicationUser.Email: "
                              + (appUser.Email));
            Console.WriteLine("[" + DateTime.Now.ToString("MM/dd/yyyy HH:mm:ss") + "][ConfirmEmailService][IsConfirmed] => tokenValue: '"
                              + tokenValue
                              + "'");

            ///////////////////////////////////////////////////////////////////////////
            // Attempt to validate the email verification token using the new method.
            //////////////////////////////////////////////////////////////////////////
            Console.WriteLine("[" + DateTime.Now.ToString("MM/dd/yyyy HH:mm:ss")
                              + "][ConfirmEmailService][IsConfirmed] => Calling _emailTokenRepo.Retrieve() ...");

            EmailToken emailToken = _emailTokenRepo.Retrieve(appUser.Id);

            Console.WriteLine("[" + DateTime.Now.ToString("MM/dd/yyyy HH:mm:ss")
                              + "][ConfirmEmailService][IsConfirmed] => EmailToken IS NULL: "
                              + (emailToken == null));

            if (emailToken == null)
            {
                //////////////////////////////////////////////////////////////////////////
                // EmailToken using the new method WAS NOT FOUND.
                // Attempt to validate email verification token
                // using the OLD method.
                //////////////////////////////////////////////////////////////////////////
                return(this.isConfirmedUsingOldMethod(appUser, tokenValue));
            }
            else
            {
                //////////////////////////////////////////////////////////////////////////
                // EmailToken using the new method WAS FOUND.
                // Attempt to validate email verification token
                // using the NEW method.
                //////////////////////////////////////////////////////////////////////////
                return(this.isConfirmedUsingNewMethod(emailToken, appUser, tokenValue));
            }
        }
Ejemplo n.º 12
0
        public void ClientEvent_OnSubmitFirstEmailToken(Client client, string providedToken)
        {
            if (!client.IsLoggedIn(true))
            {
                client.TriggerEvent(Events.ServerToClient.Authentication.DisplayError, AccountStrings.ErrorPlayerNotLoggedIn);
                return;
            }
            if (!ValidateString(ValidationStrings.EmailVerificationCode, providedToken))
            {
                client.TriggerEvent(Events.ServerToClient.Authentication.DisplayError, AccountStrings.ErrorInvalidVerificationCode);
                return;
            }
            if (client.GetAccount().HasVerifiedEmail())
            {
                client.TriggerEvent(Events.ServerToClient.Authentication.DisplayError, AccountStrings.ErrorEmailAlreadyVerified);
                return;
            }

            TaskManager.Run(client, async() =>
            {
                var accData  = client.GetAccount();
                var accToken = await EmailToken.FetchAsync(accData);
                var accEmail = accToken.EmailAddress;

                if (!await EmailToken.ValidateAsync(accData, providedToken))
                {
                    client.TriggerEvent(Events.ServerToClient.Authentication.DisplayError, AccountStrings.ErrorInvalidVerificationCode);
                    return;
                }

                accData.EmailAddress = accEmail;
                await accData.UpdateAsync();
                client.SendChatMessage(AccountStrings.SuccessEmailVerification);

                SetLoginState(client, false);
            });
        }
Ejemplo n.º 13
0
    /// <summary>
    /// Asynchronously sends an email through the SMTP server.
    /// </summary>
    /// <param name="siteName">Site name</param>
    /// <param name="message">Email message</param>
    /// <param name="smtpServer">SMTP server</param>
    /// <param name="emailToken">Email token that represents the message being sent</param>
    protected override void SendEmailAsyncInternal(string siteName, MailMessage message, SMTPServerInfo smtpServer, EmailToken emailToken)
    {
        //Send the email via SendGrid
        SendSendGridEmail(message);

        CustomCompletedEventArgs args = new CustomCompletedEventArgs(null, false, emailToken);

        OnSendCompleted(args);
    }
        private void DispatchSendGridEmail(MailMessage message, bool isAsync = false, EmailToken emailToken = null)
        {
            try
            {
                var client = new SendGridClient("Specify your SendGrid API key here");

                var messageForSendGrid = ConvertToSendGridMessage(message);
                var task   = client.SendEmailAsync(messageForSendGrid);
                var result = task.Result;

                if (result.StatusCode != HttpStatusCode.Accepted)
                {
                    var response = result.Body.ReadAsStringAsync();
                    var body     = response.Result;

                    throw new Exception(
                              $"Unsuccessful attempt to send email to {message.To}\nResponse Details.\nDateTime: {DateTime.Now}\nStatus code: {result.StatusCode}\nHeaders: {result.Headers}\nBody: {body}");
                }

                if (isAsync && emailToken != null)
                {
                    OnSendCompleted(new AsyncCompletedEventArgs(null, false, emailToken));
                }
            }
            catch (Exception exception)
            {
                EventLogProvider.LogException("SendGridEmailProvider", "DispatchSendGridEmail", exception);
                if (isAsync && emailToken != null)
                {
                    OnSendCompleted(new AsyncCompletedEventArgs(exception, false, emailToken));
                }
            }
        }
Ejemplo n.º 15
0
        public void ClientEvent_OnSubmitLoginAccount(Client client, string username, string password)
        {
            if (client.IsLoggedIn(true))
            {
                client.TriggerEvent(Events.ServerToClient.Authentication.DisplayError, AccountStrings.ErrorPlayerAlreadyLoggedIn);
                return;
            }
            if (!ValidateString(ValidationStrings.Username, username))
            {
                client.TriggerEvent(Events.ServerToClient.Authentication.DisplayError, AccountStrings.ErrorUsernameInvalid);
                return;
            }
            if (!ValidateString(ValidationStrings.Password, password))
            {
                client.TriggerEvent(Events.ServerToClient.Authentication.DisplayError, AccountStrings.ErrorPasswordInvalid);
                return;
            }
            TaskManager.Run(client, async() =>
            {
                if (!await AccountModel.ExistsAsync(username))
                {
                    client.TriggerEvent(Events.ServerToClient.Authentication.DisplayError, AccountStrings.ErrorUsernameNotExist);
                    return;
                }
                if (!await AccountModel.AuthenticateAsync(username, password))
                {
                    client.TriggerEvent(Events.ServerToClient.Authentication.DisplayError, AccountStrings.ErrorInvalidCredentials);
                    return;
                }

                var fetchedAcc = await AccountModel.FetchAsync(username);

                if (IsAccountLoggedIn(fetchedAcc))
                {
                    client.TriggerEvent(Events.ServerToClient.Authentication.DisplayError, AccountStrings.ErrorAccountAlreadyLoggedIn);
                    return;
                }

                await LoginAccount(fetchedAcc, client);

                if (!fetchedAcc.HasVerifiedEmail())
                {
                    client.TriggerEvent(Events.ServerToClient.Authentication.ShowInitialEmailVerification);
                    return;
                }
                if (fetchedAcc.Is2FAbyEmailEnabled())
                {
                    fetchedAcc.HasPassedTwoStepByEmail = false;
                    await EmailToken.CreateAsync(fetchedAcc, fetchedAcc.EmailAddress);
                    await EmailToken.SendEmail(fetchedAcc);
                    client.TriggerEvent(Events.ServerToClient.Authentication.Show2FAbyEmailAddress);
                    return;
                }
                if (fetchedAcc.Is2FAbyGAEnabled())
                {
                    fetchedAcc.HasPassedTwoStepByGA = false;
                    client.TriggerEvent(Events.ServerToClient.Authentication.Show2FAbyGoogleAuth);
                    return;
                }

                SetLoginState(client, false);
            });
        }
Ejemplo n.º 16
0
        private async void OnRemoveExpiredEmailTokens(object state)
        {
            await EmailToken.RemoveExpiredCodesAsync();

            Logger.GetInstance().ServerInfo("Removing expired email verification tokens from the database.");
        }
Ejemplo n.º 17
0
    /// <summary>
    /// Asynchronously sends an e-mail through the SMTP server.
    /// </summary>
    /// <param name="siteName">Site name</param>
    /// <param name="message">E-mail message</param>
    /// <param name="smtpServer">SMTP server</param>
    /// <param name="emailToken">E-mail token that represents the message being sent</param>
    protected override void SendEmailAsyncInternal(string siteName, MailMessage message, SMTPServerInfo smtpServer, EmailToken emailToken)
    {
        base.SendEmailAsyncInternal(siteName, message, smtpServer, emailToken);

        string detail = string.Format("E-mail from {0} through {1} was dispatched (asynchronously)", message.From.Address, smtpServer.ServerName);

        EventLogProvider.LogInformation("CMSCustom", "MyCustomEmailProvider", detail);
    }