100 lines
2.7 KiB
C#
100 lines
2.7 KiB
C#
using System;
|
||
using System.IO;
|
||
using UnityEngine;
|
||
|
||
public static class SettingsPasswordStore
|
||
{
|
||
private const string FileName = "settings-password.txt";
|
||
private const int PasswordLength = 6;
|
||
|
||
public static string PasswordFilePath => Path.Combine(Application.persistentDataPath, FileName);
|
||
|
||
public static bool HasPassword => TryGetPassword(out _);
|
||
|
||
public static bool Save(string combination)
|
||
{
|
||
string normalizedCombination = Normalize(combination);
|
||
|
||
if (IsValid(normalizedCombination) == false)
|
||
return false;
|
||
|
||
try
|
||
{
|
||
File.WriteAllText(PasswordFilePath, normalizedCombination);
|
||
return true;
|
||
}
|
||
catch (Exception exception)
|
||
{
|
||
Debug.LogError($"Не удалось сохранить пароль настроек: {exception.Message}");
|
||
return false;
|
||
}
|
||
}
|
||
|
||
public static bool Validate(string combination)
|
||
{
|
||
if (TryGetPassword(out string savedPassword) == false)
|
||
return false;
|
||
|
||
return string.Equals(savedPassword, Normalize(combination), StringComparison.Ordinal);
|
||
}
|
||
|
||
public static bool Reset()
|
||
{
|
||
try
|
||
{
|
||
if (File.Exists(PasswordFilePath))
|
||
File.Delete(PasswordFilePath);
|
||
|
||
return true;
|
||
}
|
||
catch (Exception exception)
|
||
{
|
||
Debug.LogError($"Не удалось сбросить пароль настроек: {exception.Message}");
|
||
return false;
|
||
}
|
||
}
|
||
|
||
private static bool TryGetPassword(out string password)
|
||
{
|
||
password = null;
|
||
|
||
try
|
||
{
|
||
if (File.Exists(PasswordFilePath) == false)
|
||
return false;
|
||
|
||
string savedPassword = Normalize(File.ReadAllText(PasswordFilePath));
|
||
|
||
if (IsValid(savedPassword) == false)
|
||
return false;
|
||
|
||
password = savedPassword;
|
||
return true;
|
||
}
|
||
catch (Exception exception)
|
||
{
|
||
Debug.LogError($"Не удалось прочитать пароль настроек: {exception.Message}");
|
||
return false;
|
||
}
|
||
}
|
||
|
||
private static string Normalize(string combination)
|
||
=> string.IsNullOrWhiteSpace(combination) ? string.Empty : combination.Trim().ToUpperInvariant();
|
||
|
||
private static bool IsValid(string combination)
|
||
{
|
||
if (combination.Length != PasswordLength)
|
||
return false;
|
||
|
||
for (int i = 0; i < combination.Length; i++)
|
||
{
|
||
char symbol = combination[i];
|
||
|
||
if (symbol != 'U' && symbol != 'D' && symbol != 'L' && symbol != 'R')
|
||
return false;
|
||
}
|
||
|
||
return true;
|
||
}
|
||
}
|