Select Git revision
-
L. Ellenbeck authoredL. Ellenbeck authored
Code owners
Assign users and groups as approvers for specific file changes. Learn more.
ApiTokenModel.cs 3.63 KiB
using Coscine.Database.DataModel;
using Coscine.Database.ReturnObjects;
using LinqToDB;
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Linq;
namespace Coscine.Database.Models
{
public class ApiTokenModel : DatabaseModel<ApiToken>
{
public override Expression<Func<ApiToken, Guid>> GetIdFromObject()
{
return databaseObject => databaseObject.Id;
}
public override ITable<ApiToken> GetITableFromDatabase(CoscineDB db)
{
return db.ApiTokens;
}
public override void SetObjectId(ApiToken databaseObject, Guid id)
{
databaseObject.Id = id;
}
public IEnumerable<ApiTokenObject> GetTokens(string userId)
{
return GetTokens(new Guid(userId));
}
public IEnumerable<ApiTokenObject> GetTokens(User user)
{
return GetTokens(user.Id);
}
public IEnumerable<ApiTokenObject> GetTokens(Guid userId)
{
return GetAllWhere((tableEntry) => tableEntry.UserId == userId)
.Select(x => new ApiTokenObject { Created = x.Creation, Expires = x.Expiration, Token = x.Token, Description = x.Description })
.OrderBy(x => x.Created);
}
public ApiTokenObject GetToken(string userId, string token)
{
var t = GetWhere(x => x.UserId.ToString() == userId && x.Token.ToLower() == token.ToLower());
if(t == null)
{
return null;
}
return new ApiTokenObject { Created = t.Creation, Expires = t.Expiration, Token = t.Token, Description = t.Description };
}
private ApiToken GetApiToken(string token)
{
return GetWhere(x => x.Token.ToLower() == token.ToLower());
}
public bool Valiate(string token, User user)
{
return Valiate(token, user.Id);
}
public bool Valiate(string token, string userId)
{
return Valiate(token, new Guid(userId));
}
public bool Valiate(string token, Guid userId)
{
var t = GetApiToken(token);
return t != null && t.UserId == userId
&& t.Expiration.ToUniversalTime() < DateTime.Now.ToUniversalTime()
&& t.Creation.ToUniversalTime() > DateTime.Now.ToUniversalTime();
}
public User GetUser(string token)
{
return GetUser(GetApiToken(token));
}
public User GetUser(ApiToken token)
{
var userModel = new UserModel();
return userModel.GetWhere(x => x.Id == token.UserId);
}
public string GenerateToken(Guid user, string desciption, uint expiresInDays = 370)
{
// Minimum of 7 and maximum of 370
expiresInDays = Math.Min(expiresInDays, 370);
expiresInDays = Math.Max(expiresInDays, 7);
var token = Guid.NewGuid().ToString("N").ToLower();
Insert(new ApiToken {
Creation = DateTime.Now.ToUniversalTime(),
Expiration = DateTime.Now.AddDays(expiresInDays).ToUniversalTime(),
UserId = user,
Token = token,
Description = desciption
});
return token;
}
public void Revoke(ApiToken token)
{
Delete(token);
}
public void Revoke(Guid tokenId)
{
Revoke(GetApiToken(tokenId.ToString()));
}
public void Revoke(string tokenId)
{
Revoke(GetApiToken(tokenId));
}
}
}