private AuthAction handleRegistration(AuthAction packet) { using (var userDb = new UserDb()) { int port = packet.OpenPort.Value; var entry = userDb.SearchByNickname(packet.Nickname); AuthAction responce; if (entry != null) { responce = new AuthAction(packet.Nickname, packet.Password, AuthType.WrongCredentials, port); } else { User usr = new User() { UserId = Guid.NewGuid(), Nickname = packet.Nickname, PasswordHash = packet.Password }; usr = userDb.Users.Add(usr); userDb.SaveChangesAsync(); responce = new AuthAction(usr.UserId, usr.Nickname, usr.PasswordHash, AuthType.Success, port); } return(responce); } }
public async Task <IActionResult> Edit(int id, [Bind("Id,ControllerId,ActionTitle,ActionName")] AuthAction authAction) { if (id != authAction.Id) { return(NotFound()); } if (ModelState.IsValid) { try { _context.Update(authAction); await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!AuthActionExists(authAction.Id)) { return(NotFound()); } else { throw; } } return(RedirectToAction(nameof(Index))); } return(View(authAction)); }
private AuthAction handleLogin(AuthAction packet) { using (userDb = new UserDb()) { int port = packet.OpenPort.Value; var entry = userDb.SearchByNickname(packet.Nickname); AuthAction responce; if (entry != null) { if (entry.PasswordHash == packet.Password && entry.Nickname == packet.Nickname) { responce = new AuthAction(entry.UserId, entry.Nickname, entry.PasswordHash, AuthType.Success, port); } else { responce = new AuthAction(packet.Nickname, packet.Password, AuthType.WrongCredentials, port); } } else { responce = new AuthAction(packet.Nickname, packet.Password, AuthType.WrongCredentials, port); } return(responce); } }
public async Task Invoke(aiAuthdbContext dbContext, CancellationToken cancellationToken) { aiAuthdbContext _context = dbContext; List <Emotions> _emotions = _context.Emotions.ToList(); List <Objects> _objects = _context.Objects.ToList(); int numberOfEmotions = new Random().Next(1, 3); // Create a new list if (Auth.Current == null) { Auth.Current = new Auth(); } Auth.Current.items.Clear(); // Add the new AuthAction emotions to the static class list for (int i = 1; i <= numberOfEmotions; i++) { Emotions temp = GetRandomEmotion(_emotions); AuthAction newaction = new AuthAction { name = temp.Name, description = temp.Description }; Auth.Current.items.Add(newaction); } Objects tempObject = GetRandomObjects(_objects); AuthAction newActionObject = new AuthAction { name = tempObject.Name, description = tempObject.Description }; Auth.Current.items.Add(newActionObject); }
public static void SendAuthMessage(string user, string secret) { AuthAction action = new AuthAction(user, secret); var bytes = Encoding.ASCII.GetBytes(action.ToString()); stream.Write(bytes, 0, bytes.Length); }
public PhoneAuthPhoneNumberEntryViewModel( AuthAction authAction, IObservable <Unit> whenVerified, IFirebaseAuthService firebaseAuthService = null, IViewStackService viewStackService = null) : base(viewStackService) { _firebaseAuthService = firebaseAuthService ?? Locator.Current.GetService <IFirebaseAuthService>(); var canExecute = this.WhenAnyValue( vm => vm.PhoneNumber, phoneNumber => { return(!string.IsNullOrEmpty(phoneNumber)); }); VerifyPhoneNumber = ReactiveCommand.CreateFromObservable( () => { if (authAction == AuthAction.SignIn) { return(_firebaseAuthService .SignInWithPhoneNumber(_phoneNumber) .SelectMany(result => HandleResult(authAction, result, whenVerified))); } else { return(_firebaseAuthService.CurrentUser .LinkWithPhoneNumber(PhoneNumberTest) .SelectMany(result => HandleResult(authAction, result, whenVerified))); } }, canExecute); VerifyPhoneNumber.ThrownExceptions .Subscribe( ex => { if (ex is FirebaseAuthException firebaseEx) { switch (firebaseEx.FirebaseAuthExceptionType) { case FirebaseAuthExceptionType.FirebaseAuth: Console.WriteLine(firebaseEx.Message); break; case FirebaseAuthExceptionType.FirebaseAuthInvalidCredentials: Console.WriteLine(firebaseEx.Message); break; } Console.WriteLine(firebaseEx.Message); } else { Console.WriteLine(ex.Message); } }); }
/// <summary> /// 修改操作 /// </summary> /// <param name="dto">传入操作信息</param> public void ModifyAction(ActionDto dto) { AuthAction entity = _actionRepository.Get(dto.Id); entity.Name = dto.Name; entity.Template = dto.Template; entity.Description = dto.Description; _actionRepository.Update(entity); }
private IObservable <Unit> HandleResult(AuthAction authAction, PhoneNumberSignInResult result, IObservable <Unit> completionObservable) { if (result.AuthResult != null) { return(completionObservable); } else { return(ViewStackService.PushPage(new PhoneAuthVerificationCodeEntryViewModel(authAction, result.VerificationId, completionObservable))); } }
public async Task <IActionResult> Create([Bind("Id,ControllerId,ActionTitle,ActionName")] AuthAction authAction) { if (ModelState.IsValid) { _context.Add(authAction); await _context.SaveChangesAsync(); return(RedirectToAction(nameof(Index))); } return(View(authAction)); }
public void OnLoaded(AuthAction authAction) { switch (authAction) { case AuthAction.Authorize: NavigateToAuthorizationPage(); break; case AuthAction.Deauthorize: NavigateToDeauthorizationPage(); break; } }
/// <summary> /// Create token /// 创建令牌 /// </summary> /// <param name="action">Action</param> /// <returns>Token</returns> public string CreateToken(AuthAction action) { // Token validation parameters var validataionParameters = new TokenValidationParameters { ValidIssuer = validIssuer, ValidIssuers = validIssuers, ValidAudience = action.Audience }; // Security key var keys = issuerSigningKeyResolver(string.Empty, null, action.KeyId, validataionParameters); var securityKey = string.IsNullOrEmpty(action.KeyId) || action.KeyId == DefaultIssuer?keys.FirstOrDefault() : keys.FirstOrDefault(item => !string.IsNullOrEmpty(item.KeyId) && item.KeyId.Equals(action.KeyId)); var encryptionKeys = tokenDecryptionKeyResolver(string.Empty, null, action.KeyId, validataionParameters); var encryptionKey = string.IsNullOrEmpty(action.KeyId) || action.KeyId == DefaultIssuer?encryptionKeys.FirstOrDefault() : encryptionKeys.FirstOrDefault(item => !string.IsNullOrEmpty(item.KeyId) && item.KeyId.Equals(action.KeyId)); // Enable only with private key if (securityKey == null || encryptionKey == null || (securityKey is RsaSecurityKey sk && sk.PrivateKeyStatus != PrivateKeyStatus.Exists)) { throw new InvalidOperationException("No Security Key"); } // Token handler var tokenHandler = new JwtSecurityTokenHandler(); // Token descriptor var tokenDescriptor = new SecurityTokenDescriptor { // User identity Subject = action.Claims, // TimeSpan.FromMinutes or TimeSpan.FromDays Expires = DateTime.UtcNow.AddTicks(action.LiveSpan.Ticks), // Issuer Issuer = validataionParameters.ValidIssuer, // Audience Audience = validataionParameters.ValidAudience, // JWE vs JWS // https://stackoverflow.com/questions/33589353/what-are-the-pros-cons-of-using-jwe-or-jws SigningCredentials = new SigningCredentials(securityKey, securityAlgorithms), EncryptingCredentials = new EncryptingCredentials(encryptionKey, SecurityAlgorithms.Aes256KeyWrap, SecurityAlgorithms.Aes256CbcHmacSha512) }; // Create the token return(tokenHandler.CreateEncodedJwt(tokenDescriptor)); }
public override Action Handle(Packet packet) { var authPacket = AuthAction.Parse(packet); if (authPacket == null || authPacket.Action == AuthType.Null || authPacket.OpenPort == null) { return(base.Handle(packet)); } int port = authPacket.OpenPort ?? 0; var responce = resolveAuthAction(authPacket); return(() => AuthRequested?.Invoke(responce, new IPEndPoint(packet.Sender.Address, port))); }
private AuthAction resolveAuthAction(AuthAction request) { switch (request.Action) { case AuthType.Null: return(request); case AuthType.Register: return(handleRegistration(request)); case AuthType.Login: return(handleLogin(request)); default: return(new AuthAction(request.Nickname, request.Password, AuthType.Null)); } }
public bool OnWebBrowserNavigated(string url, AuthAction authAction) { Debug.WriteLine($"Browser navigated to url = {url}\nAction = {authAction}"); switch (authAction) { case AuthAction.Authorize: var response = _vkAuthorization.TryToSetupTokenFromUrl(_token, url); if (response.Successful) { _eventAggregator.GetEvent <VkAuthorizationEvents.AcquiredTheToken>().Publish(_token); return(true); } return(false); case AuthAction.Deauthorize: return(true); } return(false); }
private void sendAuthResponce(AuthAction responce, IPEndPoint sender) { if (responce.Action == AuthType.Success) { var user = new PublicUser(sender, responce.Id.Value, responce.Nickname); if (Users.ContainsKey(sender)) { Console.WriteLine($"Multiple client access from ip " + sender); } else { Users.Add(sender, user); } } var buffer = responce.ToBytes(); _client.Send(buffer, buffer.Length, sender); }
public override Action Handle(Packet packet) { var authPacket = AuthAction.Parse(packet); if (authPacket == null || authPacket.Nickname == null) { return(base.Handle(packet)); } if (authPacket.OpenPort == null) { return () => { new Exception("Server doesn't provided open port"); } } ; var ip = new IPEndPoint(IPAddress.Loopback, authPacket.OpenPort.Value); switch (authPacket.Action) { case AuthType.UserExisting: return(() => { Error?.Invoke("Login is already reeserved"); }); case AuthType.WrongCredentials: return(() => { Error?.Invoke("Wrong password"); }); case AuthType.Success: { if (authPacket.Id == null) { return () => { new Exception("Server could not generete UUID"); } } ; Guid id = authPacket.Id.Value; return(() => { Success?.Invoke(new PublicUser(ip, id, authPacket.Nickname)); }); } default: return(() => { }); } } }
public PhoneAuthVerificationCodeEntryViewModel( AuthAction authAction, string verificationId, IObservable <Unit> whenVerified, IFirebaseAuthService firebaseAuthService = null, IViewStackService viewStackService = null) : base(viewStackService) { _firebaseAuthService = firebaseAuthService ?? Locator.Current.GetService <IFirebaseAuthService>(); var canExecute = this.WhenAnyValue(vm => vm.VerificationCode, code => code != null && code.Length == REQUIRED_CODE_LENGTH); VerifyCode = ReactiveCommand.CreateFromObservable( () => { if (authAction == AuthAction.SignIn) { return(_firebaseAuthService .SignInWithPhoneNumber(verificationId, VerificationCode) .SelectMany(_ => whenVerified)); } else { return(_firebaseAuthService.CurrentUser .LinkWithPhoneNumber(verificationId, VerificationCode) .ObserveOn(RxApp.MainThreadScheduler) .SelectMany(_ => whenVerified)); } }, canExecute); VerifyCode.ThrownExceptions .Subscribe( ex => { Console.WriteLine(ex.Message); }); }
private void sendAuthPacket(AuthAction packet) { var buffer = packet.ToBytes(); _client.Send(buffer, buffer.Length, _stanIP); }
public AuthController(AuthAction auth) { _auth = auth; }
private void LoadSiteStructure() { UnitOfWork unitOfWork = new UnitOfWork(); var assembly = Assembly.GetExecutingAssembly(); //AuthControllersRepository authControllersRepo = new AuthControllersRepository(); //AuthActionsRepository authActionsRepo = new AuthActionsRepository(); Dictionary <string, List <string> > StructureInAssembly = new Dictionary <string, List <string> >(); List <string> authActionsInAssembly = new List <string>(); foreach (Type T in assembly.GetTypes()) { if (typeof(BaseController).IsAssignableFrom(T)) { foreach (MethodInfo mi in T.GetMethods()) { if (mi.ReturnType == typeof(ActionResult) || mi.ReturnType == typeof(JsonResult) || mi.ReturnType == typeof(Task <ActionResult>)) { authActionsInAssembly.Add(mi.Name); } } StructureInAssembly.Add(T.Name, authActionsInAssembly); authActionsInAssembly = new List <string>(); } } Dictionary <string, List <string> > StructureInDb = new Dictionary <string, List <string> >(); List <string> authActionsInDb = new List <string>(); var authControllers = unitOfWork.AuthControllersRepository.GetAll(); foreach (var authController in authControllers) { foreach (var authAction in authController.AuthActions) { if (authController.Id == authAction.AuthControllerId) { authActionsInDb.Add(authAction.Name); } } StructureInDb.Add(authController.Name, authActionsInDb); authActionsInDb = new List <string>(); } foreach (KeyValuePair <string, List <string> > kvPair in StructureInAssembly) { var structureInDb = StructureInDb.FirstOrDefault(kv => kv.Key == kvPair.Key); if (structureInDb.Key == null) { AuthController authController = new AuthController(); authController.Name = kvPair.Key; unitOfWork.AuthControllersRepository.Save(authController); foreach (var item in kvPair.Value) { AuthAction authAction = new AuthAction(); authAction.Name = item; authAction.AuthController = authController; unitOfWork.AuthActionsRepository.Save(authAction); } } else { foreach (string action in kvPair.Value) { string actionInDb = structureInDb.Value.FirstOrDefault(v => v == action); if (actionInDb == null) { AuthController authController = unitOfWork.AuthControllersRepository.GetAll(a => a.Name == kvPair.Key).FirstOrDefault(); AuthAction authAction = new AuthAction(); authAction.Name = action; authAction.AuthController = authController; unitOfWork.AuthActionsRepository.Save(authAction); } } } } foreach (KeyValuePair <string, List <string> > kvPair in StructureInDb) { KeyValuePair <string, List <string> > structureInAssembly = StructureInAssembly.FirstOrDefault(kv => kv.Key == kvPair.Key); if (structureInAssembly.Key == null) { AuthController authController = unitOfWork.AuthControllersRepository.GetAll(c => c.Name == kvPair.Key).FirstOrDefault(); foreach (var item in kvPair.Value) { AuthAction authAction = unitOfWork.AuthActionsRepository.GetAll(a => a.AuthController.Id == authController.Id).FirstOrDefault(); unitOfWork.AuthActionsRepository.Delete(authAction.Id); } unitOfWork.AuthControllersRepository.Delete(authController.Id); } else { foreach (string action in kvPair.Value) { string actionToAdd = structureInAssembly.Value.FirstOrDefault(v => v == action); if (actionToAdd == null) { AuthAction authAction = unitOfWork.AuthActionsRepository.GetAll(a => a.Name == action).FirstOrDefault(); unitOfWork.AuthActionsRepository.Delete(authAction.Id); unitOfWork.Save(); } } } } unitOfWork.Save(); }
public AuthResultModel(AuthAction action) { _action = action; }
protected void Auth(Id id, AuthAction action) { User user = GetUser(); if (!AuthorizeService.IsAuthorized(user, id.ToScope(), action)) throw new UserNotAuthorizedException(user.Name, action.ToString()); }
protected void Auth(AuthAction action) { Auth(null, action); }
public static void Load() { var assembly = Assembly.GetExecutingAssembly(); var authControllerRepo = new AuthControllerRepository(); var authActionRepo = new AuthActionRepository(); var controllersInAssembly = new List <AuthController>(); foreach (Type T in assembly.GetTypes()) { if (typeof(Controller).IsAssignableFrom(T)) { AuthController controller = new AuthController(); controller.Name = T.Name; controller.AuthActions = T.GetMethods().Where(m => typeof(ActionResult).IsAssignableFrom(m.ReturnType)).Select( m => new AuthAction { AuthController = controller, Name = m.Name, MethodType = m.GetCustomAttribute <HttpPostAttribute>() == null ? AuthAction.Method.GET : AuthAction.Method.POST }).ToList(); controllersInAssembly.Add(controller); } } var controllersInDb = authControllerRepo.GetAll(); foreach (AuthController controller in controllersInDb) { var controllerInAssembly = controllersInAssembly.FirstOrDefault(c => c.Name == controller.Name); if (controllersInAssembly == null) { while (controller.AuthActions.Count > 0) { authActionRepo.Delete(controller.AuthActions.First()); } authControllerRepo.Delete(controller); continue; } List <AuthAction> actionsToDelete = new List <AuthAction>(); List <AuthAction> actionsToUpdate = new List <AuthAction>(); foreach (AuthAction action in controller.AuthActions) { AuthAction actionInAssembly = controllerInAssembly.AuthActions.FirstOrDefault(a => a.Name == action.Name); if (actionInAssembly == null) { actionsToDelete.Add(action); continue; } if (actionInAssembly.MethodType == action.MethodType) { controllerInAssembly.AuthActions.Remove(actionInAssembly); continue; } else { action.MethodType = actionInAssembly.MethodType; actionsToUpdate.Add(action); controllerInAssembly.AuthActions.Remove(actionInAssembly); } } actionsToDelete.ForEach(a => authActionRepo.Delete(a)); actionsToDelete.ForEach(a => authActionRepo.Save(a)); foreach (var newAction in controllerInAssembly.AuthActions) { newAction.AuthController = controller; authActionRepo.Save(newAction); } controllersInAssembly.Remove(controllerInAssembly); } controllersInAssembly.ForEach(c => authControllerRepo.Save(c)); }
/// <summary> /// Gets whether the user is authorized to perform the action within /// the given context based on the role matrix. The role matrix /// is first checked at the collection level and then it bubbles up /// to the workspace level and onto the service level and then /// finally the default built-in role matrix. /// </summary> /// <param name="user">The user.</param> /// <param name="id">The entry Id or the collection Id.</param> /// <param name="action">The action.</param> /// <returns></returns> public bool IsAuthorized(User user, Scope scope, AuthAction action) { return IsAuthorized(GetRoles(user, scope), scope, action); }
/// <summary> /// Gets whether any of the roles are authorized to perform the action within /// the given context based on the role matrix. The role matrix /// is first checked at the collection level and then it bubbles up /// to the workspace level and onto the service level and then /// finally the default built-in role matrix. /// </summary> /// <param name="user">The user.</param> /// <param name="id">The entry Id or the collection Id.</param> /// <param name="action">The action.</param> /// <returns></returns> public bool IsAuthorized(AuthRoles roles, Scope scope, AuthAction action) { RoleMatrix rm = null; RoleAction ra = null; AppService appService = AppServiceRepository.GetService(); if (!scope.IsEntireSite) { var w = appService.GetWorkspace(scope.Workspace); if (scope.IsCollection) { //try collection level first rm = w.GetCollection(scope.Collection).RoleMatrix; if (rm != null) ra = rm.RoleActions.Where(a => a.Name == action.ToString()).FirstOrDefault(); } //try workspace level next if (ra == null) { rm = w.RoleMatrix; if (rm != null) ra = rm.RoleActions.Where(a => a.Name == action.ToString()).FirstOrDefault(); } } //service level if (ra == null) { rm = appService.RoleMatrix; if (rm != null) ra = rm.RoleActions.Where(a => a.Name == action.ToString()).FirstOrDefault(); } //use default role matrix if (ra == null) { rm = RoleMatrix.Default; if (rm != null) ra = rm.RoleActions.Where(a => a.Name == action.ToString()).FirstOrDefault(); } if (ra == null) { LogService.Warn("Action not found in any role matrix."); return false; } return ((ra.AuthRoles & roles) > AuthRoles.None); }
/// <summary> /// 删除操作 /// </summary> /// <param name="dto">传入操作信息</param> public void DeleteAction(ActionDto dto) { AuthAction entity = _actionRepository.Get(dto.Id); _actionRepository.Delete(entity); }
/// <summary> /// 添加操作 /// </summary> /// <param name="dto">传入操作信息</param> public void AddAction(ActionDto dto) { AuthAction entity = dto.ToEntity <AuthAction> (); _actionRepository.Add(entity); }
/// <summary> /// 获取操作信息 /// </summary> /// <param name="Id">操作唯一标识</param> /// <returns>操作信息</returns> public ActionDto GetAction(string Id) { AuthAction entity = _actionRepository.Get(Id); return(entity.ToDto <ActionDto>()); }
public static void Auth(this IAuthorizeService auth, Scope scope, AuthAction action) { User user = System.Threading.Thread.CurrentPrincipal.Identity as User; if (!auth.IsAuthorized(auth.GetRoles(user, scope), scope, action)) throw new UserNotAuthorizedException(user.Name, action.ToString()); }