Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Delete db #90

Merged
merged 9 commits into from
Apr 24, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
namespace PWManager.Application.Abstractions.Interfaces;

public interface IDeleteDataContext {

void DeleteDataContext();
}
6 changes: 6 additions & 0 deletions PWManager.Application/Exceptions/MessageStrings.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ public static class MessageStrings {
public const string FAILED_ADDING_ACCOUNT = "Failed adding the account!";
public static string AccountAlreadyExist(string input) => $"Account with identifier '{input}' does already exist in your group!";
public const string NO_ACTIVE_GROUP = "No active group found. Are you in a session?";
public const string NO_ACTIVE_USER = "No active user found. Are you in a session?";

// ----------------------------------------

// GROUP SERVICE
Expand All @@ -36,11 +38,15 @@ public static class MessageStrings {
// Config File Handler
public const string READ_FILE_ERROR = "The config file could not be read.";
public const string WRITE_FILE_ERROR = "The config file could not be written.";
public const string DELETE_FILE_ERROR = "The config file could not be deleted.";
public const string PATH_ERROR = "An unknown error occured! Could not determine execution path!";
public const string DIRECTORY_ERROR = "An unknown error occured! Execution path is not a directory!";
// ----------------------------------------

// PasswordBuilder
public const string MIN_LENGTH_TO_SMALL = "MinLength cannot be smaller than 0";
public const string MAX_LENGTH_TO_SMALL = "MaxLength cannot be smaller than MinLength";

// DataContext
public const string CANNOT_DELETE_DATABASE = "Cannot delete the database!";
}
14 changes: 14 additions & 0 deletions PWManager.CLI/Abstractions/ConfigFileHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,10 @@

namespace PWManager.CLI.Abstractions {
public static class ConfigFileHandler {

public static bool DefaultFileExists() {
return File.Exists(Path.Combine(GetPath(), "last.txt"));
}
public static string ReadDefaultFile() {
var defaultFilePath = GetPath();

Expand All @@ -23,6 +27,16 @@ public static void WriteDefaultFile(string username, string path) {
}
}

public static void DeleteDefaultFile() {
var defaultFilePath = Path.Combine(GetPath(), "last.txt");
try {
File.Delete(defaultFilePath);
}
catch (IOException) {
throw new UserFeedbackException(MessageStrings.DELETE_FILE_ERROR);
}
}

private static string GetPath() {
var assembly = Assembly.GetEntryAssembly();
if (assembly is null) {
Expand Down
58 changes: 58 additions & 0 deletions PWManager.CLI/Controllers/DeleteDatabaseController.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
using PWManager.Application.Abstractions.Interfaces;
using PWManager.Application.Context;
using PWManager.Application.Exceptions;
using PWManager.Application.Services.Interfaces;
using PWManager.CLI.Abstractions;
using PWManager.CLI.Attributes;
using PWManager.CLI.Enums;
using PWManager.CLI.Interfaces;

namespace PWManager.CLI.Controllers;

[SessionOnly]
public class DeleteDatabaseController : IController {

private readonly IDeleteDataContext _dataContextDeleter;
private readonly ILoginService _loginService;
private readonly IUserEnvironment _userEnv;

public DeleteDatabaseController(IDeleteDataContext dataContextDeleter, ILoginService loginService, IUserEnvironment userEnv) {
_dataContextDeleter = dataContextDeleter;
_loginService = loginService;
_userEnv = userEnv;
}

public ExitCondition Handle(string[] args) {

if (!ConfirmPassword()) {
return ExitCondition.CONTINUE;
}

try {
_dataContextDeleter.DeleteDataContext();
}
catch(UserFeedbackException ex) {
PromptHelper.PrintColoredText(ConsoleColor.Red, ex.Message);
return ExitCondition.EXIT;
}

try {
ConfigFileHandler.DeleteDefaultFile();
}
catch (UserFeedbackException ex) {
PromptHelper.PrintColoredText(ConsoleColor.Red, ex.Message);
}

PromptHelper.PrintColoredText(ConsoleColor.Cyan, UIstrings.DATABASE_DELETED);

return ExitCondition.EXIT;
}

private bool ConfirmPassword() {
if (_userEnv.CurrentUser is null) {
throw new ApplicationException(MessageStrings.NO_ACTIVE_USER);
}
var username = _userEnv.CurrentUser.UserName;
return PromptHelper.ConfirmDeletion(UIstrings.YOUR_DATABASE, (pw) => _loginService.CheckPassword(username, pw));
}
}
22 changes: 17 additions & 5 deletions PWManager.CLI/Controllers/LoginController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -22,12 +22,24 @@ public LoginController(ILoginService loginService) {
public ExitCondition Handle(string[] args) {
(var username, var path) = ParseArgs(args);

var lastUser = ConfigFileHandler.ReadDefaultFile();
if (String.IsNullOrWhiteSpace(username)) {
username = lastUser.Split('\n')[0];
if (!ConfigFileHandler.DefaultFileExists()) {
if (string.IsNullOrWhiteSpace(username)) {
username = AskForInput(UIstrings.ENTER_USERNAME);
}

if (string.IsNullOrWhiteSpace(path)) {
path = AskForInput(UIstrings.ENTER_PATH);
}
}
if (String.IsNullOrWhiteSpace(path)) {
path = lastUser.Split('\n')[1];
else {
var lastUser = ConfigFileHandler.ReadDefaultFile();
if (String.IsNullOrWhiteSpace(username)) {
username = lastUser.Split('\n')[0];
}

if (String.IsNullOrWhiteSpace(path)) {
path = lastUser.Split('\n')[1];
}
}

var succ = PromptHelper.InputPassword((p) => _loginService.Login(username, p, path));
Expand Down
2 changes: 2 additions & 0 deletions PWManager.CLI/ExtensionMethods/RunnerExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ public static void AddControllers(this IServiceCollection services) {
services.AddTransient<NewController>();
services.AddTransient<GroupController>();
services.AddTransient<GetController>();
services.AddTransient<DeleteDatabaseController>();
services.AddTransient<SettingsController>();
services.AddTransient<QuitController>();
}
Expand All @@ -26,6 +27,7 @@ public static void MapControllers(this ConsoleRunner runner) {
runner.MapCommand<NewController>(AvailableCommands.NEW);
runner.MapCommand<GroupController>(AvailableCommands.GROUP);
runner.MapCommand<GetController>(AvailableCommands.GET);
runner.MapCommand<DeleteDatabaseController>(AvailableCommands.DELETE_DATABASE);
runner.MapCommand<SettingsController>(AvailableCommands.SETTINGS);
runner.MapCommand<QuitController>(AvailableCommands.QUIT);
}
Expand Down
6 changes: 6 additions & 0 deletions PWManager.CLI/UIstrings.cs
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,12 @@ internal static class UIstrings {
public const string NO_ACCOUNTS_AVAILABLE = "There are no accounts in this group!";
// ----------------------------------------

// DELETE DATABASE Controller
public const string YOUR_DATABASE = "your database?";
public const string DATABASE_DELETED = "Your database was deleted successfully!";

// ----------------------------------------

// SETTINGS Controller
public const string MAIN_GROUP_CHANGE = "Which group will be your new main group?";
public static string ConfirmOfMainGroupChangedTo(string input) => $"Main group set to '{input}'";
Expand Down
23 changes: 21 additions & 2 deletions PWManager.Data/DataContext.cs
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
using PWManager.Application.Abstractions.Interfaces;
using PWManager.Application.Exceptions;
using PWManager.Data.Abstraction.Interfaces;
using PWManager.Data.Persistance;

namespace PWManager.Data;

public class DataContext : IDataContextInitializer, IHaveDataContext {
public class DataContext : IDataContextInitializer, IHaveDataContext, IDeleteDataContext {

private ApplicationDbContext? _dbContext;
private const string DatabaseFileName = "pwdb.scuml";
Expand All @@ -18,10 +19,28 @@ public void InitDataContext(string path) {
return;
}
_dbContext = new ApplicationDbContext(Path.Combine(path, DatabaseFileName));

_dbContext.Database.EnsureCreated();
}

private void CloseDatabase() {
if (_dbContext is null) {
return;
}
_dbContext.Dispose();
_dbContext = null;
}

public void DeleteDataContext() {
if (_dbContext is null) {
return;
}

_dbContext.Database.EnsureDeleted();

CloseDatabase();
}

ApplicationDbContext IHaveDataContext.GetDbContext() {
if (_dbContext is null) {
throw new ApplicationException("Data Context was not initialized!");
Expand Down
2 changes: 1 addition & 1 deletion PWManager.Data/DependencyInjection.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ public static IServiceCollection AddDataServices(this IServiceCollection service
var dataContext = new DataContext();
HaveDataContextFactory.Initialize(dataContext);
services.AddSingleton<IDataContextInitializer>(dataContext);

services.AddSingleton<IDeleteDataContext>(dataContext);

services.AddTransient<IGroupRepository, GroupRepository>();
services.AddTransient<IUserRepository, UserRepository>();
Expand Down
4 changes: 4 additions & 0 deletions PWManager.Data/Persistance/ApplicationDbContext.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,11 @@ internal class ApplicationDbContext : DbContext {
public DbSet<SettingsModel> Settings { get; set; }
public DbSet<UserModel> Users { get; set; }


public string Path { get; private set; }

public ApplicationDbContext(string dbPath) : base(CreateOptionsBuilder(dbPath)) {
Path = dbPath;
}

private static DbContextOptions CreateOptionsBuilder(string path) {
Expand Down
20 changes: 12 additions & 8 deletions PWManager.Data/Repositories/SettingsRepository.cs
Original file line number Diff line number Diff line change
Expand Up @@ -36,16 +36,20 @@ public Settings GetSettings() {
var userId = _environment.CurrentUser.Id;
var settingsList = _dbContext.Settings.Where(e => e.UserId == userId).AsNoTracking().ToList();
var settingsModel = settingsList.Any() ? settingsList.First() : null;
if (settingsModel is null) {
settingsModel = new SettingsModel {
UserId = _environment.CurrentUser.Id,
Id = Guid.NewGuid().ToString(),
MainGroupIdentifier = _cryptService.Encrypt("main")
};
_dbContext.Settings.Add(settingsModel);
_dbContext.SaveChanges();
if (settingsModel is not null) {
return SettingsModelToEntity(settingsModel);
}

settingsModel = new SettingsModel {
UserId = _environment.CurrentUser.Id,
Id = Guid.NewGuid().ToString(),
MainGroupIdentifier = _cryptService.Encrypt("main"),
AccountTimeOutDuration = TimeSpan.FromMinutes(5),
ClipboardTimeOutDuration = TimeSpan.FromMinutes(1),
};
_dbContext.Settings.Add(settingsModel);
_dbContext.SaveChanges();

return SettingsModelToEntity(settingsModel);
}

Expand Down
Loading