//No Authorization Set intentionally public IActionResult getInNewuser([FromBody] UserBasic newUser) { Hashing sai = new Hashing(); newUser.PdSystem = sai.HashingPlain(newUser.PdSystem); newUser.UserIdSystem = Guid.NewGuid().ToString(); string msg = string.Empty; bool success = false; UserBasic user = newUser; if (db.UserBasic.Where(x => x.Email.ToLower() == newUser.Email.ToLower()).Any()) { msg = "User Already Exists. Please contact the Admin"; } else { db.UserBasic.Add(newUser); db.SaveChanges(); success = true; msg = "Your Request has been submitted, Email confirmation will be sent up on approval. Thanks"; AuthSession.SetUserId(HttpContext, newUser.UserIdSystem); } var result = new { success = success, msg = msg }; return(Json(result)); }
//No Authorization Set intentionally public IActionResult getInExisting([FromBody] ExistingUser existingUser) { Hashing sai = new Hashing(); existingUser.epd = sai.HashingPlain(existingUser.epd); string msg = "Bad User Name or Password"; string success = "n"; var hasUser = db.UserBasic.Where(x => x.Email == existingUser.eud); if (hasUser.Any()) { UserBasic user = hasUser.FirstOrDefault(); bool map = db.UserRoleMap.Any(x => x.UserIdSystem == user.UserIdSystem); if (user.PdSystem == existingUser.epd && map) { AuthSession.SetUserId(HttpContext, user.UserIdSystem); success = "y"; msg = "Authorization Complete"; } } var result = new { success = success, msg = msg }; return(Json(result)); }
public ActionResult Add(PcAndRole model) { Utility.ReturnData <string> returnData = new Utility.ReturnData <string>(); long count = bll.GetQueryCount(x => x.UserName == model.UserName && x.Status != 1); UserBasic ubModel = new UserBasic(); ubModel.NickName = model.UserName; ubModel.UserType = 1; ubModel.AddTime = DateTime.Now; ubModel.EnterpriseID = LoginUser.UserBasic.EnterpriseID; long id = ubBll.AddAndGetId(ubModel); UserPC upModel = new UserPC(); upModel.UserName = model.UserName; upModel.UserBasicID = id; upModel.RoleID = model.RoleID; upModel.PCType = 1; upModel.AddTime = DateTime.Now; upModel.PassWord = SimpleEncrypt.SaltMD5(model.PassWord.Replace(" ", "")); upModel.AddUserBasicID = LoginUser.UserBasicID; upModel.Status = 0; returnData = bll.AddUserPc(upModel); if (returnData.Status == false) { ubBll.Delete(s => s.ID == id); return(Content(returnData.Message)); } return(Content(returnData.Message)); }
public IActionResult Profile(string id) { CommonFunction str = new CommonFunction(); string userId = AuthSession.GetUserId(HttpContext, "userId"); ProfileDetails profile = new ProfileDetails(); bool hasError = false; if (!str.CheckIsNullOrEmpty(id)) { var hasprofile = db.ProfileDetails.Where(x => x.ProfileUserId == id); if (hasprofile.Any()) { profile = hasprofile.FirstOrDefault(); } else { hasError = true; } } else { UserBasic user = db.UserBasic.Where(x => x.UserIdSystem == userId).FirstOrDefault(); profile.ProfileId = 0; profile.FirstName = user.FirstName; profile.MiddleName = user.MiddleName; profile.LastName = user.LastName; profile.Email = user.Email; } ViewBag.error = hasError; return(View(profile)); }
internal static IUserBasic CreateUser(IApplicationSettings applicationSettings, IApplication application , DummyDataManager dummyDataManager, WorkmateRoleProvider roleProvider , WorkmateMembershipProvider membershipProvider, string password, AccountStatus accountStatus) { DummyUser user = dummyDataManager.GetDummy(); string firstName = user.Firstname; string lastName = user.Surname; TimeZoneInfo timeZoneInfo = TimeZoneUtility.GetGMTStandardTimeZone(); IUserBasic userBasic = new UserBasic(user.Email, user.Email, 1) { AccountStatus = accountStatus, TimeZoneInfo = timeZoneInfo }; Guid uniqueId; List <UserRole> userRoles = new List <UserRole>() { UserRole.SystemAdministrator, UserRole.Registered }; UserCreateStatus userCreateStatus = membershipProvider.CreateUser(ref userBasic, password, userRoles, UserNameDisplayMode.FullName , firstName, lastName , Workmate.Components.Contracts.Membership.Gender.Male , out uniqueId, application.ApplicationId).Status; Assert.AreEqual(UserCreateStatus.Success, userCreateStatus); Assert.Greater(userBasic.UserId, 0); return(membershipProvider.GetUserBasic(userBasic.UserId, false)); }
public List <OrderInfo> GetOrderList() { UserBasic objUser = new UserBasic(); objUser.UserId = Session["SessionUserId"].ToString(); objUser.Email = Session["SessionUserEmail"].ToString(); objUser.TerminalId = "admin"; List <OrderInfo> orderInfoList = new List <OrderInfo>(); var response = apiRequest.HttpPostRequest(objUser, "web/Orders/AllOrders"); var responseModel = JsonConvert.DeserializeObject <ResponseMessage>(response.ToString()); if (responseModel.MessageCode == "Y") { orderInfoList = JsonConvert.DeserializeObject <List <OrderInfo> >(responseModel.Content.ToString()); return(orderInfoList); } else { TempData["msgAlert"] = "NoOrders"; TempData["msgAlertDetails"] = "No order information found."; return(orderInfoList); } return(orderInfoList); }
public ActionResult Register(UserBasic request) { try { #region check model if (!ModelState.IsValid) { var modelState = ModelState.FirstOrDefault(); var error = modelState.Value.Errors.FirstOrDefault().ErrorMessage; throw ApiException.Get(false, error, ResultEnum.ModelError, HttpStatusCode.BadRequest); } #endregion var task = userService.Register(brandToken, request); task.Wait(); response = BaseResponse <dynamic> .Get(true, ConstantManager.Success("Register"), null, ResultEnum.Success); } catch (ApiException e) { result.StatusCode = e.StatusCode; response = BaseResponse <dynamic> .Get(e.Success, e.ErrorMessage, null, e.ErrorStatus); result = new JsonResult(response); } catch (Exception e) { result.StatusCode = (int)HttpStatusCode.InternalServerError; response = BaseResponse <dynamic> .Get(false, ConstantManager.Fail("Register : ") + e.ToString(), null, ResultEnum.InternalError); } result = new JsonResult(response); return(result); // create asp user , employee , membership , account }
public ArticleImage(int applicationId, UserBasic owner) { this._CMSFile = new CMSFile(applicationId, owner, FileType.ArticleImage); this.OwnerUserId = owner.UserId; this.Tags = new List <string>(); }
public ActionResult FirstLogin(string name, string pwd, string num) { ReturnData <string> ret = new ReturnData <string>(); AgentBll aBll = new AgentBll(); UserBasicBll uBll = new UserBasicBll(); UserPCBll pcBll = new UserPCBll(); Agent aModel = aBll.GetModelByPhone(num); UserBasic uModel = new UserBasic(); UserPC pcModel = new UserPC(); uModel.NickName = name; uModel.UserType = 1; uModel.EnterpriseID = aModel.EnterpriseID; uModel.AddTime = DateTime.Now; long id = uBll.AddAndGetId(uModel); pcModel.UserBasicID = id; pcModel.PassWord = SimpleEncrypt.SaltMD5(pwd.Replace(" ", "")); pcModel.PCType = 2; pcModel.RoleID = aModel.ID; pcModel.Status = 0; pcModel.UserName = name; pcModel.AddTime = DateTime.Now; pcModel.AddUserBasicID = 0; ret = pcBll.AddUserPc(pcModel); if (ret.Status == true) { aModel.Status = 0; aBll.EditAgent(aModel); return(Content(ret.Message)); } return(Content(ret.Message)); }
static WMUserPrincipal() { _AnonymousInstance = new WMUserPrincipal( WMUserIdentity.Create(UserBasic.GetAnonymousUserInstance() , false , DateTime.MinValue , DateTime.MinValue)); }
public bool Add(UserBasic model, string number) { var entity = new Employee(); Mapper.Map(model, entity, typeof(UserBasic), typeof(Employee)); entity.EmpEnrollNumber = number; entity.Active = true; entity.Status = (int)EmployeeStatusEnum.Active; entity = Create(entity); if (entity.Id != 0) { return(true); } return(false); }
public PrivateMessage(PrivateMessage parentMessage, UserBasic author, Folder folder, MessageStatus messageStatus, MessageType messageType, string subject, string formattedBody) { this._CMSContent = new CMSContent( author.UserId , folder.CMSThread , (byte)messageStatus , (byte)messageType , subject , formattedBody , true); this.ParentMessageId = parentMessage.PrivateMessageId; this.MessageLevel = parentMessage.MessageLevel; this.Folder = folder; }
public IActionResult ManageProfile([FromBody] ProfileDetails profileDetails) { try { string userId = AuthSession.GetUserId(HttpContext, "userId"); UserBasic userBasic = db.UserBasic.Where(x => x.UserIdSystem == userId).FirstOrDefault(); if (profileDetails.ProfileId == 0) { profileDetails.ProfileUserId = Guid.NewGuid().ToString(); profileDetails.UpdatedDate = DateTime.UtcNow; profileDetails.UpdatedByName = userBasic.FirstName + " " + userBasic.MiddleName + " " + userBasic.LastName; profileDetails.UpdatedById = userId; profileDetails.MappedToUserIdSystem = userId; db.ProfileDetails.Attach(profileDetails); db.ProfileDetails.Add(profileDetails); } else { ProfileDetails profileDetailsDb = db.ProfileDetails.Where(x => x.ProfileId == profileDetails.ProfileId).FirstOrDefault(); profileDetailsDb.FirstName = profileDetails.FirstName; profileDetailsDb.MiddleName = profileDetails.MiddleName; profileDetailsDb.LastName = profileDetails.LastName; profileDetailsDb.Gender = profileDetails.Gender; profileDetailsDb.Email = profileDetails.Email; profileDetailsDb.Phone = profileDetails.Phone; profileDetailsDb.City = profileDetails.City; profileDetailsDb.StateName = profileDetails.StateName; profileDetailsDb.Country = profileDetails.Country; profileDetailsDb.ZipCode = profileDetails.ZipCode; profileDetailsDb.Education = profileDetails.Education; profileDetailsDb.Profession = profileDetails.Profession; profileDetailsDb.Interest = profileDetails.Interest; profileDetailsDb.Expectation = profileDetails.Expectation; profileDetailsDb.YearOfBirth = profileDetails.YearOfBirth; profileDetailsDb.UpdatedDate = DateTime.UtcNow; profileDetails.UpdatedByName = userBasic.FirstName + " " + userBasic.MiddleName + " " + userBasic.LastName; profileDetails.UpdatedById = userId; } db.SaveChanges(); return(Json(new KeyValuePair <string, string>("y", "Profile Saved Successfully"))); } catch (Exception) { return(Json(new KeyValuePair <string, string>("n", "Error saving profile, contact support"))); } }
private async Task SendUserInviteEmailAsync(UserBasic userDisplay, string from, string fromEmail, IUser to, string message) { var user = await _userManager.FindByIdAsync(((int)userDisplay.Id).ToString()); var token = await _userManager.GenerateEmailConfirmationTokenAsync(user); // Use info from SMTP Settings if configured, otherwise set fromEmail as fallback var senderEmail = !string.IsNullOrEmpty(_globalSettings.Smtp?.From) ? _globalSettings.Smtp.From : fromEmail; var inviteToken = string.Format("{0}{1}{2}", (int)userDisplay.Id, WebUtility.UrlEncode("|"), token.ToUrlBase64()); // Get an mvc helper to get the URL var action = _linkGenerator.GetPathByAction( nameof(BackOfficeController.VerifyInvite), ControllerExtensions.GetControllerName <BackOfficeController>(), new { area = Constants.Web.Mvc.BackOfficeArea, invite = inviteToken }); // Construct full URL using configured application URL (which will fall back to request) var applicationUri = _hostingEnvironment.ApplicationMainUrl; var inviteUri = new Uri(applicationUri, action); var emailSubject = _localizedTextService.Localize("user", "inviteEmailCopySubject", //Ensure the culture of the found user is used for the email! UmbracoUserExtensions.GetUserCulture(to.Language, _localizedTextService, _globalSettings)); var emailBody = _localizedTextService.Localize("user", "inviteEmailCopyFormat", //Ensure the culture of the found user is used for the email! UmbracoUserExtensions.GetUserCulture(to.Language, _localizedTextService, _globalSettings), new[] { userDisplay.Name, from, message, inviteUri.ToString(), senderEmail }); // This needs to be in the correct mailto format including the name, else // the name cannot be captured in the email sending notification. // i.e. "Some Person" <*****@*****.**> var toMailBoxAddress = new MailboxAddress(to.Name, to.Email); var mailMessage = new EmailMessage(senderEmail, toMailBoxAddress.ToString(), emailSubject, emailBody, true); await _emailSender.SendAsync(mailMessage, Constants.Web.EmailTypes.UserInvite, true); }
public static IUserBasic GetUserBasicFromAuthenticationCookie(HttpContext currentContext) { if (currentContext == null) { throw new ArgumentNullException("Current HttpContext must not be null."); } if (!currentContext.User.Identity.IsAuthenticated) { return(UserBasic.GetAnonymousUserInstance()); } IUserBasic userBasic = currentContext.User.Identity as IUserBasic; if (userBasic != null) { return(new UserBasic(userBasic)); } throw new Exception("Current user is not of type FLUserPrincipal."); }
public async Task Register(string brandToken, UserBasic model) { using (var client = new HttpClient()) { //ServicePointManager.ServerCertificateValidationCallback += //(sender, cert, chain, sslPolicyErrors) => true; //System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls; client.BaseAddress = new Uri("http://authorizecore.unicode.edu.vn"); //client.DefaultRequestHeaders.Accept.Add( //new MediaTypeWithQualityHeaderValue("application/json")); var oBject = new { Email = model.Email, Password = model.Password, ConfirmPassword = model.Password, brandToken = brandToken }; var response = await client.PostAsJsonAsync("/api/authorize/register", oBject); if (response.IsSuccessStatusCode) { //var responseObj = await response.Content.ReadAsAsync<JObject>(); //var data = responseObj.SelectToken("data"); //var email = data.SelectToken("email").ToString(); var empEnrollNumber = Utils.GetCurrentDateTime().Ticks.ToString(); employeeService.Add(model, empEnrollNumber); var loyaltyResponse = RootConfig.LoyaltyClient.MembershipsApi.Create(new CreateMembership() { IncludeAccounts = true, Active = true, BrandCode = "PASSIO", Code = empEnrollNumber, CreatedBy = "PeaSystem", EmpCode = empEnrollNumber, IsSample = false, Status = 1, MembershipTypeId = 3 }).Result; var result = loyaltyResponse.Content.ReadAsAsync <BaseResponse <LoyaltyEvent> >().Result; } } }
public IActionResult ManageUserRole([FromBody] UserRoleMap userRoleDto) { string key = "n"; string value = "Error Updating the User Role"; string userId = AuthSession.GetUserId(HttpContext, "userId"); UserRoleMap userRoleMap = new UserRoleMap(); try { if (userRoleDto != null) { bool isUser = Int32.TryParse(userRoleDto.UserIdSystem, out int userid); if (isUser) { UserBasic userBasic = db.UserBasic.Where(x => x.UserIdId == userid).FirstOrDefault(); userRoleMap = db.UserRoleMap.Where(x => x.UserIdSystem == userBasic.UserIdSystem).FirstOrDefault(); if (userRoleMap != null) { db.UserRoleMap.Remove(userRoleMap); } if (userRoleDto.MapId == 1) { userRoleMap = new UserRoleMap { UserIdSystem = userBasic.UserIdSystem, IsAdmin = userRoleDto.IsAdmin, UpdateByName = userBasic.FirstName + " " + userBasic.MiddleName + " " + userBasic.LastName, UpdateById = userId, UpdatedDate = DateTime.UtcNow }; db.UserRoleMap.Attach(userRoleMap); db.UserRoleMap.Add(userRoleMap); } db.SaveChanges(); } } } catch (Exception) { return(Json(new KeyValuePair <string, string>(key, value))); } return(Json(new KeyValuePair <string, string>("y", "Role Updated Successfully"))); }
// Umbraco.Code.MapAll -Notifications -IsCurrentUser -Udi -Icon -Trashed -Alias -AdditionalData private void Map(IUser source, UserBasic target, MapperContext context) { //Loading in the user avatar's requires an external request if they don't have a local file avatar, this means that initial load of paging may incur a cost //Alternatively, if this is annoying the back office UI would need to be updated to request the avatars for the list of users separately so it doesn't look //like the load time is waiting. target.Avatars = source.GetUserAvatarUrls(_appCaches.RuntimeCache); target.Culture = source.GetUserCulture(_textService, _globalSettings).ToString(); target.Email = source.Email; target.EmailHash = source.Email.ToLowerInvariant().Trim().ToMd5(); target.Id = source.Id; target.Key = source.Key; target.LastLoginDate = source.LastLoginDate == default ? null : (DateTime?)source.LastLoginDate; target.Name = source.Name; target.ParentId = -1; target.Path = "-1," + source.Id; target.UserGroups = context.MapEnumerable <IReadOnlyUserGroup, UserGroupBasic>(source.Groups); target.Username = source.Username; target.UserState = source.UserState; }
private async Task SendUserInviteEmailAsync(UserBasic userDisplay, string from, string fromEmail, IUser to, string message) { var token = await UserManager.GenerateEmailConfirmationTokenAsync((int)userDisplay.Id); var inviteToken = string.Format("{0}{1}{2}", (int)userDisplay.Id, WebUtility.UrlEncode("|"), token.ToUrlBase64()); // Get an mvc helper to get the URL var http = EnsureHttpContext(); var urlHelper = new UrlHelper(http.Request.RequestContext); var action = urlHelper.Action("VerifyInvite", "BackOffice", new { area = GlobalSettings.GetUmbracoMvcArea(), invite = inviteToken }); // Construct full URL using configured application URL (which will fall back to request) var applicationUri = RuntimeState.ApplicationUrl; var inviteUri = new Uri(applicationUri, action); var emailSubject = Services.TextService.Localize("user", "inviteEmailCopySubject", //Ensure the culture of the found user is used for the email! UserExtensions.GetUserCulture(to.Language, Services.TextService, GlobalSettings)); var emailBody = Services.TextService.Localize("user", "inviteEmailCopyFormat", //Ensure the culture of the found user is used for the email! UserExtensions.GetUserCulture(to.Language, Services.TextService, GlobalSettings), new[] { userDisplay.Name, from, message, inviteUri.ToString(), fromEmail }); await UserManager.EmailService.SendAsync( //send the special UmbracoEmailMessage which configures it's own sender //to allow for events to handle sending the message if no smtp is configured new UmbracoEmailMessage(new EmailSender(true)) { Body = emailBody, Destination = userDisplay.Email, Subject = emailSubject }); }
public void Test_CreateUser() { IApplicationSettings applicationSettings = Workmate.Components.InstanceContainer.ApplicationSettings; WorkmateRoleProvider roleProvider = new WorkmateRoleProvider(); WorkmateMembershipProvider membershipProvider = new WorkmateMembershipProvider(); DummyUser user = this.DummyDataManager.GetDummy(); string firstName = user.Firstname; string lastName = user.Surname; string password = "******"; AccountStatus accountStatus = AccountStatus.Valid; TimeZoneInfo timeZoneInfo = TimeZoneUtility.GetGMTStandardTimeZone(); IUserBasic userBasic = new UserBasic(user.Email, user.Email, 1) { AccountStatus = accountStatus, TimeZoneInfo = timeZoneInfo }; Guid uniqueId; List <UserRole> userRoles = new List <UserRole>() { UserRole.SystemAdministrator, UserRole.Registered }; UserCreateStatus userCreateStatus = membershipProvider.CreateUser(ref userBasic, password, userRoles, UserNameDisplayMode.FullName , firstName, lastName , DebugUtility.GetRandomEnum <Workmate.Components.Contracts.Membership.Gender>(this.Random) , out uniqueId, this.Application.ApplicationId).Status; Assert.AreEqual(UserCreateStatus.Success, userCreateStatus); Assert.Greater(userBasic.UserId, 0); userBasic = membershipProvider.GetUserBasic(userBasic.UserId, false); Assert.AreEqual(user.Email, userBasic.UserName); Assert.AreEqual(user.Email, userBasic.Email); Assert.AreEqual(accountStatus, userBasic.AccountStatus); Assert.AreEqual(timeZoneInfo.Id, userBasic.TimeZoneInfoId); }
//No Authorization Set intentionally public IActionResult checkSigned() { string key = "userId"; bool hasValue = false; UserBasic user = new UserBasic(); if (HttpContext.Session.Get(key) != null) { hasValue = System.Text.Encoding.Default.GetString(HttpContext.Session.Get(key)) == "invalid" ? false : true; var hasuser = db.UserBasic.Where(x => x.UserIdSystem == System.Text.Encoding.Default.GetString(HttpContext.Session.Get(key))); if (hasuser.Any()) { user = db.UserBasic.Where(x => x.UserIdSystem == System.Text.Encoding.Default.GetString(HttpContext.Session.Get(key))).FirstOrDefault(); user.PdSystem = ""; user.UserIdSystem = ""; } } var result = new { hasValue = hasValue, User = user }; return(Json(result)); }
/// <summary> /// 获得会员信息 /// </summary> /// <param name="shopMapper"></param> /// <param name="ids"></param> /// <returns></returns> public static List <UserBasic> GetUserBasic(Dictionary <long, long> shopMapper, List <long> ids) { var oList = new List <UserBasic>(); var strShopId = string.Join(",", ids); var strSql = new StringBuilder(); strSql.Append(" SELECT uid, uNumber, uName, uPhone, accID, uPY, uPinYin from T_UserInfo WITH (NOLOCK) where "); strSql.Append(string.Format(" accid in ({0}) ", strShopId)); var model = DapperHelper.Query <UserBasicModel>(strSql.ToString()).ToList(); if (model != null && model.Count > 0) { foreach (var item in model) { if (shopMapper.ContainsKey(item.accId)) { var masterId = shopMapper[item.accId]; var oItem = new UserBasic(); oItem.account_id = item.accId; oItem.user_cardno = string.IsNullOrEmpty(item.uNumber) ? "" : item.uNumber.ToLower(); oItem.user_initials = string.IsNullOrEmpty(item.uPY) ? "" : item.uPY.ToLower(); oItem.user_name = string.IsNullOrEmpty(item.uName) ? "" : item.uName.ToLower(); oItem.user_phone = string.IsNullOrEmpty(item.uPhone) ? "" : item.uPhone.ToLower(); oItem.user_pinyin = string.IsNullOrEmpty(item.uPinYin) ? "" : item.uPinYin.ToLower(); oItem.user_id = item.uid; oItem.master_id = masterId; oList.Add(oItem); } else { Error(string.Format("未找到匹配的总店id [uid:{0},shopid:{1}]", item.uid, item.accId)); } } } return(oList); }
public static List <UserBasic> searchPerson(string q, bool username, bool email) { List <UserBasic> userList = new List <UserBasic>(); SqlConnection conn; conn = new SqlConnection(ConfigurationManager.ConnectionStrings["dbString"].ConnectionString); conn.Open(); SqlCommand command = new SqlCommand("select * from userInfo where username like @u", conn); command.Parameters.Add("@u", System.Data.SqlDbType.VarChar).Value = q + '%'; SqlDataReader reader = command.ExecuteReader(); while (reader.Read()) { UserBasic u = new UserBasic(); u.UserId = Int32.Parse(reader["userid"].ToString()); u.UserName = reader["username"].ToString(); u.Email = reader["email"].ToString(); userList.Add(u); } return(userList); }
public ActionResult Add(PcAndRole model) { Utility.ReturnData<string> returnData = new Utility.ReturnData<string>(); long count = bll.GetQueryCount(x => x.UserName == model.UserName && x.Status != 1); UserBasic ubModel = new UserBasic(); ubModel.NickName = model.UserName; ubModel.UserType = 1; ubModel.AddTime = DateTime.Now; ubModel.EnterpriseID = LoginUser.UserBasic.EnterpriseID; long id = ubBll.AddAndGetId(ubModel); UserPC upModel = new UserPC(); upModel.UserName = model.UserName; upModel.UserBasicID = id; upModel.RoleID = model.RoleID; upModel.PCType = 1; upModel.AddTime = DateTime.Now; upModel.PassWord = SimpleEncrypt.SaltMD5(model.PassWord.Replace(" ", "")); upModel.AddUserBasicID = LoginUser.UserBasicID; upModel.Status = 0; returnData = bll.AddUserPc(upModel); if (returnData.Status == false) { ubBll.Delete(s => s.ID == id); return Content(returnData.Message); } return Content(returnData.Message); }
public ActionResult Create(CreateAccountModel model) { if (ModelState.IsValid) { int profileImageId = -1; switch (model.Gender) { case Gender.Male: profileImageId = this.RequestContextData.ApplicationThemeInfo.Images.MaleSystemProfileImageId; break; case Gender.Female: profileImageId = this.RequestContextData.ApplicationThemeInfo.Images.FemaleSystemProfileImageId; break; default: throw new NotImplementedException(); } SimplePassword simplePassword = new SimplePassword(); string password = simplePassword.Generate(8, CommonTools.Components.Security.CharacterType.NumbersUpperLowerCase); IUserBasic userBasic = new UserBasic( model.Email , model.Email , profileImageId); Guid uniqueId; var report = InstanceContainer.WorkmateMembershipProvider.CreateUser( ref userBasic , password , new List <UserRole>() { UserRole.Registered } , UserNameDisplayMode.FullName , model.FirstName , model.LastName , model.Gender , out uniqueId , this.RequestContextData.ApplicationThemeInfo.ApplicationId); switch (report.Status) { case UserCreateStatus.Success: InstanceContainer.EmailPublisher.EnqueueUserCreatedEmail( this.RequestContextData.ApplicationThemeInfo.ApplicationId , this.RequestContextData.Theme , this.RequestContextData.ApplicationThemeInfo.Application.DefaultAdminSenderEmailAddress , this.RequestContextData.StaticContentLookup , model.FirstName , model.LastName , model.Email , userBasic.UserId , password); return(RedirectToAction("ViewAccountUser", "Account", new { userId = userBasic.UserId })); // TODO (Roman): congratulations message informing that login details have been sent default: model.UserCreateStatus = report.Status; model.ValidationFailedErrorMessage = report.Message; return(View(model)); } } return(View()); }
public ActionResult FirstLogin(string name, string pwd, string num) { ReturnData<string> ret = new ReturnData<string>(); AgentBll aBll = new AgentBll(); UserBasicBll uBll = new UserBasicBll(); UserPCBll pcBll = new UserPCBll(); Agent aModel = aBll.GetModelByPhone(num); UserBasic uModel = new UserBasic(); UserPC pcModel = new UserPC(); uModel.NickName = name; uModel.UserType = 1; uModel.EnterpriseID = aModel.EnterpriseID; uModel.AddTime = DateTime.Now; long id = uBll.AddAndGetId(uModel); pcModel.UserBasicID = id; pcModel.PassWord = SimpleEncrypt.SaltMD5(pwd.Replace(" ", "")); pcModel.PCType = 2; pcModel.RoleID = aModel.ID; pcModel.Status = 0; pcModel.UserName = name; pcModel.AddTime = DateTime.Now; pcModel.AddUserBasicID = 0; ret = pcBll.AddUserPc(pcModel); if (ret.Status == true) { aModel.Status = 0; aBll.EditAgent(aModel); return Content(ret.Message); } return Content(ret.Message); }
/// <summary> /// Logs the user in. /// </summary> /// <param name="userBasic">The user basic.</param> /// <param name="rememberMe">if set to <c>true</c> [remember me].</param> /// <returns></returns> public bool LogUserIn(UserBasic userBasic, bool rememberMe) { WriteAuthenticationCookie(userBasic, rememberMe); return(true); }
public BusinessObjectActionReport <DataRepositoryActionStatus> DeleteTemporaryFile(int imageId, UserBasic userBasic) { return(_CMSFileManager.DeleteTemporaryFile(imageId, userBasic.UserId)); }
public string GetName(UserBasic user) { return(user.FirstName + " " + user.MiddleName + " " + user.LastName); }
public ValidateUserStatus ValidateUser(int applicationId, string usernameOrEmail, string password, out IUserBasic userBasic) { userBasic = UserBasic.GetAnonymousUserInstance(); wm_User_GetPassword_QueryResult getPasswordResult = null; string userName = null; string email = null; this.GetEmailOrUsername(usernameOrEmail, out userName, out email); using (IDataStoreContext dataStoreContext = this.DataStore.CreateContext()) { // first, get the password information try { getPasswordResult = dataStoreContext.wm_Users_GetPassword(applicationId, userName, email); } catch (Exception ex) { _Log.Error("Error at Users_GetPassword", ex); return(ValidateUserStatus.SqlError); } if (getPasswordResult == null) { return(ValidateUserStatus.UserNotFound); } if (getPasswordResult.AccountStatus == AccountStatus.Locked) { return(ValidateUserStatus.UserIsLockedOut); } if (getPasswordResult.AccountStatus == AccountStatus.Valid || getPasswordResult.AccountStatus == AccountStatus.AwaitingEmailVerification) { int returnValue; DateTime? lastActivityDateUtc = null; DateTime? lastLoginDateUtc = null; AccountStatus?status = null; int? failedPasswordAttemptCount = null; DateTime? lastLockoutDateUtc = null; if (!this.CheckPassword(password, getPasswordResult.Password, getPasswordResult.PasswordSalt, ((MembershipPasswordFormat)getPasswordResult.PasswordFormat))) {// wrong password try { returnValue = dataStoreContext.wm_Users_UpdateUserInfo(getPasswordResult.UserId, false, false, this.MaxInvalidPasswordAttempts , out lastActivityDateUtc, out lastLoginDateUtc, out status, out failedPasswordAttemptCount, out lastLockoutDateUtc); } catch (Exception ex) { _Log.Error("Error at Users_GetPassword", ex); return(ValidateUserStatus.SqlError); } if (returnValue < 0) { _Log.Error("Error at Users_UpdateUserInfo, ErrorCode: " + returnValue); } _Log.InfoFormat("User {0} entered an invalid password.", getPasswordResult.UserId); return(ValidateUserStatus.WrongPassword); // we return wrong password for now, if the user was locked out due to too many invalid password attempts, we will get this information at the next login attempt } else { try { returnValue = dataStoreContext.wm_Users_UpdateUserInfo(getPasswordResult.UserId, true, true, this.MaxInvalidPasswordAttempts , out lastActivityDateUtc, out lastLoginDateUtc, out status, out failedPasswordAttemptCount, out lastLockoutDateUtc); } catch (Exception ex) { _Log.Error("Error at Users_GetPassword", ex); return(ValidateUserStatus.SqlError); } if (returnValue < 0) { _Log.Error("Error at Users_UpdateUserInfo, ErrorCode: " + returnValue); return(ValidateUserStatus.SqlError); } else { try { userBasic = new UserBasic( getPasswordResult.UserId , getPasswordResult.UserName , getPasswordResult.Email , lastActivityDateUtc.Value , status.Value , getPasswordResult.DateCreatedUtc , lastLoginDateUtc.Value , getPasswordResult.ProfileImageId , getPasswordResult.TimeZoneInfoId , dataStoreContext.wm_Roles_GetByUserId(getPasswordResult.UserId)); } catch (Exception ex) { _Log.Error("Error at Roles_GetByUserId", ex); return(ValidateUserStatus.SqlError); } switch (status.Value) { case AccountStatus.AwaitingEmailVerification: return(ValidateUserStatus.AccountStatusAwaitingEmail); case AccountStatus.LockedAwaitingEmailVerification: case AccountStatus.Locked: return(ValidateUserStatus.UserIsLockedOut); case AccountStatus.Valid: _Log.DebugFormat("User {0} successfully validated", userBasic.UserId); return(ValidateUserStatus.Valid); default: return(ValidateUserStatus.SqlError); } } } } else { switch (getPasswordResult.AccountStatus) { case AccountStatus.Pending: return(ValidateUserStatus.AccountStatusPending); case AccountStatus.Deleted: return(ValidateUserStatus.AccountStatusDeleted); case AccountStatus.Banned: return(ValidateUserStatus.AccountStatusBanned); case AccountStatus.LockedAwaitingEmailVerification: case AccountStatus.Locked: return(ValidateUserStatus.UserIsLockedOut); default: return(ValidateUserStatus.SqlError); } } } }
public List <UserBasic> GetUsersBasic(int?iUserType) { return(UserBasic.GetUsersBasic(iUserType)); }
static void Main(string[] args) { var search = new I200.ElasticSearch.ElasticSearch("http://192.168.20.100:9200"); var usebasic = new UserBasic(); usebasic.account_id = 397; usebasic.user_initials = "mq"; usebasic.user_name = "马强"; usebasic.user_phone = "18509915185"; usebasic.user_pinyin = "maqiang"; usebasic.user_id = 99999; usebasic.user_cardno = "99999"; var usebasic2 = new UserBasic(); usebasic2.account_id = 119; usebasic2.user_initials = "my"; usebasic2.user_name = "马云"; usebasic2.user_phone = "18509915988"; usebasic2.user_pinyin = "mayun"; usebasic2.user_id = 8888; usebasic2.user_cardno = "8888"; var userList = new List <UserBasic>(); userList.Add(usebasic); userList.Add(usebasic2); //var oResult = search.BlukDocumentPut(397, 2, userList); //search.DocumentPut(397, "user_basic", "9999999", usebasic); //Search //Console.WriteLine("输入搜索词:"); //var key = ""; //do //{ // key = Console.ReadLine(); // var oResult = search.Search<UserBasic>(50, key, 397, 397); // var oItem = oResult.FirstOrDefault(); // if (oItem == null) // { // Console.WriteLine("无结果"); // } // else // { // foreach (var item in oResult.ToList()) // { // Console.WriteLine("{0}-{1}-{2}-{3}", item.user_id, item.user_name, item.user_phone, item.account_id); // } // } //} while (key != "exit"); //Delete Document //search.BlukDocumentDelete(119); //Delete Bluk List <string> ids = new List <string>(); ids.Add("7346320"); ids.Add("7304970"); search.BlukDocumentDelete(ids); Console.ReadLine(); }