78 lines
2.3 KiB
C#
78 lines
2.3 KiB
C#
// Copyright (c) 2020 Tudor Stanciu
|
|
|
|
using Microsoft.EntityFrameworkCore;
|
|
using System;
|
|
using System.Linq;
|
|
using System.Threading.Tasks;
|
|
using Tuitio.Domain.Data.DbContexts;
|
|
using Tuitio.Domain.Entities;
|
|
using Tuitio.Domain.Models;
|
|
using Tuitio.Domain.Repositories;
|
|
|
|
namespace Tuitio.Domain.Data.Repositories
|
|
{
|
|
class UserRepository : IUserRepository
|
|
{
|
|
private readonly TuitioDbContext _dbContext;
|
|
|
|
public UserRepository(TuitioDbContext dbContext)
|
|
{
|
|
_dbContext = dbContext;
|
|
}
|
|
|
|
public Task<AppUser> GetUser(string userName, string password)
|
|
{
|
|
return _dbContext.Users
|
|
.Include(z => z.Status)
|
|
.Include(z => z.Claims)
|
|
.FirstOrDefaultAsync(z => z.UserName == userName && z.Password == password);
|
|
}
|
|
|
|
public async Task UpdateUserAfterLogin(AppUser user, Token token, string tokenRaw)
|
|
{
|
|
var userToken = new UserToken()
|
|
{
|
|
TokenId = token.TokenId,
|
|
UserId = token.UserId,
|
|
Token = tokenRaw,
|
|
ValidFrom = token.CreatedAt,
|
|
ValidUntil = token.CreatedAt.AddMilliseconds(token.ExpiresIn)
|
|
};
|
|
|
|
await _dbContext.AddAsync(userToken);
|
|
user.LastLoginDate = DateTime.UtcNow;
|
|
|
|
await _dbContext.SaveChangesAsync();
|
|
}
|
|
|
|
public async Task<UserToken[]> GetActiveTokens()
|
|
{
|
|
var currentDate = DateTime.UtcNow;
|
|
|
|
// remove expired tokens
|
|
_dbContext.UserTokens.RemoveRange(_dbContext.UserTokens.Where(z => z.ValidUntil < currentDate));
|
|
await _dbContext.SaveChangesAsync();
|
|
|
|
// retrieve active tokens
|
|
var query = _dbContext.UserTokens
|
|
.Where(z => z.ValidFrom <= currentDate && z.ValidUntil >= currentDate);
|
|
|
|
var tokens = await query.ToArrayAsync();
|
|
return tokens;
|
|
}
|
|
|
|
public Task RemoveToken(Guid tokenId)
|
|
{
|
|
var token = new UserToken()
|
|
{
|
|
TokenId = tokenId
|
|
};
|
|
|
|
_dbContext.UserTokens.Attach(token);
|
|
_dbContext.UserTokens.Remove(token);
|
|
|
|
return _dbContext.SaveChangesAsync();
|
|
}
|
|
}
|
|
}
|