private void ValidateUserAccess(User user, IServiceRequest request, IAuthenticationAttributes authAttribtues, AuthorizationInfo auth) { if (user.Policy.IsDisabled) { throw new SecurityException("User account has been disabled.") { SecurityExceptionType = SecurityExceptionType.Unauthenticated }; } if (!user.Policy.IsAdministrator && !authAttribtues.EscapeParentalControl && !user.IsParentalScheduleAllowed()) { request.AddResponseHeader("X-Application-Error-Code", "ParentalControl"); throw new SecurityException("This user account is not allowed access at this time.") { SecurityExceptionType = SecurityExceptionType.ParentalControl }; } if (!string.IsNullOrWhiteSpace(auth.DeviceId)) { if (!DeviceManager.CanAccessDevice(user.Id.ToString("N"), auth.DeviceId)) { throw new SecurityException("User is not allowed access from this device.") { SecurityExceptionType = SecurityExceptionType.ParentalControl }; } } }
private void SetDeviceSpecificData(string itemId, PlaybackInfoResponse result, DeviceProfile profile, AuthorizationInfo auth, long?maxBitrate, long startTimeTicks, string mediaSourceId, int?audioStreamIndex, int?subtitleStreamIndex, int?maxAudioChannels, string userId, bool enableDirectPlay, bool forceDirectPlayRemoteMediaSource, bool enableDirectStream, bool enableTranscoding, bool allowVideoStreamCopy, bool allowAudioStreamCopy) { var item = _libraryManager.GetItemById(itemId); foreach (var mediaSource in result.MediaSources) { SetDeviceSpecificData(item, mediaSource, profile, auth, maxBitrate, startTimeTicks, mediaSourceId, audioStreamIndex, subtitleStreamIndex, maxAudioChannels, result.PlaySessionId, userId, enableDirectPlay, forceDirectPlayRemoteMediaSource, enableDirectStream, enableTranscoding, allowVideoStreamCopy, allowAudioStreamCopy); } SortMediaSources(result, maxBitrate); }
public virtual ActionResult SetMockGlobalPermission(ActionEnum[] actions = null) { _cacheStorageService.Remove("AuthorizationInfo"); var auth = new AuthorizationOperationInfo { ActionList = new List <ActionEnum>(), RoleList = new List <RoleEnum>(), UserName = IDBContext.Current.UserLoginName }; if ((actions != null) && actions.Length > 0) { auth.ActionList.AddRange(actions); } var authPermission = new AuthorizationInfo { GlobalAuthorization = auth }; _cacheStorageService.Add("AuthorizationInfo", authPermission); return(Json(new { IsValid = true, ErrorMessage = "Permissions was changed" })); }
public object Get(ListItems request) { //Plugin.Instance.Configuration.RecycledPath = @"C:\Temp\EmbyRecycled"; //Plugin.Instance.SaveConfiguration(); string parent_id = request.parent_id; string item_type = request.item_type; _logger.Info("parent_id : " + parent_id); _logger.Info("item_type : " + item_type); AuthorizationInfo user = _ac.GetAuthorizationInfo(Request); string username = user.User.Name; InternalItemsQuery query = new InternalItemsQuery(); query.IncludeItemTypes = new string[] { item_type }; query.Recursive = false; query.User = user.User; query.IsVirtualItem = false; if (!string.IsNullOrEmpty(parent_id)) { long long_id = long.Parse(parent_id); query.ParentIds = new long[] { long_id }; } if (request.sort_by == "date_watched") { var sort = new (string, SortOrder)[1] {
private void PerformLogin() { AuthorizationInfo info = new AuthorizationInfo(UserName, Password); Task <User> validateUserTask = Task.Factory.StartNew <User>(() => { PasswordHelper passwordHelper = new PasswordHelper(); string hashedPassword = passwordHelper.CreateBase64Hash(Password); return(dataService.ValidateCredentials(UserName, hashedPassword)); }, TaskScheduler.Default); Task finishTask = validateUserTask.ContinueWith((t) => { IsBusy = false; User user = t.Result; if (user != null) { dataService.UserLoggedIn(user); CurrentUser.Assign(user); eventAggregator.GetEvent <LoginSucceededEvent>().Publish(info); } else { eventAggregator.GetEvent <LoginFailedEvent>().Publish(info); Notify("Authorization failed. Invalid user name and(or) password.", NotificationType.Error); } }, TaskScheduler.FromCurrentSynchronizationContext()); }
private void DetermineAuthorization( Microsoft.AspNetCore.Authorization.AllowAnonymousAttribute allowAnonymousAttribute, Microsoft.AspNetCore.Authorization.AuthorizeAttribute authorizeAttribute, out AuthorizationInfo authorization) { authorization = new AuthorizationInfo();; if (allowAnonymousAttribute != null) { authorization.AllowAnonymous = true; authorization.IsSigninRequired = false; } else if (authorizeAttribute != null) { authorization.AllowAnonymous = false; authorization.IsSigninRequired = true; if (!String.IsNullOrWhiteSpace(authorizeAttribute.Roles)) { authorization.Roles = authorizeAttribute.Roles; } if (!String.IsNullOrWhiteSpace(authorizeAttribute.Policy)) { authorization.Policy = authorizeAttribute.Policy; } } }
public void WriteAuthorizationInfo(TPMBlob target, AuthorizationInfo authInfo) { target.WriteUInt32(authInfo.Handle.Handle); target.Write(authInfo.Handle.NonceOdd, 0, authInfo.Handle.NonceOdd.Length); target.WriteBool(authInfo.ContinueAuthSession); target.Write(authInfo.AuthData, 0, authInfo.AuthData.Length); }
public void Post(ImportBackup request) { AuthorizationInfo user_info = _ac.GetAuthorizationInfo(Request); UserPolicy policy = _userManager.GetUserPolicy(user_info.User); if (!policy.IsAdministrator) { return; } string headers = ""; foreach (var head in Request.Headers.Keys) { headers += head + " : " + Request.Headers[head] + "\r\n"; } _logger.Info("Header : " + headers); _logger.Info("Files Length : " + Request.Files.Length); _logger.Info("ContentType : " + Request.ContentType); Stream input_data = request.RequestStream; _logger.Info("Stream Info : " + input_data.CanRead); byte[] bytes = new byte[10000]; int read = input_data.Read(bytes, 0, 10000); _logger.Info("Bytes Read : " + read); _logger.Info("Read : " + bytes); }
public virtual JsonResult ChangeRoleAndPermissions(string operationNumber, RoleEnum role) { _cacheStorageService.Remove("AuthorizationInfo"); var auth = new AuthorizationOperationInfo { ActionList = new List <ActionEnum>(), RoleList = new List <RoleEnum> { RoleEnum.PCRProjectTeamLeader, role }, UserName = IDBContext.Current.UserLoginName }; foreach (var permission in RolePermissions[role]) { auth.ActionList.Add(permission); } var authPermission = new AuthorizationInfo { Authorization = new Dictionary <string, AuthorizationOperationInfo>() }; authPermission.Authorization.Add(operationNumber, auth); _cacheStorageService.Add("AuthorizationInfo", authPermission); return(Json(new { IsValid = true, ErrorMessage = "Permissions was changed" })); }
public virtual JsonResult ChangeGlobalActionOrRoles(string workspace, RoleEnum?role, ActionEnum[] actionEnum) { _cacheStorageService.Remove("AuthorizationInfo"); var auth = new AuthorizationOperationInfo() { ActionList = new List <ActionEnum>(), RoleList = new List <RoleEnum>(), UserName = IDBContext.Current.UserLoginName }; if (role.HasValue) { auth.RoleList.Add(role.Value); } for (var i = 0; i < actionEnum.Count(); i++) { if (!auth.ActionList.Any(x => x == actionEnum[i])) { auth.ActionList.Add(actionEnum[i]); } } var authPermission = new AuthorizationInfo(); authPermission.GlobalAuthorization = auth; _cacheStorageService.Add("AuthorizationInfo", authPermission); return(Json(new { IsValid = true, ErrorMessage = "Permissions was changed" })); }
public virtual JsonResult ChangeRol(string operationNumber, ActionEnum permission) { _cacheStorageService.Remove("AuthorizationInfo"); var auth = new AuthorizationOperationInfo() { ActionList = new List <ActionEnum>(), RoleList = new List <RoleEnum>() { RoleEnum.PCRProjectTeamLeader }, UserName = IDBContext.Current.UserName }; auth.ActionList.Add(ActionEnum.ConvergenceReadPermission); if (!auth.ActionList.Any(x => x == permission)) { auth.ActionList.Add(permission); } var authPermission = new AuthorizationInfo() { Authorization = new Dictionary <string, AuthorizationOperationInfo>() }; authPermission.Authorization.Add(operationNumber, auth); _cacheStorageService.Add("AuthorizationInfo", authPermission); return(Json(new { IsValid = true, ErrorMessage = "Permissions was changed" })); }
public void SendUnicastData(IInteractor publisher, IInteractor subscriber, AuthorizationInfo authorization, UnicastData unicastData) { if (!publisher.HasRole(unicastData.Feed, Role.Publish)) { Log.Warn($"Rejected request from {publisher} to publish on feed {unicastData.Feed}"); return; } var clientUnicastData = authorization.IsAuthorizationRequired ? new ForwardedUnicastData(publisher.User, publisher.Address, unicastData.ClientId, unicastData.Feed, unicastData.Topic, unicastData.IsImage, unicastData.Data.Where(x => authorization.Entitlements.Contains(x.Header)).ToArray()) : new ForwardedUnicastData(publisher.User, publisher.Address, unicastData.ClientId, unicastData.Feed, unicastData.Topic, unicastData.IsImage, unicastData.Data); Log.Debug($"Sending unicast data from {publisher} to {subscriber}: {clientUnicastData}"); _repository.AddPublisher(publisher, clientUnicastData.Feed, clientUnicastData.Topic); try { subscriber.SendMessage(clientUnicastData); } catch (Exception exception) { Log.Debug($"Failed to send to subscriber {subscriber} unicast data {clientUnicastData}", exception); } }
public void ContinueLoginAndSchedule() { NotifyLoading(true); SimvaApi <IStudentsApi> .ContinueLogin() .Then(simvaController => { this.auth = simvaController.AuthorizationInfo; this.simvaController = simvaController; return(UpdateSchedule()); }) .Then(schedule => { var result = new AsyncCompletionSource(); StartCoroutine(AsyncCoroutine(LaunchActivity(schedule.Next), result)); return(result); }) .Catch(error => { NotifyLoading(false); NotifyManagers(error.Message); }) .Finally(() => { OpenIdUtility.tokenLogin = false; }); }
private MemberProfile CreateAuthorizationForToken(string providerName, string token) { // no provider to validate the token Services.AuthProviders.IOAuthServerTokenValidator provider = GetAuthorizationProvider(providerName); if (provider == null) { throw new WebFaultException <string>("Provider not informed", System.Net.HttpStatusCode.BadRequest); } // not a valid token if (!provider.ValidateAccessToken(token)) { throw new WebFaultException <string>("Token not Valid", System.Net.HttpStatusCode.Unauthorized); } // so the token is valid, at it the valid tokens AuthorizationInfo info = new AuthorizationInfo(); info.ProviderName = providerName; info.MemberUId = provider.MemberInfo.MemberUId; info.Token = token.Trim().Replace("\n", ""); info.IssueDate = DateTime.Now; authorizedTokens.TryAdd(info.Token, info); // Dont wanna save google/live tokens //if (info.ProviderName == "Windows Authentication") authorizationRepository.SaveAuthorizationInfo(info); return(provider.MemberInfo); }
public object Get(GetUserManage request) { AuthorizationInfo auth_user_info = _ac.GetAuthorizationInfo(Request); UserPolicy policy = _userManager.GetUserPolicy(auth_user_info.User); if (!policy.IsAdministrator) { return(-1); } string action = request.Action; string id = request.Id; if (action == "remove_unknown") { List <string> user_id_list = new List <string>(); foreach (var emby_user in _userManager.Users) { user_id_list.Add(emby_user.Id.ToString("N")); } int removed_count = repository.RemoveUnknownUsers(user_id_list); return(removed_count); } else { repository.ManageUserList(action, id); return(1); } }
public object Get(GetUserList request) { AuthorizationInfo auth_user_info = _ac.GetAuthorizationInfo(Request); UserPolicy policy = _userManager.GetUserPolicy(auth_user_info.User); if (!policy.IsAdministrator) { return(new List <Dictionary <string, object> >()); } List <string> user_id_list = repository.GetUserList(); List <Dictionary <string, object> > users = new List <Dictionary <string, object> >(); foreach (var emby_user in _userManager.Users) { Dictionary <string, object> user_info = new Dictionary <string, object>(); user_info.Add("name", emby_user.Name); user_info.Add("id", emby_user.Id.ToString("N")); user_info.Add("in_list", user_id_list.Contains(emby_user.Id.ToString("N"))); users.Add(user_info); } return(users); }
public ActionResult ReportSessionEnded() { AuthorizationInfo auth = _authContext.GetAuthorizationInfo(Request); _sessionManager.Logout(auth.Token); return(NoContent()); }
/// <summary> /// Attempts to login with given credentials /// </summary> /// <returns>Null if failed, userID string if succeeded</returns> public string LogIn(AuthorizationInfo auth) { // Validate if (auth.Username.IsBlank() || auth.Password.IsBlank()) { return(null); } // Spell check the auth object auth.Username = auth.Username.Trim(); try { // Try to log in if (!_apiService.CheckCredentials(auth)) { return(null); } // Get user id return(_apiService.GetUserID(auth.Username)); } catch (Exception ex) { Logger.Record("Could not perform a login operation"); Logger.Record(ex); return(null); } }
private bool IsExemptFromRoles(AuthorizationInfo auth, IAuthenticationAttributes authAttribtues, IRequest request, AuthenticationInfo tokenInfo) { if (!_config.Configuration.IsStartupWizardCompleted && authAttribtues.AllowBeforeStartupWizard) { return(true); } if (authAttribtues.AllowLocal && request.IsLocal) { return(true); } if (authAttribtues.AllowLocalOnly && request.IsLocal) { return(true); } if (string.IsNullOrEmpty(auth.Token)) { return(true); } if (tokenInfo != null && tokenInfo.UserId.Equals(Guid.Empty)) { return(true); } return(false); }
public SignInPageViewModel(INavigationService navigationService) : base(navigationService) { Title = "Signing In"; this.authorizationInfo = new AuthorizationInfo(); _navigationService = navigationService; }
private void ValidateUserAccess(User user, IRequest request, IAuthenticationAttributes authAttribtues, AuthorizationInfo auth) { if (user.Policy.IsDisabled) { throw new SecurityException("User account has been disabled.") { SecurityExceptionType = SecurityExceptionType.Unauthenticated }; } if (!user.Policy.EnableRemoteAccess && !NetworkManager.IsInLocalNetwork(request.RemoteIp)) { throw new SecurityException("User account has been disabled.") { SecurityExceptionType = SecurityExceptionType.Unauthenticated }; } if (!user.Policy.IsAdministrator && !authAttribtues.EscapeParentalControl && !user.IsParentalScheduleAllowed()) { request.Response.AddHeader("X-Application-Error-Code", "ParentalControl"); throw new SecurityException("This user account is not allowed access at this time.") { SecurityExceptionType = SecurityExceptionType.ParentalControl }; } }
private void ValidateUserAccess( User user, IRequest request, IAuthenticationAttributes authAttributes, AuthorizationInfo auth) { if (user.HasPermission(PermissionKind.IsDisabled)) { throw new SecurityException("User account has been disabled."); } if (!user.HasPermission(PermissionKind.EnableRemoteAccess) && !_networkManager.IsInLocalNetwork(request.RemoteIp)) { throw new SecurityException("User account has been disabled."); } if (!user.HasPermission(PermissionKind.IsAdministrator) && !authAttributes.EscapeParentalControl && !user.IsParentalScheduleAllowed()) { request.Response.Headers.Add("X-Application-Error-Code", "ParentalControl"); throw new SecurityException("This user account is not allowed access at this time."); } }
public virtual JsonResult ChangeRole(string operationNumber, ActionEnum rol) { _cacheStorageService.Remove("AuthorizationInfo"); var auth = new AuthorizationOperationInfo() { ActionList = new List <ActionEnum>(), RoleList = new List <RoleEnum>() { RoleEnum.Unrecognized }, UserName = IDBContext.Current.UserLoginName }; auth.ActionList.Add(ActionEnum.ConvergenceReadPermission); auth.ActionList.Add(rol); var authPermission = new AuthorizationInfo() { Authorization = new Dictionary <string, AuthorizationOperationInfo>() }; authPermission.Authorization.Add(operationNumber, auth); _cacheStorageService.Add("AuthorizationInfo", authPermission); return(Json(new { IsValid = true, ErrorMessage = "Permissions was changed" })); }
private void DetermineAuthorization(MethodInfo type, out AuthorizationInfo authorization) { var allowAnonymousAttribute = type.GetCustomAttribute <Microsoft.AspNetCore.Authorization.AllowAnonymousAttribute>(); var authorizeAttribute = type.GetCustomAttribute <Microsoft.AspNetCore.Authorization.AuthorizeAttribute>(); DetermineAuthorization(allowAnonymousAttribute, authorizeAttribute, out authorization); }
public object Get(GetMoviesReport request) { AuthorizationInfo user_info = _ac.GetAuthorizationInfo(Request); UserPolicy policy = _userManager.GetUserPolicy(user_info.User); if (!policy.IsAdministrator) { return(new List <Dictionary <string, object> >()); } DateTime end_date; if (string.IsNullOrEmpty(request.end_date)) { end_date = DateTime.Now; } else { _logger.Info("End_Date: " + request.end_date); end_date = DateTime.ParseExact(request.end_date, "yyyy-MM-dd", CultureInfo.InvariantCulture); } List <Dictionary <string, object> > report = repository.GetMoviesReport(request.user_id, request.days, end_date); return(report); }
public void SendUnicastData(Interactor publisher, Interactor subscriber, AuthorizationInfo authorization, UnicastData unicastData) { if (!publisher.HasRole(unicastData.Feed, Role.Publish)) { _logger.LogWarning("Rejected request from {Publisher} to publish on feed {Feed}", publisher, unicastData.Feed); return; } publisher.Metrics.UnicastMessages[unicastData.Feed].Inc(); var clientUnicastData = new ForwardedUnicastData( publisher.UserForFeed(unicastData.Feed), publisher.HostForFeed(unicastData.Feed), unicastData.ClientId, unicastData.Feed, unicastData.Topic, unicastData.IsImage, GetAuthorizedData(unicastData.DataPackets, authorization)); _logger.LogDebug("Sending unicast data from {Publisher} to {Subscriber}: {Message}", publisher, subscriber, clientUnicastData); _repository.AddPublisher(publisher, unicastData.Feed, unicastData.Topic); try { subscriber.SendMessage(clientUnicastData); } catch (Exception error) { _logger.LogDebug(error, "Failed to send to subscriber {Subscriber} unicast data {Message}", subscriber, clientUnicastData); } }
public object Post(CustomQuery request) { _logger.Info("CustomQuery : " + request.CustomQueryString); Dictionary <string, object> responce = new Dictionary <string, object>(); AuthorizationInfo user_info = _ac.GetAuthorizationInfo(Request); UserPolicy policy = _userManager.GetUserPolicy(user_info.User); if (!policy.IsAdministrator) { return(responce); } List <List <object> > result = new List <List <object> >(); List <string> colums = new List <string>(); string message = repository.RunCustomQuery(request.CustomQueryString, colums, result); int index_of_user_col = colums.IndexOf("UserId"); if (request.ReplaceUserId && index_of_user_col > -1) { colums[index_of_user_col] = "UserName"; Dictionary <string, string> user_map = new Dictionary <string, string>(); foreach (var user in _userManager.Users) { user_map.Add(user.Id.ToString("N"), user.Name); } foreach (var row in result) { String user_id = (string)row[index_of_user_col]; if (user_map.ContainsKey(user_id)) { row[index_of_user_col] = user_map[user_id]; } } } /* * List<object> row = new List<object>(); * row.Add("Shaun"); * row.Add(12); * row.Add("Some Date"); * result.Add(row); * * colums.Add("Name"); * colums.Add("Age"); * colums.Add("Started"); */ responce.Add("colums", colums); responce.Add("results", result); responce.Add("message", message); return(responce); }
public async Task <ActionResult> ReportSessionEnded() { AuthorizationInfo auth = await _authContext.GetAuthorizationInfo(Request).ConfigureAwait(false); await _sessionManager.Logout(auth.Token).ConfigureAwait(false); return(NoContent()); }
/// <summary> /// Serializes <see cref="AuthorizationInfo"/> object into a byte array. /// </summary> /// <param name="authorization">The <see cref="AuthorizationInfo"/> to serialize.</param> /// <returns>Byte array representing the serialized authorization object.</returns> public static byte[] SerializeAuthorization(AuthorizationInfo authorization) { using (var stream = new MemoryStream()) { SerializeAuthorization(authorization, stream); return(stream.ToArray()); } }
private bool IsExemptFromAuthenticationToken(AuthorizationInfo auth, IAuthenticationAttributes authAttribtues) { if (!_config.Configuration.IsStartupWizardCompleted && authAttribtues.AllowBeforeStartupWizard) { return(true); } return(false); }
public void SaveAuthorizationInfo(AuthorizationInfo info) { using (var context = new ScrumFactoryEntities(this.connectionString)) { AuthorizationInfo oldInfo = context.AuthorizationInfos.Where(a => a.MemberUId == info.MemberUId).FirstOrDefault(); if (oldInfo == null) context.AuthorizationInfos.AddObject(info); else { context.AttachTo("AuthorizationInfos", oldInfo); oldInfo.Token = info.Token; oldInfo.IssueDate = info.IssueDate; } context.SaveChanges(); }; }
public AuthorizationInfoTests() { _authorizationInfo = new AuthorizationInfo(Users, Roles); }
private MemberProfile CreateAuthorizationForToken(string providerName, string token) { // no provider to validate the token Services.AuthProviders.IOAuthServerTokenValidator provider = GetAuthorizationProvider(providerName); if (provider == null) throw new WebFaultException<string>("Provider not informed", System.Net.HttpStatusCode.BadRequest); // not a valid token if (!provider.ValidateAccessToken(token)) throw new WebFaultException<string>("Token not Valid", System.Net.HttpStatusCode.Unauthorized); // so the token is valid, at it the valid tokens AuthorizationInfo info = new AuthorizationInfo(); info.ProviderName = providerName; info.MemberUId = provider.MemberInfo.MemberUId; info.Token = token.Trim().Replace("\n", ""); info.IssueDate = DateTime.Now; authorizedTokens.TryAdd(info.Token, info); // Dont wanna save google/live tokens if (info.ProviderName == "Windows Authentication") authorizationRepository.SaveAuthorizationInfo(info); return provider.MemberInfo; }