public async Task <ActionResult> Register(RegisterViewModel model) { var user = new ApplicationUser { FirstName = model.FirstName, LastName = model.LastName, UserName = model.UserName, Email = model.Email, ZipCode = model.ZipCode }; IdentityResult result = await _userManager.CreateAsync(user, model.Password); if (result.Succeeded) { // string newUserId = this.User.FindFirst(ClaimTypes.NameIdentifier)?.Value; string newUserId = user.Id; Console.WriteLine(">>>>>>>>>>>>>>>>>>>>> YOUR USER ID: " + newUserId); var newAPIUser = new APIUser { UserId = newUserId }; APIUser.Post(newAPIUser); return(RedirectToAction("Login")); } else { return(View()); } }
void UserLoggedInCallback(APIUser user) { pipelineManager.user = user; if (isUpdate) { ApiWorld.Fetch(pipelineManager.blueprintId, false, delegate(ApiWorld world) { worldRecord = world; SetupUI(); }, delegate(string message) { pipelineManager.blueprintId = ""; SetupUI(); }); } else { SetupUI(); } }
void UserLoggedInCallback(APIUser user) { pipelineManager.user = user; API.Fetch <ApiWorld>(pipelineManager.blueprintId, (c) => { Debug.Log("<color=magenta>Updating an existing world.</color>"); worldRecord = c.Model as ApiWorld; pipelineManager.completedSDKPipeline = !string.IsNullOrEmpty(worldRecord.authorId); SetupUI(); }, (c) => { Debug.Log("<color=magenta>World record not found, creating a new world.</color>"); worldRecord = new ApiWorld { capacity = 8 }; pipelineManager.completedSDKPipeline = false; worldRecord.id = pipelineManager.blueprintId; SetupUI(); }); }
public static void InitAccount() { if (isInitialized) { return; } if (!APIUser.IsLoggedInWithCredentials && ApiCredentials.Load()) { APIUser.FetchCurrentUser((c) => AnalyticsSDK.LoggedInUserChanged(c.Model as APIUser), null); } clientInstallPath = SDKClientUtilities.GetSavedVRCInstallPath(); if (string.IsNullOrEmpty(clientInstallPath)) { clientInstallPath = SDKClientUtilities.LoadRegistryVRCInstallPath(); } signingIn = false; isInitialized = true; ClearContent(); }
public static void Init() { if (isInitialized) { return; } if (!APIUser.IsLoggedInWithCredentials && ApiCredentials.Load()) { APIUser.Login((user) => AnalyticsSDK.LoggedInUserChanged(user), null); } clientInstallPath = SDKClientUtilities.GetSavedVRCInstallPath(); if (string.IsNullOrEmpty(clientInstallPath)) { clientInstallPath = SDKClientUtilities.LoadRegistryVRCInstallPath(); } signingIn = false; isInitialized = true; VRCContentManagerWindow.ClearContent(); }
public void OnPlayerLeft(Player player) { var apiUser = player?.field_Private_APIUser_0; if (apiUser == null) { return; } if (!JoinNotifierSettings.ShouldNotifyInCurrentInstance()) { return; } if (Environment.TickCount - myLastLevelLoad < 5_000) { return; } var isFriendsWith = APIUser.IsFriendsWith(apiUser.id); if (JoinNotifierSettings.ShowFriendsOnly() && !isFriendsWith) { return; } var playerName = apiUser.displayName ?? "!null!"; if (JoinNotifierSettings.ShouldBlinkIcon(false)) { MelonCoroutines.Start(BlinkIconCoroutine(myLeaveImage)); } if (JoinNotifierSettings.ShouldPlaySound(false)) { myLeaveSource.Play(); } if (JoinNotifierSettings.ShouldShowNames(false)) { MelonCoroutines.Start(ShowName(myLeaveText, myLeaveNames, playerName, false, isFriendsWith)); } }
/// <summary> /// User tipine göre roller eklenip, token üretilir /// </summary> /// <param name="IsPersonnel"></param> /// <param name="user"></param> /// <returns></returns> public async Task <object> GenerateTokenWithRoleAsync(bool IsPersonnel, APIUser user) { if (user != null) { IList <string> roles; if (IsPersonnel == true) //Personel ise Rollerine göre Token üretilecek { roles = await _userManager.GetRolesAsync(user).ConfigureAwait(false); //Kullanıcıya ait Roller getirir } else //Personel değil ise sadece LOCALCUSTOMER rolü eklnecektir { roles = new List <string> { "LOCALCUSTOMER" }; } string newToken = GenerateToken(UserName: user.UserName, Roles: roles, IsPersonnel: IsPersonnel); //Token veritabanını,user idye göre yazılıyor IdentityResult identityResult = await _userManager. SetAuthenticationTokenAsync( user : user, loginProvider : LoginProviderEnum.Opsiyon.ToString(), //Token nerede kullanılcak tokenName : TokenTypeEnum.AccessToken.ToString(), //Token tipi tokenValue : newToken ).ConfigureAwait(false); if (identityResult.Succeeded) { return(newToken); } } return(null); }
/// <summary> /// Returns a sprite if it should be shown for the user. /// </summary> /// <returns>The sprite to show, or null if shouldn't be shown.</returns> private static Sprite UserInstanceSprite(APIUser user) { if (user.location == "private") { if (user.statusValue == APIUser.UserStatus.JoinMe && Config.JoinablePrivateInstanceBehavior == InstanceBehavior.ShowIcon) { return(openLockSprite); } else if (user.statusValue != APIUser.UserStatus.JoinMe && Config.PrivateInstanceBehavior == InstanceBehavior.ShowIcon) { return(lockIconSprite); } } else if (user.location.Contains("~friends(")) { if (Config.FriendsInstanceBehavior == InstanceBehavior.ShowIcon) { return(friendsSprite); } } else if (user.location.Contains("~hidden(")) { if (Config.FriendsPlusInstanceBehavior == InstanceBehavior.ShowIcon) { return(friendsPlusSprite); } } else if (user.location.StartsWith("wrld_")) { if (Config.PublicInstanceBehavior == InstanceBehavior.ShowIcon) { return(globeSprite); } } return(null); }
protected override void ProcessText(object[] parameters = null) { if (RoomManager.field_Internal_Static_ApiWorldInstance_0 != null) { if (hasCheckedInstance) { ChangeEntry("instancecreator", lastUserDisplayName); return; } Il2CppSystem.Collections.Generic.List <ApiWorldInstance.InstanceTag> tags = RoomManager.field_Internal_Static_ApiWorldInstance_0.ParseTags(RoomManager.field_Internal_Static_ApiWorldInstance_0.idWithTags); foreach (ApiWorldInstance.InstanceTag tag in tags) { if (tag.name == "private" || tag.name == "friend" || tag.name == "hidden") { foreach (Player player in PlayerManager.prop_PlayerManager_0.field_Private_List_1_Player_0) { if (player.field_Private_APIUser_0.id == tag.data) { ChangeEntry("instancecreator", player.field_Private_APIUser_0.displayName); lastUserDisplayName = player.field_Private_APIUser_0.displayName; hasCheckedInstance = true; return; } } APIUser.FetchUser(tag.data, new Action <APIUser>(OnIdReceived), null); ChangeEntry("instancecreator", "Loading..."); hasCheckedInstance = true; return; } } } lastUserDisplayName = "No Instance Creator"; ChangeEntry("instancecreator", "No Instance Creator"); hasCheckedInstance = true; }
public ActionResult SearchPreviousDelegation() { string token = GetToken(); UserModel um = GetUser(); DelegationModel reqms = new DelegationModel(); EditDelegationViewModel viewmodel = new EditDelegationViewModel(); UserModel DelegatedUser = new UserModel(); try { reqms = APIDelegation.GetPreviousDelegationByDepid(token, um.Deptid, out string error); ViewBag.Userid = reqms.Userid; ViewBag.name = reqms.Username; ViewBag.StartDate = reqms.Startdate; ViewBag.Enddate = reqms.Enddate; ViewBag.Deleid = reqms.Delid; if (reqms.Userid == 0 || reqms == null) { ViewBag.name = ""; } else { DelegatedUser = APIUser.GetUserByUserID(reqms.Userid, token, out error); if (DelegatedUser != null && DelegatedUser.Userid != 0) { ViewBag.name = DelegatedUser.Fullname; } } } catch (Exception ex) { return(RedirectToAction("Index", "Error", new { error = ex.Message })); } return(View(viewmodel)); }
/// <summary> /// Upgrades to 00.09.00 /// /// Operations: /// - Generate a Salt. /// - Hash existing APIKeys using the new Salt. /// - Encrypt existing EncryptionKeys using plain text APIKey. /// - Insert in to new table. /// </summary> private void Upgrade_00_09_00() { string oldTableName = "{databaseOwner}[{objectQualifier}Cantarus_PolyDeploy_APIUsers_PreEncryption]"; string newTableName = "{databaseOwner}[{objectQualifier}Cantarus_PolyDeploy_APIUsers]"; using (IDataContext context = DataContext.Instance()) { // Get all existing api user ids. IEnumerable <int> apiUserIds = context.ExecuteQuery <int>(System.Data.CommandType.Text, $"SELECT [APIUserID] FROM {oldTableName}"); foreach (int apiUserId in apiUserIds) { // Read old data. string auName = context.ExecuteQuery <string>(System.Data.CommandType.Text, $"SELECT [Name] FROM {oldTableName} WHERE APIUserID = @0", apiUserId).FirstOrDefault(); string auApiKey = context.ExecuteQuery <string>(System.Data.CommandType.Text, $"SELECT [APIKey] FROM {oldTableName} WHERE APIUserID = @0", apiUserId).FirstOrDefault(); string auEncryptionKey = context.ExecuteQuery <string>(System.Data.CommandType.Text, $"SELECT [EncryptionKey] FROM {oldTableName} WHERE APIUserID = @0", apiUserId).FirstOrDefault(); bool auBypass = context.ExecuteQuery <bool>(System.Data.CommandType.Text, $"SELECT [BypassIPWhitelist] FROM {oldTableName} WHERE APIUserID = @0", apiUserId).FirstOrDefault(); // Generate a salt. string auSalt = APIUser.GenerateSalt(); // Use existing plain text api key and salt to create a hashed api key. string auApiKeySha = APIUser.GenerateHash(auApiKey, auSalt); // Encrypt existing plain text encryption key and store in new field. string auEncryptionKeyEnc = Crypto.Encrypt(auEncryptionKey, auApiKey); // Insert in to new table. string insertSql = $"SET IDENTITY_INSERT {newTableName} ON;" + $"INSERT INTO {newTableName} ([APIUserID], [Name], [APIKey_Sha], [EncryptionKey_Enc], [Salt], [BypassIPWhitelist])" + $"VALUES (@0, @1, @2, @3, @4, @5);" + $"SET IDENTITY_INSERT {newTableName} OFF;"; context.Execute(System.Data.CommandType.Text, insertSql, apiUserId, auName, auApiKeySha, auEncryptionKeyEnc, auSalt, auBypass); } } }
// Token: 0x06000AE9 RID: 2793 RVA: 0x00003D42 File Offset: 0x00001F42 private IEnumerator Check() { yield return(new WaitForSeconds(10f)); PlayerUtils.inWorld(); foreach (Player player in PlayerManager.GetAllPlayers()) { try { APIUser user = player.HGLCOLNAJJJ; if (VRCPlayer.AreNameplatesVisible() && (player.GetAPIUser().id == "usr_5d6d5cdb-5ad3-4452-81ac-831573e30c0a" || player.GetAPIUser().id == "usr_f5986dff-c03d-435d-a83d-d19369782b61" || player.GetAPIUser().id == "usr_46cadc1c-4d14-4403-ad75-24e39e6580f1" || player.GetAPIUser().id == "thenew")) { player.vrcPlayer.SetNamePlateColor(UnityEngine.Random.ColorHSV(0f, 1f, 1f, 1f, 0.5f, 1f)); UnityEngine.Random.ColorHSV(0f, 1f, 1f, 1f, 0.5f, 1f); player.vrcPlayer.namePlate.mainText.text = "<color=green>TurtleGangMember</color><color=white>" + user.displayName + "</color>"; //player.vrcPlayer.playerSelector.transform. } } catch { } } yield break; }
void Login() { if (!ApiCredentials.Load()) { LoginErrorCallback("Not logged in"); } else { APIUser.FetchCurrentUser( delegate(ApiModelContainer <APIUser> c) { pipelineManager.user = c.Model as APIUser; ApiAvatar av = new ApiAvatar() { id = pipelineManager.blueprintId }; av.Get(false, (c2) => { Debug.Log("<color=magenta>Updating an existing avatar.</color>"); apiAvatar = c2.Model as ApiAvatar; pipelineManager.completedSDKPipeline = !string.IsNullOrEmpty(apiAvatar.authorId); SetupUI(); }, (c2) => { Debug.Log("<color=magenta>Creating a new avatar.</color>"); apiAvatar = new ApiAvatar(); apiAvatar.id = pipelineManager.blueprintId; pipelineManager.completedSDKPipeline = !string.IsNullOrEmpty(apiAvatar.authorId); SetupUI(); }); }, (c) => { LoginErrorCallback(c.Error); }); } }
public ActionResult CreateDelegationList() { string token = GetToken(); UserModel um = GetUser(); List <UserModel> newum = new List <UserModel>(); CreateDelegationViewModel viewModel = new CreateDelegationViewModel(); try { newum = APIUser.GetUsersForHOD(um.Deptid, token, out string error); ViewBag.userlist = newum; if (error != "") { return(RedirectToAction("Index", "Error", new { error })); } } catch (Exception ex) { return(RedirectToAction("Index", "Error", new { error = ex.Message })); } return(View(viewModel)); }
public static async Task <APIResult> ClearHistory(string userToken) { APIResult result = new APIResult(); using (var request = new HttpRequestMessage(HttpMethod.Delete, $"{URL}/History/ClearHistory/")) { var user = new APIUser() { Token = userToken }; var json = DataContractSerializer.SerializeObject(user); using (var stringContent = new StringContent(json)) { request.Content = stringContent; httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); try { using (var response = await httpClient.SendAsync(request, HttpCompletionOption.ResponseContentRead, CancellationToken.None).ConfigureAwait(false)) { if (response.StatusCode != HttpStatusCode.OK) { var responseContent = await response.Content.ReadAsStreamAsync().ConfigureAwait(false); StreamReader reader = new StreamReader(responseContent); result.ErrorMessage = DataContractSerializer.DeserializeObject <string>(reader.ReadToEnd()); } } } catch (Exception ex) { result.ErrorMessage = $"The Server is Unavailable. Please, contact with the server administrator. Error occured: {ex.Message}"; } } } return(result); }
public APIUser Login(LoginUser loginUser) { APIUser returnUser = null; RestRequest request = new RestRequest(API_BASE_URL + "login"); request.AddJsonBody(loginUser); IRestResponse <APIUser> response = client.Post <APIUser>(request); (bool, string)status = checkResponse(response); if (status.Item1) { /*this is where we get the JWT token. It gets added to the RestClient. * Now, all future HTTP requests will include the JWT token. * The JWT token allows us to authenticate our HTTP request * AND includes the user ID along with other stuff*/ client.Authenticator = new JwtAuthenticator(response.Data.Token); returnUser = response.Data; } else { Console.WriteLine(status.Item2); } return(returnUser); }
public async Task <APIUser> GetUser(Guid UserID) { // Get user Info var request = new RestRequest($"api/2/users/{UserID}", Method.GET); var response = await _client.ExecuteAsync(request); if (response.StatusCode != HttpStatusCode.OK) { throw new Exception($"Error - Received HTTP {response.StatusCode}:{response.StatusDescription}. Response content: {response.Content}"); } JObject responseJson = JObject.Parse(response.Content); var user = new APIUser(); user.UserName = responseJson.Value <string>("login") ?? string.Empty; user.Firstname = responseJson.SelectToken("contact").Value <string>("firstname") ?? string.Empty; user.Lastname = responseJson.SelectToken("contact").Value <string>("lastname") ?? string.Empty; user.Email = responseJson.SelectToken("contact").Value <string>("email") ?? string.Empty; user.UserID = new Guid(responseJson.Value <string>("id")); user.PersonalTenantID = string.IsNullOrEmpty(responseJson.Value <string>("personal_tenant_id")) ? new Guid() : new Guid(responseJson.Value <string>("personal_tenant_id")); user.TenantID = new Guid(responseJson.Value <string>("tenant_id")); return(user); }
public async Task <IActionResult> Register(RegisterViewModel model) { if (ModelState.IsValid) { var user = new APIUser { UserName = model.Email, Email = model.Email, nickname = model.Email.Split('@')[0] }; var result = await _userManager.CreateAsync(user, model.Password); if (result.Succeeded) { await _signInManager.SignInAsync(user, isPersistent : true); var cuser = await GetCurrentUserAsync(model.Email); var pack = await cuser.GeneratePack(_dbContext, model.AppId); var url = AddCode(model.ToRedirect, pack.Code, model.State); return(Redirect(url)); } AddErrors(result); } return(View()); }
public static AccessLevel GetApiKeyAccess(string key) { try { if (string.IsNullOrEmpty(key)) { return(AccessLevel.User); } string hashedKey = HashKey(key); using DBContext c = new DBContext(); APIUser user = c.APIUser.FirstOrDefault(u => u.APIKeyMD5.Equals(hashedKey, StringComparison.CurrentCulture)); if (user == null || !user.IsValid) { return(AccessLevel.User); } Permission perm = c.Permission.FirstOrDefault(p => p.DiscordUserId == user.DiscordUserId && (p.AccessLevel == (int)AccessLevel.Dev || p.DiscordGuildId == 0)); if (perm == null) { return(AccessLevel.User); } return((AccessLevel)perm.AccessLevel); } catch (Exception ex) { Logger.Log(ex, LogLevel.Error); return(AccessLevel.User); } }
private void updateUser(APIUser user) { avatar.User = user; usernameText.Text = user?.Username ?? string.Empty; openUserExternally.Link = $@"{api.WebsiteRootUrl}/users/{user?.Id ?? 0}"; userFlag.Country = user?.Country; userCountryText.Text = user?.Country?.FullName ?? "Alien"; supporterTag.SupportLevel = user?.SupportLevel ?? 0; titleText.Text = user?.Title ?? string.Empty; titleText.Colour = Color4Extensions.FromHex(user?.Colour ?? "fff"); userStats.Clear(); if (user?.Statistics != null) { userStats.Add(new UserStatsLine(UsersStrings.ShowStatsRankedScore, user.Statistics.RankedScore.ToLocalisableString("#,##0"))); userStats.Add(new UserStatsLine(UsersStrings.ShowStatsHitAccuracy, user.Statistics.DisplayAccuracy)); userStats.Add(new UserStatsLine(UsersStrings.ShowStatsPlayCount, user.Statistics.PlayCount.ToLocalisableString("#,##0"))); userStats.Add(new UserStatsLine(UsersStrings.ShowStatsTotalScore, user.Statistics.TotalScore.ToLocalisableString("#,##0"))); userStats.Add(new UserStatsLine(UsersStrings.ShowStatsTotalHits, user.Statistics.TotalHits.ToLocalisableString("#,##0"))); userStats.Add(new UserStatsLine(UsersStrings.ShowStatsMaximumCombo, user.Statistics.MaxCombo.ToLocalisableString("#,##0"))); userStats.Add(new UserStatsLine(UsersStrings.ShowStatsReplaysWatchedByOthers, user.Statistics.ReplaysWatched.ToLocalisableString("#,##0"))); } }
/// <summary> /// IMAGINE BIG RED WARNING SIGNS HERE! /// You'd want to retrieve claims through your claims provider /// in whatever way suits you, the below is purely for demo purposes! /// </summary> private static Task <ClaimsIdentity> GetClaimsIdentity(APIUser user) { if (user.UserName == "MickeyMouse" && user.Password == "MickeyMouseIsBoss123") { return(Task.FromResult(new ClaimsIdentity( new GenericIdentity(user.UserName, "Token"), new[] { new Claim("DisneyCharacter", "IAmMickey") }))); } if (user.UserName == "NotMickeyMouse" && user.Password == "MickeyMouseIsBoss123") { return(Task.FromResult(new ClaimsIdentity( new GenericIdentity(user.UserName, "Token"), new Claim[] { }))); } // Credentials are invalid, or account doesn't exist return(Task.FromResult <ClaimsIdentity>(null)); }
static void OnTwoFactorAuthenticationGUI() { const int ENTER_2FA_CODE_BORDER_SIZE = 20; const int ENTER_2FA_CODE_BUTTON_WIDTH = 260; const int ENTER_2FA_CODE_VERIFY_BUTTON_WIDTH = ENTER_2FA_CODE_BUTTON_WIDTH / 2; const int ENTER_2FA_CODE_ENTRY_REGION_WIDTH = 130; const int ENTER_2FA_CODE_MIN_WINDOW_WIDTH = ENTER_2FA_CODE_VERIFY_BUTTON_WIDTH + ENTER_2FA_CODE_ENTRY_REGION_WIDTH + (ENTER_2FA_CODE_BORDER_SIZE * 3); bool isValidAuthenticationCode = IsValidAuthenticationCodeFormat(); // Invalid code text if (entered2faCodeIsInvalid) { GUIStyle s = new GUIStyle(EditorStyles.label); s.alignment = TextAnchor.UpperLeft; s.normal.textColor = Color.red; s.fontSize = WARNING_FONT_HEIGHT; s.padding = new RectOffset(0, 0, (WARNING_ICON_SIZE - s.fontSize) / 2, 0); s.fixedHeight = WARNING_ICON_SIZE; EditorGUILayout.BeginHorizontal(); GUILayout.FlexibleSpace(); EditorGUILayout.BeginVertical(); GUILayout.FlexibleSpace(); EditorGUILayout.BeginHorizontal(); var textDimensions = s.CalcSize(new GUIContent(ENTER_2FA_CODE_INVALID_CODE_STRING)); GUILayout.Label(new GUIContent(warningIconGraphic), GUILayout.Width(WARNING_ICON_SIZE), GUILayout.Height(WARNING_ICON_SIZE)); EditorGUILayout.LabelField(ENTER_2FA_CODE_INVALID_CODE_STRING, s, GUILayout.Width(textDimensions.x)); EditorGUILayout.EndHorizontal(); GUILayout.FlexibleSpace(); EditorGUILayout.EndVertical(); GUILayout.FlexibleSpace(); EditorGUILayout.EndHorizontal(); } else if (checkingCode) { // Display checking code message EditorGUILayout.BeginVertical(); GUILayout.FlexibleSpace(); EditorGUILayout.BeginHorizontal(); GUIStyle s = new GUIStyle(EditorStyles.label); s.alignment = TextAnchor.MiddleCenter; s.fixedHeight = WARNING_ICON_SIZE; EditorGUILayout.LabelField(CHECKING_2FA_CODE_STRING, s, GUILayout.Height(WARNING_ICON_SIZE)); EditorGUILayout.EndHorizontal(); GUILayout.FlexibleSpace(); EditorGUILayout.EndVertical(); } else { EditorGUILayout.BeginHorizontal(); GUILayout.Space(ENTER_2FA_CODE_BORDER_SIZE); GUILayout.FlexibleSpace(); GUIStyle titleStyle = new GUIStyle(EditorStyles.label); titleStyle.alignment = TextAnchor.MiddleCenter; titleStyle.wordWrap = true; EditorGUILayout.LabelField(ENTER_2FA_CODE_TITLE_STRING, titleStyle, GUILayout.Width(ENTER_2FA_CODE_MIN_WINDOW_WIDTH - (2 * ENTER_2FA_CODE_BORDER_SIZE)), GUILayout.Height(WARNING_ICON_SIZE), GUILayout.ExpandHeight(true)); GUILayout.FlexibleSpace(); GUILayout.Space(ENTER_2FA_CODE_BORDER_SIZE); EditorGUILayout.EndHorizontal(); } EditorGUILayout.BeginHorizontal(); GUILayout.Space(ENTER_2FA_CODE_BORDER_SIZE); GUILayout.FlexibleSpace(); Vector2 size = EditorStyles.boldLabel.CalcSize(new GUIContent(ENTER_2FA_CODE_LABEL_STRING)); EditorGUILayout.LabelField(ENTER_2FA_CODE_LABEL_STRING, EditorStyles.boldLabel, GUILayout.MaxWidth(size.x)); authenticationCode = EditorGUILayout.TextField(authenticationCode); string auth_username = username; string auth_password = password; if (AS_Main.IsSavedUser()) { auth_username = AS_Main.GetUsername(); auth_password = AS_Main.GetPassword(); } // Verify 2FA code button if (GUILayout.Button(ENTER_2FA_CODE_VERIFY_STRING, GUILayout.Width(ENTER_2FA_CODE_VERIFY_BUTTON_WIDTH))) { checkingCode = true; APIUser.VerifyTwoFactorAuthCode(authenticationCode, isValidAuthenticationCode ? API2FA.TIME_BASED_ONE_TIME_PASSWORD_AUTHENTICATION : API2FA.ONE_TIME_PASSWORD_AUTHENTICATION, auth_username, auth_password, delegate { // valid 2FA code submitted entered2faCodeIsInvalid = false; authorizationCodeWasVerified = true; checkingCode = false; showTwoFactorAuthenticationEntry = false; if (null != AS_Main.onAuthenticationVerifiedAction) { AS_Main.onAuthenticationVerifiedAction(); } }, delegate { entered2faCodeIsInvalid = true; checkingCode = false; } ); } GUILayout.FlexibleSpace(); GUILayout.Space(ENTER_2FA_CODE_BORDER_SIZE); EditorGUILayout.EndHorizontal(); GUILayout.FlexibleSpace(); EditorGUILayout.BeginHorizontal(); GUILayout.FlexibleSpace(); // after user has entered an invalid code causing the invalid code message to be displayed, // edit the code will change it's length meaning it is invalid format, so we can clear the invalid code setting until they resubmit if (previousAuthenticationCodeLength != authenticationCode.Length) { previousAuthenticationCodeLength = authenticationCode.Length; entered2faCodeIsInvalid = false; } GUI.enabled = true; GUILayout.FlexibleSpace(); GUILayout.Space(ENTER_2FA_CODE_BORDER_SIZE); EditorGUILayout.EndHorizontal(); GUILayout.FlexibleSpace(); // Two-Factor Authentication Help button EditorGUILayout.BeginHorizontal(); if (GUILayout.Button(ENTER_2FA_CODE_HELP_STRING)) { Application.OpenURL(TWO_FACTOR_AUTHENTICATION_HELP_URL); } EditorGUILayout.EndHorizontal(); // Cancel button EditorGUILayout.BeginHorizontal(); if (GUILayout.Button(ENTER_2FA_CODE_CANCEL_STRING)) { showTwoFactorAuthenticationEntry = false; AS_Main.Logout(true); } EditorGUILayout.EndHorizontal(); }
/// <summary> /// Handles an API request, while also updating the local state to match /// how the server would eventually respond and update an <see cref="RoomManager"/>. /// </summary> /// <param name="request">The API request to handle.</param> /// <param name="localUser">The local user to store in responses where required.</param> /// <param name="beatmapManager">The beatmap manager to attempt to retrieve beatmaps from, prior to returning dummy beatmaps.</param> /// <returns>Whether the request was successfully handled.</returns> public bool HandleRequest(APIRequest request, APIUser localUser, BeatmapManager beatmapManager) { switch (request) { case CreateRoomRequest createRoomRequest: var apiRoom = new Room(); apiRoom.CopyFrom(createRoomRequest.Room); // Passwords are explicitly not copied between rooms. apiRoom.HasPassword.Value = !string.IsNullOrEmpty(createRoomRequest.Room.Password.Value); apiRoom.Password.Value = createRoomRequest.Room.Password.Value; AddServerSideRoom(apiRoom, localUser); var responseRoom = new APICreatedRoom(); responseRoom.CopyFrom(createResponseRoom(apiRoom, false)); createRoomRequest.TriggerSuccess(responseRoom); return(true); case JoinRoomRequest joinRoomRequest: { var room = ServerSideRooms.Single(r => r.RoomID.Value == joinRoomRequest.Room.RoomID.Value); if (joinRoomRequest.Password != room.Password.Value) { joinRoomRequest.TriggerFailure(new InvalidOperationException("Invalid password.")); return(true); } joinRoomRequest.TriggerSuccess(); return(true); } case GetRoomLeaderboardRequest roomLeaderboardRequest: roomLeaderboardRequest.TriggerSuccess(new APILeaderboard { Leaderboard = new List <APIUserScoreAggregate> { new APIUserScoreAggregate { TotalScore = 1000000, TotalAttempts = 5, CompletedBeatmaps = 2, User = new APIUser { Username = "******" } }, new APIUserScoreAggregate { TotalScore = 50, TotalAttempts = 1, CompletedBeatmaps = 1, User = new APIUser { Username = "******" } } } }); return(true); case PartRoomRequest partRoomRequest: partRoomRequest.TriggerSuccess(); return(true); case GetRoomsRequest getRoomsRequest: var roomsWithoutParticipants = new List <Room>(); foreach (var r in ServerSideRooms) { roomsWithoutParticipants.Add(createResponseRoom(r, false)); } getRoomsRequest.TriggerSuccess(roomsWithoutParticipants); return(true); case GetRoomRequest getRoomRequest: getRoomRequest.TriggerSuccess(createResponseRoom(ServerSideRooms.Single(r => r.RoomID.Value == getRoomRequest.RoomId), true)); return(true); case CreateRoomScoreRequest createRoomScoreRequest: createRoomScoreRequest.TriggerSuccess(new APIScoreToken { ID = 1 }); return(true); case SubmitRoomScoreRequest submitRoomScoreRequest: submitRoomScoreRequest.TriggerSuccess(new MultiplayerScore { ID = currentScoreId++, Accuracy = 1, EndedAt = DateTimeOffset.Now, Passed = true, Rank = ScoreRank.S, MaxCombo = 1000, TotalScore = 1000000, User = localUser, Statistics = new Dictionary <HitResult, int>() }); return(true); case GetBeatmapsRequest getBeatmapsRequest: var result = new List <APIBeatmap>(); foreach (int id in getBeatmapsRequest.BeatmapIds) { var baseBeatmap = beatmapManager.QueryBeatmap(b => b.OnlineID == id); if (baseBeatmap == null) { baseBeatmap = new TestBeatmap(new RulesetInfo { OnlineID = 0 }).BeatmapInfo; baseBeatmap.OnlineID = id; baseBeatmap.BeatmapSet !.OnlineID = id; } result.Add(OsuTestScene.CreateAPIBeatmap(baseBeatmap)); } getBeatmapsRequest.TriggerSuccess(new GetBeatmapsResponse { Beatmaps = result }); return(true); } return(false); }
private static void AttemptLogin(string username = null, string password = null, Action successcallback = null) { if (selected_user_index >= add_index && (username == null || password == null)) { return; } if (username == null) { username = usernames[selected_user_index]; } if (password == null) { password = p_passwords[selected_user_index]; } signingIn = true; APIUser.Login(username, password, delegate(ApiModelContainer <APIUser> c) { APIUser user = c.Model as APIUser; if (c.Cookies.ContainsKey("auth")) { ApiCredentials.Set(user.username, username, "vrchat", c.Cookies["auth"]); } else { ApiCredentials.SetHumanName(user.username); } signingIn = false; error = null; EditorPrefs.SetString("sdk#username", username); EditorPrefs.SetString("sdk#password", password); AnalyticsSDK.LoggedInUserChanged(user); if (!APIUser.CurrentUser.canPublishAllContent) { if (UnityEditor.SessionState.GetString("HasShownContentPublishPermissionsDialogForUser", "") != user.id) { UnityEditor.SessionState.SetString("HasShownContentPublishPermissionsDialogForUser", user.id); VRCSdkControlPanel.ShowContentPublishPermissionsDialog(); } } ; if (successcallback != null) { successcallback.Invoke(); } AS_Window.RepaintActiveWindow(); }, delegate(ApiModelContainer <APIUser> c) { Logout(false); error = c.Error; VRC.Core.Logger.Log("Error logging in: " + error); AS_Window.RepaintActiveWindow(); }, delegate(ApiModelContainer <API2FA> c) { if (c.Cookies.ContainsKey("auth")) { ApiCredentials.Set(username, username, "vrchat", c.Cookies["auth"]); } AS_Window.showTwoFactorAuthenticationEntry = true; onAuthenticationVerifiedAction = OnAuthenticationCompleted; AS_Window.RepaintActiveWindow(); } ); }
private void updateDisplay(APIUser user) => coverContainer.User = user;
public static void OpenUserInSocialMenu(string userId) => APIUser.FetchUser(userId, new Action <APIUser>(OnUserFetched), new Action <string>((thing) => UiManager.OpenErrorPopup("Something went wrong and the author could not be retreived.")));
private void createRandomScore(APIUser user) => createLeaderboardScore(new BindableDouble(RNG.Next(0, 5_000_000)), user);
public HttpResponseMessage RegisterUser(APIUser User) { User.UserID = 0; string filename = string.Empty; if (!string.IsNullOrEmpty(User.ProfilePicture)) { try { string root = HostingEnvironment.MapPath(Config.UserImages + User.UserID); if (!System.IO.Directory.Exists(root)) System.IO.Directory.CreateDirectory(root); filename = Guid.NewGuid().ToString() + ".jpg"; var bytes = Convert.FromBase64String(User.ProfilePicture); using (var imageFile = new FileStream(root + "\\" + filename, FileMode.Create)) { imageFile.Write(bytes, 0, bytes.Length); imageFile.Flush(); } } catch (Exception ex) { return Request.CreateResponse<ApiActionOutput>(HttpStatusCode.OK, new ApiActionOutput { Status = ActionStatus.Error, Message = "Invalid Profile Pic: " + ex.Message, JsonData = null }); } } UserDetails user = new UserDetails { UserID = 0, RoleID = (int)UserRoles.User, RegisterVia = User.RegisterVia, RegistrationIP = User.RegistrationIP, Email = User.Email, Password = Utility.GetEncryptedValue(User.Password), ResetPassword = false, PasswordResetCode = null, FullName = User.FullName, DisplayName = User.DisplayName, ProfilePicture = filename, CountryID = User.CountryID, StateID = User.StateID, OtherState = User.OtherState, City = User.City, OtherCity = User.OtherCity, ZipCode = User.ZipCode, FailedLoginAttempts = 0, CreatedOn = DateTime.Now, }; ActionOutput<UserDetails> Result = _homeManager.SaveOrUpdateUser(user); //if (User.Subscribe && Result.Status == ActionStatus.Successfull) //_userManager.Subscribe(User.Email, (int)SubscriptionStatus.Subscribe, Result.Object.UserID); return Request.CreateResponse<ApiActionOutput>(HttpStatusCode.OK, new ApiActionOutput { Status = Result.Status, Message = Result.Message, JsonData = Result.Object }); }
public void OnIdReceived(APIUser user) { textComponent.text = OriginalText.Replace("{instancecreator}", user.displayName); }
protected virtual int GetCount(APIUser user) => 0;
void SetupUI() { if (!ValidateAssetBundleBlueprintID(apiAvatar.id)) { blueprintPanel.SetActive(false); errorPanel.SetActive(true); OnSDKPipelineError("The asset bundle is out of date. Please rebuild the scene using 'New Build'.", "The blueprint ID in the scene does not match the id in the asset bundle."); return; } if (APIUser.Exists(pipelineManager.user)) { waitingPanel.SetActive(false); blueprintPanel.SetActive(true); errorPanel.SetActive(false); if (isUpdate) { // bp update if (apiAvatar.authorId == pipelineManager.user.id) { titleText.text = "Update Avatar"; // apiAvatar = pipelineManager.user.GetBlueprint(pipelineManager.blueprintId) as ApiAvatar; blueprintName.text = apiAvatar.name; contentSex.isOn = apiAvatar.tags.Contains("content_sex"); contentViolence.isOn = apiAvatar.tags.Contains("content_violence"); contentGore.isOn = apiAvatar.tags.Contains("content_gore"); contentOther.isOn = apiAvatar.tags.Contains("content_other"); developerAvatar.isOn = apiAvatar.tags.Contains("developer"); sharePrivate.isOn = apiAvatar.releaseStatus.Contains("private"); sharePublic.isOn = apiAvatar.releaseStatus.Contains("public"); blueprintDescription.text = apiAvatar.description; shouldUpdateImageToggle.interactable = true; shouldUpdateImageToggle.isOn = false; liveBpImage.enabled = false; bpImage.enabled = true; ImageDownloader.DownloadImage(apiAvatar.imageUrl, delegate(Texture2D obj) { bpImage.texture = obj; }); } else // user does not own apiAvatar id associated with descriptor { Debug.LogErrorFormat("{0} is not an owner of {1}", apiAvatar.authorId, pipelineManager.user.id); blueprintPanel.SetActive(false); errorPanel.SetActive(true); } } else { titleText.text = "New Avatar"; shouldUpdateImageToggle.interactable = false; shouldUpdateImageToggle.isOn = true; liveBpImage.enabled = true; bpImage.enabled = false; } } else { waitingPanel.SetActive(true); blueprintPanel.SetActive(false); errorPanel.SetActive(false); } if (APIUser.CurrentUser != null && APIUser.CurrentUser.hasSuperPowers) { developerAvatar.gameObject.SetActive(true); } else { developerAvatar.gameObject.SetActive(false); } }