Skip to content

Commit 56a06a9

Browse files
committed
Abstract ensuring the token cache away.
1 parent 19ad5c9 commit 56a06a9

File tree

1 file changed

+35
-8
lines changed

1 file changed

+35
-8
lines changed

src/Common/Commands.Common.Authentication/Authentication/ProtectedFileTokenCache.cs

Lines changed: 35 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -73,14 +73,7 @@ public ProtectedFileTokenCache(string cacheFile, IDataStore store = null)
7373

7474
private void Initialize(string fileName)
7575
{
76-
lock(fileLock)
77-
{
78-
ReadFileIntoCache(fileName);
79-
HasStateChanged = true;
80-
81-
// Eagerly create cache file.
82-
WriteCacheIntoFile(fileName);
83-
}
76+
EnsureCacheFile(fileName);
8477

8578
AfterAccess = AfterAccessNotification;
8679
BeforeAccess = BeforeAccessNotification;
@@ -171,5 +164,39 @@ private void WriteCacheIntoFile(string cacheFileName = null)
171164
}
172165
}
173166
}
167+
168+
private void EnsureCacheFile(string cacheFileName = null)
169+
{
170+
lock (fileLock)
171+
{
172+
if (_store.FileExists(cacheFileName))
173+
{
174+
var existingData = _store.ReadFileAsBytes(cacheFileName);
175+
if (existingData != null)
176+
{
177+
#if !NETSTANDARD
178+
try
179+
{
180+
Deserialize(ProtectedData.Unprotect(existingData, null, DataProtectionScope.CurrentUser));
181+
}
182+
catch (CryptographicException)
183+
{
184+
_store.DeleteFile(cacheFileName);
185+
}
186+
#else
187+
Deserialize(existingData);
188+
#endif
189+
}
190+
}
191+
192+
// Eagerly create cache file.
193+
#if !NETSTANDARD
194+
var dataToWrite = ProtectedData.Protect(Serialize(), null, DataProtectionScope.CurrentUser);
195+
#else
196+
var dataToWrite = Serialize();
197+
#endif
198+
_store.WriteFile(cacheFileName, dataToWrite);
199+
}
200+
}
174201
}
175202
}

0 commit comments

Comments
 (0)