public ErrorditeAuthorisationException(IUserEntity entity, User user) { Data.Add("User-Id", user.Id); Data.Add("User-OrganisationId", user.OrganisationId); Data.Add("UserEntity-Name", entity.GetType().Name); Data.Add("UserEntity-UserId", entity.UserId); }
protected T Return <T>(IUserEntity user, MethodBase mi, string description, Func <T> function) { try { using (UserHolder.UserSession(user)) { return(function()); } } catch (Exception e) { e.LogException(el => { el.ControllerName = GetType().Name; el.ActionName = mi.Name; el.QueryString = description; el.Version = Schema.Current.Version.ToString(); }); throw; } finally { Statics.CleanThreadContextAndAssert(); } }
public async Task <bool> SaveUser(IUserEntity user) { try { var userEntity = await GetUserByUserEmail(user.Email); var te = (UserEntity)user; if (userEntity == null) { te.RowKey = UserEntity.GenerateRowKey(te.Email); } else { te.RowKey = userEntity.RowKey; } if (te.PartitionKey == null) { te.PartitionKey = UserEntity.GeneratePartitionKey(); } await _tableStorage.InsertOrMergeAsync(te); } catch (Exception e) { Console.WriteLine(e); return(false); } return(true); }
/// <summary> /// Adds a new user to the database /// </summary> /// <param name="user">IUserEntity containing the validated ValueObjects.</param> public bool AddUser(IUserEntity user) { bool returnValue = true; Database.DatabaseManager db = null; try { db = new Database.DatabaseManager(_databaseFileLocation); db.Connection.BeginTransaction(); User insertUser = new User(); insertUser.FirstName = user.FirstName.Value; insertUser.LastName = user.LastName.Value; insertUser.Password = user.Password.Value; db.Connection.Insert(insertUser); db.Connection.Commit(); } catch { db.Connection.Rollback(); returnValue = false; } finally { db.CloseConnection(); } return(returnValue); }
public static IDisposable UserSession(IUserEntity user) { var result = ScopeSessionFactory.OverrideSession(); UserHolder.Current = user; return(result); }
public async Task RevokeUser(IUserEntity user, string userName, string ip) { var creds = user.Email; var shell = ""; if (!String.IsNullOrWhiteSpace(_appSettings.DevCertsService.PathToScriptFolder)) { shell += "cd " + _appSettings.DevCertsService.PathToScriptFolder + " && "; } shell += "./revoke.sh " + creds; shell.Bash(); Console.WriteLine("Revoke user " + creds); try { await _blobDataRepository.DelBlobAsync(creds + ".p12"); } catch (Exception e) { Console.WriteLine(e); } user.CertIsRevoked = true; user.RevokeDate = DateTime.Now.ToUniversalTime(); await _userRepository.SaveUser(user); //await UpdateDb(false, user); }
public async Task GenerateCertAsync(IUserEntity user, string userName, string ip) { var creds = user.Email; var shell = ""; if (!String.IsNullOrWhiteSpace(_appSettings.DevCertsService.PathToScriptFolder)) { shell += "cd " + _appSettings.DevCertsService.PathToScriptFolder + " && "; } shell += "./" + _appSettings.DevCertsService.ScriptName + " " + creds; shell.Bash(); Console.WriteLine("Generate cert for " + creds); user.Visible = true; user.Admin = false; user.HasCert = true; user.CertIsRevoked = false; user.CertPassword = Crypto.EncryptStringAES(GetCertPass(creds), _appSettings.DevCertsService.EncryptionPass); user.CertDate = DateTime.Now.ToUniversalTime(); await UpoadCertToBlob(user, userName, ip); var filePath = Path.Combine(_appSettings.DevCertsService.PathToScriptFolder, creds + ".p12"); if (File.Exists(filePath)) { user.CertMD5 = CalculateMD5(filePath); } await _userRepository.SaveUser(user); //await UpdateDb(false, user); }
public async Task UpoadCertToBlob(IUserEntity user, string userName, string ip) { try { var filePath = Path.Combine(_appSettings.DevCertsService.PathToScriptFolder, user.Email + ".p12"); if (File.Exists(filePath)) { var fileMd5 = CalculateMD5(filePath); if (fileMd5 == user.CertMD5) { return; } byte[] file; using (FileStream stream = new FileStream(filePath, FileMode.Open, FileAccess.Read)) { using (var reader = new BinaryReader(stream)) { file = reader.ReadBytes((int)stream.Length); } } await _blobDataRepository.UpdateBlobAsync(file, userName, ip, user.Email + ".p12"); } else { Console.WriteLine($"File {user.Email}.p12 does not exist. Path:" + filePath); } } catch (Exception e) { Console.WriteLine(e); } }
public override FunctionalSpecification Construct(IUserEntity createdBy) { var fs = base.Construct(createdBy) as FunctionalSpecification; fs.Author = createdBy.FullName; return(fs); }
public UserAccountEntity( IBaseSettings pBaseSettings, IUserEntity pUserManager, IAddressEntity pAddressManager) : base(pBaseSettings, nameof(User_Account)) { _userManager = pUserManager; _addressManager = pAddressManager; }
public SearchService(IUserEntity entity,IProductEntity product, ICategoryEntity category, IArticleEntity articel, IManufacturerEntity fac, IExamineeEntity exc ) { this.entity = entity; this.Productentity = product; this.Categoryenity = category; this.Articelenity = articel; this.ManuFacenity = fac; this.ExamineeEntity = exc; }
public UserService(IUserEntity entity, IUser_GroupEntity group, IProvinceEntity province, IUser_Role_ModuleEntity user, IExamineeEntity examinee) { this.entity = entity; this.Group = group; this.menuprovince = province; this.userrole = user ; this.examinee = examinee; }
public AccountController( IBaseSettings pBaseSettings, IUserEntity pUserEntity, IPlaylistEntity pPlaylistEntity, ILogService pLogger) : base(pLogger) { _userEntity = pUserEntity; _baseSettings = pBaseSettings; _playlistEntity = pPlaylistEntity; }
public static IUserDomainEntity ConvertToDomain(this IUserEntity entity) { return(new User { Id = entity.Id, Name = entity.Name, Login = entity.Login, Password = entity.Password, Roles = entity.Roles }); }
//public static bool SetAvatar(IUserEntity user, string value, out string result) //{ // result = value; // return true; //} //public static bool SetAvatar(IUserEntity user, string oldValue, string newValue, out string result) //{ // result = newValue; // return true; //} public static string GetAvatarUrl(IUserEntity user, string value = null) { var avatar = user.Avatar; if (string.IsNullOrEmpty(avatar)) { return(string.Empty); } return("url:" + avatar); }
public async Task NewEmailNotification <TEmailNotification>( IList <IUserEntity> users, IUserEntity userTriggerEvent, INotificationEntity notification, string targetUrl, IList <NotificationParameter> parameters, NotificationSettings settings) where TEmailNotification : class, IEmailNotificationEntity, new() { await this.NewNotification <DefaultSystemNotification, TEmailNotification, DefaultUnsubscriber>(users, userTriggerEvent, notification, targetUrl, parameters, settings); }
public void Authorise(IUserEntity entity, User currentUser) { if (ReferenceEquals(currentUser, User.System())) { return; } if (!entity.UserId.ToLowerInvariant().Equals(currentUser.Id.ToLowerInvariant())) { throw new ErrorditeAuthorisationException(entity, currentUser); } }
private TEmailNotification GetEmailNotificationToAdd <TEmailNotification>( INotificationEntity notification, IUserEntity user, IList <NotificationParameter> parameters, string defaultFromName, string defaultSubject, string defaultMessage, string siteUrl, string baseHtml, bool isManual) where TEmailNotification : class, IEmailNotificationEntity, new() { string fromName = string.Empty; string subject = string.Empty; string message = string.Empty; ////Cuando es manual envia otros parametros if (isManual) { if (string.IsNullOrEmpty(defaultFromName) || string.IsNullOrEmpty(defaultSubject) || string.IsNullOrEmpty(defaultMessage)) { throw new ArgumentNullException("fromName or defaultSubject or defaultMessage"); } fromName = defaultFromName; subject = defaultSubject; message = defaultMessage; } else { fromName = defaultFromName; subject = this.GetStringFormatted(notification.EmailSubject, parameters); message = this.GetStringFormatted(notification.EmailHtml, parameters); } ////Reemplaza el HTML string body = baseHtml .Replace("%%Body%%", message) .Replace("%%RootUrl%%", siteUrl); var emailNotification = new TEmailNotification(); emailNotification.To = user.Email; emailNotification.ToName = user.Name; emailNotification.Subject = subject; emailNotification.Body = body; emailNotification.CreatedDate = DateTime.UtcNow; emailNotification.Cc = null; emailNotification.ScheduledDate = null; emailNotification.SentDate = null; return(emailNotification); }
// private async Task<ErosRequestProcessor> GetProcessor(long podId) // { // if (!_requestProcessors.ContainsKey(podId)) // { // using(var pr = RepositoryProvider.Instance.PodRepository) // { // var pod = await pr.Read(podId); // // var erp = new ErosRequestProcessor(); // await erp.Initialize(pod, _backgroundTaskFactory, _radioProviders); // _requestProcessors.Add(podId, erp); // } // } // return _requestProcessors[podId]; // } // // public async Task QueueRequest(PodRequest request) // { // try // { // var processor = await GetProcessor(request.PodId); // await processor.QueueRequest(request); // } // catch { throw; } // // } // // public async Task<bool> WaitForResult(PodRequest request, int timeout) // { // var processor = await GetProcessor(request.PodId); // return await processor.WaitForResult(request, 0); // } // // public async Task<bool> CancelRequest(PodRequest request) // { // var processor = await GetProcessor(request.PodId); // return await processor.CancelRequest(request); // } // // public async Task<List<PodRequest>> GetActiveRequests(Pod pod) // { // var processor = await GetProcessor(pod.Id.Value); // return await processor.GetActiveRequests(); // } // // public async Task<List<PodRequest>> GetActiveRequests() // { // var processors = new List<ErosRequestProcessor>(); // var list = new List<PodRequest>(); // lock(_requestProcessors) // { // foreach(var processor in _requestProcessors.Values) // processors.Add(processor); // } // // foreach(var processor in processors) // list.AddRange(await processor.GetActiveRequests()); // // return list; // } public async Task <IPod> New(IUserEntity user, IMedicationEntity medication, IList <IRadioEntity> radios) { var podEntity = PodRepository.New(); podEntity.Medication = medication; podEntity.User = user; podEntity.Radios = radios; podEntity.UniqueId = Guid.NewGuid(); podEntity.RadioAddress = GenerateRadioAddress(); await PodRepository.Create(podEntity, CancellationToken.None); return(await GetPodInternal(podEntity)); }
public virtual TEntity Construct(IUserEntity createdBy) { var entity = Activator.CreateInstance <TEntity>(); entity.Creation = DateTime.Now; entity.CreatedBy = createdBy.Id; entity.Update = DateTime.Now; entity.ModifiedBy = createdBy.Id; entity.Active = true; return(entity); }
public async Task SaveUserLoginHistoryAsync(IUserEntity user, string userIpAddress) { var uh = new UserSignInHistoryEntity { PartitionKey = UserSignInHistoryEntity.GeneratePartitionKey(), UserEmail = user.Email, SignInDate = DateTime.UtcNow, IpAddress = userIpAddress }; uh.RowKey = uh.GetRawKey(); await _tableStorage.InsertOrMergeAsync(uh); }
public DataTable getSPUser(IUserEntity user) { DB obj = new DB(); string storedProcName = "[usp_ValidateUser]"; //List of parameter required SqlParameter[] param = { new SqlParameter("@Username", user.UserName), new SqlParameter("@Password", user.Password) }; DataTable dt = obj.getSPRecords("SecurityConnectionString", storedProcName, param); return dt; }
public Task CreateUserAsync(IUserEntity user) { var email = UserEntity.GenerateRowKey(user.Email); var usr = new UserEntity { PartitionKey = UserEntity.GeneratePartitionKey(), RowKey = email, Email = email, PasswordHash = user.PasswordHash, FirstName = user.FirstName, LastName = user.LastName, Active = user.Active, Admin = user.Admin, Roles = user.Roles, }; return(_tableStorage.InsertOrMergeAsync(usr)); }
public DataTable DeactivateUser(string userRole, string roleData, string userLogin, IUserEntity user) { DB obj = new DB(); String storedProcName = "[usp_DeactivateUser]"; //List of parameter required SqlParameter[] param = { new SqlParameter("@UserRole", userRole), new SqlParameter("@RoleData", roleData), new SqlParameter("@UserLogin", userLogin), new SqlParameter("@Name", user.UserName) }; DataTable dt = obj.getSPRecords("SecurityConnectionString", storedProcName, param); return dt; }
public AppContext( string connectionString, DbContext context = null, IUserModuleEntity userModules = null, IUserAccessTypeEntity userAccessTypes = null, IUserModuleAccessTypeEntity userModuleAccessTypes = null, IUserGroupEntity userGroups = null, IUserGroupModuleAccessEntity userGroupModuleAccesses = null, IUserEntity users = null ) { _db = context ?? new AppDatabase(connectionString); UserAccessTypes = userAccessTypes ?? new UserAccessTypeEntity(_db, true); UserModules = userModules ?? new UserModuleEntity(_db, true); UserModuleAccessTypes = userModuleAccessTypes ?? new UserModuleAccessTypeEntity(_db, true); UserGroups = userGroups ?? new UserGroupEntity(_db, true); UserGroupModuleAccesses = userGroupModuleAccesses ?? new UserGroupModuleAccessEntity(_db, true); Users = users ?? new UserEntity(_db, true); }
public string CreateToken(IUserEntity userEntity) { var descriptor = new SecurityTokenDescriptor(); var claims = new List <Claim> { new(ClaimTypes.NameIdentifier, userEntity.Id.ToString()), new (ClaimTypes.Email, userEntity.Email), new (ClaimTypes.Role, userEntity.Role) }; var identity = new ClaimsIdentity(claims); descriptor.Subject = identity; descriptor.Expires = DateTime.Now.AddHours(3); descriptor.SigningCredentials = new SigningCredentials(_settings.JwtKey, SecurityAlgorithms.HmacSha512Signature); var handler = new JwtSecurityTokenHandler(); var token = handler.CreateToken(descriptor); return(handler.WriteToken(token)); }
public async Task <bool> UpdateUserAsync(IUserEntity user) { try { var te = (UserEntity)user; if (te.PartitionKey == null) { te.PartitionKey = UserEntity.GeneratePartitionKey(); } te.RowKey = UserEntity.GenerateRowKey(te.Email); await _tableStorage.InsertOrMergeAsync(te); } catch { return(false); } return(true); }
public async Task <JwtTokenDto> SignInAsync(SignInDto dto) { IUserEntity userEntity = await _userRepository.GetByEmailAsync(dto.Email); if (userEntity is null) { throw new InvalidUserCredentialsException(); } if (!_passwordService.CheckPassword(dto.Password, userEntity.Password)) { throw new InvalidUserCredentialsException(); } var token = _tokenService.CreateToken(userEntity); var refresh = _passwordService.GenerateSalt(); await _refreshTokenRepository.SaveTokenAsync(userEntity.Id, refresh, DateTime.Now.AddHours(3)); return(new JwtTokenDto(token, refresh)); }
public DataTable getUser(IUserEntity user) { DB obj = new DB(); string queryString = "SELECT r.RoleName, u.* " + "FROM Users u, UsersToRoles s, Roles r " + "WHERE u.UserID = s.FKUserID " + "AND s.FKRoleID = r.RoleID " + "AND " + "Name='" + user.UserName + "' and password='******'and IsApproved ='" + true + "'and IsLockedOut ='" + false + "'"; return obj.getRecords(queryString, "SecurityConnectionString"); }
/// <summary> /// Generates the test data. /// </summary> private void GenerateTestData() { List <IUserEntity> saveList = new List <IUserEntity>(); IUserEntity current = CreateUser("Edward", "Rush", "123PWd"); saveList.Add(current); current = CreateUser("Eric", "Evans", "456PWd"); saveList.Add(current); current = CreateUser("Martin", "Fowler", "789PWd"); saveList.Add(current); current = CreateUser("James", "Montemagno", "1012PWd"); saveList.Add(current); current = CreateUser("Frank", "Krueger", "1213PWd"); saveList.Add(current); current = CreateUser("Nat", "Friedman", "1415PWs"); saveList.Add(current); current = CreateUser("Miguel", "Icaza", "1617PWd"); saveList.Add(current); SaveUsers(saveList); }
public DataTable InsertUser(string userRole, string roleData, string userLogin, IUserEntity user) { DB obj = new DB(); String storedProcName = "[usp_InsertUser]"; //List of parameter required SqlParameter[] param = { new SqlParameter("@UserRole", userRole), new SqlParameter("@RoleData", roleData), new SqlParameter("@UserLogin", userLogin), new SqlParameter("@UserName", user.UserName), new SqlParameter("@Password", user.Password), new SqlParameter("@Email", user.Email), new SqlParameter("@IsApproved", user.IsApproved), new SqlParameter("@IsLockedOut", user.IsLockedOut) }; DataTable dt = obj.getSPRecords("SecurityConnectionString", storedProcName, param); return dt; }
static IDisposable SchedulerLogic_ApplySession(ITaskEntity task, ScheduledTaskEntity scheduled, IUserEntity user) { return(IsolationEntity.Override(scheduled?.TryIsolation() ?? task?.TryIsolation() ?? user?.TryIsolation())); }
public UserService(IAppContext context) : base() { _context = context; _users = _context.Users; }
public static IDisposable UserSession(IUserEntity user) { var result = ScopeSessionFactory.OverrideSession(); UserHolder.Current = user; return result; }
public static void ExecuteAsync(ITaskEntity task, ScheduledTaskEntity scheduledTask, IUserEntity user) { Task.Factory.StartNew(() => { try { ExecuteSync(task, scheduledTask, user); } catch (Exception e) { e.LogException(ex => { ex.ControllerName = "SchedulerLogic"; ex.ActionName = "ExecuteAsync"; }); } }); }
public ArticleService(IArticleEntity entity, IUserEntity userentity) { this.entity = entity; this.userentity = userentity; //bat 1 tien trinh check hang ton kho/thoi han khuyen mai }
public static string GetAvatar(IUserEntity user, string value) { return(value); }
public Task SaveAsync(IUserEntity userEntity) => _repository.AddAsync(userEntity.AsDocument());
public static Lite<IEntity> ExecuteSync(ITaskEntity task, ScheduledTaskEntity scheduledTask, IUserEntity user) { IUserEntity entityIUser = user ?? (IUserEntity)scheduledTask.User.Retrieve(); using (IsolationEntity.Override(entityIUser.TryIsolation())) { ScheduledTaskLogEntity stl = new ScheduledTaskLogEntity { Task = task, ScheduledTask = scheduledTask, StartTime = TimeZoneManager.Now, MachineName = Environment.MachineName, ApplicationName = Schema.Current.ApplicationName, User = entityIUser.ToLite(), }; using (AuthLogic.Disable()) { using (Transaction tr = Transaction.ForceNew()) { stl.Save(); tr.Commit(); } } try { using (UserHolder.UserSession(entityIUser)) { using (Transaction tr = Transaction.ForceNew()) { stl.ProductEntity = ExecuteTask.Invoke(task); using (AuthLogic.Disable()) { stl.EndTime = TimeZoneManager.Now; stl.Save(); } tr.Commit(); } } } catch (Exception ex) { using (AuthLogic.Disable()) { if (Transaction.InTestTransaction) throw; var exLog = ex.LogException().ToLite(); using (Transaction tr = Transaction.ForceNew()) { stl.Exception = exLog; stl.EndTime = TimeZoneManager.Now; stl.Save(); tr.Commit(); } } throw; } return stl.ProductEntity; } }
public static void ExecuteAsync(ITaskEntity task, ScheduledTaskEntity scheduledTask, IUserEntity user) { using (ExecutionContext.SuppressFlow()) Task.Run(() => { try { ExecuteSync(task, scheduledTask, user); } catch (Exception e) { e.LogException(ex => { ex.ControllerName = "SchedulerLogic"; ex.ActionName = "ExecuteAsync"; }); } }); }
public static bool IsUserKey(this IUserEntity entity, IKey userKey) => entity.UserId == userKey.AsStringKey().Identifier;
public async Task UpdateDb(bool force = false) { try { var filePath = Path.Combine(_appSettings.DevCertsService.PathToScriptFolder, "db"); filePath = Path.Combine(filePath, "index.txt"); if (!File.Exists(filePath)) { var shell = ""; if (!String.IsNullOrWhiteSpace(_appSettings.DevCertsService.PathToScriptFolder)) { shell += "cd " + _appSettings.DevCertsService.PathToScriptFolder + " && "; } shell += "./create.sh "; shell.Bash(); } else { var NowMD5Hash = CalculateMD5(filePath); if (LastMD5Hash != NowMD5Hash) { Console.WriteLine("Starting reparce..." + DateTime.Now.ToLongTimeString()); var usersInCloud = await _userRepository.GetUsers(); var userEntityList = new List <IUserEntity>(); string lineOfText = ""; using (FileStream stream = new FileStream(filePath, FileMode.Open, FileAccess.Read)) { using (var reader = new StreamReader(stream, System.Text.Encoding.UTF8, true, 128)) { while ((lineOfText = reader.ReadLine()) != null) { var user = new UserEntity(); var line = lineOfText.Split("\t ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries); int offset = 0; for (int i = 0; i < line.Length; i++) { switch (i) { case 0: user.CertIsRevoked = line[i] == "V" ? false : true; break; case 1: line[i] = line[i].Substring(0, line[i].Length - 1); var dateTill = DateTime.ParseExact(line[i], "yyMMddHHmmss", CultureInfo.InvariantCulture).ToLocalTime(); dateTill = dateTill.AddYears(-10); dateTill = dateTill.AddDays(3); user.CertDate = dateTill; break; case 2: if ((bool)user.CertIsRevoked) { line[i] = line[i].Substring(0, line[i].Length - 1); user.RevokeDate = DateTime.ParseExact(line[i], "yyMMddHHmmss", CultureInfo.InvariantCulture).ToLocalTime(); offset = 1; } var serialNum = line[i + offset]; break; case 4: var parameters = line[i + offset].Split('/'); for (int j = 0; j < parameters.Length; j++) { if (parameters[j].Contains("CN=")) { user.Email = parameters[j].Remove(0, parameters[j].IndexOf('=') + 1); } } break; } } var userToAdd = userEntityList.Where(u => u.Email == user.Email).FirstOrDefault(); if (userToAdd == null) { userEntityList.Add(user); } else if (user.CertDate.Value.ToUniversalTime() > userToAdd.CertDate.Value.ToUniversalTime()) { userEntityList.Remove(userToAdd); userEntityList.Add(user); } } } } if (userEntityList.Count > 0) { foreach (var user in userEntityList) { user.HasCert = true; user.CertPassword = Crypto.EncryptStringAES(GetCertPass(user.Email), _appSettings.DevCertsService.EncryptionPass); var users = usersInCloud.Where(u => u.Email == user.Email); IUserEntity userInCloud = null; if (users != null) { userInCloud = users.FirstOrDefault(); } if (userInCloud != null) { user.CertMD5 = userInCloud.CertMD5; } if (!(bool)user.CertIsRevoked && (userInCloud == null || force)) { await UpoadCertToBlob(user, "Lykke.Service.DevCerts", "localhost"); } var path = Path.Combine(_appSettings.DevCertsService.PathToScriptFolder, user.Email + ".p12"); if (!(bool)user.CertIsRevoked && File.Exists(path)) { user.CertMD5 = CalculateMD5(path); } if (userInCloud == null || user.CertIsRevoked != userInCloud.CertIsRevoked || user.CertPassword != userInCloud.CertPassword || user.CertDate.Value.ToUniversalTime() != userInCloud.CertDate.Value.ToUniversalTime() || (user.RevokeDate.HasValue && user.RevokeDate.Value.ToUniversalTime() != userInCloud.RevokeDate.Value.ToUniversalTime())) { await _userRepository.SaveUser(user); } ; } } Console.WriteLine("Finished reparce..." + DateTime.Now.ToLongTimeString()); LastMD5Hash = NowMD5Hash; } } } catch (Exception e) { Console.WriteLine(e); } }
public ExamineeService(IExamineeEntity entity,IUserEntity user, IPictureExamEntity pic) { this.entity = entity; this.user = user; this.pictureexam = pic; }