ascnet/AscNet.Common/Database/Account.cs

70 lines
2.2 KiB
C#
Raw Normal View History

2023-10-06 13:29:27 +00:00
using MongoDB.Bson;
using MongoDB.Driver;
using MongoDB.Bson.Serialization.Attributes;
namespace AscNet.Common.Database
{
#pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable.
public class Account
{
public static readonly IMongoCollection<Account> collection = Common.db.GetCollection<Account>("accounts");
public static Account? FromUID(long uid)
{
return collection.AsQueryable().FirstOrDefault(x => x.Uid == uid);
}
2023-10-08 02:27:30 +00:00
public static Account? FromToken(string token)
2023-10-06 13:29:27 +00:00
{
2023-10-08 02:27:30 +00:00
return collection.AsQueryable().FirstOrDefault(x => x.Token == token);
2023-10-06 13:29:27 +00:00
}
2023-10-08 02:27:30 +00:00
public static Account? FromUsername(string username)
2023-10-06 13:29:27 +00:00
{
2023-10-08 02:27:30 +00:00
return collection.AsQueryable().FirstOrDefault(x => x.Username == username);
2023-10-06 13:29:27 +00:00
}
2023-10-08 02:27:30 +00:00
public static Account? FromUsername(string username, string password)
2023-10-06 13:29:27 +00:00
{
2023-10-08 02:27:30 +00:00
return collection.AsQueryable().FirstOrDefault(x => x.Username == username && x.Password == password);
2023-10-06 13:29:27 +00:00
}
/// <exception cref="ArgumentException"></exception>
2023-10-08 02:27:30 +00:00
public static Account Create(string username, string password)
2023-10-06 13:29:27 +00:00
{
2023-10-08 02:27:30 +00:00
if (collection.AsQueryable().FirstOrDefault(x => x.Username == username) is not null)
throw new ArgumentException("Username is already registered!", nameof(username));
2023-10-06 13:29:27 +00:00
Account account = new()
{
Uid = (collection.AsQueryable().OrderByDescending(x => x.Uid).FirstOrDefault()?.Uid ?? 0) + 1,
2023-10-08 02:27:30 +00:00
Username = username,
2023-10-06 13:29:27 +00:00
Password = password,
2023-10-08 02:27:30 +00:00
Token = Guid.NewGuid().ToString()
2023-10-06 13:29:27 +00:00
};
collection.InsertOne(account);
return account;
}
[BsonId]
public ObjectId Id { get; set; }
[BsonElement("uid")]
[BsonRequired]
public long Uid { get; set; }
2023-10-08 02:27:30 +00:00
[BsonElement("username")]
2023-10-06 13:29:27 +00:00
[BsonRequired]
2023-10-08 02:27:30 +00:00
public string Username { get; set; }
2023-10-06 13:29:27 +00:00
[BsonElement("password")]
[BsonRequired]
public string Password { get; set; }
2023-10-08 02:27:30 +00:00
[BsonElement("token")]
2023-10-06 13:29:27 +00:00
[BsonRequired]
2023-10-08 02:27:30 +00:00
public string Token { get; set; }
2023-10-06 13:29:27 +00:00
}
}