/// <summary>
        /// Get new token
        /// </summary>
        /// <param name="username">login</param>
        /// <returns>token</returns>
        private async Task <string> GetToken(string username)
        {
            int userId = await _appDbContext.FindByLogin(username);

            var identity = await _authorizationManager.GetIdentity(username, userId);

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

            _log.LogInfo("Set token options.");
            var now = DateTime.Now;

            var jwt = new JwtSecurityToken(
                issuer: AuthorizationOptions.Issuer,
                audience: AuthorizationOptions.Audience,
                notBefore: now,
                claims: identity.Claims,
                expires: now.Add(TimeSpan.FromMinutes(AuthorizationOptions.Lifetime)),
                signingCredentials: new SigningCredentials(AuthorizationOptions.GetSymmetricSecurityKey(), SecurityAlgorithms.HmacSha256));
            var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt);

            _log.LogInfo("Set session options.");
            Sessions start = new Sessions()
            {
                Token       = encodedJwt,
                UserId      = userId,
                ExpiredDate = now.Add(TimeSpan.FromMinutes(AuthorizationOptions.Lifetime))
            };

            _log.LogInfo("Check for previous session.");
            if (await _appDbContext.IsExistPreviousSession(userId))
            {
                _log.LogInfo("The session was founded. I`ll delete it.");
                await _appDbContext.DeleteSessions(userId);

                _log.LogInfo("Success delete.");
            }

            _log.LogInfo("Add session");
            await _appDbContext.AddSession(start);

            _log.LogInfo("Session was add.");

            _log.LogInfo("Return session's token");
            return(encodedJwt);
        }
        /// <summary>
        /// Get identity by credentials
        /// </summary>
        /// <param name="userLogin">user's login</param>
        /// <param name="password">user's password</param>
        /// <returns>user</returns>
        public async Task <ClaimsIdentity> GetClaimsIdentity(string userLogin, string password)
        {
            if (string.IsNullOrEmpty(userLogin) || string.IsNullOrEmpty(password))
            {
                return(null);
            }

            var userToVerify = await _appDbContext.FindByLogin(userLogin);

            if (userToVerify == 0)
            {
                return(null);
            }

            if (await _appDbContext.CheckPassword(password, userToVerify))
            {
                return(await GetIdentity(userLogin, userToVerify));
            }

            return(null);
        }
        public async Task <IActionResult> Registration(UsersData userData, Secrets userSecrets)
        {
            _log.LogInfo("Get userData for registration.");
            if (!ModelState.IsValid)
            {
                _log.LogError("Incorrect input.");
                return(BadRequest(ModelState));
            }

            _log.LogInfo("Check is password safe.");
            try
            {
                if (PasswordManager.ValidatePassword(userSecrets.Password))
                {
                    _log.LogInfo("Safety of password is good.");

                    _log.LogInfo("Check is it a new user.");
                    if (!await _appDbContext.IsUserExist(userData.Email))
                    {
                        using (SqlConnection connection =
                                   new SqlConnection("Data Source=JULIKROP\\SQLEXPRESS;Initial Catalog=EHospital;Integrated Security=True"))
                        {
                            connection.Open();
                            using (var transaction = connection.BeginTransaction())
                            {
                                try
                                {
                                    _log.LogInfo("Add default role.");
                                    await _appDbContext.AddRoles(new Roles
                                                                 { Id = (int)UsersRoles.NoRole, Title = UsersRoles.NoRole.ToString() });

                                    _log.LogInfo("Add login.");
                                    await _appDbContext.AddLogin(new Logins { Login       = userData.Email,
                                                                              RegisterKey = emailSender.GenerateKey(), Status = "New" });

                                    _log.LogInfo("Add user's userData");
                                    await _appDbContext.AddUserData(new UsersData
                                    {
                                        FirstName   = userData.FirstName,
                                        LastName    = userData.LastName,
                                        BirthDate   = userData.BirthDate,
                                        PhoneNumber = userData.PhoneNumber,
                                        Country     = userData.Country,
                                        City        = userData.City,
                                        Adress      = userData.Adress,
                                        Gender      = userData.Gender,
                                        Email       = userData.Email
                                    });

                                    _log.LogInfo("Add password.");
                                    await _appDbContext.AddSecrets(new Secrets { Password = userSecrets.Password });

                                    transaction.Commit();
                                }
                                catch (Exception ex)
                                {
                                    _log.LogError("Account is not created." + ex.Message);
                                    transaction.Rollback();
                                    return(new BadRequestObjectResult("Creation of account was failed." + ex.Message));
                                }
                                finally
                                {
                                    transaction.Dispose();
                                }
                            }
                        }
                    }
                    else
                    {
                        _log.LogError("Account is not created.");
                        return(new BadRequestObjectResult("Creation of account was failed."));
                    }

                    string greetingText;

                    using (StreamReader streamreader = new StreamReader(@"..\EHospital.Authorization.WebAPI\Letters\greetings.txt"))
                    {
                        greetingText = streamreader.ReadToEnd();
                    }

                    _log.LogInfo("Send greetings.");
                    await emailSender.SendEmail(userData.Email, "Welcome to EHospital", greetingText);

                    int id = await _appDbContext.FindByLogin(userData.Email);

                    string key = await _appDbContext.GetRegisterKey(userData.Email);

                    var callbackUrl = $"{Request.Scheme}://{Request.Host}/authorization/api/Registration/Confirmation?userId={id}&token={key}";

                    _log.LogInfo("Send confirmation");
                    await emailSender.SendEmail(userData.Email, "Confirm the registration",
                                                $"Confirm the registration by clicking the following link: <a href='{callbackUrl}'>confirm</a>");

                    _log.LogInfo("Account created");
                    Task.WaitAll();
                    return(new OkObjectResult("Account created. We sent letter on your email.Confirm it. If you don`t see the letter, please, check the spam."));
                }

                _log.LogError("Account is not created.");
                return(new BadRequestObjectResult("Creation of account was failed."));
            }
            catch (ArgumentException ex)
            {
                _log.LogError("Account is not created." + ex.Message);
                return(new BadRequestObjectResult("Creation of account was failed." + ex.Message));
            }
        }