retroactiune/Retroactiune.Core/Entities/Token.cs

62 lines
2 KiB
C#
Raw Normal View History

2021-06-09 21:03:07 +00:00
using System;
using System.Runtime.CompilerServices;
2021-06-09 21:03:07 +00:00
using System.Text.Json.Serialization;
using Ardalis.GuardClauses;
2021-06-09 21:03:07 +00:00
using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;
namespace Retroactiune.Core.Entities
2021-06-09 21:03:07 +00:00
{
/// <summary>
/// Token represents a token.
/// Token is used to authorize a <see cref="FeedbackReceiver"/> for the <see cref="Feedback"/>.
2021-06-09 21:03:07 +00:00
/// </summary>
public class Token
{
public Token()
{
Id = ObjectId.GenerateNewId().ToString();
CreatedAt = DateTime.UtcNow;
}
2021-06-09 21:03:07 +00:00
[BsonId, JsonPropertyName("id")]
[BsonRepresentation(BsonType.ObjectId)]
public string Id { get; set; }
2021-06-11 19:49:12 +00:00
2021-06-09 21:03:07 +00:00
[BsonRepresentation(BsonType.ObjectId), JsonPropertyName("feedback_receiver_id")]
public string FeedbackReceiverId { get; set; }
2021-06-11 19:49:12 +00:00
[JsonPropertyName("time_used")] public DateTime? TimeUsed { get; set; }
[JsonPropertyName("created_at")] public DateTime CreatedAt { get; set; }
[JsonPropertyName("expiry_time")] public DateTime? ExpiryTime { get; set; }
public override bool Equals(object obj)
{
if (!(obj is Token convertedObj))
{
return false;
}
return string.Equals(Id, convertedObj.Id) &&
string.Equals(FeedbackReceiverId, convertedObj.FeedbackReceiverId) &&
(CreatedAt - convertedObj.CreatedAt).Milliseconds == 0;
2021-06-11 19:49:12 +00:00
}
public override int GetHashCode()
{
return RuntimeHelpers.GetHashCode(this);
2021-06-11 19:49:12 +00:00
}
public bool IsValid(FeedbackReceiver feedbackReceiver)
{
Guard.Against.Null(feedbackReceiver, nameof(feedbackReceiver));
var hasExpired = ExpiryTime != null && ExpiryTime <= DateTime.UtcNow;
var differentFeedbackReceiver = !FeedbackReceiverId.Equals(feedbackReceiver.Id);
var isUsed = TimeUsed != null;
return !(hasExpired || differentFeedbackReceiver || isUsed);
}
2021-06-09 21:03:07 +00:00
}
}