DocSpace-client/web/ASC.Web.Api/Controllers/AuthenticationController.cs

101 lines
3.0 KiB
C#
Raw Normal View History

2019-05-28 09:40:37 +00:00
using System;
using ASC.Core;
using ASC.Core.Tenants;
using ASC.Core.Users;
using ASC.Security.Cryptography;
using ASC.Web.Api.Models;
using ASC.Web.Api.Routing;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace ASC.Web.Api.Controllers
{
[DefaultRoute]
[ApiController]
[AllowAnonymous]
public class AuthenticationController : ControllerBase
{
2019-09-09 12:56:33 +00:00
public UserManager UserManager { get; }
public TenantManager TenantManager { get; }
public SecurityContext SecurityContext { get; }
2019-09-13 11:18:27 +00:00
public TenantCookieSettings TenantCookieSettings { get; }
2019-09-09 12:56:33 +00:00
public AuthenticationController(
UserManager userManager,
TenantManager tenantManager,
2019-09-13 11:18:27 +00:00
SecurityContext securityContext,
TenantCookieSettings tenantCookieSettings)
2019-09-09 12:56:33 +00:00
{
UserManager = userManager;
TenantManager = tenantManager;
SecurityContext = securityContext;
2019-09-13 11:18:27 +00:00
TenantCookieSettings = tenantCookieSettings;
2019-09-09 12:56:33 +00:00
}
2019-06-25 10:46:10 +00:00
[Create(false)]
2019-05-28 09:40:37 +00:00
public AuthenticationTokenData AuthenticateMe([FromBody]AuthModel auth)
{
2019-09-09 12:56:33 +00:00
var tenant = TenantManager.GetCurrentTenant();
2019-08-08 09:26:58 +00:00
var user = GetUser(tenant.TenantId, auth.UserName, auth.Password);
2019-05-28 09:40:37 +00:00
try
{
2019-08-09 12:28:19 +00:00
var token = SecurityContext.AuthenticateMe(tenant.TenantId, user.ID);
2019-08-08 09:26:58 +00:00
var expires = TenantCookieSettings.GetExpiresTime(tenant.TenantId);
2019-05-28 09:40:37 +00:00
return new AuthenticationTokenData
{
Token = token,
Expires = expires
};
}
catch
{
throw new Exception("User authentication failed");
}
}
2019-09-09 12:56:33 +00:00
private UserInfo GetUser(int tenantId, string userName, string password)
2019-05-28 09:40:37 +00:00
{
2019-09-09 12:56:33 +00:00
var user = UserManager.GetUsers(
2019-08-08 09:26:58 +00:00
tenantId,
2019-05-28 09:40:37 +00:00
userName,
Hasher.Base64Hash(password, HashAlg.SHA256));
2019-09-09 12:56:33 +00:00
if (user == null || !UserManager.UserExists(user))
2019-05-28 09:40:37 +00:00
{
throw new Exception("user not found");
}
return user;
}
}
public class AuthenticationTokenData
{
public string Token { get; set; }
public DateTime Expires { get; set; }
public bool Sms { get; set; }
public string PhoneNoise { get; set; }
public bool Tfa { get; set; }
public string TfaKey { get; set; }
public static AuthenticationTokenData GetSample()
{
return new AuthenticationTokenData
{
Expires = DateTime.UtcNow,
Token = "abcde12345",
Sms = false,
PhoneNoise = null,
Tfa = false,
TfaKey = null
};
}
}
}