513 lines
21 KiB
C#
513 lines
21 KiB
C#
using System.Linq;
|
|
using System.Threading.Tasks;
|
|
using Microsoft.EntityFrameworkCore;
|
|
|
|
using EnumsNET;
|
|
using AyaNova.Util;
|
|
using AyaNova.Api.ControllerHelpers;
|
|
using AyaNova.Models;
|
|
|
|
namespace AyaNova.Biz
|
|
{
|
|
|
|
|
|
internal class UserBiz : BizObject, IJobObject, ISearchAbleObject
|
|
{
|
|
|
|
public bool SeedOrImportRelaxedRulesMode { get; set; }
|
|
|
|
internal UserBiz(AyContext dbcontext, long currentUserId, long userTranslationId, AuthorizationRoles userRoles)
|
|
{
|
|
ct = dbcontext;
|
|
UserId = currentUserId;
|
|
UserTranslationId = userTranslationId;
|
|
CurrentUserRoles = userRoles;
|
|
BizType = AyaType.User;
|
|
SeedOrImportRelaxedRulesMode = false;//default
|
|
}
|
|
|
|
//This is where active tech license consumers are accounted for
|
|
internal static async Task<long> ActiveCountAsync()
|
|
{
|
|
var ct = ServiceProviderProvider.DBContext;
|
|
var ret = await ct.User.Where(x => x.Active == true && (x.UserType == UserType.Schedulable || x.UserType == UserType.Subcontractor)).LongCountAsync();
|
|
|
|
return ret;
|
|
}
|
|
|
|
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.BizAdminFull);
|
|
}
|
|
|
|
|
|
|
|
////////////////////////////////////////////////////////////////////////////////////////////////
|
|
//CREATE
|
|
internal async Task<dtUser> CreateAsync(User inObj)
|
|
{
|
|
//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(inObj.Password))
|
|
{
|
|
inObj.Password = Hasher.GenerateSalt();//set it to some big random value
|
|
}
|
|
|
|
if (string.IsNullOrWhiteSpace(inObj.Login))
|
|
{
|
|
inObj.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
|
|
inObj.Salt = Hasher.GenerateSalt();
|
|
inObj.Password = Hasher.hash(inObj.Salt, inObj.Password);
|
|
|
|
|
|
inObj.Tags = TagUtil.NormalizeTags(inObj.Tags);
|
|
inObj.CustomFields = JsonUtil.CompactJson(inObj.CustomFields);
|
|
|
|
//Seeder sets user options in advance so no need to create them here in that case
|
|
if (inObj.UserOptions == null)
|
|
{
|
|
inObj.UserOptions = new UserOptions();
|
|
//todo: for now defaulting to server boot config but might need to add this to the route as an option
|
|
//now that it's not in the actual user record itself anymore as it's kind of critical
|
|
//revisit when get to client ui
|
|
inObj.UserOptions.TranslationId = ServerBootConfig.AYANOVA_DEFAULT_TRANSLATION_ID;
|
|
}
|
|
|
|
await ValidateAsync(inObj, null);
|
|
if (HasErrors)
|
|
return null;
|
|
else
|
|
{
|
|
|
|
await ct.User.AddAsync(inObj);
|
|
//save to get Id
|
|
await ct.SaveChangesAsync();
|
|
|
|
//Handle child and associated items
|
|
|
|
//Log event
|
|
await EventLogProcessor.LogEventToDatabaseAsync(new Event(UserId, inObj.Id, BizType, AyaEvent.Created), ct);
|
|
|
|
//SEARCH INDEXING
|
|
await SearchIndexAsync(inObj, true);
|
|
|
|
//TAGS
|
|
await TagUtil.ProcessUpdateTagsInRepositoryAsync(ct, inObj.Tags, null);
|
|
|
|
dtUser retUser = new dtUser();
|
|
CopyObject.Copy(inObj, retUser);
|
|
return retUser;
|
|
|
|
|
|
}
|
|
}
|
|
|
|
|
|
////////////////////////////////////////////////////////////////////////////////////////////////
|
|
/// GET
|
|
|
|
//Get one
|
|
internal async Task<dtUser> GetAsync(long fetchId)
|
|
{
|
|
//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.SingleOrDefaultAsync(m => m.Id == fetchId);
|
|
if (dbFullUser != null)
|
|
{
|
|
//Log
|
|
await EventLogProcessor.LogEventToDatabaseAsync(new Event(UserId, fetchId, BizType, AyaEvent.Retrieved), ct);
|
|
|
|
|
|
dtUser retUser = new dtUser();
|
|
CopyObject.Copy(dbFullUser, retUser);
|
|
return retUser;
|
|
}
|
|
else return null;
|
|
}
|
|
|
|
|
|
|
|
////////////////////////////////////////////////////////////////////////////////////////////////
|
|
//UPDATE
|
|
//
|
|
|
|
//put
|
|
internal async Task<bool> PutAsync(User dbObj, User inObj)
|
|
{
|
|
//Get a snapshot of the original db value object before changes
|
|
User SnapshotOfOriginalDBObj = new User();
|
|
CopyObject.Copy(dbObj, SnapshotOfOriginalDBObj);
|
|
|
|
//Update the db object with the PUT object values
|
|
CopyObject.Copy(inObj, dbObj, "Id, Salt, CurrentAuthToken, DlKey, DlKeyExpire");
|
|
dbObj.Tags = TagUtil.NormalizeTags(dbObj.Tags);
|
|
dbObj.CustomFields = JsonUtil.CompactJson(dbObj.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(inObj.Password) && SnapshotOfOriginalDBObj.Password != inObj.Password)
|
|
{
|
|
//YES password is being updated:
|
|
dbObj.Password = Hasher.hash(SnapshotOfOriginalDBObj.Salt, inObj.Password);
|
|
}
|
|
else
|
|
{
|
|
//No, use the snapshot password value
|
|
dbObj.Password = SnapshotOfOriginalDBObj.Password;
|
|
dbObj.Salt = SnapshotOfOriginalDBObj.Salt;
|
|
}
|
|
//Updating login?
|
|
if (!string.IsNullOrWhiteSpace(inObj.Login))
|
|
{
|
|
//YES Login is being updated:
|
|
dbObj.Login = inObj.Login;
|
|
}
|
|
else
|
|
{
|
|
//No, use the original value
|
|
dbObj.Login = SnapshotOfOriginalDBObj.Login;
|
|
}
|
|
|
|
|
|
//Set "original" value of concurrency token to input token
|
|
//this will allow EF to check it out
|
|
ct.Entry(dbObj).OriginalValues["Concurrency"] = inObj.Concurrency;
|
|
|
|
await ValidateAsync(dbObj, SnapshotOfOriginalDBObj);
|
|
if (HasErrors)
|
|
return false;
|
|
await ct.SaveChangesAsync();
|
|
|
|
//Log modification and save context
|
|
await EventLogProcessor.LogEventToDatabaseAsync(new Event(UserId, dbObj.Id, BizType, AyaEvent.Modified), ct);
|
|
|
|
await SearchIndexAsync(dbObj, false);
|
|
|
|
await TagUtil.ProcessUpdateTagsInRepositoryAsync(ct, dbObj.Tags, SnapshotOfOriginalDBObj.Tags);
|
|
|
|
return true;
|
|
}
|
|
|
|
//put
|
|
internal async Task<bool> ChangePasswordAsync(long userId, string newPassword)
|
|
{
|
|
User dbObj = await ct.User.FirstOrDefaultAsync(m => m.Id == userId);
|
|
dbObj.Password = Hasher.hash(dbObj.Salt, newPassword);
|
|
await ct.SaveChangesAsync();
|
|
|
|
//Log modification and save context
|
|
await EventLogProcessor.LogEventToDatabaseAsync(new Event(UserId, dbObj.Id, BizType, AyaEvent.Modified), ct);
|
|
|
|
return true;
|
|
}
|
|
|
|
|
|
private async Task SearchIndexAsync(User obj, bool isNew)
|
|
{
|
|
//SEARCH INDEXING
|
|
var SearchParams = new Search.SearchIndexProcessObjectParameters(UserTranslationId, obj.Id, BizType);
|
|
SearchParams.AddText(obj.Notes).AddText(obj.Name).AddText(obj.EmployeeNumber).AddText(obj.Tags).AddText(obj.Wiki).AddCustomFields(obj.CustomFields);
|
|
|
|
if (isNew)
|
|
await Search.ProcessNewObjectKeywordsAsync(SearchParams);
|
|
else
|
|
await Search.ProcessUpdatedObjectKeywordsAsync(SearchParams);
|
|
}
|
|
|
|
public async Task<Search.SearchIndexProcessObjectParameters> GetSearchResultSummary(long id)
|
|
{
|
|
var obj = await ct.User.SingleOrDefaultAsync(m => m.Id == id);
|
|
var SearchParams = new Search.SearchIndexProcessObjectParameters();
|
|
if (obj != null)
|
|
SearchParams.AddText(obj.Notes).AddText(obj.Name).AddText(obj.EmployeeNumber).AddText(obj.Tags).AddText(obj.Wiki).AddCustomFields(obj.CustomFields);
|
|
|
|
return SearchParams;
|
|
}
|
|
|
|
////////////////////////////////////////////////////////////////////////////////////////////////
|
|
//DELETE
|
|
//
|
|
internal async Task<bool> DeleteAsync(User dbObj)
|
|
{
|
|
await ValidateCanDelete(dbObj);
|
|
if (HasErrors)
|
|
return false;
|
|
|
|
//Remove the object
|
|
ct.User.Remove(dbObj);
|
|
await ct.SaveChangesAsync();
|
|
|
|
//Delete sibling objects
|
|
//USEROPTIONS
|
|
await ct.Database.ExecuteSqlInterpolatedAsync($"delete from auseroptions where userid = {dbObj.Id}");
|
|
//personal datalistview
|
|
await ct.Database.ExecuteSqlInterpolatedAsync($"delete from adatalistview where public = {false} and userid = {dbObj.Id}");
|
|
|
|
await EventLogProcessor.DeleteObjectLogAsync(UserId, BizType, dbObj.Id, dbObj.Name, ct);
|
|
|
|
await Search.ProcessDeletedObjectKeywordsAsync(dbObj.Id, BizType);
|
|
await TagUtil.ProcessDeleteTagsInRepositoryAsync(ct, dbObj.Tags);
|
|
|
|
return true;
|
|
}
|
|
|
|
|
|
////////////////////////////////////////////////////////////////////////////////////////////////
|
|
//VALIDATION
|
|
//
|
|
|
|
//Can save or update?
|
|
private async Task ValidateAsync(User proposedObj, User currentObj)
|
|
{
|
|
//run validation and biz rules
|
|
bool isNew = currentObj == null;
|
|
|
|
|
|
|
|
//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
|
|
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
|
|
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");
|
|
|
|
//Name must be less than 255 characters
|
|
if (proposedObj.Name.Length > 255)
|
|
AddError(ApiErrorCode.VALIDATION_LENGTH_EXCEEDED, "Name", "255 max");
|
|
|
|
//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(m => m.Name == proposedObj.Name && m.Id != proposedObj.Id))
|
|
{
|
|
AddError(ApiErrorCode.VALIDATION_NOT_UNIQUE, "Name");
|
|
}
|
|
}
|
|
|
|
//LOGIN must be unique
|
|
if (await ct.User.AnyAsync(m => m.Login == proposedObj.Login && m.Id != proposedObj.Id))
|
|
{
|
|
AddError(ApiErrorCode.VALIDATION_NOT_UNIQUE, "Login");
|
|
}
|
|
|
|
//TODO: Validation rules that require future other objects that aren't present yet:
|
|
/*
|
|
//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 (!SeedOrImportRelaxedRulesMode && proposedObj.UserType == UserType.Customer)
|
|
{
|
|
if (proposedObj.CustomerId == null || proposedObj.CustomerId == 0)
|
|
{
|
|
AddError(ApiErrorCode.VALIDATION_REQUIRED, "CustomerId");
|
|
}
|
|
else
|
|
{
|
|
//verify that client exists
|
|
//TODO WHEN CLIENT OBJECT MADE if(!ct.Client.any(m))
|
|
}
|
|
}
|
|
|
|
//Validate headoffice type user
|
|
if (!SeedOrImportRelaxedRulesMode && proposedObj.UserType == UserType.HeadOffice)
|
|
{
|
|
if (proposedObj.HeadOfficeId == null || proposedObj.HeadOfficeId == 0)
|
|
{
|
|
AddError(ApiErrorCode.VALIDATION_REQUIRED, "HeadOfficeId");
|
|
}
|
|
else
|
|
{
|
|
//verify that HeadOfficeId exists
|
|
//TODO WHEN HEADOFFICE OBJECT MADE if(!ct.HeadOffice.any(m))
|
|
}
|
|
}
|
|
|
|
//Validate headoffice type user
|
|
if (!SeedOrImportRelaxedRulesMode && proposedObj.UserType == UserType.Subcontractor)
|
|
{
|
|
if (proposedObj.SubVendorId == null || proposedObj.SubVendorId == 0)
|
|
{
|
|
AddError(ApiErrorCode.VALIDATION_REQUIRED, "SubVendorId");
|
|
}
|
|
else
|
|
{
|
|
//verify that VENDOR SubVendorId exists
|
|
//TODO WHEN VENDOR OBJECT MADE if(!ct.Vendor.any(m))
|
|
}
|
|
}
|
|
|
|
if (!proposedObj.Roles.IsValid())
|
|
{
|
|
AddError(ApiErrorCode.VALIDATION_INVALID_VALUE, "Roles");
|
|
}
|
|
|
|
//Optional employee number field must be less than 255 characters
|
|
if (!string.IsNullOrWhiteSpace(proposedObj.EmployeeNumber) && proposedObj.EmployeeNumber.Length > 255)
|
|
AddError(ApiErrorCode.VALIDATION_LENGTH_EXCEEDED, "EmployeeNumber", "255 max");
|
|
|
|
//Any form customizations to validate?
|
|
var FormCustomization = await ct.FormCustom.SingleOrDefaultAsync(x => x.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 void CheckActiveForValidation(long CurrentActiveCount, long LicensedUserCount)
|
|
{
|
|
if (CurrentActiveCount >= LicensedUserCount)
|
|
{
|
|
AddError(ApiErrorCode.INVALID_OPERATION, null, "LT: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(m => m).Where(m => m.UserId == inObj.Id).Count() > 0)
|
|
if (await ct.Event.AnyAsync(m => m.UserId == inObj.Id))
|
|
{
|
|
AddError(ApiErrorCode.INVALID_OPERATION, "user", "LT:ErrorDBForeignKeyViolation");
|
|
return;
|
|
}
|
|
|
|
}
|
|
|
|
|
|
////////////////////////////////////////////////////////////////////////////////////////////////
|
|
// Utilities
|
|
//
|
|
|
|
//replaced by dtUser object instead
|
|
// internal static object CleanUserForReturn(User o)
|
|
// {
|
|
// return new
|
|
// {
|
|
// Id = o.Id,
|
|
// Concurrency = o.Concurrency,
|
|
// Active = o.Active,
|
|
// Name = o.Name,
|
|
// Roles = o.Roles,
|
|
// TranslationId = o.UserOptions.TranslationId,
|
|
// UserType = o.UserType,
|
|
// EmployeeNumber = o.EmployeeNumber,
|
|
// Notes = o.Notes,
|
|
// CustomerId = o.CustomerId,
|
|
// HeadOfficeId = o.HeadOfficeId,
|
|
// SubVendorId = o.SubVendorId
|
|
// };
|
|
// }
|
|
|
|
|
|
|
|
////////////////////////////////////////////////////////////////////////////////////////////////
|
|
// JOB / OPERATIONS
|
|
//
|
|
public async Task HandleJobAsync(OpsJob job)
|
|
{
|
|
//just to hide compiler warning for now
|
|
await Task.CompletedTask;
|
|
//Hand off the particular job to the corresponding processing code
|
|
//NOTE: If this code throws an exception the caller (JobsBiz::ProcessJobsAsync) will automatically set the job to failed and log the exeption so
|
|
//basically any error condition during job processing should throw up an exception if it can't be handled
|
|
switch (job.JobType)
|
|
{
|
|
|
|
default:
|
|
throw new System.ArgumentOutOfRangeException($"UserBiz.HandleJob-> Invalid job type{job.JobType.ToString()}");
|
|
}
|
|
|
|
}
|
|
|
|
|
|
//Other job handlers here...
|
|
|
|
|
|
/////////////////////////////////////////////////////////////////////
|
|
|
|
}//eoc
|
|
|
|
|
|
}//eons
|
|
|