/// <summary>
        /// Creates or or adds a user with an external identityprovider using AuthWebSecurity
        /// </summary>
        /// <param name="provider">Name of Identity Provider</param>
        /// <param name="providerUserId">User Id provided by the Identity Provider</param>
        /// <param name="email">Username (aka email) of the userIdentity</param>
        /// <returns>A bool if the update has succeded or not</returns>
        public bool CreateOrUpdateOAuthAccount(string provider, string providerUserId, string email)
        {
            using (UsersContext db = new UsersContext())
            {
                Thinktecture.IdentityServer.Repositories.Sql.UserProfile user = db.UserProfiles.FirstOrDefault(u => u.Email.ToLower() == email.ToLower());
                // Check if user already exists
                if (user == null)
                {
                    // Insert name into the profile table
                    db.UserProfiles.Add(new Thinktecture.IdentityServer.Repositories.Sql.UserProfile { Email = email, IsDirty = true, IsVerified = true });
                }
                else if (user.OAuthMemberships.Count > 0)
                {
                    foreach (var OAuthProvider in user.OAuthMemberships)
                    {
                        if (OAuthProvider.Provider == provider)
                        {
                            return false;
                        }
                    }
                }
                else
                {
                    user.IsDirty = true;

                }
                db.SaveChanges();

                OAuthWebSecurity.CreateOrUpdateAccount(provider, providerUserId, email);
                return true;
            }

        }
 public void SetUserDirty(string email)
 {
     using (UsersContext db = new UsersContext())
     {
         var user = db.UserProfiles.FirstOrDefault(u => u.Email.ToLower() == email.ToLower());
         user.IsDirty = true;
         db.SaveChanges();
     }
 }
        /// <summary>
        /// Updates the user profile
        /// </summary>
        /// <param name="model">user profile model</param>
        public void Update(Thinktecture.IdentityServer.Models.UserProfile model)
        {
            if (model == null) throw new ArgumentException("model");

            using (var entities = new UsersContext())
            {
                var item = entities.UserProfiles.Where(u => u.UserId == model.UserId).Single();
                model.UpdateEntity(item);
                entities.SaveChanges();
            }
        }
        public bool CheckUserForValidatedTokenOrValidateToken(string email, string token, EmailFunctionType type)
        {
            using (var userContext = new UsersContext())
            {
                var userProfile = userContext.UserProfiles.Where(u => u.Email.Equals(email)).FirstOrDefault();
                var tokens = userProfile.TemporarilyValidGeneratedToken.Split(';');

                //We must make sure we can only have 1 validated token here
                var validToken = tokens.Where(t => t.EndsWith("Validated")).FirstOrDefault();
                var dycriptedvalidToken = string.IsNullOrEmpty(validToken) ? "" : validToken.Replace("Validated", "").Decrypt();
                if (string.IsNullOrEmpty(validToken))
                {
                    userProfile.TemporarilyValidGeneratedToken = userProfile.TemporarilyValidGeneratedToken.Replace(token, token + "Validated");
                    userContext.SaveChanges();
                    return false;
                }
                else
                {
                    if (dycriptedvalidToken.Split(';')[2].Equals(type.ToString()))
                    {
                        return false;
                    }
                    else
                    {
                        //Remove the tokens and return true
                        //if we want to use these tokens for more then just email change we must only remove the 2 email change tokens.
                        userProfile.TemporarilyValidGeneratedToken = "";
                        userContext.SaveChanges();
                        return true;
                    }
                }
            }
        }
 public void RemoveTemporaryValidToken(string userName, string token)
 {
     using (var userContext = new UsersContext())
     {
         var userProfile = userContext.UserProfiles.Where(u => u.Email.Equals(userName)).FirstOrDefault();
         if (!string.IsNullOrEmpty(userProfile.TemporarilyValidGeneratedToken))
         {
             var tokens = userProfile.TemporarilyValidGeneratedToken.Split(';');
             string validTokens = "";
             foreach (var newtoken in tokens)
             {
                 if (newtoken != token)
                 {
                     validTokens += newtoken + ";";
                 }
             }
             userProfile.TemporarilyValidGeneratedToken = validTokens.TrimEnd(';');
         }
         userContext.SaveChanges();
     }
 }
        /// <summary>
        /// Generates a temporaryValid token using a username and datetime from now.
        /// this token can be used as a variable in urls to identify valid users.
        /// Make sure to Remove the token after it has been used or when they are no longer valid
        /// </summary>
        /// <param name="userName">username</param>
        /// <param name="tokenExperationInMinutesFromNow">The ammount of minutes the token should be valid</param>
        /// <returns></returns>
        private string GenerateTemporaryValidToken(string userName, int tokenExperationInMinutesFromNow, EmailFunctionType type)
        {
            var token = string.Format("{0};{1};{2}", userName, DateTime.Now.AddMinutes(tokenExperationInMinutesFromNow), type.ToString()).Encrypt();
            using (var userContext = new UsersContext())
            {
                var userProfile = userContext.UserProfiles.Where(u => u.Email.Equals(userName)).FirstOrDefault();
                //If the token conaints a splitter it already has a set token, so just remove them and set it again
                if (!string.IsNullOrEmpty(userProfile.TemporarilyValidGeneratedToken))
                {
                    if (userProfile.TemporarilyValidGeneratedToken.Contains(';'))
                    {
                        userProfile.TemporarilyValidGeneratedToken = "";
                        userProfile.TemporarilyValidGeneratedToken = token;
                    }
                    else
                    {
                        userProfile.TemporarilyValidGeneratedToken += ";" + token;
                    }
                }
                else
                {
                    userProfile.TemporarilyValidGeneratedToken = token;
                }
                userContext.SaveChanges();
            }

            return token;
        }
        public void SendEmailChangeConfirmationMail(string newEmail, string oldEmail)
        {
            //Using the password reset token we can generate a temporary unique url where we can change the password
            string token = GenerateTemporaryValidToken(oldEmail, 30, EmailFunctionType.EmailAdressChangeConfirm);

            //Updating the new email in the database, we will set this email as username/main email when the validation link has been clicked
            try
            {
                using (var userContext = new UsersContext())
                {
                    var userProfile = userContext.UserProfiles.Where(u => u.Email.Equals(oldEmail)).FirstOrDefault();
                    userProfile.NewEmail = newEmail;
                    userContext.SaveChanges();
                }
            }
            catch (Exception e)
            {
                logger.LogException(LogLevel.Error, "An error occured while trying to add a NewEmail to a userprofile", e);
            }
            try
            {

                var subject = "Identity Provider Confirm Email Change";
                var url = GenerateConfirmNewEmailurl(token);
                var body = string.Format("To confirm your email change click this link: {0}", url);
                SendEmail(body, subject, newEmail);

            }
            catch (FormatException ex)
            {
                logger.LogException(LogLevel.Error, "EmailAdress Format incorrect Can't send confirm change emailadress, email", ex);
                throw new MembershipCreateUserException(MembershipCreateStatus.InvalidEmail);
            }
            catch (Exception ex)
            {
                logger.LogException(LogLevel.Error, "An Error occured while trying to send a confirm change emailadress, email", ex);
            }
        }