public ReceivedChannelModeEventArgs(ServerBase server, ChannelBase channel, UserBase user, string argument) { Server = server; Channel = channel; User = user; Argument = argument; }
public void Init(UserBase user) { myCam = GetComponent(typeof(Camera)) as Camera; xpBar.Value = user.userStats.GetXPPercentage; levelText.Text = user.userStats.level.ToString(); coinButton.AddInputDelegate(CoinButtonClickedDelegate); coinText.maxWidth = coinText.characterSize * 6; cashText.maxWidth = cashText.characterSize * 6; coinText.Text = user.userAssets.coins.ToString(); cashText.Text = user.userAssets.cash.ToString(); coinText.SetColor(Color.yellow); cashText.SetColor(Color.green); fatigueBar.Value = user.userStats.GetFatiguePercentage; hungerBar.Value = user.userStats.GetHungerPercentage; fatigueBar.AddInputDelegate(CoinButtonClickedDelegate); friendButton.AddInputDelegate(FriendButtonClickedDelegate); gameObject.name = this.GetType().ToString(); }
private void btnOK_Click(object sender, EventArgs e) { Cursor.Current = Cursors.WaitCursor; try { if (this.txtLoginName.Text.Trim() == string.Empty) { ClientHelper.ControlCheck(this, this.txtLoginName, "登录名不能为空", DevExpress.XtraEditors.DXErrorProvider.ErrorType.Warning); this.txtLoginName.Focus(); } else if (this.txtPassword.Text.Trim() == string.Empty) { ClientHelper.ControlCheck(this, this.txtPassword, "密码不能为空", DevExpress.XtraEditors.DXErrorProvider.ErrorType.Warning); this.txtPassword.Focus(); } else { string str = MainHelper.EncryptoPassword(this.txtPassword.Text); MainHelper.LoginName = this.txtLoginName.Text.Trim(); MainHelper.Password = str; this.m_UserBase = MainHelper.ValidateLogin(); base.DialogResult = System.Windows.Forms.DialogResult.OK; } } catch (Exception exception) { MainHelper.ShowException(exception); } }
/// <summary> /// If you get a list back with no errors then you can successfully do the excercise /// </summary> /// <param name="player"></param> /// <returns></returns> public List<ReasonForCantDoExcercise> CanDoExcercise(UserBase user) { ScreenLog.AddMessage(GetCoolDownSaveName); List<ReasonForCantDoExcercise> errorList = new List<ReasonForCantDoExcercise>(); if (user.userStats.level < requiredLevel) errorList.Add(ReasonForCantDoExcercise.InsufficientLevel); if (user.CurrentExcercise != null) errorList.Add(ReasonForCantDoExcercise.DoingOtherExcercise); /*if ((user.userStats.fatigue + fatigueyModifierVal) < 0) errorList.Add(ReasonForCantDo.InsufficientFatigue); if ((user.userStats.hunger + hungerModifierVal) > GameValues.hungerMax) errorList.Add(ReasonForCantDo.ToHungry);*/ if (PlayerPrefs.HasKey(GetCoolDownSaveName) == true) { string lastBeginCooldown = PlayerPrefs.GetString(GetCoolDownSaveName); //get our last saved cool down time DateTime lastCoolDownTime = DateTime.Parse(lastBeginCooldown); //parse it into a DateTime object TimeSpan timeSinceBeggningCoolDown = DateTime.Now.Subtract(lastCoolDownTime); //Find the length between the start time of the cool down and the current time if (timeSinceBeggningCoolDown.TotalSeconds < coolDownTimeInSeconds) // we are still cooling down and cant do this excercising errorList.Add(ReasonForCantDoExcercise.CoolingDown); else PlayerPrefs.DeleteKey(GetCoolDownSaveName); // we are done our cool down and can do this excercise again } return errorList; }
public static int GetXPForLevel(UserBase user) { if (user != null) { return user.userStats.level * 1010; //1010 is hard coded number xpmax / levelmax ish } else return 0; }
public override void OnInspectorGUI() { val = (UserBase)target; if (val == null) return; //call this before on inspector GUI so we know none of our functions called will throw nulls base.OnInspectorGUI(); if (GUI.changed == true) EditorUtility.SetDirty(val); }
public static int GetFatigueIncreaseValPerSecond(UserBase user) { /*float baseVal = player.Stats.Stamina - player.Stats.Hunger; //baseVal = baseVal / player.Stats.Level; baseVal = baseVal * 0.05f; baseVal = Mathf.Clamp(baseVal, 1, int.MaxValue); return Mathf.RoundToInt(baseVal);*/ return 1; //return player.Stats.Level; }
public static Checklist CreateChecklist(this DAL<MainDbContext> dal, UserBase user, IEnumerable<AttribValue> attributeValues) { var checkList = dal.Create<Checklist>(); checkList.AttrbuteValues = new List<AttribValue>(attributeValues); var checklistTypeCode = string.Empty; if (user is PromouterUser) checklistTypeCode = PromouterChecklistTypeCode; else if (user is EmployerUser) checklistTypeCode = CompanyChecklistTypeCode; checkList.ChecklistType = dal.DbContext.ChecklistTypes.FirstOrDefault(x => x.Code == checklistTypeCode); checkList.User = user; return checkList; }
public IEnumerator DoUseBuffAtCustomTime(UserBase user, DateTime customStartTime) { startTime = customStartTime; TimeSpan runningTime = TimeSpan.MinValue; timeInSecondsTillCompletion = timeoutInSeconds; while (runningTime.TotalSeconds < timeoutInSeconds) { runningTime = DateTime.Now.Subtract(startTime); timeInSecondsTillCompletion = timeoutInSeconds - (float)runningTime.TotalSeconds; yield return null; } DeleteBuffSaveData(user); timeInSecondsTillCompletion = 0; user.ActiveBuffs.Remove(this); }
public unsafe override void AddPrefix(UserBase user, char add) { if (user.Level >= Authorizations.Service) { return; } if (add == '$' || add == '!') { return; } if (IsSystem && user.Level >= Authorizations.NetworkOperator) { return; } if (Prefixes.ContainsKey(user.Mask.Account)) { char[] chars = Prefixes[user.Mask.Account].ToCharArray(); int max = chars.Length + 1; int len = 0; char* prefix = stackalloc char[max]; for (int i = 0; i < CoreProtocol.RANK_CHARS.Length && len < max; i++) { char c = CoreProtocol.RANK_CHARS[i]; if (add == c || chars.Contains(c)) { prefix[len++] = c; } } Prefixes[user.Mask.Account] = new string(prefix, 0, len); } else { Prefixes[user.Mask.Account] = add.ToString(); } Server.Commit(this); }
public DataTable User_DeleteById(UserBase userBase) { dtContainer = new DataTable(); try { MyParameter[] myParams = { new MyParameter("@ID", userBase.ID) }; Common.Set_Procedures("User_DeleteById"); Common.Set_ParameterLength(myParams.Length); Common.Set_Parameters(myParams); dtContainer = Common.Execute_Procedures_LoadData(); } catch (Exception ex) { ErrorReporting.DataLayerError(ex); } return(dtContainer); }
public DataTable State_LoadByCountryId(UserBase userBase) { dtContainer = new DataTable(); try { MyParameter[] myParams = { new MyParameter("@CountryId", userBase.Country) }; Common.Set_Procedures("USP_S_Master_tblState"); Common.Set_ParameterLength(myParams.Length); Common.Set_Parameters(myParams); dtContainer = Common.Execute_Procedures_LoadData(); } catch (Exception ex) { ErrorReporting.DataLayerError(ex); } return(dtContainer); }
private DetailUser GetDetailUser(int id) { UserBase user = DataBase.Users.Get(p => p.UserId == id && p.UserRole.Any(q => q.Role.OrganizationId == this.OrganizationId), includeProperties: "Contact,UserRole").SingleOrDefault(); RoleBase role = user.UserRole.First(p => p.Role.OrganizationId == this.OrganizationId).Role; DetailUser detailUser = new Security.Models.DetailUser(); detailUser.UserId = user.UserId; detailUser.LogonName = user.LogonName; detailUser.Email = user.Contact.Email; detailUser.LastNames = user.Contact.LastNames; detailUser.Names = user.Contact.Names; detailUser.RoleId = role.RoleId; detailUser.RoleName = role.Name; detailUser.Active = user.Active; return(detailUser); }
protected void Page_Load(object sender, EventArgs e) { mCurrentUser = (UserBase)Session["CurrentUser"]; if (mCurrentUser != null) { if (!mCurrentUser.IsNull) { lblName.Text = "Hello " + mCurrentUser.FirstName + " " + mCurrentUser.LastName; } else { lnkbtnlogout.Text = ""; } } else { lnkbtnlogout.Text = ""; } }
public PresetUserPermissionModel(IUnitOfWork uow, UserBase user) { this.user = user; this.uow = uow; originalPermissionList = UserPermissionRepository.GetUserAllPresetPermissions(uow, user.Id); ObservablePermissionsList = new GenericObservableList <PresetUserPermission>(originalPermissionList.ToList()); originalPermissionsSourceList = PermissionsSettings.PresetPermissions.Values.ToList(); //убираем типы уже загруженные в права foreach (var item in originalPermissionList.Where(x => !x.IsLostPermission)) { if (originalPermissionsSourceList.Contains(item.PermissionSource)) { originalPermissionsSourceList.Remove(item.PermissionSource); } } ObservablePermissionsSourceList = new GenericObservableList <PresetUserPermissionSource>(originalPermissionsSourceList); }
public override UserBase GetUser(string nickname) { string id = nickname.ToLower(); if (!UsersById.ContainsKey(id)) { return(null); } UserBase user = UsersById[id]; if (user.Level < Authorizations.Unregistered) { return(null); } else { return(user); } }
public bool LogInTest(string email, string password, int id, string[] roles = null) { bool isSuccessful = false; IUserAuthData response = new UserBase { Id = id , Name = "FakeUser" + id.ToString() , Roles = roles ?? new[] { "User", "Super", "Content Manager" } }; Claim tenant = new Claim("Tenant", "AAAA"); Claim fullName = new Claim("FullName", "net5hondahack Bootcamp"); //Login Supports multiple claims //and multiple roles a good an quick example to set up for 1 to many relationship _authenticationService.LogIn(response, new Claim[] { tenant, fullName }); return(isSuccessful); }
public static Checklist CreateChecklist(this DAL <MainDbContext> dal, UserBase user, IEnumerable <AttribValue> attributeValues) { var checkList = dal.Create <Checklist>(); checkList.AttrbuteValues = new List <AttribValue>(attributeValues); var checklistTypeCode = string.Empty; if (user is PromouterUser) { checklistTypeCode = PromouterChecklistTypeCode; } else if (user is EmployerUser) { checklistTypeCode = CompanyChecklistTypeCode; } checkList.ChecklistType = dal.DbContext.ChecklistTypes.FirstOrDefault(x => x.Code == checklistTypeCode); checkList.User = user; return(checkList); }
public bool GetSubscriptionExists(Post post, UserBase user) { if (user is User) { return(( from s in context.oxite_Subscriptions where s.PostID == post.ID && s.UserID == user.ID select s ).Any()); } Guid userID = context.oxite_Users.Where(u => u.Username == "Anonymous").FirstOrDefault().UserID; return(( from s in context.oxite_Subscriptions join sa in context.oxite_SubscriptionAnonymous on s.SubscriptionID equals sa.SubscriptionID where s.PostID == post.ID && s.UserID == userID && sa.Email == user.Email select s ).Any()); }
private static Comment getComment(oxite_Comment comment, UserBase user) { return(new Comment { Body = comment.Body, Created = comment.CreatedDate, Creator = user, CreatorIP = comment.CreatorIP, CreatorUserAgent = comment.UserAgent, ID = comment.CommentID, Language = new Language { DisplayName = comment.oxite_Language.LanguageDisplayName, ID = comment.oxite_Language.LanguageID, Name = comment.oxite_Language.LanguageName }, Modified = comment.ModifiedDate, State = (EntityState)comment.State }); }
protected void btnAddToUser_Click(object sender, EventArgs e) { IList <int> groupIds = new List <int>(); foreach (RepeaterItem item in this.rptAllGroup.Items) { HtmlInputCheckBox chk = item.FindControl("checkbox") as HtmlInputCheckBox; if (chk != null && chk.Checked) { groupIds.Add(int.Parse(chk.Value)); } } if (groupIds.Count > 0) { int[] arrayIds = new int[groupIds.Count]; groupIds.CopyTo(arrayIds, 0); using (_session = new Session()) { UserBase user = Magic.Sys.User.Retrieve(_session, this._userId); try { AuthorizationRepository repository = new AuthorizationRepository(_session); repository.AddUsersToGroups(new UserBase[] { user }, arrayIds); LoadUserToGroup(); } catch (UnauthorizedException ex) { WebUtil.ShowMsg(this, ex.Message, "警告"); } catch (ApplicationException ex) { WebUtil.ShowMsg(this, ex.Message, "提示"); } catch (Exception ex) { logger.Info("AddUsersToGroups", ex); WebUtil.ShowError(this, ex); } } } }
/// <summary> /// 取得資料範圍 /// </summary> /// <param name="Data"></param> public override void GetDataAuth(ref UserBase Data) { //if (!IsMatch(Data)) //{ // _iterator.GetDataAuth(ref Data); // return; //} //UserBase temp = Data; //var con = new Conditions<DataBase.TZOCODE>(); ////關聯區域底下的門市 //con.Include(x => x.TSTRMST); ////關聯所屬公司 //con.Include(x => x.TCMPDAT); ////找到所屬的區域 //con.And(x => x.Zo_Manager == temp.UserId); ////公司別 //con.And(x => x.Comp_Cd == temp.CompCd); ////取得區域(所屬權限) //IEnumerable<Tzocode> range = _zoRepo.GetList(con); //Data.CompShort = range?.FirstOrDefault()? // .TCMPDAT? // .CompShort; //var datarange = new DataRange(); //var zocd = new List<string>(); //range.Select(x => x.ZoCd).ForEach(x => //{ // zocd.Add(x); //}); //datarange.ZoCd = zocd; //Data.DataRange = datarange; }
public ActionResult AdminLogin(LoginModel model) { UserBase userBase = new UserBase(); try { if (ModelState.IsValid) { int result = 0; userBase.UserName = model.UserName; userBase.Password = model.Password; userBase.RoleType = 2; model.RememberMe = model.RememberMe; actionResult = accountAction.Login_Load(userBase); if (actionResult.IsSuccess) { DataRow dr = actionResult.dtResult.Rows[0]; result = Convert.ToInt32(dr[0]); if (result < 0) { TempData["ErrorMessage"] = "UserName or Passwrd is wrong."; return(View(model)); } else { Session["Admin"] = Convert.ToInt32(dr["Id"]); Session["RoleName"] = "Admin"; Session["UserName"] = Convert.ToString(dr["UserName"]); // return RedirectToAction("Index", "Subject", new { area = "Subject" }); return(Redirect("~/Home/Index")); } } } } catch (Exception ex) { TempData["ErrorMessage"] = "Error in login. Please try again later."; ErrorReporting.WebApplicationError(ex); } return(RedirectToAction("AdminLogin")); }
public void SetLoginCookie(string email) { int UserId = 0; string FirstName = ""; UserBase userInfo = new UserBase(); List <string> Roles = new List <string>(); dataProvider.ExecuteNonQuery( "User_SetLoginCookie", (parameters) => { parameters.AddWithValue("@Email", email); parameters.Add("@Id", SqlDbType.Int).Direction = ParameterDirection.Output; parameters.Add("@FirstName", SqlDbType.NVarChar, 50).Direction = ParameterDirection.Output; }, (parameters) => { UserId = (int)parameters["@Id"].Value; FirstName = (string)parameters["@FirstName"].Value; }); dataProvider.ExecuteCmd( "User_GetRoles", (parameters) => { parameters.AddWithValue("@Id", UserId); }, (reader, resultsIndex) => { Roles.Add((string)reader["Role"]); } ); authenticationService.LogIn(new UserBase() { Id = UserId, Name = FirstName, Roles = Roles }); }
public void Test() { try { IServiceCollection serviceCollection = new ServiceCollection(); FluentMappingConfiguration.ConfigureMapping(); IConfigurationRoot configuration = GetConfiguration(); using (UnitOfWork unitOfWork = new UnitOfWork(configuration)) { unitOfWork.BeginTransaction(); UserBase user = new UserBase() { Login = "******", Name = "--", Surname = "login", CreatedOn = DateTime.Now, PasswordHash = SecurePasswordHasher.Hash("password") }; user.Id = unitOfWork.UserRepository.Insert(user); var list = unitOfWork.UserRepository.Query(new UserFilter() { Login = "******" }); unitOfWork.RollbackTransaction(); // unitOfWork.BeginTransaction(); // List<_TestEntityBase> list = unitOfWork._TestEntityRepository.GetAllBase(); //_TestEntityBase first = list.First(); // first.Name = "Updated name 3"; // unitOfWork._TestEntityRepository.Update(first); // unitOfWork.RollbackTransaction(); } } catch (Exception ex) { throw; } }
//User has selected to reset the PIN for the user currently selected in the grid. private void buttonResetPIN_Click(object sender, EventArgs e) { if (gridUsers.SelectedRows.Count < 1) { MessageBox.Show("You must first select a user to set the PIN for."); return; } //the objectID and alias values will always be in the result set. string strObjectID = gridUsers.SelectedRows[0].Cells["ObjectId"].Value.ToString(); string strAlias = gridUsers.SelectedRows[0].Cells["Alias"].Value.ToString(); using (FormCollectPIN oForm = new FormCollectPIN()) { if (oForm.ShowDialog() != DialogResult.OK) { return; } //reset the PIN - pass in null's for the flag values we aren't allowing the user to fiddle with so their current //values will be left alone. Easy enough to extend the PIN collection form to allow passing the "can't change" and //"locked" values if you want. WebCallResult res = UserBase.ResetUserPin(GlobalItems.CurrentConnectionServer, strObjectID, oForm.NewPIN, false, oForm.MustChange, null, oForm.DoesNotExpire, oForm.ClearHackedLockout); if (res.Success) { MessageBox.Show("PIN reset for user: "******"PIN reset failed for user: {0}/nError={1}", strAlias, res.ErrorText)); } } }
public UserBase GetUser(int id) { UserBase user = new UserBase(); logger.Info("Запрос пользователя №{0}...", id); string sql = "SELECT * FROM users WHERE users.id = @id"; MySqlDataReader rdr = null; try { mysqlProvider.CheckConnectionAlive(); MySqlCommand cmd = new MySqlCommand(sql, mysqlProvider.DbConnection); cmd.Parameters.AddWithValue("@id", id); rdr = cmd.ExecuteReader(); var valueReader = new DBValueReader(rdr); rdr.Read(); user.Id = valueReader.GetInt("id", 0); user.Name = valueReader.GetString("name"); user.Login = valueReader.GetString("login"); user.Deactivated = valueReader.GetBoolean("deactivated", false); user.Email = valueReader.GetString("email"); user.IsAdmin = valueReader.GetBoolean("admin", false); user.Description = valueReader.GetString("description"); logger.Info("Ok"); return(user); } catch (Exception ex) { logger.Error(ex, "Ошибка получения информации о пользователе!"); throw ex; } finally { if (rdr != null) { rdr.Close(); } } }
public ActionResult ExternalLoginConfirmation(RegisterExternalLoginModel model, string returnUrl) { string provider = null; string providerUserId = null; if (User.Identity.IsAuthenticated || !OAuthWebSecurity.TryDeserializeProviderUserId(model.ExternalLoginData, out provider, out providerUserId)) { return(RedirectToAction("Manage")); } if (ModelState.IsValid) { // Insert a new user into the database using (var db = new LinkerDb()) { UserBase user = db.UsersBase.FirstOrDefault(u => u.UserName.ToLower() == model.UserName.ToLower()); // Check if user already exists if (user == null) { // Insert name into the profile table db.UsersBase.Add(new UserBase { UserName = model.UserName }); db.SaveChanges(); OAuthWebSecurity.CreateOrUpdateAccount(provider, providerUserId, model.UserName); OAuthWebSecurity.Login(provider, providerUserId, createPersistentCookie: false); return(RedirectToLocal(returnUrl)); } else { ModelState.AddModelError("UserName", "User name already exists. Please enter a different user name."); } } } ViewBag.ProviderDisplayName = OAuthWebSecurity.GetOAuthClientData(provider).DisplayName; ViewBag.ReturnUrl = returnUrl; return(View(model)); }
public void OnActionExecuting(ActionExecutingContext filterContext) { Comment incomingComment = filterContext.ActionParameters["commentInput"] as Comment; PostAddress postAddress = filterContext.ActionParameters["postAddress"] as PostAddress; UserBase user = filterContext.ActionParameters["userBaseInput"] as UserBase; if (incomingComment != null) { SpamFilterContext context = new SpamFilterContext() { Comment = incomingComment, PostAddress = postAddress, AnonymousUser = user, RequestContext = filterContext.RequestContext }; if (this.spamFilter.IsSpam(context)) { incomingComment.State = EntityState.Removed; } } }
public void Handler(object sender, ReceivedCommandEventArgs e) { if (e.Arguments.Length < 1) { e.User.ErrorNeedMoreParams(CMD); return; } UserBase user = e.Server.GetUser(e.Arguments[0]); if (user == null) { e.User.SendNumeric(Numerics.ERR_NOSUCHNICK, e.Arguments[0], ":That nickname does not exist."); return; } string reason = e.Arguments.Length > 1 ? "Killed: " + e.Arguments[1] : "Killed by network operator."; e.User.SendCommand(CMD, e.Server.Id, e.User.Mask.Nickname, reason); e.User.Dispose(reason); }
public ActionResult ChangePassword(UserModel model) { UserBase userBase = new UserBase(); userBase.ID = model.ID; userBase.UserName = Session["UserName"].ToString(); userBase.Password = model.NewPassword; actionResult = adminAction.Users_Password_Update(userBase); if (actionResult.IsSuccess) { TempData["SuccessMessage"] = "Password changed successfully."; } else { TempData["ErrorMessage"] = "Old password is wrong."; } return(RedirectToAction("ChangePassword")); }
public DataTable VerifyEmailAccount(UserBase userBase) { dtContainer = new DataTable(); dsContainer = new DataSet(); try { MyParameter[] myParams = { new MyParameter("@UserGuid", userBase.UserGuid) }; Common.Set_Procedures("VerifyAccount"); Common.Set_ParameterLength(myParams.Length); Common.Set_Parameters(myParams); dtContainer = Common.Execute_Procedures_LoadData(); } catch (Exception ex) { throw ex; } return(dtContainer); }
public DataTable Login_Load(UserBase userBase) { dtContainer = new DataTable(); try { MyParameter[] myParams = { new MyParameter("@UserName", userBase.UserName), new MyParameter("@Password", userBase.Password) }; Common.Set_Procedures("SuperAdminLogin"); Common.Set_ParameterLength(myParams.Length); Common.Set_Parameters(myParams); dtContainer = Common.Execute_Procedures_LoadData(); } catch (Exception ex) { ErrorReporting.DataLayerError(ex); } return(dtContainer); }
public UserBase VerifyUser(string login, string password) { Argument.Require(!string.IsNullOrWhiteSpace(login), "Логин пользователя не задан."); Argument.Require(!string.IsNullOrWhiteSpace(password), "Пароль пользователя не задан."); using (var unitOfWork = _unitOfWorkFactory.Create(this._configuration)) { UserBase user = unitOfWork.UserRepository.Query(new UserFilter() { Login = login }) .FirstOrDefault(); if (user == null) { return(null); } bool isUserExists = this._VerifyPassword(password, user.PasswordHash); return(isUserExists ? user : null); } }
public int GetUserId(string login) { UserBase user = new UserBase(); logger.Info("Запрос пользователя логин {0}...", login); string sql = "SELECT id FROM users WHERE users.login = @login"; try { mysqlProvider.CheckConnectionAlive(); MySqlCommand cmd = new MySqlCommand(sql, mysqlProvider.DbConnection); cmd.Parameters.AddWithValue("@login", login); int result = (int)cmd.ExecuteScalar(); logger.Info("Ok"); return(result); } catch (Exception ex) { logger.Error(ex, "Ошибка получения информации о пользователе!"); return(0); } }
public new static void MyClassInitialize(TestContext testContext) { BaseIntegrationTests.MyClassInitialize(testContext); //create new list with GUID in the name to ensure uniqueness String strUserAlias = "TempUserPrivList_" + Guid.NewGuid().ToString().Replace("-", ""); //generate a random number and tack it onto the end of some zeros so we're sure to avoid any legit numbers on the system. Random random = new Random(); int iExtPostfix = random.Next(100000, 999999); string strExtension = "000000" + iExtPostfix.ToString(); //use a bogus extension number that's legal but non dialable to avoid conflicts WebCallResult res = UserBase.AddUser(_connectionServer, "voicemailusertemplate", strUserAlias, strExtension, null, out _tempUser); Assert.IsTrue(res.Success, "Failed creating temporary user:"******"Test Private List1", 1, out _tempPrivateList); Assert.IsTrue(res.Success, "Failed to create new private list for user:" + res); }
public TokenInfo RefreshToken([FromBody] RefreshTokenModel refreshTokenRequest) { Argument.Require(refreshTokenRequest?.RefreshToken != null, "Некорректный запрос, пустой токен обновления токенов."); var splittedData = refreshTokenRequest.RefreshToken.Split('.'); Argument.Require(splittedData.Length == 2, "Некорректный формат токена для обновления токенов."); Argument.Require(Int32.TryParse(splittedData[1], out int userId), "Некорректный формат идентификатора пользователя в токене для обновления токенов."); var tokenId = splittedData[0]; if (this.TokensStorage.Get(userId) != refreshTokenRequest.RefreshToken) { Argument.Require(this.TokensStorage.Get(userId) == refreshTokenRequest.RefreshToken, "Некорректный токен обновления токенов."); } UserBase existUser = this.AuthenticationDataService.GetUserById(userId); Argument.Require(existUser != null, "Не найден пользователь-владелец токена."); TokenInfo token = this._GenerateToken(existUser); this.TokensStorage.Store(existUser.Id, token.RefreshToken); return(token); }
//===================Login with the hash password========== public UserBase UserLogInWithHash(string email, string passwordHash) { UserBase response = new UserBase(); this._dataProvider.ExecuteCmd( //"Emma_Login", "HRB_users_select_by_email", inputParamMapper : delegate(SqlParameterCollection paramList) { paramList.AddWithValue("Email", email); paramList.AddWithValue("Password", passwordHash); }, singleRecordMapper : delegate(IDataReader reader, short set) { //int index = 0; response = LoginMapper(reader); }); return(response); }
/// <summary> /// Gets the Data call to get a given user /// </summary /// <param name="email"></param> /// <param name="passwordHash"></param> /// <returns></returns> private IUserAuthData Get(string login, string passwordHash) { UserBase userAuthData = new UserBase(); _dataProvider.ExecuteCmd( "user_getauthdata", inputParamMapper : delegate(SqlParameterCollection parameters) { parameters.AddWithValue("@Login", login); parameters.AddWithValue("@Password", passwordHash); }, singleRecordMapper : delegate(IDataReader reader, short set) { userAuthData.Id = reader.GetInt32(0); userAuthData.FullName = reader.GetString(1); //userAuthData.Roles = // <== how do I get the roles from dbo.user_group? } ); return(userAuthData); }
public virtual UserBase GetAuthenticatedUser() { if (_cachedCustomer != null) { return(_cachedCustomer); } if (_httpContext == null || _httpContext.Request == null || !_httpContext.Request.IsAuthenticated || !(_httpContext.User.Identity is FormsIdentity)) { return(null); } var formsIdentity = (FormsIdentity)_httpContext.User.Identity; var customer = GetAuthenticatedCustomerFromTicket(formsIdentity.Ticket); _cachedCustomer = customer; return(_cachedCustomer); }
public void BeginSoloChallenge(UserBase user, int deadLiftWeight) { if (user.CanDoDeadLift(deadLiftWeight) == true) { string finalMessage = "You Just Deadlifted " + deadLiftWeight + "LBS! "; int cashReward = 0; int xpReward = 0; if (user.userStats.soloChallengeDeadliftRecord >= deadLiftWeight) // we have already deadlifted this weight { cashReward = deadLiftWeight; finalMessage += "Since you didnt beat a previous record, you earned $" + cashReward + " but no xp"; } else if (user.userStats.soloChallengeDeadliftRecord < deadLiftWeight) //this is a new record! { cashReward = deadLiftWeight * 10; xpReward = user.userStats.level * 500; finalMessage += "You Beat Your Record! You get $" + cashReward + " and " + xpReward + " XP"; } user.userStats.SetNewSoloChallengeDeadliftRecord(deadLiftWeight); user.userAssets.ModifyCash(cashReward); user.userStats.ModifyXP(xpReward); OneButtonPopup temp= PopupManager.CreatePopup<OneButtonPopup>() as OneButtonPopup; temp.titleText.Text = "Finished Challenge"; temp.messageText.Text = finalMessage; } else { OneButtonPopup temp= PopupManager.CreatePopup<OneButtonPopup>() as OneButtonPopup; temp.titleText.Text = "FAIL!"; temp.messageText.Text = "You Need To Gain More Strength To Lift " + deadLiftWeight + " Keep Excercising!"; } }
public void IncreaseExcercisesDone(UserBase user, params MuscleGroup[] affectedMuscleGroups) { foreach(MuscleGroup muscleGroup in affectedMuscleGroups) { switch(muscleGroup) { case MuscleGroup.Quads: quadExcercisesDone += 1; break; case MuscleGroup.Back: backExcercisesDone += 1; break; case MuscleGroup.Biceps: bicepExcercisesDone += 1; break; case MuscleGroup.Glutes: gluteExcercisesDone += 1; break; case MuscleGroup.Hamstring: hamstringExcercisesDone += 1; break; case MuscleGroup.Abs: abExcercisesDone += 1; break; } } CheckForStrengthIncrease(user); //SaveLoadHelper.Save(this); //TODO SAVE }
public abstract string GetPrefix(UserBase user);
public abstract void BroadcastInclusive(string command, UserBase sender, params object[] arguments);
public abstract void AddPrefix(UserBase user, char c);
/// <summary> /// This method loads all Users for a client /// </summary> /// <param name="user"></param> /// <returns></returns> private static async Task<UserListModel> GetClientUsersTask(UserBase user) { var client = ClientConnection.GetConnection(); try { client.Open(); var response = await client.GetClientUsersAsync(new GetClientUsersRequest { MessageGuid = Guid.NewGuid(), ClientRID = user.ClientRID }); client.Close(); return new UserListModel { List = response.Users, IsError = false, Message = "Success" }; } catch (Exception ex) { client.Close(); return new UserListModel { IsError = false, Message = "Failde:" + ex }; } }
public abstract void RemoveUser(UserBase user, bool removeFromUser = true);
/// <summary> /// BTNs the save click. /// </summary> /// <param name="sender">The sender.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> private void BtnSaveClick(object sender, EventArgs e) { if ((!string.IsNullOrEmpty(txtPassword.Text.Trim())) | (!string.IsNullOrEmpty(txtConfirmPassword.Text.Trim()))) { if (txtPassword.Text.Trim().Length < 6) { MessageBox.Show(@"Password minimum 6 characters!", @"Password", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } if (!txtPassword.Text.Trim().Equals(txtConfirmPassword.Text.Trim())) { MessageBox.Show(@"Confirm password does not match!", @"Password", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } } // --- EMPTY PASSWORD if (!string.IsNullOrEmpty(txtPassword.Text.Trim())) { _user.Password = UserCryptoService.Encrypt( _user.UserId,txtPassword.Text.Trim()); var userDao = new UserBase(); if (userDao.Update(_user) == 1) { // Message MessageBox.Show(@"Your password has been successfully changed!", @"Information", MessageBoxButtons.OK, MessageBoxIcon.Information); } else { MessageBox.Show(@"Change password failed!", @"Information", MessageBoxButtons.OK, MessageBoxIcon.Information); } Close(); Dispose(); } }
public static int GetHungerIncreaseValPerSecond(UserBase user) { return user.userStats.level; }
public static readonly int baseStamina = 1000; //the base level for stamina. will be increased exponentially based on level public static int GetStaminaMaxForLevel(UserBase user) { return baseStamina * user.userStats.level; }
public override void Commit(UserBase user) { if (string.IsNullOrEmpty(user.Mask.Account)) { return; } foreach (UserBase u in UsersByMask.Values) { if (u.Mask.Account == user.Mask.Account) { u.Flags = user.Flags; u.Password = user.Password; u.Properties = user.Properties; } } if (user.Mask.Account[0] == '/') { return; } Cache.Accounts[user.Mask.Account] = new UserSurrogate(user); }
public override ChannelBase CreateChannel(string name, UserBase user) { Channel channel = new Channel(this, name, name.ToLower()); if (Cache.Channels.ContainsKey(channel.Id)) { channel.Load(Cache.Channels[channel.Id]); } else { if (channel.IsSystem && user.Level < Authorizations.NetworkOperator) { user.SendNumeric(Numerics.ERR_UNIQOPRIVSNEEDED, ":You need to be a network operator to register a system channel."); return null; } if (channel.IsRegistered && user.Level < Authorizations.Registered) { user.SendNumeric(Numerics.ERR_NOLOGIN, ":You need to be registered to own a channel. To create a temporary channel, prefix the channel name with # instead of !."); return null; } channel.AddPrefix(user, '~'); switch (channel.Name[0]) { case '!': channel.SetModes(null, Settings.DefaultChannelModesReg); break; case '#': channel.SetModes(null, Settings.DefaultChannelModesTemp); break; case '&': channel.SetModes(null, Settings.DefaultChannelModesLoc); break; } } if (channel != null) { Channels.Add(channel.Id, channel); } return channel; }
public override bool Register(UserBase user, byte[] password, string email) { try { if (user.Level >= Authorizations.Registered) { return false; } user.Password = password; user.Properties["E-Mail"] = email; user.Level = Cache.Accounts.Count > 0 ? Authorizations.Registered : Authorizations.NetworkOperator; user.Mask.Account = user.Id; Cache.Accounts.Add(user.Mask.Account, user); user.Commit(); UsersByAccount.Add(user.Mask.Account, new List<UserBase>(new UserBase[] { user })); user.SendNumeric(Numerics.RPL_REGISTERED, ":You are now registered and logged in. Use /login password to log in next time you connect."); return true; } catch { return false; } }
public abstract UserBase GetUser(string nick, UserBase notifyOnError = null);
public abstract void RemovePrefix(UserBase user, char c);
public abstract void SetModes(UserBase user, string modes);
public abstract void SetModes(UserBase user, string flags, string arguments);
public void BeginHeadToHeadChallenge(UserBase user, UserBase opponent, int deadLiftWeight) { UserBase winningPlayer; winningPlayer = (user.userStats.strength > opponent.userStats.strength) ? user : opponent; if (user.userStats.strength == opponent.userStats.strength) winningPlayer = null; string finalMessage = ""; if (winningPlayer != null) finalMessage = (winningPlayer.Equals(user)) ? "You Won!" : opponent.name + " Won!"; else finalMessage = "TIE!"; OneButtonPopup temp= PopupManager.CreatePopup<OneButtonPopup>() as OneButtonPopup; temp.titleText.Text = "Head To Head Challenge Results"; temp.messageText.Text = finalMessage; }
public override bool LogIn(UserBase user, string account, byte[] password) { try { if (!Cache.Accounts.ContainsKey(account)) { return false; } UserSurrogate cache = Cache.Accounts[account]; if (password.Length != cache.Password.Length) { return false; } for (int i = 0; i < password.Length; i++) { if (password[i] != cache.Password[i]) { return false; } } cache.LastSeen = DateTime.Now; user.Load(cache); user.Mask.Account = account; if (UsersByAccount.ContainsKey(account)) { UsersByAccount[account].Add(user); } else { UsersByAccount.Add(account, new List<UserBase>(new UserBase[] { user })); } user.SetModes(null, "+r" + (user.Level < Authorizations.NetworkOperator ? "" : "o"), string.Empty); return true; } catch { return false; } }
private void OnJoin(ChannelBase channel, UserBase user) { channel.BroadcastInclusive(CMD, user, channel.Name); user.Names(channel); if (channel.Properties.ContainsKey("Topic")) { // Note: Shouldn't send RPL_NOTOPIC under any circumstances at this point. user.SendNumeric(Numerics.RPL_TOPIC, channel.Name, ":" + (string)channel.Properties["Topic"]); } if (channel.Users.Count < 2) { return; } string prefix = channel.GetPrefix(user); if (!string.IsNullOrEmpty(prefix)) { StringBuilder modes = new StringBuilder(prefix.Length + 1).Append('+'); StringBuilder args = new StringBuilder(prefix.Length * (user.Mask.Nickname.Length + 1)); foreach (char c in prefix) { char m; switch (c) { case '$': m = 'X'; break; case '~': m = 'O'; break; case '&': m = 'a'; break; case '@': m = 'o'; break; case '%': m = 'h'; break; case '+': m = 'v'; break; case '!': m = 'x'; break; default: continue; } modes.Append(m); args.Append(' ').Append(user.Mask.Nickname); } channel.BroadcastInclusive("MODE", null, channel.Name, modes.ToString() + args.ToString()); } }