yavsc/src/Yavsc/Helpers/ExternalAuthStoreHelper.cs

57 lines
2 KiB
C#
Raw Normal View History

2023-03-19 17:57:55 +00:00

2018-12-27 22:23:02 +00:00
using Newtonsoft.Json.Linq;
2019-05-08 03:13:07 +01:00
namespace Yavsc.Helpers.Auth
2019-03-17 00:03:04 +00:00
{
2023-03-19 17:57:55 +00:00
using Microsoft.EntityFrameworkCore;
2018-12-27 22:23:02 +00:00
using Yavsc.Models;
using Yavsc.Models.Auth;
2019-05-08 03:13:07 +01:00
public static class ExternalAuthStoreHelper {
2018-12-27 22:23:02 +00:00
2019-05-08 03:13:07 +01:00
public static Task<OAuth2Tokens> GetTokensAsync(this ApplicationDbContext context, string externalUserId)
2018-12-27 22:23:02 +00:00
{
2019-05-08 03:13:07 +01:00
if (string.IsNullOrEmpty(externalUserId))
2018-12-27 22:23:02 +00:00
{
2019-05-08 03:13:07 +01:00
throw new ArgumentException("externalUserId MUST have a value");
2018-12-27 22:23:02 +00:00
}
2019-05-08 03:13:07 +01:00
var item = context.OAuth2Tokens.FirstOrDefault(x => x.UserId == externalUserId);
2018-12-27 22:23:02 +00:00
// TODO Refresh token
return Task.FromResult(item);
}
2019-05-08 03:13:07 +01:00
public static Task StoreTokenAsync(this ApplicationDbContext context, string externalUserId, JObject response, string accessToken,
2018-12-27 22:23:02 +00:00
string tokenType, string refreshToken, string expiresIn
)
{
2019-05-08 03:13:07 +01:00
if (string.IsNullOrEmpty(externalUserId))
2018-12-27 22:23:02 +00:00
{
throw new ArgumentException("googleUserId MUST have a value");
}
2019-05-08 03:13:07 +01:00
var item = context.OAuth2Tokens.SingleOrDefaultAsync(x => x.UserId == externalUserId).Result;
2018-12-27 22:23:02 +00:00
if (item == null)
{
2019-05-08 03:13:07 +01:00
context.OAuth2Tokens.Add(new OAuth2Tokens
2018-12-27 22:23:02 +00:00
{
TokenType = "Bearer",
AccessToken = accessToken,
RefreshToken = refreshToken,
Expiration = DateTime.Now.AddSeconds(int.Parse(expiresIn)),
2019-05-08 03:13:07 +01:00
UserId = externalUserId
2018-12-27 22:23:02 +00:00
});
}
else
{
item.AccessToken = accessToken;
item.Expiration = DateTime.Now.AddMinutes(int.Parse(expiresIn));
if (refreshToken != null)
item.RefreshToken = refreshToken;
2019-05-08 03:13:07 +01:00
context.OAuth2Tokens.Update(item);
2018-12-27 22:23:02 +00:00
}
2019-05-08 03:13:07 +01:00
context.SaveChanges(externalUserId);
2018-12-27 22:23:02 +00:00
return Task.FromResult(0);
}
}
}