public async Task <ActionResult> Register(RegisterViewModel model) { if (ModelState.IsValid) { var user = new ApplicationAccount { UserName = model.Email, Email = model.Email }; var result = await UserManager.CreateAsync(user, model.Password); if (result.Succeeded) { await SignInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false); // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771 // Send an email with this link // string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id); // var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme); // await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>"); return(RedirectToAction("Index", "Home")); } AddErrors(result); } // If we got this far, something failed, redisplay form return(View(model)); }
private VAppsCustomAuthHandler GetCustomAuthHandler(ApplicationAccount account) { var app = (PhotonCloudApp)this.application; var virtualApp = app.VirtualAppCache.GetOrCreateVirtualApp(account.ApplicationId); return(app.CustomAuthenticationCache.GetOrCreateHandler(account.ApplicationId, virtualApp)); }
private static void OnGetAccountInfoForVerifing(AsyncRequestState asyncRequestState, bool allowOnFailure, Action <ApplicationAccount> callback) { ApplicationAccount account; var appId = asyncRequestState.AppId.ToString(); try { switch (asyncRequestState.ResultCode) { case AccountServiceResult.Ok: account = new ApplicationAccount(appId, asyncRequestState.ResultCode, asyncRequestState.RequestResult); break; case AccountServiceResult.NotFound: account = new ApplicationAccount(appId, asyncRequestState.ResultCode, false, ErrorMessages.InvalidAppId); break; default: account = new ApplicationAccount(appId, asyncRequestState.ResultCode, allowOnFailure, asyncRequestState.ErrorMessage); break; } } catch (Exception e) { log.Warn(e); account = new ApplicationAccount(appId, AccountServiceResult.Error, allowOnFailure, e.Message); } callback(account); }
public void OnGetApplicationAccount(ApplicationAccount applicationAccount, RestRequest request, IRestRequestContext context, NameValueCollection queryParams) { if (log.IsDebugEnabled) { log.DebugFormat("MonitorRequestHandler, OnGetApplicationAccount '{0}': {1}/{2}", applicationAccount.ApplicationId, applicationAccount.PrivateCloud, applicationAccount.ServiceType); } if (string.IsNullOrEmpty(applicationAccount.ApplicationId)) { if (log.IsDebugEnabled) { log.DebugFormat("MonitorRequestHandler, OnGetApplicationAccount error: '{0}'", applicationAccount.DebugMessage); } context.SendResponse("Could not retrieve account information"); return; } if (applicationAccount.ServiceType != ServiceType.Realtime && applicationAccount.ServiceType != ServiceType.Pun) { context.SendResponse("Only Realtime applications are supported. Application has ServiceType " + applicationAccount.ServiceType); return; } var servers = this.photonCloudApp.CloudCache.TryGetPhotonEndpoints(applicationAccount.PrivateCloud, applicationAccount.ServiceType); if (servers == null || servers.Count == 0) { if (log.IsDebugEnabled) { log.DebugFormat("No servers found for appId '{0}' cloud '{1}' ServiceType '{2}'", applicationAccount.ApplicationId, applicationAccount.PrivateCloud, applicationAccount.ServiceType); } context.SendResponse("Found no servers for App"); return; } var servernamesList = new List <string>(); //TODO ? add cluster filter param? foreach (var photonEndpointInfo in servers) { var servernameAndRegion = GetServernameAndRegion(photonEndpointInfo); if (string.IsNullOrEmpty(servernameAndRegion)) { continue; } servernamesList.Add(servernameAndRegion); } var servernames = string.Join(";", servernamesList.ToArray()); if (log.IsDebugEnabled) { log.DebugFormat("Call GetMonitoringResult for application {0}/{1}: {2}", applicationAccount.ApplicationId, applicationAccount.PrivateCloud, servernames); } this.MonitoringCache.GetMonitoringResult(applicationAccount.ApplicationId, servernames, GetMonitoringResultCallback, context); }
private void OnGetApplicationAccountToGetRegionList(ApplicationAccount appAccount, Photon.NameServer.Operations.GetRegionListRequest regionListRequest, SendParameters sendParameters) { if (!this.Connected) { return; } if (!appAccount.IsAuthenticated) { this.SendOperationResponse(new OperationResponse(regionListRequest.OperationRequest.OperationCode) { ReturnCode = (short)ErrorCode.InvalidAuthentication, DebugMessage = string.IsNullOrEmpty(appAccount.DebugMessage) ? ErrorMessages.InvalidAppId : appAccount.DebugMessage }, sendParameters); this.ScheduleDisconnect(this.GetDisconnectTime()); return; } if (log.IsDebugEnabled) { log.DebugFormat("GetRegionList for App ID {0}, Private Cloud {1}, Service Type {2}", regionListRequest.ApplicationId, appAccount.PrivateCloud, appAccount.ServiceType); } List <string> regions; List <string> endPoints; string message; if (!((PhotonCloudApp)this.application).CloudCache.GetRegionList(regionListRequest, appAccount, this.NetworkProtocol, this.LocalPort, this.LocalIPAddressIsIPv6, this.IsIPv6ToIPv4Bridged, out regions, out endPoints, out message)) { { this.SendOperationResponse(new OperationResponse((byte)OperationCode.GetRegionList) { ReturnCode = (short)ErrorCode.InvalidRegion, DebugMessage = message }, sendParameters); this.ScheduleDisconnect(this.GetDisconnectTime()); return; } } var regionListResponse = new Photon.NameServer.Operations.GetRegionListResponse { Endpoints = endPoints.ToArray(), Region = regions.ToArray() }; this.SendOperationResponse(new OperationResponse((byte)OperationCode.GetRegionList, regionListResponse), sendParameters); }
private void SetCacheItem(CacheItem <ApplicationAccount> currentItem, ApplicationAccount authResult) { var newCachedItem = new CacheItem <ApplicationAccount>(authResult); var oldItem = Interlocked.CompareExchange(ref this.cachedItem, newCachedItem, currentItem); if (oldItem == currentItem) { this.cache.OnAuthenticateResultUpdated(this.ApplicationId, authResult); if (log.IsDebugEnabled) { log.DebugFormat("Updated cached auth result for {0}: {1}", this.ApplicationId, authResult.IsAuthenticated); } } }
private void CreateNewUser(ref DataContext context, string email, string password, string roleToAdd) { // Jei dar nera userio su tokiu email'u if (!context.Users.Any(u => u.Email == email)) { UserManager <ApplicationAccount> userManager = new UserManager <ApplicationAccount>(new UserStore <ApplicationAccount>(context)); var date = DateTime.Now; ApplicationAccount user = new ApplicationAccount() { Email = email, UserName = email, RegisteredDate = date }; userManager.Create(user, password); userManager.AddToRole(user.Id, roleToAdd); } }
public async Task <ActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl) { if (User.Identity.IsAuthenticated) { return(RedirectToAction("Index", "Manage")); } if (ModelState.IsValid) { // Get the information about the user from the external login provider var info = await AuthenticationManager.GetExternalLoginInfoAsync(); if (info == null) { return(View("ExternalLoginFailure")); } var user = new ApplicationAccount { UserName = model.Email, Email = model.Email }; var result = await UserManager.CreateAsync(user); if (result.Succeeded) { result = await UserManager.AddLoginAsync(user.Id, info.Login); if (result.Succeeded) { await SignInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false); return(RedirectToLocal(returnUrl)); } } AddErrors(result); } ViewBag.ReturnUrl = returnUrl; return(View(model)); }
public ApplicationAccount VerifyVAppsAccount(string appId, bool allowOnFailure) { var result = new ApplicationAccount(appId, AccountServiceResult.Ok, true, "OK", int.MaxValue, false, DefaultCloud, true, ServiceType.Realtime) { IsClientAuthenticationEnabled = true, ClientAuthenticationServices = new List <ClientAuthenticationServiceInfo> { new ClientAuthenticationServiceInfo(ClientAuthenticationType.Custom, "http://localhost:50925/Account/Authenticate", null) }, ExternalApiList = this.GetExternalApiInfo(), // adding clusters for US region in order to test sharding: RegionClusterInfos = new Dictionary <string, List <string> > { { "us", new List <string> { "cluster2", "cluster3" } } } }; return(result); }
private OperationResponse HandleDefaultAuthenticateRequest(AuthenticateRequest authenticateRequest, ApplicationAccount applicationAccount, string masterEndPoint, CloudPhotonEndpointInfo masterServer) { // generate a userid if its not set by the client var userId = string.IsNullOrEmpty(authenticateRequest.UserId) ? Guid.NewGuid().ToString() : authenticateRequest.UserId; // create auth token var unencryptedToken = this.application.TokenCreator.CreateAuthenticationToken(authenticateRequest, applicationAccount, userId, new Dictionary <string, object>()); var authToken = this.GetEncryptedAuthToken(unencryptedToken, masterServer); this.CheckEncryptedToken(authToken, authenticateRequest, applicationAccount, masterServer); var authResponse = new AuthenticateResponse { MasterEndpoint = masterEndPoint, AuthenticationToken = authToken, UserId = userId, Cluster = masterServer.Cluster, EncryptionData = GetEncryptionData(unencryptedToken), }; return(new OperationResponse(authenticateRequest.OperationRequest.OperationCode, authResponse)); }
private void OnGetApplicationAccount(ApplicationAccount account, AuthenticateRequest request, SendParameters sendParameters, NetworkProtocolType endpointProtocol) { if (!this.Connected) { if (log.IsDebugEnabled) { log.DebugFormat("OnGetApplicationAccount: Client disconnected. Ignore response."); } return; } if (!ConnectionRequirementsChecker.Check(this, account.RequireSecureConnection, account.ApplicationId, this.authOnceUsed)) { log.Warn(secureConnectionLogGuard, $"Client used non secure connection type when it is required. appId:{account.ApplicationId}, Connection: {this.NetworkProtocol}. AuthOnce {this.authOnceUsed}"); return; } if (log.IsDebugEnabled) { log.DebugFormat("OnGetApplicationAccount app:{0}, result:{1}, msg:{2}", account.ApplicationId, account.AccountServiceResult, account.DebugMessage); } var operationRequest = request.OperationRequest; if (!account.IsAuthenticated) { if (log.IsInfoEnabled) { log.InfoFormat("Authentication of client failed: Msg={0}, AppId={1}", account.DebugMessage, request.ApplicationId); } this.SendOperationResponse(new OperationResponse(operationRequest.OperationCode) { ReturnCode = (short)ErrorCode.InvalidAuthentication, DebugMessage = string.IsNullOrEmpty(account.DebugMessage) ? ErrorMessages.InvalidAppId : account.DebugMessage }, sendParameters); this.ScheduleDisconnect(this.GetDisconnectTime()); return; } if (log.IsDebugEnabled) { log.DebugFormat( "HandleAuthenticateRequest for App ID {0}, Private Cloud {1}, Service Type {2}, Region {3}", request.ApplicationId, account.PrivateCloud, account.ServiceType, request.Region); } // store for debugging purposes. this.authenticatedApplicationId = request.ApplicationId; // try to get the master server instance for the specified application id CloudPhotonEndpointInfo masterServer; string message; if (!((PhotonCloudApp)this.application).CloudCache.TryGetPhotonEndpoint(request, account, out masterServer, out message)) { if (string.Equals(request.Region, "none", StringComparison.CurrentCultureIgnoreCase)) { if (log.IsDebugEnabled) { log.DebugFormat("MasterServer not found for region '{0}' on cloud '{1}' / service type '{2}': '{3}'. AppId: {4}/{5}", request.Region, account.PrivateCloud, account.ServiceType, message, request.ApplicationId, request.ApplicationVersion); } } else { if (log.IsWarnEnabled) { log.WarnFormat(masterNotFoundGuard, "MasterServer not found for region '{0}' on cloud '{1}' / service type '{2}': '{3}'. AppId: {4}/{5}", request.Region, account.PrivateCloud, account.ServiceType, message, request.ApplicationId, request.ApplicationVersion); } } this.SendOperationResponse(new OperationResponse(operationRequest.OperationCode) { ReturnCode = (short)ErrorCode.InvalidRegion, DebugMessage = string.Format("Cloud {0} / Region {1} is not available.", account.PrivateCloud, request.Region) }, sendParameters); this.ScheduleDisconnect(this.GetDisconnectTime()); return; } var masterEndPoint = masterServer.GetEndPoint(endpointProtocol, this.LocalPort, isIPv6: this.LocalIPAddressIsIPv6, useHostnames: this.IsIPv6ToIPv4Bridged); if (masterEndPoint == null) { if (log.IsWarnEnabled) { log.WarnFormat(masterNotFoundForProtocolGuard, "Master server endpoint for protocol {0} not found on master server {1}. appId:{2}", this.NetworkProtocol, masterServer, account.ApplicationId); } this.SendOperationResponse(new OperationResponse(operationRequest.OperationCode) { ReturnCode = (short)AuthErrorCode.ProtocolNotSupported, DebugMessage = ErrorMessages.ProtocolNotSupported }, sendParameters); this.ScheduleDisconnect(this.GetDisconnectTime()); return; } // check for custom authentication if (account.IsClientAuthenticationEnabled) { var customAuthHandler = this.GetCustomAuthHandler(account); customAuthHandler.AuthenticateClient(this, request, account, sendParameters, account); return; // custom authentication is handled async } var response = this.HandleDefaultAuthenticateRequest(request, account, masterEndPoint, masterServer); this.SendOperationResponse(response, sendParameters); this.ScheduleDisconnect(this.MaxDisconnectTime); }
private void OnGetApplicationAccount(ApplicationAccount applicationAccount) { if (log.IsDebugEnabled) { log.DebugFormat("Authenticating: appId={0}", this.ApplicationId); } if (log.IsDebugEnabled) { log.DebugFormat( "Authenticate: appId={0}, result={1}, ccu={2}, burst={3}, cloud={4}", this.ApplicationId, applicationAccount.IsAuthenticated, applicationAccount.MaxCcu, applicationAccount.IsCcuBurstAllowed, applicationAccount.PrivateCloud); log.DebugFormat( "GameListLimits: UseLegacyLobbies={0}, GameListLimit={1}, GameListLimitUpdates={2}, GameListLimitSqlFilterResults={3}", applicationAccount.GameListUseLegacyLobbies, applicationAccount.GameListLimit, applicationAccount.GameListLimitUpdates, applicationAccount.GameListLimitSqlFilterResults); } // store in cache EITHER if the authentication call succeeded OR // if we allow "failed" auth calls. switch (applicationAccount.AccountServiceResult) { case AccountServiceResult.Ok: this.SetCacheItem(this.cachedItem, applicationAccount); this.updateInterval = this.initialUpdateInterval; break; default: if (applicationAccount.AccountServiceResult == AccountServiceResult.NotFound) { log.DebugFormat("Account NOT found. appId:'{0}'", this.ApplicationId); } if (this.cache.allowOnFailure) { this.SetCacheItem(this.cachedItem, applicationAccount); } else if (this.cachedItem != null && this.cachedItem.Value != null) { // if we have valid value and got some error from account service // we extend update interval this.updateInterval = new TimeSpan(0, 1, this.random.Next(30)); // and return existing value to clients applicationAccount = this.cachedItem.Value; } else { log.WarnFormat(this.logCountGuard, "We got error response from AccountService for very first" + " request for account. AppId:{0}, ErrorCode:{1}, DebugMessage:{2}", applicationAccount.ApplicationId, applicationAccount.AccountServiceResult, applicationAccount.DebugMessage); } break; } ThreadPool.QueueUserWorkItem(s => { Action <ApplicationAccount> calls; lock (this.syncLock) { calls = this.callbacks; this.callbacks = null; } Debug.Assert(calls != null, "calls != null"); calls(applicationAccount); } ); }
public bool GetRegionList(GetRegionListRequest request, ApplicationAccount appAccount, NetworkProtocolType networkProtocol, int port, bool isIPv6, bool useHostnames, out List <string> regions, out List <string> endPoints, out string message) { regions = new List <string>(); endPoints = new List <string>(); message = null; // check submitted ID: Guid appId; if (!Guid.TryParse(request.ApplicationId, out appId)) { message = string.Format("Invalid Application ID format: {0}", request.ApplicationId); if (log.IsDebugEnabled) { log.Debug(message); return(false); } } if (string.IsNullOrEmpty(appAccount.PrivateCloud)) { message = string.Format("No private cloud set for applicaton ID {0} - can not get Master", request.ApplicationId); log.Error(message); return(false); } var privateCloud = appAccount.PrivateCloud; if (log.IsDebugEnabled) { log.DebugFormat("PrivateCloud: {0}", privateCloud); var infos = appAccount.RegionClusterInfos; if (infos == null) { log.DebugFormat("RegionClusterInfos == null!"); } else { log.DebugFormat("RegionClusterInfos:"); foreach (var info in infos) { log.DebugFormat(info.Key); foreach (var clusterInfo in info.Value) { log.DebugFormat("\t{0}", clusterInfo); } } } } var allPhotonEndpoints = this.GetAllPhotonEndpoints(privateCloud, appAccount.ServiceType, appAccount); //tmp for whitelist var allRegions = new List <string>(); var allEndPoints = new List <string>(); foreach (var server in allPhotonEndpoints) { var endpoint = server.GetEndPoint(networkProtocol, port, isIPv6, useHostnames); if (endpoint == null) { continue; } string regionCluster = FormatRegionCultureString(server, allPhotonEndpoints); //use regionwhite list if (!string.IsNullOrEmpty(appAccount.GetRegionsFilter)) { //store all in case whitelist leaves no result allRegions.Add(regionCluster); allEndPoints.Add(endpoint); if (!IsRegionClusterWhitelisted(appAccount.GetRegionsFilter, server.Region, server.Cluster)) { if (log.IsDebugEnabled) { log.DebugFormat("Whitelist does not contain regionCluster '{0}', skipping", regionCluster); } continue; } } regions.Add(regionCluster); endPoints.Add(endpoint); if (log.IsDebugEnabled) { log.DebugFormat("RegionCluster: {0} -> Endpoint: {1}", regionCluster, endpoint); } } if (!string.IsNullOrEmpty(appAccount.GetRegionsFilter) && regions.Count == 0) { if (log.IsDebugEnabled) { log.DebugFormat("Whitelist left no entries, ignoring whitelist, returning all {0} entries", allRegions.Count); } regions.AddRange(allRegions); endPoints.AddRange(allEndPoints); } if (isIPv6 && regions.Count == 0) { message = string.Format("No IPv6 capable Master found for applicaton ID {0}", request.ApplicationId); log.Error(message); return(false); } return(true); }
protected virtual void OnAuthenticateResultUpdated(string appId, ApplicationAccount appAccount) { }
private List <CloudPhotonEndpointInfo> GetAllPhotonEndpoints(string privateCloud, ServiceType serviceType, ApplicationAccount applicationAccount) { var serversByPrivateCloudAndServiceType = this.servers.FindAll( serverConfig => serverConfig.PrivateCloud == privateCloud && serverConfig.ServiceType.Contains(serviceType)); var serversWithDuplicates = new List <CloudPhotonEndpointInfo>(); var regionClusterInfo = applicationAccount.RegionClusterInfos; foreach (var server in serversByPrivateCloudAndServiceType) { if (regionClusterInfo != null) { // we have a region/cluster filter specified: add only the "matching" cluster nodes. List <string> clusters; if (regionClusterInfo.TryGetValue(server.Region, out clusters)) { if (clusters.Contains(server.Cluster)) { serversWithDuplicates.Add(server); } continue; } } // if this is cluster0 app and we have cluster0 in this region var defaultCluster = applicationAccount.IsAppForCluster0 && this.cluster0Presence[MakeCluster0IndexKey(applicationAccount, server.Region)] ? Cluster0Name : DefaultClusterName; // we have no region/cluster filter specified: add only "default" or "cluster0" nodes. if (server.Cluster != defaultCluster) { continue; } serversWithDuplicates.Add(server); } var result = new List <CloudPhotonEndpointInfo>(); var comparer = new PhotonEndpointInfoComparer(); // the result contains now ALL photonEndpoints, filtered by serviceType, Cloud. //However, there might still be multiple entries for the same serviceType / Cloud / Cluster - we need to choose one by random. foreach (var server in serversWithDuplicates) { var duplicates = serversWithDuplicates.FindAll(duplicate => comparer.Equals(duplicate, server)); if (duplicates.Count > 0 && !result.Exists(x => comparer.Equals(x, server))) { if (duplicates.Count == 1) { result.Add(duplicates[0]); } else { var firstD = duplicates[0]; log.ErrorFormat("There are {3} duplicated nodes in region '{0}', cloud: '{1}', cluster:'{2}'", firstD.Region, firstD.PrivateCloud, firstD.Cluster, duplicates.Count); // choose one of the duplicate servers by random. result.Add(this.GetServerFromDuplicates(duplicates)); } } } return(result); }
private static string MakeCluster0IndexKey(ApplicationAccount appAccount, string region) { return($"{region}_{appAccount.PrivateCloud}_{appAccount.ServiceType}"); }
private void CheckEncryptedToken(object authToken, IAuthenticateRequest authenticateRequest, ApplicationAccount applicationAccount, CloudPhotonEndpointInfo master) { VAppsAuthTokenFactory.CheckEncryptedToken(this.application.TokenCreator, appCheckGuard, authToken, authenticateRequest, applicationAccount, master.UseV1Token); }
public bool TryGetPhotonEndpoint(IAuthenticateRequest request, ApplicationAccount appAccount, out CloudPhotonEndpointInfo result, out string message) { result = null; message = null; if (string.IsNullOrEmpty(appAccount.PrivateCloud)) { message = string.Format("No private cloud set for applicaton ID {0} - can not get Master", request.ApplicationId); log.Error(message); return(false); } if (string.IsNullOrEmpty(request.Region)) { message = string.Format("No region set in authenticate request for application ID {0} - can not determine Master", request.ApplicationId); log.Error(message); return(false); } var privateCloud = appAccount.PrivateCloud; var requestedRegion = request.Region.ToLower(); var cluster = DefaultClusterName; // if a cluster "*" has been passed then we return a random cluster // if an actual value has been passed we try to return that particular cluster if (requestedRegion.Contains("/")) { var regionArray = requestedRegion.Split(RegionSeparators, StringSplitOptions.RemoveEmptyEntries); if (regionArray.Length > 0) { requestedRegion = regionArray[0]; } // if account is enterprise account, we allow to select cluster using auth request if (regionArray.Length > 1 && appAccount.IsEnterprise) { cluster = regionArray[1]; } } var defaultAppCluster = DefaultClusterName; // app is cluster0 app and there is cluster0 in requested region then we set cluster0 if (appAccount.IsAppForCluster0 && this.cluster0Presence.TryGetValue(MakeCluster0IndexKey(appAccount, requestedRegion), out bool present) && present) { defaultAppCluster = Cluster0Name; cluster = Cluster0Name; } if (appAccount.RegionClusterInfos != null && appAccount.RegionClusterInfos.ContainsKey(requestedRegion)) { var clusters = appAccount.RegionClusterInfos[requestedRegion]; // if "*" has been passed we just chose a random one: if (RandomClusterName.Equals(cluster)) { cluster = clusters[rnd.Next(0, clusters.Count)]; } else { // check if a valid cluster has been found: if (!clusters.Contains(cluster)) { if (!clusters.Contains(defaultAppCluster)) { cluster = clusters[0]; } else { cluster = defaultAppCluster; } } } } //enterprise customer who send "*" and cluster was not replaced with value from RegionClusterInfos (because info is not set) if (RandomClusterName.Equals(cluster) && appAccount.IsEnterprise) { cluster = DefaultClusterName; } result = this.TryGetPhotonEndpoint(privateCloud, requestedRegion, cluster, appAccount.ServiceType); if (log.IsDebugEnabled) { if (result == null) { log.Debug("No endpoint found"); } else { log.DebugFormat("Endpoint found 2 - Hostname {0}, UDP: {1}, HTTP: {2}", result.UdpHostname, result.UdpEndPoint, result.HttpEndPoint); } } return(result != null); }