public static async Task RunAsync([QueueTrigger("processchanges", Connection = "AzureWebJobsStorage")] WebhookNotification notificationModel, ILogger log) { log.LogInformation($"ProcesResourceChange queue trigger function process Site:{notificationModel.SiteUrl} Resource{notificationModel.Resource} "); string tenant = System.Environment.GetEnvironmentVariable("Tenant", EnvironmentVariableTarget.Process); string siteUrl = $"https://{tenant}.sharepoint.com{notificationModel.SiteUrl}"; log.LogInformation("Getting Azure SharePoint Token"); LoginEntity loginDetails = await LoginUtil.CertificateLoginDetails(); OfficeDevPnP.Core.AuthenticationManager authManager = new OfficeDevPnP.Core.AuthenticationManager(); log.LogInformation("Connecting to SharePoint"); using (ClientContext clientContext = authManager.GetAzureADAppOnlyAuthenticatedContext(siteUrl, loginDetails.ClientId, loginDetails.Tenant, loginDetails.Certificate)) { log.LogInformation("Getting SharePoint List"); Guid listId = new Guid(notificationModel.Resource); List list = clientContext.Web.Lists.GetById(listId); // grab the changes to the provided list using the GetChanges method // on the list. Only request Item changes as that's what's supported via // the list web hooks ChangeQuery changeQuery = new ChangeQuery(false, false) { Item = true, Add = true, DeleteObject = false, Update = true, FetchLimit = 1000 }; ChangeToken lastChangeToken = null; if (null == notificationModel.ClientState) { throw new ApplicationException("Webhook doesn't contain a Client State"); } Guid id = new Guid(notificationModel.ClientState); log.LogInformation("Checking Database for Change Token"); AzureTableSPWebHook listWebHookRow = await AzureTable.GetListWebHookByID(id, listId); if (!string.IsNullOrEmpty(listWebHookRow.LastChangeToken)) { log.LogInformation("Change Token found"); lastChangeToken = new ChangeToken { StringValue = listWebHookRow.LastChangeToken }; } //Start pulling down the changes bool allChangesRead = false; do { if (lastChangeToken == null) { log.LogInformation("Change Token not found grabbing the last 5 days of changes"); //If none found, grab only the last 5 day changes. lastChangeToken = new ChangeToken { StringValue = string.Format("1;3;{0};{1};-1", notificationModel.Resource, DateTime.Now.AddDays(-5).ToUniversalTime().Ticks.ToString()) }; } //Assing the change token to the query..this determins from what point in time we'll receive changes changeQuery.ChangeTokenStart = lastChangeToken; ChangeCollection changes = list.GetChanges(changeQuery); clientContext.Load(list); clientContext.Load(changes); await clientContext.ExecuteQueryAsync(); if (changes.Count > 0) { log.LogInformation($"Found {changes.Count} changes"); foreach (Change change in changes) { lastChangeToken = change.ChangeToken; if (change is ChangeItem item) { log.LogInformation($"Change {change.ChangeType} on Item:{item.ItemId} on List:{list.Title} Site:{notificationModel.SiteUrl}"); } } if (changes.Count < changeQuery.FetchLimit) { allChangesRead = true; } } else { allChangesRead = true; } } while (allChangesRead == false); if (!listWebHookRow.LastChangeToken.Equals(lastChangeToken.StringValue, StringComparison.InvariantCultureIgnoreCase)) { listWebHookRow.LastChangeToken = lastChangeToken.StringValue; log.LogInformation("Updating change token"); await AzureTable.InsertOrReplaceListWebHook(listWebHookRow); } if (notificationModel.ExpirationDateTime.AddDays(-30) < DateTime.Now) { bool updateResult = list.UpdateWebhookSubscription(new Guid(notificationModel.SubscriptionId), DateTime.Now.AddMonths(2)); if (!updateResult) { log.LogError($"The expiration date of web hook {notificationModel.SubscriptionId} with endpoint 'https://{Environment.GetEnvironmentVariable("WEBSITE_HOSTNAME")}/SharePointWebHook' could not be updated"); } else { log.LogInformation($"The expiration date of web hook {notificationModel.SubscriptionId} with endpoint 'https://{Environment.GetEnvironmentVariable("WEBSITE_HOSTNAME")}/SharePointWebHook' successfully updated until {DateTime.Now.AddMonths(2).ToLongDateString()} "); } } } }
public (AuthEntity, bool) Login(LoginEntity user) { return(_login.LoginAccount(user)); }
public static MemberEntity GetLogin(LoginEntity member) { return(new LoginProvider().SelectLogin(member)); }
public bool LoginCheck(LoginEntity eLog) { return(login.LoginValidation(eLog)); }
public Task <ValidState> ValidateLoginAsync(LoginEntity login, ValidState state) { throw new NotImplementedException(); }
public virtual void Login(LoginEntity model) { InternetExplorer browser = null; if (IsOpened(model.URL, out browser)) { #region 网页已经打开,绑定数据 BindData(browser, model); #endregion #region 提交 HTMLDocument doc = (HTMLDocument)browser.Document; if (model.SUBMITID != null && model.SUBMITID != "") { IHTMLElement login = doc.getElementById(model.SUBMITID); if (login != null) { login.click(); } } else if (model.SUBMITCLASS != null && model.SUBMITCLASS != "") { bool clicked = false; IHTMLElementCollection login2 = doc.getElementsByTagName("INPUT"); IHTMLElementCollection login1 = doc.getElementsByTagName("A"); foreach (IHTMLElement l in login2) { if (l.className == model.SUBMITCLASS) { l.click(); clicked = true; break; } } if (!clicked) { foreach (IHTMLElement l in login1) { if (l.className == model.SUBMITCLASS) { l.click(); clicked = true; break; } } } } #endregion } else { #region 网页没有打开,尝试打开 OpenUrl(model.URL); #endregion #region 如果已经打开,执行登录,如果没打开,则认为已经登录过 if (IsOpened(model.URL, out browser)) { Login(model); } #endregion } return; }
public ActionResult Index() { LoginEntity model = new LoginEntity(); return(View(model)); }
public ActionResult InsertLogin(LoginEntity loginEntity) { using (IDbContextTransaction trans = _context.Database.BeginTransaction()) { try { //if (Utility.CheckLoginExists(loginEntity)) //{ // HttpError error = new HttpError("Phone number is exists!"); // return Request.CreateErrorResponse(HttpStatusCode.Created, error); //} //M_LOGIN loginAdd = new M_LOGIN(); //loginAdd.PHONE_NUMBER = loginEntity.PhoneNumber; //string password = Utility.Encrypt(loginEntity.Password); //loginAdd.PASSWORD = password; //db.M_LOGIN.InsertOnSubmit(loginAdd); //db.SubmitChanges(); //var query = from d in db.M_LOGIN // where d.PHONE_NUMBER == loginEntity.PhoneNumber // select d; //if (query.Any()) //{ // M_USER user = new M_USER(); // user.USER_ID = query.FirstOrDefault().USER_ID; // user.NAME = loginEntity.UserName; // user.SEX = loginEntity.Sex; // user.INTRODUCE = string.Empty; // user.MODE_DEFAULT = loginEntity.ModeDefault; // user.REG_DATETIME = Utility.GetSysDateTime(); // user.MODE_USER = loginEntity.ModeDefault; // db.M_USER.InsertOnSubmit(user); // M_WORKER_INFO worker = new M_WORKER_INFO(); // worker.USER_ID = query.FirstOrDefault().USER_ID; // worker.SCORE = 0; // worker.RECEIVE_CNT = 0; // worker.CANCEL_CNT = 0; // worker.STATUS = (int)Status.Offline; // worker.REG_DATETIME = Utility.GetSysDateTime(); // db.M_WORKER_INFO.InsertOnSubmit(worker); // M_HIRER_INFO hirer = new M_HIRER_INFO(); // hirer.USER_ID = query.FirstOrDefault().USER_ID; // hirer.SCORE = 0; // hirer.POST_CNT = 0; // hirer.CANCEL_CNT = 0; // hirer.STATUS = (int)Status.Offline; // hirer.REG_DATETIME = Utility.GetSysDateTime(); // db.M_HIRER_INFO.InsertOnSubmit(hirer); //} //db.SubmitChanges(); // Commit transaction. trans.Commit(); HttpError errorHttp = new HttpError("Insert is success!"); return(Ok(new Result { Status = 200, Message = errorHttp.Message, Data = true })); } catch { // Rollback transaction. trans.Rollback(); HttpError error = new HttpError("Error system!"); return(Ok(new Result { Status = 404, Message = error.Message, Data = null })); } } }
public ActionResult SignIn([FromBody] LoginEntity loginEntity) { IDbContextTransaction tran = _context.Database.BeginTransaction(); M_USER user = null; AuthorEntity author = new AuthorEntity(); author.phoneNumber = loginEntity.phoneNumber; author.token = loginEntity.token; if (!Utility.ValidatiTokenId(author)) { System.Web.Http.HttpError error = new System.Web.Http.HttpError("Error validati token id!"); return(Ok(new Result { Status = 404, Message = error.Message, Data = null })); } try { if (Utility.CheckPhoneExists(_context, loginEntity.phoneNumber)) { var query = from d in _context.M_USERS where d.PHONE_NUMBER == loginEntity.phoneNumber && d.DELETE_FLG == 0 select d; user = query.Single(); if (!string.IsNullOrEmpty(loginEntity.languageType)) { user.LANGUAGE_TYPE = loginEntity.languageType; } else { user.LANGUAGE_TYPE = Constant.LANGUAGE_VN; } user.SIGNIN_LAST = Utility.GetSysDateTime(); } else { user = new M_USER(); user.NAME = string.Empty; user.PHONE_NUMBER = loginEntity.phoneNumber; user.MODE_DEFAULT = (int)Mode.Partner; user.REG_DATETIME = Utility.GetSysDateTime(); user.MODE_USER = (int)Mode.Partner; user.SIGNIN_LAST = Utility.GetSysDateTime(); user.BLOCK_FLG = (int)BlockFlag.NotBlock; user.DELETE_FLG = (int)DeleteFlag.Using; if (!string.IsNullOrEmpty(loginEntity.languageType)) { user.LANGUAGE_TYPE = loginEntity.languageType; } else { user.LANGUAGE_TYPE = Constant.LANGUAGE_VN; } _context.M_USERS.Add(user); _context.SaveChanges(); var query = from d in _context.M_USERS where d.PHONE_NUMBER == loginEntity.phoneNumber && d.DELETE_FLG == 0 select d; M_PARTNER_INFO worker = new M_PARTNER_INFO(); worker.USER_ID = user.USER_ID; worker.SCORE = 0; worker.STATUS = (int)Status.Offline; worker.REG_DATETIME = Utility.GetSysDateTime(); _context.M_PARTNER_INFOS.Add(worker); _context.SaveChanges(); M_HIRER_INFO hirer = new M_HIRER_INFO(); hirer.USER_ID = user.USER_ID; hirer.SCORE = 0; hirer.STATUS = (int)Status.Offline; hirer.REG_DATETIME = Utility.GetSysDateTime(); _context.M_HIRER_INFOS.Add(hirer); _context.SaveChanges(); } _context.SaveChanges(); // Commit transaction. tran.Commit(); var queryUser = from d in _context.M_USERS where d.PHONE_NUMBER == loginEntity.phoneNumber && d.DELETE_FLG == 0 select d; user = queryUser.Single(); string token = Utility.GenerateToken(user, Utility.GetSysDateTime()); AuthRepository auth = new AuthRepository(); auth.UpdateToken(_context, user.USER_ID, token); if (loginEntity.modeUser == (int)Mode.Partner) { PartnerEntity partnerEntity = Utility.GetPartnerInfo(_context, user.USER_ID); partnerEntity.token = token; return(Ok(new Result { Status = 200, Message = string.Empty, Data = partnerEntity })); } else { UserEntity entity = new UserEntity(); entity.userId = user.USER_ID; entity.phoneNumber = user.PHONE_NUMBER; entity.modeDefault = user.MODE_DEFAULT; entity.modeUser = user.MODE_USER; entity.name = user.NAME; ImageInfoEntity avatar = new ImageInfoEntity(); avatar.path = user.AVATAR; entity.avatar = avatar; entity.token = token; M_HIRER_INFO hirer = _context.M_HIRER_INFOS.FirstOrDefault(x => x.USER_ID == entity.userId); entity.userId = hirer.USER_ID; entity.score = hirer.SCORE; entity.likeNum = hirer.LIKE_NUM; return(Ok(new Result { Status = 200, Message = string.Empty, Data = entity })); } } catch (Exception ex) { // Rollback transaction. tran.Rollback(); return(Ok(new Result { Status = 400, Message = ex.Data.ToString(), Data = null })); } }
public ReturnCertEntity PostLoginData(LoginEntity loginData) { var result = BCryptService.Verify(loginData, _appSettings); return((result.err == true) ? new ReturnCertEntity() : result.data); }
public ActionResult ForgotPassword(User user) { try { if (ModelState.IsValid) { LoginEntity userExist = new LoginEntity(); bool IsExist = userExist.EmailExistOrNot(user.EmailID); if (IsExist == true) { //password Generator string numbers = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz!@#$%^&*()-="; Random objrandom = new Random(); string passwordString = ""; string strrandom = string.Empty; for (int i = 0; i < 15; i++) { int temp = objrandom.Next(0, numbers.Length); passwordString = numbers.ToCharArray()[temp].ToString(); strrandom += passwordString; } //update password in database var PasswordOfUser = db.Users.Where(x => x.EmailID.Equals(user.EmailID)).FirstOrDefault(); PasswordOfUser.Password = strrandom; db.SaveChanges(); // Email sending var sender = new MailAddress(ConstantStrings.supportEmail, ConstantStrings.supportName); var receiver = new MailAddress(user.EmailID, user.FirstName); var password = ConstantStrings.supportPassword; var body = string.Empty; var subject = "New Temporary Password has been created for you"; using (StreamReader reader = new StreamReader(Server.MapPath("~/EmailTemplates/ForgotPasswordMail.html"))) { body = reader.ReadToEnd(); } body = body.Replace("{newPassword}", strrandom); var smtp = new SmtpClient { Host = System.Configuration.ConfigurationManager.AppSettings["Host"].ToString(), Port = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["Port"]), EnableSsl = Convert.ToBoolean(System.Configuration.ConfigurationManager.AppSettings["EnableSsl"]), DeliveryMethod = SmtpDeliveryMethod.Network, UseDefaultCredentials = Convert.ToBoolean(System.Configuration.ConfigurationManager.AppSettings["UseDefaultCredentials"]), Credentials = new NetworkCredential(sender.Address, password) }; using (var messege = new MailMessage(sender, receiver) { Body = body, Subject = subject, IsBodyHtml = true }) { smtp.Send(messege); } ModelState.AddModelError("EmailID", "Please Check your Email ID for Updated Password"); return(View(user)); } else { ModelState.AddModelError("EmailID", "Please Enter Valid Email ID"); return(View(user)); } } } catch (Exception) { throw; } return(RedirectToAction("Login", "Account")); }
public ActionResult Signup(RegisterUser model) { // below code is for email sending try { if (ModelState.IsValid) { LoginEntity userExist = new LoginEntity(); bool IsExist = userExist.CheckIfUserExistOrNot(model.Email); if (IsExist == false) { var sender = new MailAddress(ConstantStrings.supportEmail, ConstantStrings.supportName); var receiver = new MailAddress(model.Email, model.FirstName); var password = ConstantStrings.supportPassword; var body = string.Empty; var subject = "Note Marketplace - Email Verification"; string URL = ConfigurationManager.AppSettings["Localhost"] + "Account/VefiryEmail?Email=" + model.Email + ""; using (StreamReader reader = new StreamReader(Server.MapPath("~/EmailTemplates/emailVerification.html"))) { body = reader.ReadToEnd(); } body = body.Replace("{UserName}", model.FirstName); body = body.Replace("{confirmUrl}", URL); var smtp = new SmtpClient { Host = ConfigurationManager.AppSettings["Host"], Port = Convert.ToInt32(ConfigurationManager.AppSettings["Port"]), EnableSsl = Convert.ToBoolean(ConfigurationManager.AppSettings["EnableSsl"]), DeliveryMethod = SmtpDeliveryMethod.Network, UseDefaultCredentials = Convert.ToBoolean(ConfigurationManager.AppSettings["UseDefaultCredentials"]), Credentials = new NetworkCredential(sender.Address, password) }; using (var messege = new MailMessage(sender, receiver) { Body = body, Subject = subject, IsBodyHtml = true }) { smtp.Send(messege); } var EmailExist = db.Users.Where(x => x.EmailID.Equals(model.Email) && x.IsActive == true).FirstOrDefault(); if (EmailExist == null) { var user = new User { FirstName = model.FirstName, LastName = model.LastName, EmailID = model.Email, Password = model.Password, RoleID = Convert.ToInt32(Enums.UserRoleId.Member), CreatedDate = System.DateTime.Now, ModifiedDate = System.DateTime.Now, IsActive = true }; //user.CreatedBy = user.ID; //user.ModifiedBy = user.ID; db.Users.Add(user); db.SaveChanges(); } } else { ModelState.AddModelError("Email", "Email is Already Exist try with another Email ID"); return(View(model)); } return(RedirectToAction("Login", "Account")); } } catch (Exception) { throw; } // If we got this far, something failed, redisplay form // return View(model); return(View()); }
/// <summary> /// 更新参数值 /// </summary> /// <param name="communityID">社区标识</param> /// <param name="paramID">参数标识</param> /// <param name="paramValue">参数值(整型)</param> /// <param name="sysLogID">系统登录标识</param> /// <returns>IRAP系统通用错误对象,如果其中的ErrCode:0-执行成功;非0执行失败</returns> public IRAPError Modify( int communityID, byte paramID, int paramValue, long sysLogID) { IRAPError rlt = new IRAPError(); #region 根据系统登录标识获取登录信息 LoginEntity loginInfo = null; try { IRAPLog loginSet = new IRAPLog(); loginInfo = loginSet.GetLogin(communityID, sysLogID); if (loginInfo == null) { loginInfo = new LoginEntity() { UserCode = "Unknown", LanguageID = 30, }; } } catch (Exception error) { if (error.InnerException.InnerException != null) { rlt.ErrText = $"获取登录信息发生异常:" + $"{error.InnerException.InnerException.Message}"; } else { rlt.ErrText = $"获取登录信息发生异常:{error.Message}"; } rlt.ErrCode = 9999; return(rlt); } #endregion List <IRAPParameterDTO> iParams = GetByParamID(communityID, new int[] { paramID }); if (iParams.Count <= 0) { rlt.ErrCode = 9999; rlt.ErrText = $"[{communityID}]社区中未找到ParameterID=[{paramID}]的参数"; return(rlt); } try { irapParams.Update( new IRAPParameterEntity() { PartitioningKey = iParams[0].PartitioningKey, ParameterID = iParams[0].ParameterID, ParameterNameID = iParams[0].ParameterNameID, ParameterValue = paramValue, ParameterValueStr = iParams[0].ParameterValueStr, UpdatedBy = loginInfo.UserCode, TimeUpdated = DateTime.Now, }); irapParams.SaveChanges(); rlt.ErrCode = 0; rlt.ErrText = "更新参数值(整型)成功"; } catch (Exception error) { rlt.ErrCode = 9999; if (error.InnerException.InnerException != null) { rlt.ErrText = $"更新参数值发生异常:" + $"{error.InnerException.InnerException.Message}"; } else { rlt.ErrText = $"更新参数值发生异常:{error.Message}"; } } return(rlt); }
/// <summary> /// 新增参数 /// </summary> /// <remarks>本方法需要在序列服务器中配置NextParameterID序列</remarks> /// <param name="communityID">社区标识</param> /// <param name="paramName">参数名称</param> /// <param name="paramValue">参数值(整型)</param> /// <param name="paramStrValue">参数值(字符串)</param> /// <param name="sysLogID">系统登录标识</param> /// <param name="paramID">输出参数,新增参数的参数标识</param> /// <returns>IRAP系统通用错误对象,如果其中的ErrCode:0-执行成功;非0执行失败</returns> public IRAPError Add( int communityID, string paramName, int paramValue, string paramStrValue, long sysLogID, out int paramID) { IRAPError rlt = new IRAPError(); paramID = 0; LoginEntity loginInfo = null; try { IRAPLog loginSet = new IRAPLog(); loginInfo = loginSet.GetLogin(communityID, sysLogID); if (loginInfo == null) { loginInfo = new LoginEntity() { UserCode = "Unknown", LanguageID = 30, }; } } catch (Exception error) { if (error.InnerException.InnerException != null) { rlt.ErrText = $"获取登录信息发生异常:" + $"{error.InnerException.InnerException.Message}"; } else { rlt.ErrText = $"获取登录信息发生异常:{error.Message}"; } rlt.ErrCode = 9999; return(rlt); } IIRAPNamespaceSet namespaceSet = IRAPNamespaceSetFactory.CreatInstance(Enums.NamespaceType.Sys); rlt = namespaceSet.Add( communityID, paramName, loginInfo.LanguageID, out int nameID); if (rlt.ErrCode != 0) { return(rlt); } rlt = RequestParameterID(out paramID); if (rlt.ErrCode != 0) { return(rlt); } IRAPParameterEntity entity = new IRAPParameterEntity() { ParameterID = (byte)paramID, ParameterNameID = nameID, PartitioningKey = communityID * 10000, ParameterValue = paramValue, ParameterValueStr = paramStrValue, UpdatedBy = loginInfo.UserCode, TimeUpdated = DateTime.Now, }; try { irapParams.Insert(entity); irapParams.SaveChanges(); rlt.ErrCode = 0; rlt.ErrText = "参数新增成功"; } catch (Exception error) { rlt.ErrCode = 9999; if (error.InnerException.InnerException != null) { rlt.ErrText = $"新增参数发生异常:" + $"{error.InnerException.InnerException.Message}"; } else { rlt.ErrText = $"新增参数发生异常:{error.Message}"; } } return(rlt); }
private object SuccessObject(DateTime createDate, DateTime expirationDate, string token, LoginEntity loginEntity) { return(new { authenticated = true, create = createDate.ToString("yyyy-MM-dd HH:mm:ss"), expiration = expirationDate.ToString("yyyy-MM-dd HH:mm:ss"), accessToken = token, logador = loginEntity.Email, message = $"{loginEntity.Name} Logado com sucesso" }); }
public ActionResult Index(LoginEntity user) { try { if (ModelState.IsValid) { if (user.Password == "" || user.Password == null) { TempData["Message"] = "Please Check Password "; TempData["MessageClass"] = "danger"; var c = new HttpCookie("Login"); c.Expires = DateTime.Now.AddDays(-1); Response.Cookies.Add(c); return(RedirectToAction("Index")); } if (user.UserName == "" || user.UserName == null) { TempData["Message"] = "Please Check UserName "; TempData["MessageClass"] = "danger"; var c = new HttpCookie("Login"); c.Expires = DateTime.Now.AddDays(-1); Response.Cookies.Add(c); return(RedirectToAction("Index")); } user.Password = Helper.Helper.Encrypt(user.Password); // var records = Service.Authenticate(user); var records = obj.Authenticateuser(user); if (records.Id != 0) { Session.Add("LoggedUser", records); return(RedirectToAction("Index", "Dashboard")); } else { TempData["Message"] = "Login Failed..Please Check UserName and Password "; TempData["MessageClass"] = "danger"; return(RedirectToAction("Index")); } } else { TempData["Message"] = "Login Failed..Please Check UserName and Password "; TempData["MessageClass"] = "danger"; return(RedirectToAction("Index")); } return(View()); } catch (Exception ex) { //ExceptionLogging.SendErrorToText(ex); return(RedirectToAction("Index", "Login")); } }
public Responser Login([FromBody] LoginEntity loginEntity_) { try { List <MEmployees> employees = PayRollDB.Employees_Tab.ToList().MapTo <Employees_Tab, MEmployees>(); employees = employees.Where(item => item.Email == loginEntity_.UserName && item.Password == loginEntity_.Password && item.Active == true).ToList(); if (employees.Count > 0) { //Get logged user MUser userLogged = new MUser(); MEmployees employee = employees.FirstOrDefault(); userLogged.UserID = employee.EmployeeID; userLogged.Name = string.Format("{0} {1}", employee.Name, employee.LastNames); userLogged.UserName = employee.Email; userLogged.Password = employee.Password; userLogged.RoleName = employee.RoleName; responser_.Status = 0; responser_.StatusMessage = "Login Successfully"; responser_.Data = userLogged; //Generate a Token Guid tokenLogged = Guid.NewGuid(); userLogged.Token = tokenLogged.ToString(); Employees_Tab empTab = PayRollDB.Employees_Tab.Where(item => item.EmployeeID == userLogged.UserID).ToList().FirstOrDefault(); if (empTab != null) { //Record Token in OAuth's Table TokenAuth tokenRecords = new TokenAuth(); tokenRecords.Token = tokenLogged; tokenRecords.CreationDate = DateTime.Now; tokenRecords.TokenStatusID = PayRollDB.TokenStatus.Where(item => item.Name == "Active").ToList().FirstOrDefault().TokenStatusID; PayRollDB.TokenAuth.Add(tokenRecords); PayRollDB.SaveChanges(); //Set token to user empTab.Token = tokenLogged; PayRollDB.SaveChanges(); } } else { responser_.Status = -2; responser_.StatusMessage = "Login failed: User or password is incorrect."; responser_.Data = null; } return(responser_); } catch (Exception e) { responser_.Status = -1; responser_.StatusMessage = e.Message.ToString(); responser_.Data = null; return(responser_); } }
public ActionResult CheckLogin(LoginEntity loginEntity) { //PartTimeDataClassesDataContext db = new PartTimeDataClassesDataContext(); //if (!Utility.CheckLoginExists(loginEntity)) //{ // return NotFound(); //} //M_LOGIN login = db.M_LOGIN.FirstOrDefault(x => x.PHONE_NUMBER == loginEntity.PhoneNumber); //string password = Utility.Encrypt(loginEntity.Password); //if (login.PASSWORD.Equals(password)) //{ // var query = from d in db.M_USER // where d.USER_ID == login.USER_ID // select d; // if (query.Any()) // { // M_USER user = query.First(); // UserEntity entity = new UserEntity(); // entity.UserId = user.USER_ID; // entity.Name = user.NAME; // entity.Sex = user.SEX; // entity.BirthDay = user.BIRTHDAY; // entity.Avatar = user.AVATAR; // entity.Introduce = user.INTRODUCE; // entity.ModeDefault = user.MODE_DEFAULT; // entity.AccountType = user.ACCOUNT_TYPE; // entity.MemberType = user.MEMBER_TYPE; // entity.ModeUser = user.MODE_USER; // var query3 = from d in db.M_WORKER // where d.USER_ID == user.USER_ID // select d; // List<WorkerEntity> workerEntityList = new List<WorkerEntity>(); // if (query3.Any()) // { // foreach (M_WORKER worker in query3.ToList()) // { // WorkerEntity wkEntity = new WorkerEntity(); // wkEntity.UserId = worker.USER_ID; // wkEntity.CatalogCd = worker.CATALOG_CD; // var query1 = from d in db.M_CATALOG // where d.CD == worker.CATALOG_CD // select d; // if (query1.Any()) // { // wkEntity.CatalogName = query1.First().NAME; // } // wkEntity.Cost = worker.COST; // wkEntity.UnitCd = worker.UNIT_CD; // var query2 = from d in db.M_UNIT // where d.CD == worker.UNIT_CD // select d; // if (query2.Any()) // { // wkEntity.UnitName = query2.First().NAME; // } // workerEntityList.Add(wkEntity); // } // } // entity.WorkerEntityList = workerEntityList; // return Ok(new JavaScriptSerializer().Serialize(entity)); // } //} return(Ok(new Result { Status = 404, Message = "Not found.", Data = null })); }
public virtual IObservable <HttpResponseMessage> tryLogin(LoginEntity creditentials) { var arguments = new object[] { creditentials }; return((IObservable <HttpResponseMessage>)methodImpls["tryLogin"](Client, arguments)); }
public Task <ChangeResult> SaveLoginAsync(LoginEntity login) { throw new NotImplementedException(); }
/// <summary> /// 账号密码 /// </summary> /// <param name="zhanghao"></param> /// <param name="mima"></param> public static void GetQianDao(string zhanghao, string mima) { LoginEntity loginModel = GetLoginModel(zhanghao, mima); if (loginModel == null) { Console.WriteLine(zhanghao + " 登录接口授权异常" + " " + DateTime.Now); return; } if (loginModel.result != "000000") { Console.WriteLine(zhanghao + " 登录接口授权异常" + " " + DateTime.Now + " " + loginModel.resultdesc); return; } #region 签到 CaozuoClass post = new CaozuoClass(); IDictionary <string, string> parameters = new Dictionary <string, string>(); parameters.Add("service_name", "mbm_signdetail_req"); parameters.Add("godId", loginModel.god.id.ToString()); parameters.Add("tokenId", loginModel.tokenId); var json = post.getPostHttpResult("https://weixin.wanjiajinfu.com/webAPI/api", parameters); var model = new JavaScriptSerializer().Deserialize <ResultEntity>(json); var xiangqingModel = GetXiangQing(loginModel.tokenId, Convert.ToInt32(loginModel.god.id)); if (model == null) { Console.WriteLine(zhanghao + " 签到接口异常,无返回数据"); return; } else if (model.result == "000000") { Console.WriteLine(zhanghao + " 签到成功:" + DateTime.Now + " " + model.msg + " " + "此账号一共有" + (xiangqingModel == null ? 0 : xiangqingModel.userjfAmount) + "积分"); } else { Console.WriteLine(zhanghao + " 签到 " + DateTime.Now + " " + model.msg + " " + model.resultdesc); } #endregion #region 转盘 string pass = CaozuoClass.GetMD5(mima.Trim()); string aa = "huaxiawanjia_" + CaozuoClass.ConvertDateTimeToInt(DateTime.Now) + "_e6416ce85cf0e"; string url = "https://weixin.wanjiajinfu.com/webAPI/uc/api"; Encoding encoding = Encoding.GetEncoding("utf-8"); IDictionary <string, string> parameters1 = new Dictionary <string, string>(); parameters1.Add("service_name", "lottery.roll"); parameters1.Add("godId", "703958"); parameters1.Add("tokenId", loginModel.tokenId); parameters1.Add("aId", "1"); string json1 = HttpWebResponseUtility.CreatePostHttpResponse(url, parameters1, null, null, encoding, null); var chouJiangEntity = new JavaScriptSerializer().Deserialize <ChouJiangEntity>(json1); if (chouJiangEntity == null) { Console.WriteLine(zhanghao + " 抽奖接口异常,无返回数据"); return; } else if (chouJiangEntity.result == "000000") { Console.WriteLine(zhanghao + " 抽奖成功:" + DateTime.Now + " " + chouJiangEntity.data.name + " " + chouJiangEntity.data.value + " " + chouJiangEntity.resultdesc); } else { Console.WriteLine(zhanghao + " 抽奖 " + DateTime.Now + " " + chouJiangEntity.resultdesc); } #endregion }
public MResult <int> LoginMember(string sid, string token, string guid, string user_id, string uid, LoginEntity loginEntity) { var result = new MResult <int>(); try { result = MemberBLL.LoginMember(guid, (int)SystemType, loginEntity.uid, loginEntity.pwd); } catch (Exception ex) { result.status = MResultStatus.ExceptionError; result.msg = "处理数据出错!"; } return(result); }
public User LoginUser(LoginEntity loginentity) { LoginDAC loginDAC = new LoginDAC(); return(loginDAC.LoginMethod(loginentity)); }
public async Task <LoginEntity> FindUser(string userName, string password) { LoginEntity loginBO = NV7200_UserBusiness.Instance().Login(userName, password); return(loginBO); }
public UserEntity ValidateLogin(LoginEntity loginentity) { LoginDAC loginDAC = new LoginDAC(); return(loginDAC.ValidateLogin(loginentity)); }
public bool NewSignUp(LoginEntity eLog) { return(login.SignUp(eLog)); }
public ResultResponse <LoginAutoridadResponse> LogInAutoridad(PapeletaVirtualDBContext _context, IConfiguration _config, LoginEntity model) { try { var userAutoridad = false; ResultResponse <LoginAutoridadResponse> response = new ResultResponse <LoginAutoridadResponse>(); userAutoridad = _context.Autoridad.Any(x => x.Username == model.Username && x.Password == model.Password); if (userAutoridad) { var autoridad = _context.Autoridad.FirstOrDefault(x => x.Username == model.Username && x.Password == model.Password); LoginTokenAutoridad(_config, autoridad, response); } else { userAutoridad = _context.Autoridad.Any(x => x.Email == model.Username && x.Password == model.Password); if (userAutoridad) { var autoridad = _context.Autoridad.FirstOrDefault(x => x.Email == model.Username && x.Password == model.Password); LoginTokenAutoridad(_config, autoridad, response); } if (!userAutoridad) { response.Data = null; response.Error = true; response.Message = "Usuario y/o password incorrecto"; } } return(response); } catch (Exception ex) { throw new Exception(ex.Message); } }
public ActionResult <LoginResponseModel> Login([FromBody] LoginEntity entity) { var model = new LoginResponseModel(); var loginSuccess = false; var userName = entity.UserName.Trim(); var password = entity.Password.Trim(); var exsitsUser = this.Repository.GetUserByName(entity.UserName); var exsitsUserByEmployee = this.Repository.GetUserByEmployeeNo(entity.UserName); Action loginByAd = () => { try { exsitsUser = LoginByLpad(userName, password); loginSuccess = true; } catch { loginSuccess = false; } }; if (exsitsUser == null && exsitsUserByEmployee == null) { loginByAd(); } else if (exsitsUser != null) { if (string.IsNullOrEmpty(exsitsUser.PasswordSalt) && string.IsNullOrEmpty(exsitsUser.Password)) { loginByAd(); } else if (string.IsNullOrEmpty(exsitsUser.PasswordSalt)) { loginSuccess = exsitsUser.Password == entity.Password; } else { var encryptPassword = SHA_Encrypt(entity.Password, exsitsUser.PasswordSalt); loginSuccess = exsitsUser.Password == encryptPassword; } } else { var encryptPassword = SHA_Encrypt(entity.Password, exsitsUserByEmployee.PasswordSalt); loginSuccess = exsitsUserByEmployee.Password == encryptPassword; } if (loginSuccess) { model.Success = true; if (exsitsUser != null) { HttpContext.SignIn(exsitsUser.Name, exsitsUser.EmployeeNo); model.User = exsitsUser; } else { HttpContext.SignIn(exsitsUserByEmployee.Name, exsitsUserByEmployee.EmployeeNo); model.User = exsitsUserByEmployee; } } else { model.Success = false; model.Message = "Username or password is invalid"; } // Response.Headers["token"] = "1233"; return(Ok(model)); }
/// <summary> /// 用户登录 /// </summary> /// <param name="clientID">渠道标识</param> /// <param name="plainPWD">密码(明文)</param> /// <param name="veriCode">验证码</param> /// <param name="stationID">站点标识,如果是BS系统调用传CommunityID</param> /// <param name="ipAddress">IP地址</param> /// <param name="agencyLeaf">机构标识</param> /// <param name="roleLeaf">角色标识</param> /// <returns>返回信息DTO类</returns> public BackLoginInfo Login(string clientID, string plainPWD, string veriCode, string stationID, string ipAddress, int agencyLeaf, int roleLeaf) { BackLoginInfo backRes = new BackLoginInfo { UserName = user.UserName, LanguageID = user.LanguageID, NickName = user.UserEnglishName, MPhoneNo = user.MPhoneNo, OPhoneNo = user.OPhoneNo, HPhoneNo = user.HPhoneNo }; try { //验证密码 IRAPError error = VerifyPWD(plainPWD); if (error.ErrCode != 0) { backRes.ErrCode = error.ErrCode; backRes.ErrText = error.ErrText; return(backRes); } //判断信息站点是否注册 if (!Regex.IsMatch(stationID, @"^\d+$")) { IRAPStation station = new IRAPStation(); StationEntity r = station.GetStation(stationID); if (r == null) { backRes.ErrCode = 9999; backRes.ErrText = $"站点{stationID}不存在!"; return(backRes); } backRes.HostName = r.HostName; } //短信验证码是否有效 //申请登录标识 long sysLogID = IRAPSequence.GetSysLogID(); //登录 Repository <LoginEntity> loginRep = _unitOfWork.Repository <LoginEntity>(); LoginEntity loginEntity = new LoginEntity(); loginEntity.PartitioningKey = PK; loginEntity.ClientID = clientID; loginEntity.SysLogID = (int)sysLogID; loginEntity.UserCode = _userCode; loginEntity.AgencyLeaf = agencyLeaf; loginEntity.RoleLeaf = roleLeaf; loginEntity.Access_Token = Guid.NewGuid().ToString(); loginEntity.StationID = stationID; loginEntity.MPhoneNo = user.MPhoneNo; loginEntity.Status = 1; loginEntity.LanguageID = user.LanguageID; loginEntity.IPAddress = ipAddress; loginEntity.LoginMode = 1; loginRep.Insert(loginEntity); _unitOfWork.Commit(); backRes.SysLogID = sysLogID; backRes.access_token = loginEntity.Access_Token; backRes.AgencyName = _unitOfWork.Repository <ETreeSysLeaf>().Table.FirstOrDefault(r => r.LeafID == agencyLeaf).NodeName; backRes.ErrCode = 0; backRes.ErrText = $"登录成功:{sysLogID}"; return(backRes); } catch (Exception err) { backRes.ErrCode = 9999; backRes.ErrText = $"登录遇到异常:{err.Message}"; return(backRes); } }
public LoginEntity Login(string userName, string password) { db = new TimeAttendanceEntities(); LoginEntity loginEntity = new LoginEntity(); try { var userLogin = (from a in db.User.AsNoTracking() where a.Name.Equals(userName) && a.DeleteFlg == 0 //join b in db.UserGroups.AsNoTracking() on a.UserId equals b.UserId into ab //from abv in ab.DefaultIfEmpty() select new { a.UserId, // a.UnitId, a.Name, a.FullName, a.BirthDay, // a.Agency, a.Email, a.Role, a.PhoneNumber, a.Password, a.PasswordHash, a.Status, a.Type, a.Description, a.ImageLink, a.CreateBy, a.CreateDate, a.UpdateBy, a.UpdateDate, a.IsAdmin, //abv.GroupId, }).FirstOrDefault(); if (userLogin != null) { if (userLogin.Status == Constants.Lock) { //Tài khoản bị khóa. Lên hệ quản trị để kích hoạt lại loginEntity.ResponseCode = -6; } else { var securityStamp = PasswordUtil.ComputeHash(password + userLogin.Password); if (userLogin.PasswordHash.Equals(securityStamp)) { UserEntity userEntity = new UserEntity() { UserName = userLogin.Name, UserId = userLogin.UserId, FullName = userLogin.FullName, Role = "1", //UnitId = userLogin.UnitId, //GroupId = userLogin.GroupId, ImageLink = userLogin.ImageLink, //Agency = userLogin.Agency, Type = userLogin.Type, IsAdmin = userLogin.IsAdmin.ToString(), securityKey = PasswordUtil.CreatePasswordHash(), }; userEntity.ListPermission = new List <string>(); userEntity.ListPermission = (from c in db.UserPermission.AsNoTracking() where c.UserId.Equals(userLogin.UserId) join d in db.Function.AsNoTracking() on c.FunctionId equals d.FunctionId select d.Code).ToList <string>(); userEntity.HomePage = (from r in db.Group.AsNoTracking() join a in db.UserGroup on r.GroupId equals a.GroupId where a.UserId.Equals(userEntity.UserId) select r.HomePage).FirstOrDefault(); loginEntity.UserInfor = userEntity; LogBusiness.SaveLogLogin(db, userEntity.UserId); } else { // Mật khẩu không đúng loginEntity.ResponseCode = -5; } } } else { // tài khoản không có trong hệ thống loginEntity.ResponseCode = -4; } } catch (Exception e) { Console.Write(e.ToString()); } return(loginEntity); }
/// <summary> /// Creates an account with given id and password. /// </summary> /// <param name="accountId">The account id.</param> /// <param name="password">The account password.</param> public void CreateAccount( EmailAddress accountId, SecureString password) { PasswordHash passwordHash = PasswordHash.Create(password); CloudTable loginTable = this.GetLoginTable(); CloudTable accountTable = this.GetAccountTable(); LoginEntity existingEntity = FindExistingLogin(loginTable, accountId); if (existingEntity != null) { if (existingEntity.Activated) { throw new InvalidOperationException("account already activated."); } AccountEntity existingAccount = FindExistingAccount(accountTable, accountId); if (existingAccount == null) { existingAccount = new AccountEntity(); existingAccount.PartitionKey = accountId.Domain; existingAccount.RowKey = accountId.LocalPart; } else if (existingAccount.CreatedTime + ActivationTimeout > DateTime.UtcNow) { throw new InvalidOperationException("Account creation cannot be retried yet."); } existingEntity.Salt = passwordHash.Salt; existingEntity.SaltedHash = passwordHash.Hash; TableOperation replaceOperation = TableOperation.InsertOrReplace(existingEntity); loginTable.Execute(replaceOperation); existingAccount.CreatedTime = DateTime.UtcNow; TableOperation insertAccountOperation = TableOperation.InsertOrReplace(existingAccount); accountTable.Execute(insertAccountOperation); } else { LoginEntity newEntity = new LoginEntity(); newEntity.PartitionKey = accountId.Domain; newEntity.RowKey = accountId.LocalPart; newEntity.Salt = passwordHash.Salt; newEntity.SaltedHash = passwordHash.Hash; TableOperation insertOperation = TableOperation.Insert(newEntity); loginTable.Execute(insertOperation); AccountEntity newAccount = new AccountEntity(); newAccount.PartitionKey = accountId.Domain; newAccount.RowKey = accountId.LocalPart; newAccount.CreatedTime = DateTime.UtcNow; TableOperation insertAccountOperation = TableOperation.InsertOrReplace(newAccount); accountTable.Execute(insertAccountOperation); } }