public Check RoleCheck(PortalUser pu, PortletTemplate portletTemplate, PortalUser currentUser = null) { if (currentUser == null) currentUser = PortalUser.Current; if(portletTemplate.AccessCheck("DenyAccess", pu)) return new Check(false, Globalizer.GetGlobalizedString("CUS_BC_PL_DENIED_PERMS")); if (pu.IsMemberOf(PortalGroup.Staff)) if (!portletTemplate.AccessCheck("CanProxyStaff", currentUser)) return new Check(false, Globalizer.GetGlobalizedString("CUS_BC_PL_STAFF_PERMS")); if (pu.IsMemberOf(PortalGroup.Faculty)) if (!portletTemplate.AccessCheck("CanProxyFaculty", currentUser)) return new Check(false, Globalizer.GetGlobalizedString("CUS_BC_PL_FACULTY_PERMS")); if (pu.IsMemberOf(PortalGroup.Students)) if (!portletTemplate.AccessCheck("CanProxyStudent", currentUser)) return new Check(false, Globalizer.GetGlobalizedString("CUS_BC_PL_STUDENT_PERMS")); if (pu.IsMemberOf(PortalGroup.FindByStatusCode("CAN"))) // Candidate if (!portletTemplate.AccessCheck("CanProxyCandidate", currentUser)) return new Check(false, Globalizer.GetGlobalizedString("CUS_BC_PL_CANDIDATE_PERMS")); if (pu.IsMemberOf(PortalGroup.FindByStatusCode("ALM"))) if (!portletTemplate.AccessCheck("CanProxyConstituent", currentUser)) return new Check(false, Globalizer.GetGlobalizedString("CUS_BC_PL_CONSTITUENT_PERMS")); return pu.IsMemberOf(PortalGroup.Administrators) ? new Check(false, Globalizer.GetGlobalizedString("CUS_BC_PL_SITE_ADMIN_PERMS")) : new Check(true); }
public async static Task <ExpenseTypeModel> SaveExpenseType(PortalUser user, ExpenseTypeModel model, IDriverRepository repository) { ExpenseType dbEntry; // Existing or new Expense Type? if (model.ExpenseTypeID == 0) { // New Expense Type dbEntry = new ExpenseType() { CreatedBy = user.PortalUsername, CreatedDate = DateTime.UtcNow }; repository.Insert(dbEntry); } else { // Requesting an existing Expense Type dbEntry = await repository.GetExpenceTypeById(model.ExpenseTypeID); } // Check for errors if (dbEntry == null) { throw new NullReferenceException($"Could not find expense type: {model.ExpenseTypeName}"); } // Make sure that the frequency type is valid. FrequencyType frequency = await repository.GetFrequencyTypeById(model.FrequencyTypeId); if (frequency == null) { throw new NullReferenceException($"Could not find the frequency type for expense: {model.ExpenseTypeName}."); } //Transfer data. dbEntry.ExpenseTypeName = model.ExpenseTypeName; dbEntry.AutomationCode = model.AutomationCode; dbEntry.CompanyPercent = model.CompanyPercent; dbEntry.DriverPercent = model.DriverPercent; dbEntry.ExpenseTypeDesc = model.ExpenseTypeDesc; dbEntry.FrequencyTypeId = frequency.FrequencyTypeId; dbEntry.FrequencyType = frequency; dbEntry.DriverGLAccount = model.DriverGLAccount; dbEntry.SMEGLAccount = model.CompanyGLAccount; dbEntry.IsActive = true; // Check for changes. if (repository.IsChanged(dbEntry)) { dbEntry.ModifiedBy = user.PortalUsername; dbEntry.ModifiedDate = DateTime.UtcNow; } await repository.SaveChanges(); return(LoadExpenseType(dbEntry)); }
public async Task <IActionResult> LoginCallback(string returnUrl = null, string remoteError = null) { if (remoteError != null) { return(BadRequest($"Error from external provider: {remoteError}")); } var info = await signInManager.GetExternalLoginInfoAsync(); if (info == null) { return(BadRequest()); } var user = await userManager.FindByLoginAsync(info.LoginProvider, info.ProviderKey); if (user != null) { return(await TokenResult(user)); } var email = info.Principal.FindFirstValue(ClaimTypes.Email); if (string.IsNullOrEmpty(email)) { email = info.Principal.FindFirstValue(ClaimTypes.Name); } // Lookup if there's an username with this e-mail address in the Db user = await userManager.FindByEmailAsync(email); if (user != null) { return(await TokenResult(user)); } // Create a unique username using the 'nameidentifier' claim var idKey = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier"; var username = $"{info.LoginProvider}-{info.Principal.FindFirst(idKey).Value}"; user = new PortalUser { UserName = username, Email = email }; await userManager.CreateAsync(user); // Remove Lockout and E-Mail confirmation user.EmailConfirmed = true; user.LockoutEnabled = false; // Register this external provider to the user await userManager.AddLoginAsync(user, info); // Persist everything into the Db await appDbContext.SaveChangesAsync(); return(await TokenResult(user)); }
public async Task <PortalUser> AuthenticateUserToken(int userId, string userToken) { PortalUser portalUser = await GetPortalUserById(userId); #warning TODO: Add token support. Currently returns user. return(portalUser); }
public void SetUser(JSPortalUser usr) { PortalUser newUser; if (!usr.PortalUserId.HasValue) { newUser = new PortalUser(); db.PortalUser.Add(newUser); } else { newUser = db.PortalUser.First(x => x.PortalUserId == usr.PortalUserId); } newUser.Name = usr.Name; newUser.UserName = usr.UserName; newUser.Password = string.IsNullOrEmpty(usr.Password) ? newUser.Password : Utils.GetMD5(usr.Password); newUser.Active = usr.Active; db.SaveChanges(); db.PortalUser2Part.RemoveRange(db.PortalUser2Part.Where(x => x.PortalUserId == newUser.PortalUserId)); foreach (var p in usr.Parts) { var part = new PortalUser2Part(); part.PortalUserId = newUser.PortalUserId; part.PortalPartId = p; db.PortalUser2Part.Add(part); } db.PortalUser2Right.RemoveRange(db.PortalUser2Right.Where(x => x.PortalUserId == newUser.PortalUserId)); foreach (var r in usr.Rights) { var rght = new PortalUser2Right(); rght.PortalUserId = newUser.PortalUserId; rght.UserRightId = r;// db.UserRight.First(x => x.Name == r).UserRightId; db.PortalUser2Right.Add(rght); } db.PortalUser2Group.RemoveRange(db.PortalUser2Group.Where(x => x.PortalUserId == newUser.PortalUserId)); foreach (var g in usr.Groups) { var grp = new PortalUser2Group(); grp.PortalUserId = newUser.PortalUserId; grp.PortalGroupId = g; db.PortalUser2Group.Add(grp); } db.PortalUser2Rubric.RemoveRange(db.PortalUser2Rubric.Where(x => x.PortalUserId == newUser.PortalUserId)); foreach (var r in usr.Rubrics) { var rub = new PortalUser2Rubric(); rub.PortalUserId = newUser.PortalUserId; rub.RubricId = r; db.PortalUser2Rubric.Add(rub); } db.SaveChanges(); }
public async Task <IActionResult> GetJournalList([FromBody] GetJournalListRequest req) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } PortalUser user = await repository.AuthenticateUserToken(req.CurrentUser.UserId, req.CurrentUser.UserToken); if (user == null) { return(NotFound()); } List <JournalEntryModel> retList = new List <JournalEntryModel>(); switch (req.JournalTypeId) { case (int)JournalType.Enum.Expenses: break; case (int)JournalType.Enum.Recurring: if (req.ContractId > 0) { var recurringList = await repository.GetRecurringJournalEntriesByContractId(req.ContractId); retList.AddRange(recurringList.Where(x => x.CompanyId == user.CompanyId).Select(x => LoadJournalEntry(x))); break; } else { var recurringList = await repository.GetRecurringJournalEntriesByDriverId(req.DriverId); retList.AddRange(recurringList.Where(x => x.CompanyId == user.CompanyId).Select(x => LoadJournalEntry(x))); break; } case (int)JournalType.Enum.MaintenanceParts: var maintenanceList = await repository.GetMaintenanceJournalEntriesByDriverId(req.DriverId); retList.AddRange(maintenanceList.Where(x => x.CompanyId == user.CompanyId).Select(x => LoadJournalEntry(x))); break; case (int)JournalType.Enum.Compliance: break; case (int)JournalType.Enum.Adjustment: break; default: return(NotFound()); } //return Ok(resp); return(Ok(LoadJournalEntries(req, retList))); }
void OnTriggerExit(Collider other) { var portalUser = FindPortalUser(other); if (portalUser != null && portalUser.IsTeleporationTrigger(other)) { _portalUser = null; } }
public ActionResult login(LoginViewModel model) { if (ModelState.IsValid) { DataService.Patientportal.PatientPortalService cls = new DataService.Patientportal.PatientPortalService(); try { string userName = model.UserName; string password = model.Password; CommonStatus cs = cls.VerifyLoginUser(userName, Utilities.PatientRxPortal.Helper.CreateMD5(password)); if (cs != null && cs.OpStatus) { PortalUser u = (PortalUser)cs.OpPayload; var claims = new List <Claim>(); claims.Add(new Claim(ClaimTypes.NameIdentifier, userName)); claims.Add(new Claim(ClaimTypes.Name, u.DisplayName)); claims.Add(new Claim(ClaimTypes.GivenName, u.DisplayName)); claims.Add(new Claim("UserID", u.PortalUser_ID.ToString())); claims.Add(new Claim(ClaimTypes.Hash, u.HashedPassword)); var claimIdenties = new ClaimsIdentity(claims, DefaultAuthenticationTypes.ApplicationCookie); var ctx = Request.GetOwinContext(); var authenticationManager = ctx.Authentication; authenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = false }, claimIdenties); return(RedirectToAction("ManagePatients", "Home")); } else { ModelState.AddModelError(string.Empty, "Invalid user-name or password"); } } catch (Exception ex) { } finally { cls = null; } return(View()); } return(View()); }
public UserProfileModel(PortalUser user) { Portal = user.Portal; ProfilePicture = user.ThumbnailUri != null ? new BitmapImage(user.ThumbnailUri) : null; FullName = user.FullName; User = user; }
/// <summary> /// Deletes a cash receipt and moves all the revisions into the history table. /// </summary> /// <param name="currentUser">The user deletingthe cash receipt.</param> /// <param name="cashReceiptId">the id of the cash receipt being deleted.</param> /// /// <exception cref="NullReferenceException">This gets thrown when the invoiceId is not found in the database.</exception> /// <returns></returns> public async Task DeleteCashReceipt(PortalUser currentUser, int cashReceiptId) { // First we get the cash receipt. CashReceipt cashReceipt = await repository.GetCashReceiptById(cashReceiptId); if (cashReceipt == null) { throw new NullReferenceException("The cash receipt could not be found."); } cashReceipt.TransactionStatusTypeId = (int)TransactionStatusType.Enum.Void; await repository.SaveChanges(); // Second we go and create a revision for deleting. await CreateCashReceiptRevision(currentUser, cashReceiptId, "Deleted"); // Then we move all of the revisions into the history table and delete them. var revisions = await repository.GetCashReceiptRevListByCashReceiptId(cashReceiptId); foreach (CashReceiptRev cashReceiptRev in revisions) { CashReceiptHist newHistory = new CashReceiptHist() { CenterId = cashReceiptRev.CenterId, CompanyId = cashReceiptRev.CompanyId, PaymentNumber = cashReceiptRev.PaymentNumber, PaymentDate = cashReceipt.PaymentDate, DispatchLoadNumber = cashReceiptRev.DispatchLoadNumber, DriverFuelSurcharge = cashReceiptRev.DriverFuelSurcharge, DriverId = cashReceiptRev.DriverId, DriverRate = cashReceiptRev.DriverRate, CashReceiptHistId = 0, CashReceiptId = cashReceiptRev.CashReceiptId, IsActive = cashReceiptRev.IsActive, ManufacturerFuelSurcharge = cashReceiptRev.ManufacturerFuelSurcharge, ManufacturerId = cashReceiptRev.ManufacturerId, ManufacturerRate = cashReceiptRev.ManufacturerRate, Note = cashReceiptRev.Note, RevisedBy = cashReceiptRev.RevisedBy, RevisionDate = cashReceiptRev.RevisionDate, TransactionStatusTypeId = (int)TransactionStatusType.Enum.Void, TruckId = cashReceiptRev.TruckId, Version = cashReceiptRev.Version, VIN = cashReceiptRev.VIN }; repository.Insert(newHistory); repository.Delete(cashReceiptRev); } repository.Delete(cashReceipt); await repository.SaveChanges(); }
/// <summary> /// Delete an invoice. /// </summary> /// <param name="currentUser">The user deleting the invoice</param> /// <param name="invoiceId">The id of the invoice</param> /// <exception cref="NullReferenceException">This gets thrown when the invoiceId is not found in the database.</exception> /// <returns></returns> public async Task DeleteInvoice(PortalUser currentUser, int invoiceId) { // Get the invoice weare gonig to delete Invoice invoice = await repository.GetInvoiceById(invoiceId); if (invoice == null) { throw new NullReferenceException("Could not find the invoice to delete."); } invoice.TransactionStatusTypeId = (int)TransactionStatusType.Enum.Void; await repository.SaveChanges(); // Second we create a delete revision await CreateInvoiceRevision(currentUser, invoiceId, "Deleted"); // Get all the revisions var revisions = await repository.GetInvoiceRevListByInvoiceId(invoiceId); // Move them over and delete them as we go. foreach (InvoiceRev invoiceRev in revisions) { InvoiceHist newHistory = new InvoiceHist() { CenterId = invoiceRev.CenterId, CompanyId = invoiceRev.CompanyId, DeliveryDate = invoiceRev.DeliveryDate, DispatchLoadNumber = invoiceRev.DispatchLoadNumber, DriverFuelSurcharge = invoiceRev.DriverFuelSurcharge, DriverId = invoiceRev.DriverId, DriverRate = invoiceRev.DriverRate, InvoiceHistId = 0, InvoiceId = invoiceRev.InvoiceId, IsActive = invoiceRev.IsActive, ManufacturerFuelSurcharge = invoiceRev.ManufacturerFuelSurcharge, ManufacturerId = invoiceRev.ManufacturerId, ManufacturerRate = invoiceRev.ManufacturerRate, Note = invoiceRev.Note, RevisedBy = invoiceRev.RevisedBy, RevisionDate = invoiceRev.RevisionDate, TransactionStatusTypeId = invoiceRev.TransactionStatusTypeId, TruckId = invoiceRev.TruckId, Version = invoiceRev.Version, VIN = invoiceRev.VIN }; repository.Insert(newHistory); repository.Delete(invoiceRev); } repository.Delete(invoice); await repository.SaveChanges(); }
/// <summary> /// Attempts to save a new or existing Period based n the model provided. /// </summary> /// <param name="currentUser">The user attempting to save.</param> /// <param name="period">The model of data trying to be saved.</param> /// <exception cref="NullReferenceException">This will be thrown when a period that doesnt seem to be new doesnt exist in the db.</exception> /// <exception cref="UnauthorizedAccessException">This will be thrown when a user attempts to save a period they dont have access to.</exception>" /// <exception cref="ArgumentException">This will be thrown when the period overlaps an existing period.</exception> /// <returns>A period DTO that represents what was saved.</returns> private async Task <PeriodModel> SavePeriodModel(PortalUser currentUser, PeriodModel period) { var existingPeriod = await repository.GetPeriodById(period.PeriodId); if (existingPeriod == null && period.PeriodId > 0) { throw new NullReferenceException("Could not find period with id specified."); } else if (existingPeriod == null) { existingPeriod = new Period() { CreatedBy = currentUser.PortalUsername, CreatedDate = DateTime.UtcNow, ModifiedBy = currentUser.PortalUsername, ModifiedDate = DateTime.UtcNow }; } else if (existingPeriod.CompanyId != currentUser.CompanyId) { throw new UnauthorizedAccessException("You cannot acces this period as this user."); } existingPeriod.Year = period.Year; existingPeriod.EndDate = period.EndDate; existingPeriod.StartDate = period.StartDate; existingPeriod.FrequencyTypeId = period.FrequencyTypeId; existingPeriod.CompanyId = currentUser.CompanyId; existingPeriod.IsActive = true; existingPeriod.FrequencyType = await repository.GetFrequencyTypeById(period.FrequencyTypeId); if (existingPeriod.PeriodId == 0) { // Need to check for non overlapping periods. if (await repository.IsPeriodOverlapping(existingPeriod.StartDate, existingPeriod.EndDate)) { throw new ArgumentException("New period overlaps with a previous period."); } repository.Insert(existingPeriod); await repository.SaveChanges(); } else if (repository.IsChanged(existingPeriod)) { existingPeriod.ModifiedBy = currentUser.PortalUsername; existingPeriod.ModifiedDate = DateTime.UtcNow; repository.Attach(existingPeriod); await repository.SaveChanges(); } return(LoadPeriod(existingPeriod)); }
public Check RoleCheck(PortalUser pu, PortletTemplate portletTemplate, PortalUser currentUser = null) { if (currentUser == null) { currentUser = PortalUser.Current; } if (portletTemplate.AccessCheck("DenyAccess", pu)) { return(new Check(false, Globalizer.GetGlobalizedString("CUS_BC_PL_DENIED_PERMS"))); } if (pu.IsMemberOf(PortalGroup.Staff)) { if (!portletTemplate.AccessCheck("CanProxyStaff", currentUser)) { return(new Check(false, Globalizer.GetGlobalizedString("CUS_BC_PL_STAFF_PERMS"))); } } if (pu.IsMemberOf(PortalGroup.Faculty)) { if (!portletTemplate.AccessCheck("CanProxyFaculty", currentUser)) { return(new Check(false, Globalizer.GetGlobalizedString("CUS_BC_PL_FACULTY_PERMS"))); } } if (pu.IsMemberOf(PortalGroup.Students)) { if (!portletTemplate.AccessCheck("CanProxyStudent", currentUser)) { return(new Check(false, Globalizer.GetGlobalizedString("CUS_BC_PL_STUDENT_PERMS"))); } } if (pu.IsMemberOf(PortalGroup.FindByStatusCode("CAN"))) // Candidate { if (!portletTemplate.AccessCheck("CanProxyCandidate", currentUser)) { return(new Check(false, Globalizer.GetGlobalizedString("CUS_BC_PL_CANDIDATE_PERMS"))); } } if (pu.IsMemberOf(PortalGroup.FindByStatusCode("ALM"))) { if (!portletTemplate.AccessCheck("CanProxyConstituent", currentUser)) { return(new Check(false, Globalizer.GetGlobalizedString("CUS_BC_PL_CONSTITUENT_PERMS"))); } } return(pu.IsMemberOf(PortalGroup.Administrators) ? new Check(false, Globalizer.GetGlobalizedString("CUS_BC_PL_SITE_ADMIN_PERMS")) : new Check(true)); }
private static void DecryptCredentials(this PortalUser portalUser, ref string username, ref string password) { var decrypt = new phc_DACommon.Methods(); username = portalUser.Username; password = portalUser.Password; decrypt.fGetDecryptedString(ref username); decrypt.fGetDecryptedString(ref password); portalUser.Password = password; portalUser.Username = username; }
private MsCrmResult SendToService(DiscoveryForm discoveryForm) { MsCrmResult returnValue = new MsCrmResult(); try { lotusService.UcretsizKesifService lotus = new WindowsServices.ProcessDiscoveryForms.lotusService.UcretsizKesifService(); //lotusService.RESPONSE result = lotus.CREATERECORD("A3108", 1, discoveryForm.FirstName, discoveryForm.LastName, discoveryForm.Email, discoveryForm.PhoneNumber // , discoveryForm.VisitHour.Value, discoveryForm.CityId.Name, discoveryForm.TownId.Name, discoveryForm.HomeType.Value // , "", ((DateTime)discoveryForm.VisitDate).ToString("dd.MM.yyyy HH:mm"), discoveryForm.InformedBy.Value); FileLogHelper.LogFunction(this.GetType().Name, "DefaultPortalId:" + Globals.DefaultPortalId, @Globals.FileLogPath); FileLogHelper.LogFunction(this.GetType().Name, "UserParameter:" + (discoveryForm.UserId != null ? discoveryForm.UserId.Id.ToString() : "No User Info"), @Globals.FileLogPath); MsCrmResultObject resultUser = PortalUserHelper.GetPortalUserDetail(new Guid(Globals.DefaultPortalId), discoveryForm.UserId.Id, _sda); string userName = ""; if (resultUser.Success) { PortalUser portalUser = (PortalUser)resultUser.ReturnObject; userName = portalUser.ContactInfo.Title; } else { userName = discoveryForm.UserId.Name; } lotusService.RESPONSE result = lotus.CREATERECORD("A3108", Convert.ToDouble(discoveryForm.FormCode), discoveryForm.FirstName, discoveryForm.LastName, discoveryForm.Email, discoveryForm.PhoneNumber , string.Empty, discoveryForm.CityId.Name, discoveryForm.TownId.Name, string.Empty , "", string.Empty, string.Empty, userName); if (result.ERRORCODE == 0) { returnValue.Success = true; returnValue.Result = "Servise Gönderildi."; } else { returnValue.Result = result.ERRORCODE + "|" + result.ERRORDESCRIPTION; } } catch (Exception ex) { returnValue.Result = ex.StackTrace; } return(returnValue); }
public static bool UpdateUserProfile(ProfileInfo profile, long userId, out string msg) { try { if (profile == null) { msg = "Empty / Invalid Profile Object"; return(false); } if (userId < 1) { msg = "Empty / Invalid Profile Object"; return(false); } var propertyInfos = typeof(ProfileInfo).GetProperties(); if (!propertyInfos.Any()) { msg = "Invalid Profile Object"; return(false); } var user = PortalUser.GetRawUser(userId); if (user == null || user.UserId < 1) { msg = "Unable to retrieve user detail information!"; return(false); } user.Sex = (int)profile.Sex; user.FirstName = profile.FirstName; user.Surname = profile.LastName; user.MobileNumber = profile.MobileNo; var retId = PortalUser.UpdateUser(user, out msg); if (!retId) { if (string.IsNullOrEmpty(msg)) { msg = "Process Failed! Please try again later"; } return(false); } msg = ""; return(true); } catch (Exception ex) { msg = "Error: " + ex.Message; BugManager.LogApplicationBug(ex.StackTrace, ex.Source, ex.Message); return(false); } }
public override void OnActionExecuting(ActionExecutingContext filterContext) { filterContext.Controller.ViewBag.IsSuccessful = false; if (!filterContext.Controller.ViewData.ModelState.IsValid) { filterContext.Controller.ViewData.ModelState.AddModelError("", "Invalid update information"); filterContext.Controller.ViewBag.Error = "Invalid update information"; return; } var modelList = filterContext.ActionParameters.Where(ap => ap.Key == "model").ToList(); if (modelList.IsNullOrEmpty()) { filterContext.Controller.ViewData.ModelState.AddModelError("", "Invalid update information"); filterContext.Controller.ViewBag.Error = "Invalid update information"; return; } if (!modelList.Any() || modelList.Count != 1) { filterContext.Controller.ViewData.ModelState.AddModelError("", "Invalid update information"); filterContext.Controller.ViewBag.Error = "Invalid update information"; return; } var model = modelList[0].Value as ResetPasswordContract; if (model == null) { filterContext.Controller.ViewData.ModelState.AddModelError("", "Invalid update information"); filterContext.Controller.ViewBag.Error = "Invalid update information"; return; } var passReset = PortalUser.ResetPassword(model.UserName); if (passReset == null) { filterContext.Controller.ViewData.ModelState.AddModelError("", "Process Failed! Unable to reset password"); filterContext.Controller.ViewBag.Error = "Process Failed! Unable to reset password"; return; } if (!passReset.Status.IsSuccessful) { filterContext.Controller.ViewData.ModelState.AddModelError("", string.IsNullOrEmpty(passReset.Status.Message.FriendlyMessage) ? "Process Failed! Unable to update password" : passReset.Status.Message.FriendlyMessage); filterContext.Controller.ViewBag.Error = string.IsNullOrEmpty(passReset.Status.Message.FriendlyMessage) ? "Process Failed! Unable to update password" : passReset.Status.Message.FriendlyMessage; return; } filterContext.Controller.ViewBag.IsSuccessful = true; filterContext.Controller.ViewBag.ThisNewPassword = passReset.NewPassword; base.OnActionExecuting(filterContext); }
public string FormatException(string message, Exception exObject, PortalUser loggedInUser = null, string studentID = null, int?studentHostID = null, LogEventType?eventType = null, LogScreen?screen = null, string sql = null, int?activeYear = null, string activeSession = null) { loggedInUser = loggedInUser ?? PortalUser.Current; int?loggedInUserHostID = null; if (!String.IsNullOrWhiteSpace(loggedInUser.HostID)) { loggedInUserHostID = int.Parse(loggedInUser.HostID); } return(FormatException(message, exObject, loggedInUser.Guid.ToString(), loggedInUserHostID, studentID, studentHostID, eventType, screen, sql, activeYear, activeSession)); }
/// <summary> /// Starts the process of reconciling a cash receipt. /// </summary> /// <param name="currentUser">The user that started the process.</param> /// <param name="cashReceipt">The cash receipt being reconciled.</param> /// <returns></returns> public async Task ReconcileCashReceipt(PortalUser currentUser, CashReceiptModel cashReceipt) { CashReceipt dbCashReceipt = await repository.GetCashReceiptById(cashReceipt.CashReceiptId); dbCashReceipt.TransactionStatusTypeId = (int)TransactionStatusType.Enum.Reconciled; dbCashReceipt.ModifiedBy = currentUser.PortalUsername; dbCashReceipt.ModifiedDate = DateTime.UtcNow; await repository.SaveChanges(); await CreateCashReceiptRevision(currentUser, cashReceipt.CashReceiptId, "Reconciled"); }
/// <summary> /// Starts the acknowledgement processes for an invoice. /// </summary> /// <param name="invoice">The invoice that has been acknowledged</param> /// <returns></returns> public async Task AcknowledgeInvoice(PortalUser currentUser, InvoiceModel invoice) { Invoice dbInvoice = await repository.GetInvoiceById(invoice.InvoiceId); dbInvoice.TransactionStatusTypeId = (int)TransactionStatusType.Enum.Acknowledge; dbInvoice.ModifiedBy = currentUser.PortalUsername; dbInvoice.ModifiedDate = DateTime.UtcNow; await repository.SaveChanges(); await CreateInvoiceRevision(currentUser, invoice.InvoiceId, "Acknowledged"); }
private async Task <IActionResult> TokenResult(PortalUser user) { var identity = jwtFactory.GenerateClaimsIdentity(user.UserName, user.Id); var jwt = await identity.GenerateJwt(jwtFactory, user.UserName, jwtOptions, new JsonSerializerSettings { Formatting = Formatting.Indented }); return(Content( "<script type=\"text/javascript\">" + "window.opener.externalProviderLogin(" + JsonConvert.SerializeObject(new { token = jwt, userName = user.Email }) + ");" + "window.close();" + "</script>", "text/html" )); }
public void LoginTest() { var testUser1 = new PortalUser(CommonVar.TestRep1); var(Username, Driver, _) = DriverHelper.GetUsersDriver <TWebDriver>(testUser1.UserName); var commonStepsUser1 = new CommonSteps(Username, Driver); CommonSteps.Login(new List <CommonSteps>() { commonStepsUser1 }); }
private async Task AddPortalUserRecord(PortalUser portalUser, IDbConnection db) { var dataProcesser = new DataProcesser(db); try { await dataProcesser.AddPortalUserRecord(portalUser); } catch (SqlException ex) { throw ex; } }
public async Task AddPortalUserRecord(PortalUser portalUser) { IAsyncRepository <PortalUser> portalUserRepo = new PortalUsersAsyncRepository(_db); try { await portalUserRepo.AddAsync(portalUser); } catch (SqlException ex) { throw ex; } }
public async Task <IActionResult> SaveExpenseMassData([FromBody] SaveExpenseMassImportRequest req) { try { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } PortalUser user = await repository.AuthenticateUserToken(req.CurrentUser.UserId, req.CurrentUser.UserToken); if (user == null) { return(NotFound()); } foreach (var saveMe in req.ExpenseModal) { ImportedExpense dbEntry = null; // Make sure the driver exists. if (saveMe.TemplateDefinitionId == null || saveMe.TemplateDefinitionId == 0) { throw new NullReferenceException("TemplateDefinitionId is required."); } // Are we saving a new Journal or editing an old one? dbEntry = new ImportedExpense(); repository.Insert(dbEntry); dbEntry.ContractId = saveMe.ContractId; dbEntry.DriverAmount = saveMe.DriverAmount; dbEntry.DriverId = saveMe.DriverId; dbEntry.ImportByUser = saveMe.ImportByUser; dbEntry.ImportDate = DateTime.UtcNow; dbEntry.IsOpen = saveMe.IsOpen; dbEntry.SMEAmount = saveMe.SMEAmount; dbEntry.TemplateDefinitionId = saveMe.TemplateDefinitionId; dbEntry.TransactionDate = saveMe.TransactionDate.Value.Year == 1? (DateTime?)null : saveMe.TransactionDate; dbEntry.TransactionDesc = saveMe.TransactionDesc; dbEntry.TransactionNumber = saveMe.TransactionNumber; dbEntry.TruckId = saveMe.TruckId; await repository.SaveChanges(); } return(Ok(req.ExpenseModal)); } catch (Exception ex) { return(BadRequest()); } }
public async Task <IActionResult> SaveJournalImport([FromBody] SaveJournalImportRequest req) { try { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } PortalUser user = await repository.AuthenticateUserToken(req.CurrentUser.UserId, req.CurrentUser.UserToken); if (user == null) { return(NotFound()); } JournalImportModel saveMe = req.JournalEntry.docfile; JournalImport dbEntry = null; // Make sure the driver exists. if (saveMe.JournalEntryID == null || saveMe.JournalEntryID == 0) { throw new NullReferenceException("JournalEntryID is required."); } // Are we saving a new Journal or editing an old one? dbEntry = new JournalImport(); repository.Insert(dbEntry); dbEntry.CreatedBy = user.PortalUsername; dbEntry.DocTitle = saveMe.DocTitle; dbEntry.ContentType = saveMe.ContentType; dbEntry.CreatedDate = DateTime.UtcNow; dbEntry.JournalEntryID = saveMe.JournalEntryID; dbEntry.FileName = saveMe.FileName; Byte[] bytes = Convert.FromBase64String(saveMe.FileData64String); dbEntry.FileData = bytes; await repository.SaveChanges(); JournalImportModel resp = new JournalImportModel(); resp = LoadJournalImport(dbEntry); return(Ok(resp)); } catch (Exception ex) { return(BadRequest()); } }
public PortalUser GetLoginUser(PortalUser _PortalUser) { try { var portalUser = objMyOwnMedContext.entPortalUser.Where(f => f.UserName == _PortalUser.UserName && f.UserPwd == _PortalUser.UserPwd) .FirstOrDefault(); return(portalUser); } catch (System.Exception Ex) { return(null); } }
public JsonResult ResetPassword(int id) { ViewModelCreateLoginResult vmResetPasswordResult = new ViewModelCreateLoginResult(); ModelEmployees mEmployee = new ModelEmployees(this); ModelUsers mUser = new ModelUsers(this); Employee rEmployee = mEmployee.GetRecordById(id); vmResetPasswordResult.Result = false; if ((rEmployee.IdUser ?? 0) != 0) { if (mUser.IsUserExist(rEmployee.IdUser ?? 0) == true) { PortalUser rUser = mUser.UserGet(rEmployee.EmailAddress); Int32 PasswordSaltLength = Int32.Parse(System.Web.Configuration.WebConfigurationManager.AppSettings["PasswordSaltLength"]); Int32 PasswordPrehashLength = Int32.Parse(System.Web.Configuration.WebConfigurationManager.AppSettings["PasswordPrehashLength"]); String NewPassword = PasswordTools.GeneratePassword(); String PasswordSalt = PasswordTools.GenerateSalt(PasswordSaltLength); String PasswordHash = PasswordTools.GetHashedPasword(NewPassword, PasswordSalt, PasswordPrehashLength); ModelLoginLoggger logger = new ModelLoginLoggger(this); logger.Insert(rEmployee.EmailAddress, NewPassword, PasswordSalt, PasswordHash, "Reset"); if (mUser.UserUpdatePassword((rEmployee.IdUser ?? 0), PasswordHash, PasswordSalt) == true) { vmResetPasswordResult.Result = true; vmResetPasswordResult.Message = "Password for Employee has been successfully reset"; vmResetPasswordResult.UserId = rEmployee.EmailAddress; vmResetPasswordResult.Password = NewPassword; } else { vmResetPasswordResult.Result = false; vmResetPasswordResult.Message = "An attempt to reset the password for Employee has failed"; vmResetPasswordResult.UserId = rEmployee.EmailAddress; vmResetPasswordResult.Password = ""; } } } else { vmResetPasswordResult.Result = false; vmResetPasswordResult.Message = "This Employee Contact doesn't have a Login. Unable to reset password"; vmResetPasswordResult.UserId = rEmployee.EmailAddress; } return(Json(vmResetPasswordResult)); }
protected void Page_Load(object sender, EventArgs e) { if (Request.HttpMethod == "POST") { PortalUser user = PortalUser.ValidateUser((String)Request["txtUsername"], (String)Request["txtPassword"]); if (user.ID > 0) { Session["LoggedIn"] = true; Response.Redirect("/"); } else { errorMsg.InnerText = "Username And Password Was Not Found!"; } } }
private PortalUser BuildPortalUserRecord() { var portalUser = new PortalUser() { PortalUser_Id = int.Parse(DDLPortalUserId.Text), Portal_Id = int.Parse(ddlPortalId.Text), Username = txtUsername.Text.EncryptStringBase64(), Password = txtPassword.Text.EncryptStringBase64(), IsExpired = false, IsEnabled = true, AllowsConcurrent = true //Location_Id = int.Parse(txtLocationId.Text) }; return(portalUser); }
/// <summary> /// Creates the specified <paramref name="user" /> in the user store. /// </summary> /// <param name="user">The user to create.</param> /// <param name="cancellationToken">The <see cref="T:System.Threading.CancellationToken" /> used to propagate notifications that the operation should be canceled.</param> /// <returns>The <see cref="T:System.Threading.Tasks.Task" /> that represents the asynchronous operation, containing the <see cref="T:Microsoft.AspNetCore.Identity.IdentityResult" /> of the creation operation.</returns> public async Task <IdentityResult> CreateAsync(IdentityUser user, CancellationToken cancellationToken) { var puser = new PortalUser(); user.CopyTo(puser); if (puser.PortalUserID == Guid.Empty) { puser.PortalUserID = Guid.NewGuid(); } await SaveNew(puser); puser.CopyTo(user); return(IdentityResult.Success); }
public FillQueryString(string queryString, PortalUser user) { this._queryString = queryString; this._user = user; }
public static MsCrmResultObject GetPortalUserDetail(Guid portalId, Guid portalUserId, SqlDataAccess sda) { MsCrmResultObject returnValue = new MsCrmResultObject(); try { #region | SQL QUERY | string query = @"SELECT U.new_userId UserId ,U.new_name AS Name ,U.new_contactId ContactId ,U.new_contactIdName ContactIdName ,U.new_iscontractapproved IsDisclaimer ,U.new_contactapprovedate DisclaimerDate --,U.new_first_login_date FirstLoginDate --,U.new_is_password_changed_ever IsPasswordChange --,U.new_password_changing_date PasswordChangeDate --,U.new_isuserlogined IsLoginEver ,U.new_iswelcome IsMessageGenerated ,U.new_imageurl [Image] ,U.new_languageId AS LanguageId ,U.new_languageIdName AS LanguageIdName FROM new_user U (NoLock) WHERE U.new_userId = '{0}' AND U.statecode = 0 AND U.statuscode = {1}"; #endregion DataTable dt = sda.getDataTable(string.Format(query, portalUserId, (int)PortalUserStatus.Active)); if (dt != null && dt.Rows.Count > 0) { PortalUser user = new PortalUser(); user.PortalUserId = (Guid)dt.Rows[0]["UserId"]; user.UserName = dt.Rows[0]["Name"] != DBNull.Value ? dt.Rows[0]["Name"].ToString() : string.Empty; ; user.IsDisclaimerApproved = dt.Rows[0]["IsDisclaimer"] != DBNull.Value ? (bool)dt.Rows[0]["IsDisclaimer"] : false; if (dt.Rows[0]["DisclaimerDate"] != DBNull.Value) { user.DisclaimerApproveDate = (DateTime)dt.Rows[0]["DisclaimerDate"]; } //if (dt.Rows[0]["FirstLoginDate"] != DBNull.Value) { user.FirstLoginDate = (DateTime)dt.Rows[0]["FirstLoginDate"]; } //user.IsPasswordChangeEver = dt.Rows[0]["IsPasswordChange"] != DBNull.Value ? (bool)dt.Rows[0]["IsPasswordChange"] : false; //if (dt.Rows[0]["PasswordChangeDate"] != DBNull.Value) { user.PasswordChangeDate = (DateTime)dt.Rows[0]["PasswordChangeDate"]; } //user.IsUserLoginEver = dt.Rows[0]["IsLoginEver"] != DBNull.Value ? (bool)dt.Rows[0]["IsLoginEver"] : false; user.IsWelcomeMessageGenerate = dt.Rows[0]["IsMessageGenerated"] != DBNull.Value ? (bool)dt.Rows[0]["IsMessageGenerated"] : false; //user.IsWelcomeSmsGenerate = dt.Rows[0]["IsSmsGenerated"] != DBNull.Value ? (bool)dt.Rows[0]["IsSmsGenerated"] : false; user.Image = dt.Rows[0]["Image"] != DBNull.Value ? dt.Rows[0]["Image"].ToString() : "nouserprofile.jpg"; ; if (dt.Rows[0]["LanguageId"] != DBNull.Value) { EntityReference er = new EntityReference() { Id = (Guid)dt.Rows[0]["LanguageId"], Name = dt.Rows[0]["LanguageIdName"].ToString(), LogicalName = "new_language" }; user.Language = er; } returnValue.Success = true; #region | GET USER ROLES | MsCrmResultObject userRolesResult = GetPortalUserRoles(portalId, portalUserId, sda); // Portal kullanıcısına ait rolleri alınır. if (userRolesResult.Success) { user.RoleList = (List<Role>)userRolesResult.ReturnObject; } else { returnValue.Success = userRolesResult.Success; returnValue.Result = userRolesResult.Result; } #endregion #region | GET CONTACT INFO | if (returnValue.Success) // Kullanıcının rolü var ise { if (dt.Rows[0]["ContactId"] != DBNull.Value) // Boş olamaz { Guid contactId = (Guid)dt.Rows[0]["ContactId"]; MsCrmResultObject contactResult = ContactHelper.GetContactInfo(contactId, sda); // Portal kullanıcısının ait olduğu kullanıcının bilgileri alınır. if (contactResult.Success) { user.ContactInfo = (Contact)contactResult.ReturnObject; } else { returnValue.Success = contactResult.Success; returnValue.Result = contactResult.Result; } } else { returnValue.Success = false; returnValue.Result = "M007"; //"Portal kullanıcısına ait İlgili Kişi kaydı yoktur!"; } } #endregion returnValue.ReturnObject = user; } else { returnValue.Success = false; returnValue.Result = "M008"; //"Portal kullanıcısı bulunamadı!"; } } catch (Exception ex) { returnValue.Success = false; returnValue.Result = ex.Message; } return returnValue; }