public async Task <Unit> Handle(Command request, CancellationToken cancellationToken) { if (string.IsNullOrEmpty(request.Token)) { throw new RestException(HttpStatusCode.BadRequest, new { Message = "Token must not be empty" }); } var user = await context.AppUsers .Include(x => x.RefreshTokens) .SingleOrDefaultAsync(u => u.RefreshTokens.Any(t => t.Token == request.Token), cancellationToken: cancellationToken); if (user == null) { throw new RestException(System.Net.HttpStatusCode.NotFound); } var refreshToken = user.RefreshTokens.Single(x => x.Token == request.Token); if (!refreshToken.IsActive) { throw new RestException(System.Net.HttpStatusCode.Unauthorized); } refreshToken.Revoked = DateTime.UtcNow; refreshToken.RevokedByIp = request.Ip; context.Update(user); await context.SaveChangesAsync(cancellationToken); return(Unit.Value); }
public async Task <User> Handle(Query request, CancellationToken cancellationToken) { if (string.IsNullOrEmpty(request.Token)) { throw new RestException(HttpStatusCode.BadRequest, new { Message = "Token must not be empty" }); } var user = await context.AppUsers .Include(x => x.RefreshTokens) .Include(x => x.Photo) .SingleOrDefaultAsync(u => u.RefreshTokens.Any(t => t.Token == request.Token), cancellationToken: cancellationToken); if (user == null) { throw new RestException(System.Net.HttpStatusCode.NotFound); } var refreshToken = user.RefreshTokens.Single(x => x.Token == request.Token); if (!refreshToken.IsActive) { throw new RestException(System.Net.HttpStatusCode.Forbidden); } var newRefreshToken = refreshTokenGenerator.GenerateRefreshToken(request.Ip); refreshToken.Revoked = DateTime.Now; refreshToken.RevokedByIp = request.Ip; refreshToken.ReplacedByToken = newRefreshToken.Token; user.RefreshTokens.Add(newRefreshToken); context.Update(user); await context.SaveChangesAsync(cancellationToken); var jwtToken = await jwtGenerator.CreateToken(user); return(new User() { Username = user.UserName, ImageUrl = user.Photo.Url, JwtToken = jwtToken, RefreshToken = newRefreshToken.Token }); }