1260 lines
60 KiB
C#
1260 lines
60 KiB
C#
using System.Linq;
|
|
using System.Threading.Tasks;
|
|
using Microsoft.EntityFrameworkCore;
|
|
using Microsoft.Extensions.Logging;
|
|
using EnumsNET;
|
|
using AyaNova.Util;
|
|
using AyaNova.Api.ControllerHelpers;
|
|
using AyaNova.Models;
|
|
using System;
|
|
using Newtonsoft.Json.Linq;
|
|
using System.Collections.Generic;
|
|
using Newtonsoft.Json;
|
|
|
|
|
|
namespace AyaNova.Biz
|
|
{
|
|
|
|
|
|
internal class UserBiz : BizObject, IJobObject, ISearchAbleObject, IReportAbleObject, IExportAbleObject, IImportAbleObject, INotifiableObject
|
|
{
|
|
|
|
|
|
|
|
internal UserBiz(AyContext dbcontext, long currentUserId, long userTranslationId, AuthorizationRoles userRoles)
|
|
{
|
|
ct = dbcontext;
|
|
UserId = currentUserId;
|
|
UserTranslationId = userTranslationId;
|
|
CurrentUserRoles = userRoles;
|
|
BizType = AyaType.User;
|
|
}
|
|
|
|
//This is where active tech license consumers are accounted for
|
|
internal static async Task<long> ActiveCountAsync()
|
|
{
|
|
using (AyContext ct = ServiceProviderProvider.DBContext)
|
|
{
|
|
// var ret = await ct.Database.ExecuteSqlRawAsync($"SELECT COUNT(*) FROM auser AS a WHERE (a.active = TRUE) AND ((a.usertype = 2) OR (a.usertype = 7))");
|
|
|
|
var ret = await ct.User.AsNoTracking().Where(z => z.Active == true && (
|
|
z.UserType == UserType.Service ||
|
|
z.UserType == UserType.ServiceContractor)).LongCountAsync();
|
|
return ret;
|
|
}
|
|
}
|
|
|
|
//check for active status of user
|
|
//used by notification processing and others
|
|
internal static async Task<bool> UserIsActive(long userId)
|
|
{
|
|
using (AyContext ct = ServiceProviderProvider.DBContext)
|
|
{
|
|
return await ct.User.AsNoTracking().Where(z => z.Id == userId).Select(z => z.Active).FirstAsync();
|
|
}
|
|
}
|
|
|
|
//Called by license processor when use downgrades to lesser amount of techs
|
|
internal static async Task DeActivateExcessiveTechs(long KeepThisManyActiveTechs, ILogger _log)
|
|
{
|
|
var TotalActiveTechs = await ActiveCountAsync();
|
|
int CountOfTechsToSetInactive = (int)(TotalActiveTechs - KeepThisManyActiveTechs);
|
|
if (CountOfTechsToSetInactive < 1) return;
|
|
_log.LogInformation($"New license is a downgrade with fewer scheduleable resources, deactivating {CountOfTechsToSetInactive} scheduleable users automatically so the license can be installed");
|
|
//bugbug: exactly wrong, deactivating the most recently logged in over some who never logged in, could be that null login is causing it?
|
|
using (AyContext ct = ServiceProviderProvider.DBContext)
|
|
{
|
|
|
|
//Algorithm: For deactivation favor subcontractors first over servicetechs, favor ones that have no login records and finally favor by oldest last login
|
|
//theory is to catch the least likely to be currently active techs
|
|
|
|
var NoLoginTechList = await ct.User.Where(z => z.Active == true && z.LastLogin == null && (
|
|
z.UserType == UserType.Service ||
|
|
z.UserType == UserType.ServiceContractor)).OrderByDescending(z => z.UserType).Take(CountOfTechsToSetInactive).ToListAsync();
|
|
|
|
CountOfTechsToSetInactive -= NoLoginTechList.Count();
|
|
foreach (User u in NoLoginTechList)
|
|
{
|
|
u.Active = false;
|
|
var msg = $"User {u.Name} with no prior login automatically set to inactive to free up downgraded license";
|
|
await NotifyEventHelper.AddOpsProblemEvent(msg);
|
|
_log.LogInformation(msg);
|
|
}
|
|
await ct.SaveChangesAsync();
|
|
|
|
|
|
var HasLoginTechList = await ct.User.Where(z => z.Active == true && z.LastLogin != null && (
|
|
z.UserType == UserType.Service ||
|
|
z.UserType == UserType.ServiceContractor)).OrderByDescending(z => z.UserType).ThenBy(z => z.LastLogin).Take(CountOfTechsToSetInactive).ToListAsync();
|
|
foreach (User u in HasLoginTechList)
|
|
{
|
|
u.Active = false;
|
|
_log.LogInformation($"User {u.Name} who last logged in {u.LastLogin} automatically set to inactive to free up license");
|
|
}
|
|
await ct.SaveChangesAsync();
|
|
}
|
|
}
|
|
|
|
internal static void ResetSuperUserPassword()
|
|
{
|
|
using (AyContext ct = ServiceProviderProvider.DBContext)
|
|
{
|
|
User dbObject = ct.User.FirstOrDefault(z => z.Id == 1);
|
|
dbObject.Password = Hasher.hash(dbObject.Salt, ServerBootConfig.AYANOVA_SET_SUPERUSER_PW);
|
|
ct.SaveChanges();
|
|
|
|
NotifyEventHelper.AddOpsProblemEvent("AYANOVA_SET_SUPERUSER_PW setting was used at most recent server boot to reset SuperUser account password").Wait();
|
|
}
|
|
}
|
|
|
|
internal static async Task<CustomerRightsRecord> CustomerUserEffectiveRightsAsync(long userId)
|
|
{
|
|
using (AyContext ct = ServiceProviderProvider.DBContext)
|
|
{
|
|
|
|
var UserInfo = await ct.User.AsNoTracking().Where(x => x.Id == userId).Select(x => new { x.UserType, x.HeadOfficeId, x.CustomerId, x.Tags }).FirstAsync();
|
|
if (UserInfo.UserType != UserType.Customer && UserInfo.UserType != UserType.HeadOffice)
|
|
throw new System.NotSupportedException($"UserBiz::CustomerUserEffectiveRights - Requested for non Customer type user with ID {userId} who is UserType: {UserInfo.UserType}");
|
|
|
|
List<string> AllTags = new List<string>();
|
|
AllTags.AddRange(UserInfo.Tags);
|
|
|
|
bool EntityActive = false;
|
|
//Contact is for a customer or for a head office not both so...
|
|
if (UserInfo.CustomerId != null && UserInfo.CustomerId != 0)
|
|
{
|
|
var CustomerInfo = await ct.Customer.AsNoTracking().Where(x => x.Id == UserInfo.CustomerId).Select(x => new { x.HeadOfficeId, x.Tags, x.Active }).FirstAsync();
|
|
AllTags.AddRange(CustomerInfo.Tags);
|
|
EntityActive = CustomerInfo.Active;
|
|
//does the customer have a head office??
|
|
if (CustomerInfo.HeadOfficeId != null && CustomerInfo.HeadOfficeId != 0)
|
|
AllTags.AddRange(await ct.HeadOffice.AsNoTracking().Where(x => x.Id == CustomerInfo.HeadOfficeId).Select(x => x.Tags).FirstAsync());
|
|
}
|
|
else if (UserInfo.HeadOfficeId != null && UserInfo.HeadOfficeId != 0)
|
|
{
|
|
var HOInfo = await ct.HeadOffice.AsNoTracking().Where(x => x.Id == UserInfo.HeadOfficeId).Select(x => new { x.Tags, x.Active }).FirstAsync();
|
|
AllTags.AddRange(HOInfo.Tags);
|
|
EntityActive = HOInfo.Active;
|
|
}
|
|
|
|
long EntityId = 0;
|
|
if (UserInfo.UserType == UserType.Customer) EntityId = UserInfo.CustomerId ?? 0;
|
|
if (UserInfo.UserType == UserType.HeadOffice) EntityId = UserInfo.HeadOfficeId ?? 0;
|
|
|
|
|
|
return new CustomerRightsRecord(
|
|
CustomerUserEffectiveRightsAllowed(AyaNova.Util.ServerGlobalBizSettings.Cache.CustomerAllowCSR,
|
|
AllTags,
|
|
AyaNova.Util.ServerGlobalBizSettings.Cache.CustomerAllowCSRInTags,
|
|
AyaNova.Util.ServerGlobalBizSettings.Cache.CustomerAllowCSROutTags),
|
|
|
|
CustomerUserEffectiveRightsAllowed(AyaNova.Util.ServerGlobalBizSettings.Cache.CustomerAllowViewWO,
|
|
AllTags,
|
|
AyaNova.Util.ServerGlobalBizSettings.Cache.CustomerAllowViewWOInTags,
|
|
AyaNova.Util.ServerGlobalBizSettings.Cache.CustomerAllowViewWOOutTags),
|
|
|
|
CustomerUserEffectiveRightsAllowed(AyaNova.Util.ServerGlobalBizSettings.Cache.CustomerAllowWOWiki,
|
|
AllTags,
|
|
AyaNova.Util.ServerGlobalBizSettings.Cache.CustomerAllowWOWikiInTags,
|
|
AyaNova.Util.ServerGlobalBizSettings.Cache.CustomerAllowWOWikiOutTags),
|
|
|
|
CustomerUserEffectiveRightsAllowed(AyaNova.Util.ServerGlobalBizSettings.Cache.CustomerAllowUserSettings,
|
|
AllTags,
|
|
AyaNova.Util.ServerGlobalBizSettings.Cache.CustomerAllowUserSettingsInTags,
|
|
AyaNova.Util.ServerGlobalBizSettings.Cache.CustomerAllowUserSettingsOutTags),
|
|
|
|
CustomerUserEffectiveRightsAllowed(AyaNova.Util.ServerGlobalBizSettings.Cache.CustomerAllowNotifyServiceImminent,
|
|
AllTags,
|
|
AyaNova.Util.ServerGlobalBizSettings.Cache.CustomerAllowNotifyServiceImminentInTags,
|
|
AyaNova.Util.ServerGlobalBizSettings.Cache.CustomerAllowNotifyServiceImminentOutTags),
|
|
|
|
CustomerUserEffectiveRightsAllowed(AyaNova.Util.ServerGlobalBizSettings.Cache.CustomerAllowNotifyCSRAccepted,
|
|
AllTags,
|
|
AyaNova.Util.ServerGlobalBizSettings.Cache.CustomerAllowNotifyCSRAcceptedInTags,
|
|
AyaNova.Util.ServerGlobalBizSettings.Cache.CustomerAllowNotifyCSRAcceptedOutTags),
|
|
|
|
CustomerUserEffectiveRightsAllowed(AyaNova.Util.ServerGlobalBizSettings.Cache.CustomerAllowNotifyCSRRejected,
|
|
AllTags,
|
|
AyaNova.Util.ServerGlobalBizSettings.Cache.CustomerAllowNotifyCSRRejectedInTags,
|
|
AyaNova.Util.ServerGlobalBizSettings.Cache.CustomerAllowNotifyCSRRejectedOutTags),
|
|
|
|
CustomerUserEffectiveRightsAllowed(AyaNova.Util.ServerGlobalBizSettings.Cache.CustomerAllowNotifyWOCreated,
|
|
AllTags,
|
|
AyaNova.Util.ServerGlobalBizSettings.Cache.CustomerAllowNotifyWOCreatedInTags,
|
|
AyaNova.Util.ServerGlobalBizSettings.Cache.CustomerAllowNotifyWOCreatedOutTags),
|
|
|
|
CustomerUserEffectiveRightsAllowed(AyaNova.Util.ServerGlobalBizSettings.Cache.CustomerAllowNotifyWOCompleted,
|
|
AllTags,
|
|
AyaNova.Util.ServerGlobalBizSettings.Cache.CustomerAllowNotifyWOCompletedInTags,
|
|
AyaNova.Util.ServerGlobalBizSettings.Cache.CustomerAllowNotifyWOCompletedOutTags),
|
|
EntityId,
|
|
EntityActive
|
|
);
|
|
|
|
}
|
|
}
|
|
|
|
|
|
private static bool CustomerUserEffectiveRightsAllowed(bool allowed, List<string> contactTags, List<string> inTags, List<string> outTags)
|
|
{
|
|
//Note: tag match rule as planned and documented is that it's a match if *any* single tag in intags or outtags are a match to any single tag in contact tags,
|
|
//not the whole list, just any one of them which differs from how notifications are checked for example which need to *all* match
|
|
|
|
//if outright banned then quickest short circuit here
|
|
if (!allowed) return false;
|
|
|
|
//No tags to verify means allowed
|
|
if (inTags.Count == 0 && outTags.Count == 0) return true;
|
|
|
|
//if contact tags is empty and inclusive is empty then it's a match and can short circuit
|
|
if (contactTags.Count == 0 && inTags.Count == 0) return true;
|
|
|
|
//if contact tags is empty and inclusive is not empty then no match is possible
|
|
if (contactTags.Count == 0 && inTags.Count > 0) return false;
|
|
|
|
//any of the exclusive tags in contact tags?
|
|
if (contactTags.Intersect(outTags).Any()) return false;
|
|
|
|
//any of the inclusive tags in contact tags?
|
|
if (contactTags.Intersect(inTags).Any()) return true;
|
|
|
|
return false;//this is because there are contact and in tags but there is no match
|
|
}
|
|
|
|
|
|
internal static UserBiz GetBiz(AyContext ct, Microsoft.AspNetCore.Http.HttpContext httpContext = null)
|
|
{
|
|
if (httpContext != null)
|
|
return new UserBiz(ct, UserIdFromContext.Id(httpContext.Items), UserTranslationIdFromContext.Id(httpContext.Items), UserRolesFromContext.Roles(httpContext.Items));
|
|
else//when called internally for internal ops there will be no context so need to set default values for that
|
|
return new UserBiz(ct, 1, ServerBootConfig.AYANOVA_DEFAULT_TRANSLATION_ID, AuthorizationRoles.BizAdmin);
|
|
}
|
|
|
|
////////////////////////////////////////////////////////////////////////////////////////////////
|
|
//EXISTS
|
|
internal async Task<bool> ExistsAsync(long id)
|
|
{
|
|
return await ct.User.AnyAsync(z => z.Id == id);
|
|
}
|
|
|
|
////////////////////////////////////////////////////////////////////////////////////////////////
|
|
//CREATE
|
|
internal async Task<dtUser> CreateAsync(User newObject)
|
|
{
|
|
|
|
//Also used for Contacts (customer type user or ho type user)
|
|
//by users with no User right but with Customer rights so need to double check here
|
|
if (
|
|
(newObject.IsOutsideUser && !Authorized.HasCreateRole(CurrentUserRoles, AyaType.Customer)) ||
|
|
(!newObject.IsOutsideUser && !Authorized.HasCreateRole(CurrentUserRoles, AyaType.User))
|
|
)
|
|
{
|
|
AddError(ApiErrorCode.NOT_AUTHORIZED);
|
|
return null;
|
|
}
|
|
|
|
|
|
//password and login are optional but in the sense that they can be left out in a PUT
|
|
// but if left out here we need to generate a random value instead so they can't login but the code is happy
|
|
//because a login name and password are required always
|
|
if (string.IsNullOrWhiteSpace(newObject.Password))
|
|
newObject.Password = Hasher.GenerateSalt();//set it to some big random value
|
|
|
|
if (string.IsNullOrWhiteSpace(newObject.Login))
|
|
newObject.Login = Hasher.GenerateSalt();//set it to some big random value
|
|
|
|
|
|
//This is a new user so it will have been posted with a password in plaintext which needs to be salted and hashed
|
|
newObject.Salt = Hasher.GenerateSalt();
|
|
newObject.Password = Hasher.hash(newObject.Salt, newObject.Password);
|
|
|
|
|
|
newObject.Tags = TagBiz.NormalizeTags(newObject.Tags);
|
|
newObject.CustomFields = JsonUtil.CompactJson(newObject.CustomFields);
|
|
|
|
//Seeder sets user options in advance so no need to create them here in that case
|
|
if (newObject.UserOptions == null)
|
|
{
|
|
newObject.UserOptions = new UserOptions();
|
|
newObject.UserOptions.TranslationId = ServerBootConfig.AYANOVA_DEFAULT_TRANSLATION_ID;
|
|
}
|
|
|
|
await ValidateAsync(newObject, null);
|
|
if (HasErrors)
|
|
return null;
|
|
else
|
|
{
|
|
|
|
await ct.User.AddAsync(newObject);
|
|
await ct.SaveChangesAsync();
|
|
await EventLogProcessor.LogEventToDatabaseAsync(new Event(UserId, newObject.Id, BizType, AyaEvent.Created), ct);
|
|
await SearchIndexAsync(newObject, true);
|
|
await TagBiz.ProcessUpdateTagsInRepositoryAsync(ct, newObject.Tags, null);
|
|
await HandlePotentialNotificationEvent(AyaEvent.Created, newObject);
|
|
dtUser retUser = new dtUser();
|
|
CopyObject.Copy(newObject, retUser);
|
|
return retUser;
|
|
}
|
|
}
|
|
|
|
// ////////////////////////////////////////////////////////////////////////////////////////////////
|
|
// //DUPLICATE
|
|
// //
|
|
// internal async Task<User> DuplicateAsync(long id)
|
|
// {
|
|
// User dbObject = await GetAsync(id, false);
|
|
|
|
// if (dbObject == null)
|
|
// {
|
|
// AddError(ApiErrorCode.NOT_FOUND, "id");
|
|
// return null;
|
|
// }
|
|
|
|
// //Also used for Contacts (customer type user or ho type user)
|
|
// //by users with no User right but with Customer rights so need to double check here
|
|
// if (
|
|
// (dbObject.IsOutsideUser && !Authorized.HasCreateRole(CurrentUserRoles, AyaType.Customer)) ||
|
|
// (!dbObject.IsOutsideUser && !Authorized.HasCreateRole(CurrentUserRoles, AyaType.User))
|
|
// )
|
|
// {
|
|
// AddError(ApiErrorCode.NOT_AUTHORIZED);
|
|
// return null;
|
|
// }
|
|
|
|
// User newObject = new User();
|
|
// CopyObject.Copy(dbObject, newObject, "Id, Salt, Login, Password, CurrentAuthToken, DlKey, DlKeyExpire, Wiki, Serial");
|
|
// string newUniqueName = string.Empty;
|
|
// bool NotUnique = true;
|
|
// long l = 1;
|
|
// do
|
|
// {
|
|
// newUniqueName = Util.StringUtil.UniqueNameBuilder(dbObject.Name, l++, 255);
|
|
// NotUnique = await ct.User.AnyAsync(z => z.Name == newUniqueName);
|
|
// } while (NotUnique);
|
|
// newObject.Name = newUniqueName;
|
|
// newObject.Id = 0;
|
|
// newObject.Concurrency = 0;
|
|
// newObject.Salt = Hasher.GenerateSalt();
|
|
// newObject.Password = Hasher.GenerateSalt();
|
|
// newObject.Login = Hasher.GenerateSalt();
|
|
// newObject.UserOptions = new UserOptions();
|
|
// newObject.UserOptions.TranslationId = ServerBootConfig.AYANOVA_DEFAULT_TRANSLATION_ID;
|
|
// await ct.User.AddAsync(newObject);
|
|
// await ct.SaveChangesAsync();
|
|
// await EventLogProcessor.LogEventToDatabaseAsync(new Event(UserId, newObject.Id, BizType, AyaEvent.Created), ct);
|
|
// await SearchIndexAsync(newObject, true);
|
|
// await TagBiz.ProcessUpdateTagsInRepositoryAsync(ct, newObject.Tags, null);
|
|
// await HandlePotentialNotificationEvent(AyaEvent.Created, newObject);
|
|
// return newObject;
|
|
// }
|
|
|
|
////////////////////////////////////////////////////////////////////////////////////////////////
|
|
/// GET
|
|
|
|
//Get one
|
|
internal async Task<dtUser> GetForPublicAsync(long Id, bool logTheGetEvent = true)
|
|
{
|
|
|
|
//This is simple so nothing more here, but often will be copying to a different output object or some other ops
|
|
var dbFullUser = await ct.User.AsNoTracking().SingleOrDefaultAsync(z => z.Id == Id);
|
|
if (dbFullUser != null)
|
|
{
|
|
//Log
|
|
if (logTheGetEvent)
|
|
await EventLogProcessor.LogEventToDatabaseAsync(new Event(UserId, Id, BizType, AyaEvent.Retrieved), ct);
|
|
|
|
|
|
dtUser retUser = new dtUser();
|
|
CopyObject.Copy(dbFullUser, retUser);
|
|
return retUser;
|
|
}
|
|
else return null;
|
|
}
|
|
|
|
//Get one for internal use
|
|
internal async Task<User> GetAsync(long Id, bool logTheGetEvent = true)
|
|
{
|
|
|
|
//This is simple so nothing more here, but often will be copying to a different output object or some other ops
|
|
var dbObject = await ct.User.AsNoTracking().SingleOrDefaultAsync(z => z.Id == Id);
|
|
if (dbObject != null)
|
|
{
|
|
//Log
|
|
if (logTheGetEvent)
|
|
await EventLogProcessor.LogEventToDatabaseAsync(new Event(UserId, Id, BizType, AyaEvent.Retrieved), ct);
|
|
return dbObject;
|
|
}
|
|
else return null;
|
|
}
|
|
|
|
|
|
// ////////////////////////////////////////////////////////////////////////////////////////////////
|
|
// //UPDATE
|
|
// //
|
|
// internal async Task<User> PutAsync(User putObject)
|
|
// {
|
|
// //todo: update to use the new PUT methodology
|
|
// var dbObject = await GetAsync(putObject.Id, false);
|
|
// if (dbObject == null)
|
|
// {
|
|
// AddError(ApiErrorCode.NOT_FOUND, "id");
|
|
// return null;
|
|
// }
|
|
// //Also used for Contacts (customer type user or ho type user)
|
|
// //by users with no User right but with Customer rights so need to double check here
|
|
// if (
|
|
// (dbObject.IsOutsideUser && !Authorized.HasModifyRole(CurrentUserRoles, AyaType.Customer)) ||
|
|
// (!dbObject.IsOutsideUser && !Authorized.HasModifyRole(CurrentUserRoles, AyaType.User))
|
|
// )
|
|
// {
|
|
// AddError(ApiErrorCode.NOT_AUTHORIZED);
|
|
// return null;
|
|
// }
|
|
|
|
|
|
// User SnapshotOfOriginalDBObj = new User();
|
|
// CopyObject.Copy(dbObject, SnapshotOfOriginalDBObj);
|
|
// CopyObject.Copy(putObject, dbObject, "Id, Salt, CurrentAuthToken, LoginKey, DlKey, DlKeyExpire");
|
|
// dbObject.Tags = TagBiz.NormalizeTags(dbObject.Tags);
|
|
// dbObject.CustomFields = JsonUtil.CompactJson(dbObject.CustomFields);
|
|
|
|
// //NOTE: It's valid to call this without intending to change login or password (null values)
|
|
// //Is the user updating the password?
|
|
// if (!string.IsNullOrWhiteSpace(putObject.Password))
|
|
// {
|
|
// //YES password is being updated:
|
|
// dbObject.Password = Hasher.hash(SnapshotOfOriginalDBObj.Salt, putObject.Password);
|
|
// }
|
|
// else
|
|
// {
|
|
// //No, use the snapshot password value
|
|
// dbObject.Password = SnapshotOfOriginalDBObj.Password;
|
|
// dbObject.Salt = SnapshotOfOriginalDBObj.Salt;
|
|
// }
|
|
// //Updating login?
|
|
// if (!string.IsNullOrWhiteSpace(putObject.Login))
|
|
// {
|
|
// //YES Login is being updated:
|
|
// dbObject.Login = putObject.Login;
|
|
// }
|
|
// else
|
|
// {
|
|
// //No, use the original value
|
|
// dbObject.Login = SnapshotOfOriginalDBObj.Login;
|
|
// }
|
|
|
|
|
|
// ct.Entry(dbObject).OriginalValues["Concurrency"] = putObject.Concurrency;
|
|
// await ValidateAsync(dbObject, SnapshotOfOriginalDBObj);
|
|
// if (HasErrors) return null;
|
|
// try
|
|
// {
|
|
// await ct.SaveChangesAsync();
|
|
// }
|
|
// catch (DbUpdateConcurrencyException)
|
|
// {
|
|
// if (!await ExistsAsync(putObject.Id))
|
|
// AddError(ApiErrorCode.NOT_FOUND);
|
|
// else
|
|
// AddError(ApiErrorCode.CONCURRENCY_CONFLICT);
|
|
// return null;
|
|
// }
|
|
// await EventLogProcessor.LogEventToDatabaseAsync(new Event(UserId, dbObject.Id, BizType, AyaEvent.Modified), ct);
|
|
// await SearchIndexAsync(dbObject, false);
|
|
// await TagBiz.ProcessUpdateTagsInRepositoryAsync(ct, dbObject.Tags, SnapshotOfOriginalDBObj.Tags);
|
|
// await HandlePotentialNotificationEvent(AyaEvent.Modified, dbObject, SnapshotOfOriginalDBObj);
|
|
|
|
|
|
// return dbObject;
|
|
// }
|
|
|
|
|
|
////////////////////////////////////////////////////////////////////////////////////////////////
|
|
//UPDATE
|
|
//
|
|
internal async Task<User> PutAsync(User putObject)
|
|
{
|
|
var dbObject = await GetAsync(putObject.Id, false);
|
|
if (dbObject == null)
|
|
{
|
|
AddError(ApiErrorCode.NOT_FOUND, "id");
|
|
return null;
|
|
}
|
|
if (dbObject.Concurrency != putObject.Concurrency)
|
|
{
|
|
AddError(ApiErrorCode.CONCURRENCY_CONFLICT);
|
|
return null;
|
|
}
|
|
//Also used for Contacts (customer type user or ho type user)
|
|
//by users with no User right but with Customer rights so need to double check here
|
|
if (
|
|
(dbObject.IsOutsideUser && !Authorized.HasModifyRole(CurrentUserRoles, AyaType.Customer)) ||
|
|
(!dbObject.IsOutsideUser && !Authorized.HasModifyRole(CurrentUserRoles, AyaType.User))
|
|
)
|
|
{
|
|
AddError(ApiErrorCode.NOT_AUTHORIZED);
|
|
return null;
|
|
}
|
|
|
|
putObject.Tags = TagBiz.NormalizeTags(putObject.Tags);
|
|
putObject.CustomFields = JsonUtil.CompactJson(putObject.CustomFields);
|
|
|
|
//Fields not sent with the put object
|
|
//(it's only location is in the db and since this putObject is replacing the dbObject we need to set it again here)
|
|
putObject.Salt = dbObject.Salt;
|
|
putObject.CurrentAuthToken = dbObject.CurrentAuthToken;
|
|
putObject.DlKey = dbObject.DlKey;
|
|
putObject.DlKeyExpire = dbObject.DlKeyExpire;
|
|
putObject.PasswordResetCode = dbObject.PasswordResetCode;
|
|
putObject.PasswordResetCodeExpire = dbObject.PasswordResetCodeExpire;
|
|
|
|
|
|
//NOTE: It's valid to call this without intending to change login or password (null values)
|
|
//Is the user updating the password?
|
|
if (!string.IsNullOrWhiteSpace(putObject.Password))
|
|
{
|
|
//YES password is being updated:
|
|
putObject.Password = Hasher.hash(putObject.Salt, putObject.Password);
|
|
}
|
|
else
|
|
{
|
|
//No, use the snapshot password value
|
|
putObject.Password = dbObject.Password;
|
|
}
|
|
//Updating login?
|
|
if (string.IsNullOrWhiteSpace(putObject.Login))
|
|
{
|
|
//No, use the original value
|
|
putObject.Login = dbObject.Login;
|
|
}
|
|
|
|
await ValidateAsync(putObject, dbObject);
|
|
if (HasErrors) return null;
|
|
ct.Replace(dbObject, putObject);
|
|
try
|
|
{
|
|
await ct.SaveChangesAsync();
|
|
}
|
|
catch (DbUpdateConcurrencyException)
|
|
{
|
|
if (!await ExistsAsync(putObject.Id))
|
|
AddError(ApiErrorCode.NOT_FOUND);
|
|
else
|
|
AddError(ApiErrorCode.CONCURRENCY_CONFLICT);
|
|
return null;
|
|
}
|
|
await EventLogProcessor.LogEventToDatabaseAsync(new Event(UserId, dbObject.Id, BizType, AyaEvent.Modified), ct);
|
|
await SearchIndexAsync(putObject, false);
|
|
await TagBiz.ProcessUpdateTagsInRepositoryAsync(ct, putObject.Tags, dbObject.Tags);
|
|
await HandlePotentialNotificationEvent(AyaEvent.Modified, putObject, dbObject);
|
|
return putObject;
|
|
}
|
|
|
|
|
|
|
|
/////////////////////////////////////////////
|
|
//PASSWORD
|
|
//
|
|
internal async Task<bool> ChangePasswordAsync(long userId, string newPassword)
|
|
{
|
|
User dbObject = await ct.User.FirstOrDefaultAsync(z => z.Id == userId);
|
|
dbObject.Password = Hasher.hash(dbObject.Salt, newPassword);
|
|
|
|
//remove reseet code and date so it can't be used again
|
|
dbObject.PasswordResetCode = null;
|
|
dbObject.DlKeyExpire = null;
|
|
|
|
await ct.SaveChangesAsync();
|
|
|
|
//Log modification and save context
|
|
await EventLogProcessor.LogEventToDatabaseAsync(new Event(UserId, dbObject.Id, BizType, AyaEvent.Modified), ct);
|
|
|
|
return true;
|
|
}
|
|
|
|
|
|
/////////////////////////////////////////////
|
|
// GENERATE AND EMAIL Password reset code
|
|
//
|
|
internal async Task<uint> SendPasswordResetCode(long userId)
|
|
{
|
|
User dbObject = await ct.User.Include(o => o.UserOptions).FirstOrDefaultAsync(z => z.Id == userId);
|
|
if (dbObject == null)
|
|
{
|
|
AddError(ApiErrorCode.NOT_FOUND);
|
|
return 0;
|
|
}
|
|
//Also used for Contacts (customer type user or ho type user)
|
|
//by users with no User right but with Customer rights so need to double check here
|
|
if (
|
|
(dbObject.IsOutsideUser && !Authorized.HasModifyRole(CurrentUserRoles, AyaType.Customer)) ||
|
|
(!dbObject.IsOutsideUser && !Authorized.HasModifyRole(CurrentUserRoles, AyaType.User))
|
|
)
|
|
{
|
|
AddError(ApiErrorCode.NOT_AUTHORIZED);
|
|
return 0;
|
|
}
|
|
|
|
if (string.IsNullOrWhiteSpace(dbObject.UserOptions.EmailAddress))
|
|
{
|
|
AddError(ApiErrorCode.VALIDATION_REQUIRED, "EmailAddress");
|
|
return 0;
|
|
}
|
|
var ServerUrl = ServerGlobalOpsSettingsCache.Notify.AyaNovaServerURL;
|
|
if (string.IsNullOrWhiteSpace(ServerUrl))
|
|
{
|
|
await NotifyEventHelper.AddOpsProblemEvent("User::SendPasswordResetCode - The OPS Notification setting is empty for AyaNova Server URL. This prevents Notification system from linking events to openable objects.");
|
|
AddError(ApiErrorCode.VALIDATION_REQUIRED, "ServerUrl", "Error: no server url configured in notification settings. Can't direct user to server for login. Set server URL and try again.");
|
|
return 0;
|
|
}
|
|
|
|
var ResetCode = Hasher.GetRandomAlphanumericString(32);
|
|
|
|
dbObject.PasswordResetCode = ResetCode;
|
|
dbObject.PasswordResetCodeExpire = DateTime.UtcNow.AddHours(48);//This is not enough time to issue a reset code on a friday at 5pm and use it Monday before noon, but it is more understandable and clear
|
|
await ct.SaveChangesAsync();
|
|
|
|
//send message
|
|
ServerUrl = ServerUrl.Trim().TrimEnd('/');
|
|
|
|
//Translations
|
|
List<string> TransKeysRequired = new List<string>();
|
|
TransKeysRequired.Add("PasswordResetMessageBody");
|
|
TransKeysRequired.Add("PasswordResetMessageTitle");
|
|
long EffectiveTranslationId = dbObject.UserOptions.TranslationId;
|
|
if (EffectiveTranslationId == 0) EffectiveTranslationId = ServerBootConfig.AYANOVA_DEFAULT_TRANSLATION_ID;
|
|
var TransDict = await TranslationBiz.GetSubsetStaticAsync(TransKeysRequired, EffectiveTranslationId);
|
|
var Title = TransDict["PasswordResetMessageTitle"];
|
|
var MessageBody = TransDict["PasswordResetMessageBody"];
|
|
var loginName = Uri.EscapeDataString(dbObject.Login);
|
|
|
|
//Hello {user_name},\n\nYour online account for service is available to you after you set your password.\nYou can use the following link for the next 48 hours to set your password.\n\nSet your password: {action_link}\n\nIf you did not request an account or password reset, please ignore this email.\n\nThanks,\n{registered_to}"
|
|
MessageBody = MessageBody.Replace("{user_name}", dbObject.Name).Replace("{action_link}", $"{ServerUrl}/home-reset?rc={ResetCode}&tr={EffectiveTranslationId}&lg={loginName}").Replace("{registered_to}", AyaNova.Core.License.ActiveKey.RegisteredTo);
|
|
IMailer m = AyaNova.Util.ServiceProviderProvider.Mailer;
|
|
|
|
await m.SendEmailAsync(dbObject.UserOptions.EmailAddress, Title, MessageBody, ServerGlobalOpsSettingsCache.Notify);
|
|
|
|
//Log modification and save context
|
|
await EventLogProcessor.LogEventToDatabaseAsync(new Event(UserId, dbObject.Id, BizType, AyaEvent.Modified, "SendPasswordResetCode"), ct);
|
|
return dbObject.Concurrency;
|
|
}
|
|
|
|
|
|
|
|
////////////////////////////////////////////////////////////////////////////////////////////////
|
|
//SEARCH
|
|
//
|
|
private async Task SearchIndexAsync(User obj, bool isNew)
|
|
{
|
|
var SearchParams = new Search.SearchIndexProcessObjectParameters(UserTranslationId, obj.Id, BizType);
|
|
DigestSearchText(obj, SearchParams);
|
|
if (isNew)
|
|
await Search.ProcessNewObjectKeywordsAsync(SearchParams);
|
|
else
|
|
await Search.ProcessUpdatedObjectKeywordsAsync(SearchParams);
|
|
}
|
|
|
|
public async Task<Search.SearchIndexProcessObjectParameters> GetSearchResultSummary(long id, AyaType specificType)
|
|
{
|
|
var obj = await GetAsync(id, false);
|
|
var SearchParams = new Search.SearchIndexProcessObjectParameters();
|
|
DigestSearchText(obj, SearchParams);
|
|
return SearchParams;
|
|
}
|
|
|
|
public void DigestSearchText(User obj, Search.SearchIndexProcessObjectParameters searchParams)
|
|
{
|
|
if (obj != null)
|
|
searchParams.AddText(obj.Notes)
|
|
.AddText(obj.Name)
|
|
.AddText(obj.Wiki)
|
|
.AddText(obj.Tags)
|
|
.AddText(obj.EmployeeNumber)
|
|
.AddCustomFields(obj.CustomFields);
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
////////////////////////////////////////////////////////////////////////////////////////////////
|
|
//DELETE
|
|
//
|
|
internal async Task<bool> DeleteAsync(long id, Microsoft.EntityFrameworkCore.Storage.IDbContextTransaction parentTransaction = null)
|
|
{
|
|
//this may be part of a larger delete operation involving other objects (e.g. Customer delete and remove contacts)
|
|
//if so then there will be a parent transaction otherwise we make our own
|
|
Microsoft.EntityFrameworkCore.Storage.IDbContextTransaction transaction = null;
|
|
if (parentTransaction == null)
|
|
transaction = await ct.Database.BeginTransactionAsync();
|
|
User dbObject = await ct.User.SingleOrDefaultAsync(z => z.Id == id);
|
|
if (dbObject == null)
|
|
{
|
|
AddError(ApiErrorCode.NOT_FOUND);
|
|
return false;
|
|
}
|
|
|
|
|
|
//Also used for Contacts (customer type user or ho type user)
|
|
//by users with no User right but with Customer rights so need to double check here
|
|
if (
|
|
(dbObject.IsOutsideUser && !Authorized.HasDeleteRole(CurrentUserRoles, AyaType.Customer)) ||
|
|
(!dbObject.IsOutsideUser && !Authorized.HasDeleteRole(CurrentUserRoles, AyaType.User))
|
|
)
|
|
{
|
|
AddError(ApiErrorCode.NOT_AUTHORIZED);
|
|
return false;
|
|
}
|
|
|
|
await ValidateCanDelete(dbObject);
|
|
if (HasErrors)
|
|
return false;
|
|
|
|
//Delete sibling objects
|
|
//USEROPTIONS
|
|
await ct.Database.ExecuteSqlInterpolatedAsync($"delete from auseroptions where userid = {dbObject.Id}");
|
|
//NOTIFY SUBSCRIPTIONS
|
|
//Note: will cascade delete notifyevent, and notification automatically
|
|
await ct.Database.ExecuteSqlInterpolatedAsync($"delete from anotifysubscription where userid = {dbObject.Id}");
|
|
//personal datalist options
|
|
await ct.Database.ExecuteSqlInterpolatedAsync($"delete from adatalistsavedfilter where public = {false} and userid = {dbObject.Id}");
|
|
await ct.Database.ExecuteSqlInterpolatedAsync($"delete from adatalistcolumnview where userid = {dbObject.Id}");
|
|
//Dashboard view
|
|
await ct.Database.ExecuteSqlInterpolatedAsync($"delete from adashboardview where userid = {dbObject.Id}");
|
|
|
|
//Remove the object
|
|
ct.User.Remove(dbObject);
|
|
try
|
|
{
|
|
await ct.SaveChangesAsync();
|
|
}
|
|
catch (Microsoft.EntityFrameworkCore.DbUpdateException)
|
|
{
|
|
//SPECIAL EXCEPTION
|
|
//seeded data isn't always attributed to the user who would normally have created data so
|
|
//this could fail due to referential integrity as they wouldn't be in the event log check above
|
|
//easiest workaround to avoid having to check a whole host of items is to just check if this fails due to ref.integrity and return sane message
|
|
AddError(ApiErrorCode.INVALID_OPERATION, "generalerror", await Translate("ErrorDBForeignKeyViolation"));
|
|
return false;
|
|
}
|
|
|
|
await EventLogProcessor.DeleteObjectLogAsync(UserId, BizType, dbObject.Id, dbObject.Name, ct);
|
|
await Search.ProcessDeletedObjectKeywordsAsync(dbObject.Id, BizType, ct);
|
|
await TagBiz.ProcessDeleteTagsInRepositoryAsync(ct, dbObject.Tags);
|
|
await FileUtil.DeleteAttachmentsForObjectAsync(BizType, dbObject.Id, ct);
|
|
|
|
//all good do the commit if it's ours
|
|
if (parentTransaction == null)
|
|
await transaction.CommitAsync();
|
|
await HandlePotentialNotificationEvent(AyaEvent.Deleted, dbObject);
|
|
return true;
|
|
|
|
}
|
|
|
|
|
|
////////////////////////////////////////////////////////////////////////////////////////////////
|
|
//VALIDATION
|
|
//
|
|
|
|
//Can save or update?
|
|
private async Task ValidateAsync(User proposedObj, User currentObj)
|
|
{
|
|
//skip validation if seeding
|
|
if (ServerBootConfig.SEEDING) return;
|
|
|
|
//run validation and biz rules
|
|
bool isNew = currentObj == null;
|
|
|
|
//UserType change has Inside / Outside role implications
|
|
//a user attempting to change a UserType between inside or outside status must have the correct rights
|
|
//to *BOTH* Customer and User since it's affecting both types
|
|
if (!isNew && (currentObj.IsOutsideUser != proposedObj.IsOutsideUser))
|
|
{
|
|
//only can change if have both rights
|
|
if (
|
|
!Authorized.HasModifyRole(CurrentUserRoles, AyaType.User) ||
|
|
!Authorized.HasModifyRole(CurrentUserRoles, AyaType.Customer)
|
|
)
|
|
{
|
|
AddError(ApiErrorCode.NOT_AUTHORIZED, "UserType");
|
|
}
|
|
}
|
|
|
|
//do we need to check the license situation?
|
|
if (proposedObj.IsTech && proposedObj.Active)
|
|
{
|
|
//Yes, it might be affected depending on things
|
|
long CurrentActiveCount = await UserBiz.ActiveCountAsync();
|
|
long LicensedUserCount = AyaNova.Core.License.ActiveKey.ActiveNumber;
|
|
|
|
if (isNew)
|
|
{
|
|
//This operation is about to consume one more license, check that we are not at the limit already
|
|
await CheckActiveForValidation(CurrentActiveCount, LicensedUserCount);
|
|
}
|
|
else
|
|
{
|
|
//did anything that might affect licensing change?
|
|
if (!currentObj.IsTech || (!currentObj.Active))//currently not a tech or if it is it's not active
|
|
{
|
|
//going from non tech to tech and active
|
|
//Yes, this is about to consume one more license, check that we are not at the limit already
|
|
await CheckActiveForValidation(CurrentActiveCount, LicensedUserCount);
|
|
}
|
|
}
|
|
}
|
|
|
|
|
|
// TODO: check user count if not new to see if affected that way
|
|
//also check user count in general to see if it's exceeded
|
|
//And maybe check it in login as well as a good central spot or wherever makes sense
|
|
|
|
//Name required
|
|
if (string.IsNullOrWhiteSpace(proposedObj.Name))
|
|
AddError(ApiErrorCode.VALIDATION_REQUIRED, "Name");
|
|
|
|
|
|
//If name is otherwise OK, check that name is unique
|
|
if (!PropertyHasErrors("Name"))
|
|
{
|
|
//Use Any command is efficient way to check existance, it doesn't return the record, just a true or false
|
|
if (await ct.User.AnyAsync(z => z.Name == proposedObj.Name && z.Id != proposedObj.Id))
|
|
{
|
|
AddError(ApiErrorCode.VALIDATION_NOT_UNIQUE, "Name");
|
|
}
|
|
}
|
|
|
|
//LOGIN must be unique
|
|
if (await ct.User.AnyAsync(z => z.Login == proposedObj.Login && z.Id != proposedObj.Id))
|
|
{
|
|
AddError(ApiErrorCode.VALIDATION_NOT_UNIQUE, "Login");
|
|
}
|
|
|
|
|
|
//SUPERUSER ACCOUNT CAN"T BE MODIFIED IN SOME WAYS
|
|
if (!isNew && proposedObj.Id == 1)
|
|
{
|
|
//prevent certain changes to superuser account like roles etc
|
|
|
|
if (proposedObj.Roles != currentObj.Roles)
|
|
AddError(ApiErrorCode.NOT_AUTHORIZED, "Roles");
|
|
|
|
if (proposedObj.Active != currentObj.Active)
|
|
AddError(ApiErrorCode.NOT_AUTHORIZED, "Active");
|
|
|
|
if (proposedObj.Name != currentObj.Name)
|
|
AddError(ApiErrorCode.NOT_AUTHORIZED, "Name");
|
|
|
|
if (proposedObj.UserType != currentObj.UserType)
|
|
AddError(ApiErrorCode.NOT_AUTHORIZED, "UserType");
|
|
|
|
}
|
|
|
|
//TODO: Validation rules that require future other objects that aren't present yet:
|
|
/*
|
|
|
|
|
|
//MIGRATE_OUTSTANDING TODO: role changes when has things that require a role like notification subscriptions and others
|
|
|
|
|
|
//Don't allow to go from non scheduleable if there are any scheduled workorder items because
|
|
//it would damage the history
|
|
BrokenRules.Assert("UserType","User.Label.MustBeScheduleable","UserType",(mUserType==UserTypes.Schedulable) && (ScheduledUserCount(this.mID,false)>0));
|
|
|
|
mUserType = value;
|
|
|
|
BrokenRules.Assert("UserTypeInvalid","Error.Object.FieldValueNotBetween,User.Label.UserType,1,7","UserType",((int)value<1 || (int)value>6));
|
|
|
|
bool bOutOfLicenses=OutOfLicenses;
|
|
BrokenRules.Assert("ActiveLicense","Error.Security.UserCapacity","Active",bOutOfLicenses);
|
|
BrokenRules.Assert("UserTypeLicense","Error.Security.UserCapacity","UserType",bOutOfLicenses);
|
|
|
|
//Case 850
|
|
BrokenRules.Assert("ClientIDInvalid", "Error.Object.RequiredFieldEmpty,O.Client", "ClientID",
|
|
(mUserType== UserTypes.Client && mClientID==Guid.Empty));
|
|
|
|
BrokenRules.Assert("HeadOfficeIDInvalid", "Error.Object.RequiredFieldEmpty,O.HeadOffice", "HeadOfficeID",
|
|
(mUserType == UserTypes.HeadOffice && mHeadOfficeID == Guid.Empty));
|
|
|
|
|
|
ACTIVE: need to check user count against license when re-activating a user
|
|
need to check open workorders and any other critical items when de-activating a user
|
|
*/
|
|
|
|
if (!proposedObj.UserType.IsValid())
|
|
{
|
|
AddError(ApiErrorCode.VALIDATION_INVALID_VALUE, "UserType");
|
|
}
|
|
|
|
//Validate customer type user
|
|
if (proposedObj.UserType == UserType.Customer)
|
|
{
|
|
if (proposedObj.CustomerId == null || proposedObj.CustomerId == 0)
|
|
{
|
|
AddError(ApiErrorCode.VALIDATION_REQUIRED, "CustomerId");
|
|
}
|
|
else
|
|
{
|
|
//verify chosen customer exists
|
|
if (!await ct.Customer.AnyAsync(z => z.Id == proposedObj.CustomerId))
|
|
AddError(ApiErrorCode.NOT_FOUND, "CustomerId");
|
|
}
|
|
}
|
|
|
|
//Validate headoffice type user
|
|
if (proposedObj.UserType == UserType.HeadOffice)
|
|
{
|
|
if (proposedObj.HeadOfficeId == null || proposedObj.HeadOfficeId == 0)
|
|
{
|
|
AddError(ApiErrorCode.VALIDATION_REQUIRED, "HeadOfficeId");
|
|
}
|
|
else
|
|
{
|
|
//verify chosen HO exists
|
|
if (!await ct.HeadOffice.AnyAsync(z => z.Id == proposedObj.HeadOfficeId))
|
|
AddError(ApiErrorCode.NOT_FOUND, "HeadOfficeId");
|
|
}
|
|
}
|
|
|
|
//Validate subcontractor type user
|
|
if (proposedObj.UserType == UserType.ServiceContractor)
|
|
{
|
|
if (proposedObj.VendorId == null || proposedObj.VendorId == 0)
|
|
{
|
|
AddError(ApiErrorCode.VALIDATION_REQUIRED, "VendorId");
|
|
}
|
|
else
|
|
{
|
|
//verify that VENDOR VendorId exists
|
|
if (!await ct.Vendor.AnyAsync(z => z.Id == proposedObj.VendorId))
|
|
AddError(ApiErrorCode.NOT_FOUND, "VendorId");
|
|
}
|
|
}
|
|
|
|
if (!proposedObj.Roles.IsValid())
|
|
{
|
|
AddError(ApiErrorCode.VALIDATION_INVALID_VALUE, "Roles");
|
|
}
|
|
|
|
|
|
//Any form customizations to validate?
|
|
var FormCustomization = await ct.FormCustom.SingleOrDefaultAsync(z => z.FormKey == AyaType.User.ToString());
|
|
if (FormCustomization != null)
|
|
{
|
|
//Yeppers, do the validation, there are two, the custom fields and the regular fields that might be set to required
|
|
|
|
//validate users choices for required non custom fields
|
|
RequiredFieldsValidator.Validate(this, FormCustomization, proposedObj);
|
|
|
|
//validate custom fields
|
|
CustomFieldsValidator.Validate(this, FormCustomization, proposedObj.CustomFields);
|
|
}
|
|
|
|
return;
|
|
}
|
|
|
|
private async Task CheckActiveForValidation(long CurrentActiveCount, long LicensedUserCount)
|
|
{
|
|
if (CurrentActiveCount >= LicensedUserCount)
|
|
{
|
|
AddError(ApiErrorCode.INVALID_OPERATION, null, await Translate("ErrorSecurityUserCapacity"));
|
|
}
|
|
}
|
|
|
|
|
|
//Can delete?
|
|
private async Task ValidateCanDelete(User inObj)
|
|
{
|
|
|
|
|
|
//To make this simple and avoid a whole host of issues and work
|
|
//I've decided that a user can't be deleted if they have *any* activity in the event log
|
|
//this way a newly created user can be deleted before they do any real work still to cover a scenario where a user
|
|
//makes a user but then doesn't need it or did it wrong
|
|
//This avoids the whole issues related to having to check every table everywhere for their work and
|
|
//the associated fuckery with trying to back them out of those tables without knock-on effects
|
|
//They can always make any user inactive to get rid of them and it will mean referential integrity issues are not there
|
|
|
|
//There's only one rule - have they done anything eventlog worthy yet?
|
|
//if (await ct.Event.Select(z => z).Where(z => z.UserId == inObj.Id).Count() > 0)
|
|
if (await ct.Event.AnyAsync(z => z.UserId == inObj.Id))
|
|
{
|
|
//Theres no more specific error to show for this
|
|
AddError(ApiErrorCode.INVALID_OPERATION, "generalerror", await Translate("ErrorDBForeignKeyViolation"));
|
|
return;
|
|
}
|
|
|
|
}
|
|
|
|
|
|
////////////////////////////////////////////////////////////////////////////////////////////////
|
|
// Utilities
|
|
//
|
|
internal static async Task<User> ValidateDownloadTokenAndReturnUserAsync(string dlToken, AyContext ct)
|
|
{
|
|
if (string.IsNullOrWhiteSpace(dlToken))
|
|
return null;
|
|
//get user by key, if not found then reject
|
|
var DownloadUser = await ct.User.AsNoTracking().SingleOrDefaultAsync(z => z.DlKey == dlToken && z.Active == true);
|
|
if (DownloadUser == null)
|
|
return null;
|
|
//this is necessary because they might have an expired JWT but this would just keep on working without a date check
|
|
//the default is the same timespan as the jwt so it's all good
|
|
var utcNow = new DateTimeOffset(DateTime.Now.ToUniversalTime(), TimeSpan.Zero);
|
|
if (DownloadUser.DlKeyExpire < utcNow.DateTime)
|
|
return null;
|
|
return DownloadUser;
|
|
}
|
|
|
|
////////////////////////////////////////////////////////////////////////////////////////////////
|
|
//REPORTING
|
|
//
|
|
public async Task<JArray> GetReportData(DataListSelectedRequest dataListSelectedRequest)
|
|
{
|
|
var idList = dataListSelectedRequest.SelectedRowIds;
|
|
JArray ReportData = new JArray();
|
|
while (idList.Any())
|
|
{
|
|
var batch = idList.Take(IReportAbleObject.REPORT_DATA_BATCH_SIZE);
|
|
idList = idList.Skip(IReportAbleObject.REPORT_DATA_BATCH_SIZE).ToArray();
|
|
//query for this batch, comes back in db natural order unfortunately
|
|
var batchResults = await ct.User.AsNoTracking().Include(z => z.UserOptions).Where(z => batch.Contains(z.Id)).ToArrayAsync();
|
|
//order the results back into original
|
|
var orderedList = from id in batch join z in batchResults on id equals z.Id select z;
|
|
|
|
//cache frequent viz data
|
|
//usertypes
|
|
var UserTypesEnumList = await AyaNova.Api.Controllers.EnumListController.GetEnumList(
|
|
StringUtil.TrimTypeName(typeof(UserType).ToString()),
|
|
UserTranslationId,
|
|
CurrentUserRoles);
|
|
|
|
//foreach (User w in orderedList)
|
|
foreach (var w in orderedList)
|
|
{
|
|
await PopulateVizFields(w, UserTypesEnumList);
|
|
var jo = JObject.FromObject(w);
|
|
if (!JsonUtil.JTokenIsNullOrEmpty(jo["CustomFields"]))
|
|
jo["CustomFields"] = JObject.Parse((string)jo["CustomFields"]);
|
|
jo.Remove("Login");
|
|
jo.Remove("Password");
|
|
jo["UserOptions"] = JObject.FromObject(w.UserOptions);
|
|
|
|
ReportData.Add(jo);
|
|
}
|
|
}
|
|
return ReportData;
|
|
}
|
|
|
|
//populate viz fields from provided object
|
|
private async Task PopulateVizFields(User o, List<NameIdItem> userTypesEnumList)
|
|
{
|
|
if (o.CustomerId != null)
|
|
o.CustomerViz = await ct.Customer.AsNoTracking().Where(x => x.Id == o.CustomerId).Select(x => x.Name).FirstOrDefaultAsync();
|
|
|
|
if (o.HeadOfficeId != null)
|
|
o.HeadOfficeViz = await ct.HeadOffice.AsNoTracking().Where(x => x.Id == o.HeadOfficeId).Select(x => x.Name).FirstOrDefaultAsync();
|
|
|
|
if (o.VendorId != null)
|
|
o.VendorViz = await ct.Vendor.AsNoTracking().Where(x => x.Id == o.VendorId).Select(x => x.Name).FirstOrDefaultAsync();
|
|
|
|
o.UserTypeViz = userTypesEnumList.Where(x => x.Id == (long)o.UserType).Select(x => x.Name).First();
|
|
}
|
|
|
|
////////////////////////////////////////////////////////////////////////////////////////////////
|
|
// IMPORT EXPORT
|
|
//
|
|
|
|
|
|
public async Task<JArray> GetExportData(DataListSelectedRequest dataListSelectedRequest)
|
|
{
|
|
//for now just re-use the report data code
|
|
//this may turn out to be the pattern for most biz object types but keeping it seperate allows for custom usage from time to time
|
|
return await GetReportData(dataListSelectedRequest);
|
|
}
|
|
|
|
|
|
|
|
|
|
public async Task<List<string>> ImportData(JArray ja)
|
|
{
|
|
List<string> ImportResult = new List<string>();
|
|
string ImportTag = $"imported-{FileUtil.GetSafeDateFileName()}";
|
|
|
|
var jsset = JsonSerializer.CreateDefault(new JsonSerializerSettings { ContractResolver = new AyaNova.Util.JsonUtil.ShouldSerializeContractResolver(new string[] { "Concurrency", "Id", "CustomFields" }) });
|
|
foreach (JObject j in ja)
|
|
{
|
|
var w = j.ToObject<User>(jsset);
|
|
if (j["CustomFields"] != null)
|
|
w.CustomFields = j["CustomFields"].ToString();
|
|
w.Tags.Add(ImportTag);//so user can find them all and revert later if necessary
|
|
var res = await CreateAsync(w);
|
|
if (res == null)
|
|
{
|
|
ImportResult.Add($"* {w.Name} - {this.GetErrorsAsString()}");
|
|
this.ClearErrors();
|
|
}
|
|
else
|
|
{
|
|
ImportResult.Add($"{w.Name} - ok");
|
|
}
|
|
}
|
|
return ImportResult;
|
|
}
|
|
|
|
////////////////////////////////////////////////////////////////////////////////////////////////
|
|
// JOB / OPERATIONS
|
|
//
|
|
public async Task HandleJobAsync(OpsJob job)
|
|
{
|
|
switch (job.JobType)
|
|
{
|
|
case JobType.BatchCoreObjectOperation:
|
|
await ProcessBatchJobAsync(job);
|
|
break;
|
|
default:
|
|
throw new System.ArgumentOutOfRangeException($"User.HandleJob-> Invalid job type{job.JobType.ToString()}");
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private async Task ProcessBatchJobAsync(OpsJob job)
|
|
{
|
|
await JobsBiz.UpdateJobStatusAsync(job.GId, JobStatus.Running);
|
|
await JobsBiz.LogJobAsync(job.GId, $"LT:StartJob {job.SubType}");
|
|
List<long> idList = new List<long>();
|
|
long FailedObjectCount = 0;
|
|
JObject jobData = JObject.Parse(job.JobInfo);
|
|
if (jobData.ContainsKey("idList"))
|
|
idList = ((JArray)jobData["idList"]).ToObject<List<long>>();
|
|
else
|
|
idList = await ct.User.AsNoTracking().Select(z => z.Id).ToListAsync();
|
|
bool SaveIt = false;
|
|
foreach (long id in idList)
|
|
{
|
|
try
|
|
{
|
|
SaveIt = false;
|
|
ClearErrors();
|
|
//a little different than normal here because the built in getasync doesn't return
|
|
//a full User object normally
|
|
User o = null;
|
|
//save a fetch if it's a delete
|
|
if (job.SubType != JobSubType.Delete)
|
|
o = await GetAsync(id, false);
|
|
switch (job.SubType)
|
|
{
|
|
case JobSubType.TagAddAny:
|
|
case JobSubType.TagAdd:
|
|
case JobSubType.TagRemoveAny:
|
|
case JobSubType.TagRemove:
|
|
case JobSubType.TagReplaceAny:
|
|
case JobSubType.TagReplace:
|
|
SaveIt = TagBiz.ProcessBatchTagOperation(o.Tags, (string)jobData["tag"], jobData.ContainsKey("toTag") ? (string)jobData["toTag"] : null, job.SubType);
|
|
break;
|
|
case JobSubType.Delete:
|
|
if (!await DeleteAsync(id))
|
|
{
|
|
await JobsBiz.LogJobAsync(job.GId, $"LT:Errors {GetErrorsAsString()} id {id}");
|
|
FailedObjectCount++;
|
|
}
|
|
break;
|
|
default:
|
|
throw new System.ArgumentOutOfRangeException($"ProcessBatchJobAsync -> Invalid job Subtype{job.SubType}");
|
|
}
|
|
|
|
if (SaveIt)
|
|
{
|
|
o = await PutAsync(o);
|
|
if (o == null)
|
|
{
|
|
await JobsBiz.LogJobAsync(job.GId, $"LT:Errors {GetErrorsAsString()} id {id}");
|
|
FailedObjectCount++;
|
|
}
|
|
}
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
await JobsBiz.LogJobAsync(job.GId, $"LT:Errors id({id})");
|
|
await JobsBiz.LogJobAsync(job.GId, ExceptionUtil.ExtractAllExceptionMessages(ex));
|
|
}
|
|
}
|
|
await JobsBiz.LogJobAsync(job.GId, $"LT:BatchJob {job.SubType} {idList.Count}{(FailedObjectCount > 0 ? " - LT:Failed " + FailedObjectCount : "")}");
|
|
await JobsBiz.UpdateJobStatusAsync(job.GId, JobStatus.Completed);
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
////////////////////////////////////////////////////////////////////////////////////////////////
|
|
// NOTIFICATION PROCESSING
|
|
//
|
|
public async Task HandlePotentialNotificationEvent(AyaEvent ayaEvent, ICoreBizObjectModel proposedObj, ICoreBizObjectModel currentObj = null)
|
|
{
|
|
ILogger log = AyaNova.Util.ApplicationLogging.CreateLogger<UserBiz>();
|
|
if (ServerBootConfig.SEEDING || ServerBootConfig.MIGRATING) return;
|
|
log.LogDebug($"HandlePotentialNotificationEvent processing: [AyaType:{this.BizType}, AyaEvent:{ayaEvent}]");
|
|
|
|
bool isNew = currentObj == null;
|
|
|
|
|
|
//STANDARD EVENTS FOR ALL OBJECTS
|
|
await NotifyEventHelper.ProcessStandardObjectEvents(ayaEvent, proposedObj, ct);
|
|
|
|
//SPECIFIC EVENTS FOR THIS OBJECT
|
|
if (ayaEvent == AyaEvent.Modified)
|
|
{
|
|
//USER MODIFIED ROLES CHANGED MIGHT AFFECT ALLOWED SUBS
|
|
//This one's a little different, if user has had roles changed, then pre-existing subs may not be allowed anymore
|
|
//Remove any notification subscriptions user doesn't have rights to:
|
|
if (((User)currentObj).Roles != ((User)proposedObj).Roles)
|
|
{
|
|
var DeleteList = new List<long>();
|
|
var NewRoles = ((User)proposedObj).Roles;
|
|
//iterate subs and remove any user shouldn't have
|
|
var userSubs = await ct.NotifySubscription.Where(z => z.UserId == proposedObj.Id).ToListAsync();
|
|
foreach (var sub in userSubs)
|
|
{
|
|
if (sub.AyaType != AyaType.NoType)
|
|
{
|
|
//check if user has rights to it or not still
|
|
//must have read rights to be valid
|
|
if (!AyaNova.Api.ControllerHelpers.Authorized.HasAnyRole(NewRoles, sub.AyaType))
|
|
{
|
|
//no rights whatsoever, so delete it
|
|
DeleteList.Add(sub.Id);
|
|
}
|
|
}
|
|
}
|
|
if (DeleteList.Count > 0)
|
|
{
|
|
var NSB = NotifySubscriptionBiz.GetBiz(ct);
|
|
foreach (var l in DeleteList)
|
|
{
|
|
await NSB.DeleteAsync(l);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
}//end of process notifications
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
/////////////////////////////////////////////////////////////////////
|
|
|
|
}//eoc
|
|
|
|
|
|
}//eons
|
|
|