Search code examples
c#entity-frameworkgoogle-apigoogle-oauthgoogle-api-dotnet-client

Save user credentials to database with Google Web Authorization Broker


I have successfully user the GoogleWebAuthorizationBroker to save user credentials to a file. But I want my app to be a little more secure. So I am trying to save the credentials to my my sqlite database. I have followed some information from this Stack overflow Post Here I have made the Entity Framework class but now Im unsure on how to use it to save the data to the database. This is my Current code

return GoogleWebAuthorizationBroker.AuthorizeAsync(
                    GoogleClientSecrets.FromStream(stream).Secrets,
                    _scopes,
                    "user",
                    CancellationToken.None,
                    GoogleCredentialsDataStore.GenerateStoredKey("What string value goes here")

So Im a little lost on what string value goes into the GenerateStoredKey parameter so that it will process and save to my database.

this is the Data interface part of the project .

public class GoogleCredentialsDataStore : SqLiteDbContext, IDataStore
    {
        /// <summary>
        /// Database context to access database
        /// </summary>
        private readonly SqLiteDbContext _context;
        public GoogleCredentialsDataStore(SqLiteDbContext context)
        {
            _context = context;
        }

        /// <summary>
        /// Stores the given value for the given key. It creates a new row in the database with the user id of
        /// (primary key <see cref="GenerateStoredKey"/>) in <see cref="GoogleUserCredentials"/>.
        /// </summary>
        /// <typeparam name="T">The type to store in the data store.</typeparam>
        /// <param name="key">The key.</param>
        /// <param name="value">The value to store in the data store.</param>
        Task IDataStore.StoreAsync<T>(string key, T value)
        {
            if (string.IsNullOrEmpty(key))
            {
                throw new ArgumentNullException("key Must have a value");
            }

            var serialized = NewtonsoftJsonSerializer.Instance.Serialize(value);

            _context.GoogleCredentials.Add(new()
            {
                Key = GenerateStoredKey(key),
                Credentials = serialized
            });
            _context.SaveChanges();
            return Task.Delay(0);
        }
        /// <summary>
        /// Deletes the given key. It deletes the <see cref="GenerateStoredKey"/> row in
        /// <see cref="GoogleCredentials"/>.
        /// </summary>
        /// <param name="key">The key to delete from the data store.</param>
        Task IDataStore.DeleteAsync<T>(string key)
        {
            if (string.IsNullOrEmpty(key))
            {
                throw new ArgumentException("Key MUST have a value");
            }

            try
            {
                var hold = _context.GoogleCredentials.Where(a => a.Key == key).FirstOrDefault();
                _context.GoogleCredentials.Remove(hold);
                _context.SaveChangesAsync();
            }
            catch (Exception)
            {
                throw new Exception("Failed to delete credentials");
            }

            return Task.Delay(0);
        }

        /// <summary>
        /// Returns the stored value for the given key or <c>null</c> if the matching row (<see cref="GenerateStoredKey"/>
        /// in <see cref="GoogleCredentials"/> doesn't exist.
        /// </summary>
        /// <typeparam name="T">The type to retrieve.</typeparam>
        /// <param name="key">The key to retrieve from the data store.</param>
        /// <returns>The stored object.</returns>
        Task<T> IDataStore.GetAsync<T>(string key)
        {
            if (string.IsNullOrEmpty(key))
            {
                throw new ArgumentException("Key MUST have a value");
            }

            TaskCompletionSource<T> tcs = new TaskCompletionSource<T>();
            var user = GetUserByKey(GenerateStoredKey(key));
            if (user != null)
            {
                try
                {
                    tcs.SetResult(NewtonsoftJsonSerializer.Instance.Deserialize<T>(user.Credentials));
                }
                catch (Exception ex)
                {
                    tcs.SetException(ex);
                }
            }
            else
            {
                tcs.SetResult(default(T));
            }
            return tcs.Task;
        }

        /// <summary>
        /// Clears all values in the data store. This method deletes all files in <see cref="GoogleCredentials"/>.
        /// </summary>
        Task IDataStore.ClearAsync()
        {
            try
            {
                foreach (var item in _context.GoogleCredentials)
                {
                    _context.GoogleCredentials.Remove(item);
                }
            }
            catch (Exception)
            {
                throw new Exception("Failed to clear credentials");
            }

            return Task.Delay(0);
        }

        /// <summary>
        /// Checks if the user exists <see cref="GenerateStoredKey"/>.
        /// </summary>
        private GoogleCredentials GetUserByKey(string key)
        {
            try
            {
                var user = _context.GoogleCredentials.Where(a => a.Key == key).FirstOrDefault();

                if (user != null)
                    return user;

                return null;
            }
            catch (Exception)
            {
                return null;
            }
        }

        /// <summary>
        /// Save the credentials.  If the user <see cref="GenerateStoredKey"/> does not exists we insert it other wise we will do an update.
        /// </summary>
        /// <param name="key"></param>
        /// <param name="serialized"></param>
        private void save(string key, string serialized)
        {
            try
            {
                var user = _context.GoogleCredentials.Where(a => a.Key == key).FirstOrDefault();
                if (user == null)
                {
                    var hold = new GoogleCredentials { Key = key, Credentials = serialized };
                    _context.GoogleCredentials.Add(hold);
                }
                else
                {
                    var aUser = _context.GoogleCredentials.Where(a => a.Key == key).FirstOrDefault();
                    aUser.Credentials = serialized;
                }
                _context.SaveChanges();
            }
            catch (Exception)
            {
                throw;
            }
        }

        /// <summary>Creates a unique stored key based on the key and the current project name.</summary>
        /// <param name="key">The object key.</param>
        public static string GenerateStoredKey(string key)
        {
            return string.Format("{0}-{1}", Assembly.GetCallingAssembly().GetName().Name, key);
        }
    }

and then my google Credentials Model

public class GoogleCredentials
    {
        [Key]
        public int Id { get; set; }
        [Required, StringLength(500)]
        public string Key { get; set; }
        [Required]
        public string Credentials { get; set; }
    }

Still new to all this but this is what I have, I think I'm in the right direction from what I understand but maybe some one a little more knowledgeable can take a look and set me down the right path.


Solution

  • The constructor takes a connection string.

      public static UserCredential InstalledCredential(string credFilePath, string[] scopes, string userName, string connectionString)
            {
                return GoogleWebAuthorizationBroker.AuthorizeAsync(GoogleClientSecrets.FromFile(credFilePath).Secrets,
                    scopes,
                    userName,
                    CancellationToken.None,
                    new EntityFrameworkDataStore(connectionString)).Result;
            }
    

    EntityFrameworkDataStore

    internal sealed class EntityFrameworkDataStore : DbContext, IDataStore
    {
        public DbSet<GoogleUserCredential> GoogleUserCredentials { get; set; }
    
        /// <summary>The string used to open the connection.</summary>
        public string ConnectionString { get; set; }
    
        /// <summary>
        /// Creates a new table in the data base if the Users table does not exist within the database used in the connectionstring.
        /// </summary>
        /// <param name="connectionString">The string used to open the connection.</param>
        public EntityFrameworkDataStore(string connectionString) : base(connectionString)
        {
            ConnectionString = connectionString;
        }
    
        /// <summary>
        /// Stores the given value for the given key. It creates a new row in the database with the user id of
        /// (primary key <see cref="GenerateStoredKey"/>) in <see cref="GoogleUserCredentials"/>.
        /// </summary>
        /// <typeparam name="T">The type to store in the data store.</typeparam>
        /// <param name="key">The key.</param>
        /// <param name="value">The value to store in the data store.</param>
        Task IDataStore.StoreAsync<T>(string key, T value)
        {
            if (string.IsNullOrEmpty(key))
            {
                throw new ArgumentException("Key MUST have a value");
            }
    
            var serialized = NewtonsoftJsonSerializer.Instance.Serialize(value);
            Save(GenerateStoredKey(key), serialized);
            return Task.Delay(0);
        }
    
        /// <summary>
        /// Deletes the given key. It deletes the <see cref="GenerateStoredKey"/> row in
        /// <see cref="GoogleUserCredentials"/>.
        /// </summary>
        /// <param name="key">The key to delete from the data store.</param>
        Task IDataStore.DeleteAsync<T>(string key)
        {
            if (string.IsNullOrEmpty(key))
            {
                throw new ArgumentException("Key MUST have a value");
            }
    
            try
            {
                var hold = GoogleUserCredentials.Where(a => a.Key == key).FirstOrDefault();
                GoogleUserCredentials.Remove(hold);
                SaveChangesAsync();
            }
            catch (System.Data.SqlClient.SqlException ex)
            {
                throw new Exception("Failed to delete credentials", ex);
            }
    
            return Task.Delay(0);
        }
    
        /// <summary>
        /// Returns the stored value for the given key or <c>null</c> if the matching row (<see cref="GenerateStoredKey"/>
        /// in <see cref="GoogleUserCredentials"/> doesn't exist.
        /// </summary>
        /// <typeparam name="T">The type to retrieve.</typeparam>
        /// <param name="key">The key to retrieve from the data store.</param>
        /// <returns>The stored object.</returns>
        Task<T> IDataStore.GetAsync<T>(string key)
        {
            if (string.IsNullOrEmpty(key))
            {
                throw new ArgumentException("Key MUST have a value");
            }
    
            var tcs = new TaskCompletionSource<T>();
            var user = GetUserByKey(GenerateStoredKey(key));
            if (user != null)
            {
                try
                {
                    tcs.SetResult(NewtonsoftJsonSerializer.Instance.Deserialize<T>(user.Credentials));
                }
                catch (Exception ex)
                {
                    tcs.SetException(ex);
                }
            }
            else
            {
                tcs.SetResult(default(T));
            }
    
            return tcs.Task;
        }
    
        /// <summary>
        /// Clears all values in the data store. This method deletes all files in <see cref="GoogleUserCredentials"/>.
        /// </summary>
        Task IDataStore.ClearAsync()
        {
            try
            {
                foreach (var item in GoogleUserCredentials)
                {
                    GoogleUserCredentials.Remove(item);
                }
            }
            catch (System.Data.SqlClient.SqlException ex)
            {
                throw new Exception("Failed to clear credentials", ex);
            }
    
            return Task.Delay(0);
        }
    
        /// <summary>
        /// Checks if the user exists <see cref="GenerateStoredKey"/>.
        /// </summary>
        private GoogleUserCredential GetUserByKey(string key)
        {
            try
            {
                return GoogleUserCredentials.FirstOrDefault(a => a.Key == key);
            }
            catch (System.Data.SqlClient.SqlException)
            {
                return null;
            }
        }
    
        /// <summary>
        /// Save the credentials.  If the user <see cref="GenerateStoredKey"/> does not exists we insert it other wise we will do an update.
        /// </summary>
        /// <param name="key"></param>
        /// <param name="serialized"></param>
        private void Save(string key, string serialized)
        {
            var user = GoogleUserCredentials.FirstOrDefault(a => a.Key == key);
            if (user == null)
            {
                var hold = new GoogleUserCredential { Key = key, Credentials = serialized };
                GoogleUserCredentials.Add(hold);
            }
            else
            {
                var aUser = GoogleUserCredentials.FirstOrDefault(a => a.Key == key);
                aUser.Credentials = serialized;
            }
    
            SaveChanges();
        }
    
        /// <summary>Creates a unique stored key based on the key and the current project name.</summary>
        /// <param name="key">The object key.</param>
        public static string GenerateStoredKey(string key)
        {
            return $"{Assembly.GetCallingAssembly().GetName().Name}-{key}";
        }
    }