Esempio n. 1
0
        public IActionResult Delete(string postUuid)
        {
            var user = _authHandler.UserFromClaimsPrincipal(User);

            if (!SecureGuid.VerifyGuid(postUuid, out _))
            {
                _logger.LogInformation("Post UUID is invalid.");
                _logger.LogInformation($"Terminating session. User: {user.Uuid}" +
                                       $", IP: {HttpContext?.Connection?.RemoteIpAddress?.ToString() ?? "Unknown IP"}");
                _authHandler.TerminateSession(user);

                return(BadRequest());
            }


            var post = new Post
            {
                Uuid = postUuid
            };

            if (_database.DeletePost(post, user))
            {
                _activityLogger.LogDeletePost(Request.HttpContext.Connection.RemoteIpAddress, user, post);
                return(Ok());
            }

            _logger.LogInformation("DB failed to delete post.");
            _logger.LogInformation($"Terminating session. User: {user.Uuid}" +
                                   $", IP: {HttpContext?.Connection?.RemoteIpAddress?.ToString() ?? "Unknown IP"}");
            _authHandler.TerminateSession(user);

            return(BadRequest());
        }
Esempio n. 2
0
        public IActionResult Get(string uuid)
        {
            var user = _authHandler.UserFromClaimsPrincipal(User);

            if (!SecureGuid.VerifyGuid(uuid, out var postGuid))
            {
                _logger.LogInformation("Post UUID is invalid.");
                _logger.LogInformation($"Terminating session. User: {user.Uuid}" +
                                       $", IP: {HttpContext?.Connection?.RemoteIpAddress?.ToString() ?? "Unknown IP"}");
                _authHandler.TerminateSession(user);

                return(BadRequest());
            }


            var postInfo = _database.GetPostInfo(postGuid);

            if (postInfo == null)
            {
                _logger.LogInformation("Post does not exist.");
                _logger.LogInformation($"Terminating session. User: {user.Uuid}" +
                                       $", IP: {HttpContext?.Connection.RemoteIpAddress.ToString() ?? "Unknown IP"}");
                _authHandler.TerminateSession(user);

                return(BadRequest());
            }

            var comments = _database.GetCommentsByPost(postGuid);

            postInfo.Comments = comments;

            return(Ok(postInfo));
        }
Esempio n. 3
0
        private async Task <JObject> ConvertToJsonAsync(MasterDataKeyValue service, int newId)
        {
            var lastModifieUser =
                await _securityContext.Users.SingleOrDefaultAsync(us => us.Id == service.CreateUserId);

            return(JObject.FromObject(new
            {
                service.Id,
                service.Guid,
                NewGuid = SecureGuid.NewGuid().ToString("N"),
                NewId = newId,
                service.PathOrUrl,
                service.Key,
                service.Name,
                service.Code,
                service.Description,
                service.EditMode,
                service.SlidingExpirationTimeInMinutes,
                service.IsLeaf,
                service.ParentId,
                service.Order,
                service.ViewRoleId,
                service.ModifyRoleId,
                service.AccessRoleId,
                service.Version,
                service.EnableCache,
                service.Status,
                service.RowVersion,
                LastModifieUser = lastModifieUser.UserName,
                LastModifieLocalDateTime = service.ModifieLocalDateTime,
                JsCode = await GetResorcesAsync(service)
            }));
        }
Esempio n. 4
0
        public bool CreateComment(Comment comment, User user)
        {
            if (!SecureGuid.VerifyGuid(comment.Post, out var postGuid))
            {
                return(false);
            }

            using var conn = new MySqlConnection(_connectionStringBuilder.ConnectionString);
            conn.Open();
            using var command   = conn.CreateCommand();
            command.CommandText = "newComment";
            command.CommandType = CommandType.StoredProcedure;
            command.Parameters.Add("@postUUID", MySqlDbType.Binary, 16).Value    = postGuid.ToByteArray();
            command.Parameters.Add("@userUUID", MySqlDbType.Binary, 16).Value    = user.Uuid.ToByteArray();
            command.Parameters.Add("@commentUUID", MySqlDbType.Binary, 16).Value =
                SecureGuid.CreateSecureRfc4122Guid().ToByteArray();
            command.Parameters.AddWithValue("@commentContent", comment.Content);
            try
            {
                command.ExecuteNonQuery();
                return(true);
            }
            catch (MySqlException)
            {
                return(false);
            }
        }
Esempio n. 5
0
 public static async Task <HttpResponseMessage> GetAsync(
     [QueryParameter(Name = StatePropertyName)] string state,
     [QueryParameter(Name = ClientPropertyName)] IRef <Client> clientRef,
     [QueryParameter(Name = ValidationPropertyName)] string validation,
     Api.Azure.AzureApplication application, UrlHelper urlHelper,
     //ContentTypeResponse<Authentication> onFound,
     RedirectResponse onFound,
     ReferencedDocumentNotFoundResponse <Client> onInvalidClient)
 {
     return(await await clientRef.StorageGetAsync(
                (client) =>
     {
         var authentication = new Authentication
         {
             authenticationRef = SecureGuid.Generate().AsRef <Authentication>(),
             state = state,
         };
         return authentication.StorageCreateAsync(
             (entity) =>
         {
             var location = urlHelper.GetLocation <Authentication>(
                 auth => auth.authenticationRef.AssignQueryValue(authentication.authenticationRef),
                 application);
             return onFound(location);
         },
             () => throw new Exception("Secure guid not unique"));
     },
                () => onInvalidClient().AsTask()));
 }
Esempio n. 6
0
        public bool RegisterUser(ref User user)
        {
            if (user.TotpToken == null)
            {
                _logger.LogInformation("TOTP token has not been generated.");
                return(false);
            }

            if (!VerifyPassword(user.Password))
            {
                _logger.LogInformation("Password verification failed.");
                return(false);
            }

            if (!VerifyUsername(user.Username))
            {
                _logger.LogInformation("Username verification failed.");
                return(false);
            }

            user.PasswordHash = Pbkdf2Password.PasswordToHash(user.Password);
            user.Uuid         = SecureGuid.CreateSecureRfc4122Guid();
            _database.AddUser(user);
            _emailSender.SendRegisterEmail(user);
            return(true);
        }
Esempio n. 7
0
        /// <summary>
        /// Adds an image to the repository with the specified image processing options.
        /// </summary>
        /// <param name="stream">The stream source containing the image.</param>
        /// <param name="options">The image processing options.</param>
        /// <returns>The image key to access the image.</returns>
        public ImageKey Add(Stream stream, ImageOptions options)
        {
            var id     = SecureGuid.Create();
            var format = Add(id, null, stream, options);

            return(new ImageKey(id, format));
        }
        public IActionResult NewComment([FromBody] Comment comment)
        {
            var user = _authHandler.UserFromClaimsPrincipal(User);

            if (string.IsNullOrWhiteSpace(comment.Content) || string.IsNullOrWhiteSpace(comment.Post) ||
                string.IsNullOrWhiteSpace(comment.Captcha))
            {
                _logger.LogInformation("Comment content, post or captcha is missing.");
                _logger.LogInformation($"Terminating session. User: {user.Uuid}" +
                                       $", IP: {HttpContext?.Connection?.RemoteIpAddress?.ToString() ?? "Unknown IP"}");
                _authHandler.TerminateSession(user);

                return(BadRequest());
            }

            if (!_captcha.VerifyCaptcha(comment.Captcha, HttpContext.Connection.RemoteIpAddress, "newComment"))
            {
                _logger.LogInformation("Captcha failed verification.");
                _logger.LogInformation($"Terminating session. User: {user.Uuid}" +
                                       $", IP: {HttpContext?.Connection?.RemoteIpAddress?.ToString() ?? "Unknown IP"}");
                _authHandler.TerminateSession(user);

                return(BadRequest());
            }


            if (comment.Content.Length > 128)
            {
                _logger.LogInformation("Comment content length exceeds the permitted limit.");
                _logger.LogInformation($"Terminating session. User: {user.Uuid}" +
                                       $", IP: {HttpContext?.Connection?.RemoteIpAddress?.ToString() ?? "Unknown IP"}");
                _authHandler.TerminateSession(user);

                return(BadRequest());
            }

            if (!SecureGuid.VerifyGuid(comment.Post, out _))
            {
                _logger.LogInformation("Post UUID is invalid.");
                _logger.LogInformation($"Terminating session. User: {user.Uuid}" +
                                       $", IP: {HttpContext?.Connection?.RemoteIpAddress?.ToString() ?? "Unknown IP"}");
                _authHandler.TerminateSession(user);

                return(BadRequest());
            }


            if (_database.CreateComment(comment, user))
            {
                _activityLogger.LogNewComment(Request.HttpContext.Connection.RemoteIpAddress, user, comment);
                return(Ok());
            }

            _logger.LogInformation("Database failed to create new comment.");
            _logger.LogInformation($"Terminating session. User: {user.Uuid}" +
                                   $", IP: {HttpContext?.Connection?.RemoteIpAddress?.ToString() ?? "Unknown IP"}");
            _authHandler.TerminateSession(user);

            return(BadRequest());
        }
Esempio n. 9
0
        public IActionResult Get(string uuid)
        {
            var user = _authHandler.UserFromClaimsPrincipal(User);

            if (!SecureGuid.VerifyGuid(uuid, out _))
            {
                _logger.LogInformation("Invalid Topic UUID");
                _logger.LogInformation($"Terminating session. User: {user.Uuid}" +
                                       $", IP: {HttpContext?.Connection.RemoteIpAddress.ToString() ?? "Unknown IP"}");
                _authHandler.TerminateSession(user);

                return(BadRequest());
            }

            var topicInfo = _database.GetTopics(uuid);

            if (topicInfo.Count != 1)
            {
                _logger.LogInformation("Topic UUID does nto exist");
                _logger.LogInformation($"Terminating session. User: {user.Uuid}" +
                                       $", IP: {HttpContext?.Connection.RemoteIpAddress.ToString() ?? "Unknown IP"}");
                _authHandler.TerminateSession(user);
            }

            var posts = _database.GetPostByTopic(new Guid(uuid));

            topicInfo[0].Posts = posts;
            return(Ok(topicInfo[0]));
        }
Esempio n. 10
0
 internal async Task <TResult> CreateLoginAsync <TResult>(Guid authenticationRequestId, Guid authenticationId,
                                                          CredentialValidationMethodTypes method, Uri callbackLocation, IDictionary <string, string> authParams,
                                                          Func <Session, TResult> onSuccess,
                                                          Func <TResult> onAlreadyExists,
                                                          Func <string, TResult> onFailure)
 {
     return(await EastFive.Web.Configuration.Settings.GetUri(
                EastFive.Security.AppSettings.TokenScope,
                async (scope) =>
     {
         var sessionId = SecureGuid.Generate();
         var claims = await this.context.Claims.FindByAccountIdAsync(authenticationId,
                                                                     (cs) => cs.Select(c => c.Type.PairWithValue(c.Value)).ToDictionary(),
                                                                     () => new Dictionary <string, string>());
         return await Sessions.GenerateToken(sessionId, authenticationId, claims,
                                             (token) => this.dataContext.AuthenticationRequests.CreateAsync(authenticationRequestId,
                                                                                                            method, AuthenticationActions.signin, authenticationId, token, callbackLocation, callbackLocation,
                                                                                                            () =>
         {
             telemetry.TrackEvent("Sessions.CreateLoginAsync - Create Session", authParams);
             var session = new Session()
             {
                 id = authenticationRequestId,
                 method = method,
                 action = AuthenticationActions.signin,
                 token = token,
                 extraParams = authParams
             };
             return onSuccess(session);
         },
                                                                                                            onAlreadyExists),
                                             why => onFailure(why).ToTask());
     },
                onFailure.AsAsyncFunc()));
 }
Esempio n. 11
0
        public IActionResult Login(LoginInput input)
        {
            if (string.IsNullOrWhiteSpace(input.Username) || string.IsNullOrWhiteSpace(input.Password))
            {
                _logger.LogInformation("Username or password is null or empty");
                return(Unauthorized());
            }

            if (input.Username.Length > 50)
            {
                _logger.LogInformation("Username exceeds permitted length.");
                return(Unauthorized());
            }

            if (input.Password.Length > 64)
            {
                _logger.LogInformation("Password exceeds permitted length.");
                return(Unauthorized());
            }

            if (string.IsNullOrWhiteSpace(input.Captcha))
            {
                _logger.LogInformation("Captcha is null or empty");
                return(Unauthorized());
            }

            if (!_captcha.VerifyCaptcha(input.Captcha, Request.HttpContext.Connection.RemoteIpAddress, "login"))
            {
                _logger.LogInformation("Captcha rejected.");
                return(Unauthorized());
            }

            var user = new User
            {
                Username = input.Username,
                Password = input.Password
            };


            if (_authHandler.LoginUser(ref user))
            {
                var registerGuid      = SecureGuid.CreateSecureRfc4122Guid();
                var cacheEntryOptions = new MemoryCacheEntryOptions().SetAbsoluteExpiration(TimeSpan.FromMinutes(5));
                _memoryCache.Set("L1" + registerGuid, user, cacheEntryOptions);

                var response = new MessageResponse
                {
                    Message = registerGuid.ToString(),
                    Status  = "Ok"
                };
                return(Ok(response));
            }

            _logger.LogInformation("Auth handler rejected login.");
            return(Unauthorized());
        }
 private static Resources.AuthenticationRequestLink Convert(CredentialValidationMethodTypes method, UrlHelper urlHelper)
 {
     return(new Resources.AuthenticationRequestLink
     {
         Id = urlHelper.GetWebId <Controllers.SessionController>(SecureGuid.Generate()),
         Method = method,
         Name = method.ToString(),
         SecureId = SecureGuid.Generate(),
     });
 }
Esempio n. 13
0
        private static async Task <Auth.Session> CreateSession(string userIdentification,
                                                               IAzureApplication application, IHttpRequest request)
        {
            var authentication = new Authentication
            {
                authenticationRef  = Ref <Authentication> .SecureRef(),
                authenticated      = DateTime.UtcNow,
                userIdentification = userIdentification,
                token = SecureGuid.Generate().ToString("N"),
            };

            return(await await authentication
                   .StorageCreateAsync(
                       async (authenticationDiscard) =>
            {
                var method = EastFive.Azure.Auth.Method.ByMethodName(
                    CredentialProvider.IntegrationName, application);

                var parameters = new Dictionary <string, string>()
                {
                    { "state", authentication.authenticationRef.id.ToString() },
                    { "token", authentication.token },
                    { CredentialProvider.referrerKey, "https://example.com/internal" }
                };


                return await await method.RedeemTokenAsync(parameters, application,
                                                           async(externalAccountKey, authorizationRefMaybe, loginProvider, extraParams) =>
                {
                    var authorization = new Auth.Authorization
                    {
                        authorizationRef = new Ref <Auth.Authorization>(Security.SecureGuid.Generate()),
                        Method = method.authenticationId,
                        parameters = extraParams,
                        authorized = true,
                    };

                    return await await Auth.Redirection.AuthorizeWithAccountAsync(
                        authorization,
                        async(authorizationToSave) =>
                    {
                        bool created = await authorizationToSave.StorageCreateAsync(
                            discard => true);
                    },
                        method,
                        externalAccountKey, extraParams,
                        application, request, loginProvider,
                        request.RequestUri,
                        async(accountId, authorizationUpdated) =>
                    {
                        return await CreateSessionAsync(authorization);
                    },
                        (interruptTo, accountId, authorizationUpdated) => throw new Exception($"Cannot redirect to `{interruptTo}`"),
                        (why, authorizationUpdated) => throw new Exception(why),
Esempio n. 14
0
        private static Resources.AuthenticationRequestLink Convert(KeyValuePair <string, IProvideLogin> providerPair, UrlHelper urlHelper)
        {
            var method = providerPair.Key;
            var name   = providerPair.Value is IProvideIntegration integrationProvider?integrationProvider.GetDefaultName(null) : method.ToString();

            return(new Resources.AuthenticationRequestLink
            {
                Id = urlHelper.GetWebId <Controllers.SessionController>(SecureGuid.Generate()),
                Method = method,
                Name = name,
                SecureId = SecureGuid.Generate(),
            });
        }
        public async Task <JObject> GetWebPageContent(string url, int typeId)
        {
            var form = await _webPageBiz.GetWebPageForEditAsync(HttpUtility.UrlDecode(url.Replace(" ", "%")).Replace(Config.UrlDelimeter, Helper.RootUrl).Replace("#", ""), typeId);

            if (form != null)
            {
                return(form);
            }

            return(JObject.Parse(JsonConvert.SerializeObject(new WebPage()
            {
                Guid = SecureGuid.NewGuid().ToString("N")
            }, Formatting.None)));
        }
Esempio n. 16
0
        public static async Task <IHttpResponse> GetAsync(
            //[WorkflowNewId]
            //[WorkflowVariable(
            //    Workflows.PasswordLoginCreateAccount.Variables.State,
            //    AuthorizationPropertyName)]
            [OptionalQueryParameter(Name = AuthorizationPropertyName)]
            IRefOptional <Authorization> authorizationRefOptional,

            [WorkflowParameter(
                 Value = "d989b604-1e25-4d77-b79e-fe1c7d36f833",
                 Description = "Unique and static to each client (i.e. iOS or Web)")]
            [QueryParameter(Name = ClientPropertyName)]
            IRef <Client> clientRef,

            [WorkflowNewId(Description = "No idea what this does.")]
            [OptionalQueryParameter(Name = ValidationPropertyName)]
            string validation,

            IAuthApplication application, IProvideUrl urlHelper,
            //ContentTypeResponse<Authentication> onFound,

            [WorkflowVariable(
                 Workflows.PasswordLoginCreateAccount.Variables.Authorization,
                 Authentication.AuthenticationPropertyName)]
            [WorkflowVariableRedirectUrl(
                 VariableName = Workflows.PasswordLoginCreateAccount.Variables.AuthorizationRedirect)]
            RedirectResponse onFound,

            ReferencedDocumentNotFoundResponse <Client> onInvalidClient)
        {
            return(await await clientRef.StorageGetAsync(
                       (client) =>
            {
                var authentication = new Authentication
                {
                    authenticationRef = SecureGuid.Generate().AsRef <Authentication>(),
                    authorizationMaybe = authorizationRefOptional,
                    client = clientRef,
                };
                return authentication.StorageCreateAsync(
                    (entity) =>
                {
                    var location = urlHelper.GetLocation <Authentication>(
                        auth => auth.authenticationRef.AssignQueryValue(authentication.authenticationRef),
                        application);
                    return onFound(location);
                });
            },
                       () => onInvalidClient().AsTask()));
        }
        public async Task <TResult> SendEmailInviteAsync <TResult>(Guid inviteId, Guid actorId, string email,
                                                                   Guid performingActorId, System.Security.Claims.Claim[] claims,
                                                                   Func <Guid, Guid, Uri> getRedirectLink,
                                                                   Func <TResult> success,
                                                                   Func <TResult> inviteAlreadyExists,
                                                                   Func <TResult> onCredentialMappingDoesNotExists,
                                                                   Func <TResult> onUnauthorized,
                                                                   Func <TResult> onServiceNotAvailable,
                                                                   Func <string, TResult> onFailed)
        {
            if (!await Library.configurationManager.CanAdministerCredentialAsync(actorId, performingActorId, claims))
            {
                return(onUnauthorized());
            }

            var token   = SecureGuid.Generate();
            var loginId = Guid.NewGuid(); // This creates a "user" in the invite system
            var result  = await await this.dataContext.CredentialMappings.CreateCredentialMappingAsync(inviteId,
                                                                                                       loginId, actorId, email, token, DateTime.UtcNow, false, false,
                                                                                                       async() =>
            {
                var templateName = ConfigurationManager.AppSettings[Configuration.EmailTemplateDefinitions.InviteNewAccount];
                if (string.IsNullOrEmpty(templateName))
                {
                    return(onFailed($"Email template setting not found.  Expected template value for key {Configuration.EmailTemplateDefinitions.InviteNewAccount}"));
                }

                var mailService = Web.Services.ServiceConfiguration.SendMessageService();
                var resultMail  = await mailService.SendEmailMessageAsync(templateName,
                                                                          email, string.Empty,
                                                                          "*****@*****.**", "New Account Services",
                                                                          "New Order Owl Account",
                                                                          new Dictionary <string, string>()
                {
                    { "create_account_link", getRedirectLink(inviteId, token).AbsoluteUri }
                },
                                                                          null,
                                                                          (sentCode) => success(),
                                                                          () => onServiceNotAvailable(),
                                                                          (why) => onFailed(why));
                return(resultMail);
            },
                                                                                                       () => inviteAlreadyExists().ToTask(),
                                                                                                       () => { throw new Exception("Token generated was not unique"); },
                                                                                                       () => { throw new Exception("Login Id generated was not unique"); });

            return(result);
        }
        public void EndLogRequest(IOwinRequest request, bool isSuccessed)
        {
            try
            {
                if (!Config.EnableActionLog || !EnableLog)
                {
                    return;
                }
                if (ServiceName == null)
                {
                    return;
                }
                double duration = 0;
                if (StartTime != null)
                {
                    duration = (DateTime.Now.TimeOfDay - TimeSpan.Parse(StartTime)).TotalMilliseconds;
                }



                AddedLogDictionary.TryAdd(SecureGuid.NewGuid().ToString(), new ActionLog()
                {
                    ServiceUrl = ServiceUrl ?? "?",
                    Ip         = request.RemoteIpAddress,
                    Url        = request.Path.Value,
                    Parameters = Helper.UrlDecode(request.Method.ToLower() == "get" ? ReadableStringCollectionToString(request.Query) : Body),
                    //ReadableStringCollectionToString(request.ReadFormAsync().Result)),
                    Type          = request.Method,
                    Coockies      = JsonConvert.SerializeObject(CookieManager.GetAll()),
                    Request       = Helper.UrlDecode(ReadableStringCollectionToString(request.Headers)),
                    DateTime      = DateTime.UtcNow,
                    IsDebugMode   = Settings.IsDebugMode,
                    IsMobileMode  = Settings.IsMobileMode,
                    LocalDateTime = LanguageManager.ToLocalDateTime(DateTime.UtcNow),
                    Name          = ServiceName ?? "?",
                    User          = CurrentUserManager.UserName,
                    ExecutionTimeInMilliseconds = duration,
                    IsSuccessed = isSuccessed,
                    UrlReferrer =
                        Helper.UrlDecode(
                            (UrlReferrer ?? request.Uri.AbsoluteUri ?? new Uri("http://unknown").AbsoluteUri).ToString())
                });
            }
            catch (Exception ex)
            {
                LogException(ex.ToString());
            }
        }
Esempio n. 19
0
        public IActionResult RegisterTest()
        {
            if (_webHostEnvironment.IsDevelopment())
            {
                var user = new User
                {
                    Uuid     = SecureGuid.CreateSecureRfc4122Guid(),
                    Username = "******"
                };

                var token = _authHandler.GenerateToken(user);
                return(Ok(token));
            }

            return(NotFound());
        }
        public async Task <string> GetWcfGenreatedCode(JObject data)
        {
            var wcfGuid = SecureGuid.NewGuid().ToString("N");

            //save xml as file by guid name;
            await _dotNetBiz.WriteWcfWebServiceMetaDataAsync(data, wcfGuid);


            dynamic wcfData = data;

            return(_dotNetBiz.GetWcfWebServiceCode(HttpContext.Current.Request.Url.Scheme + "://"
                                                   + (HttpContext.Current.Request.Url.Authority +
                                                      "/develop/code/os/dotnet/WebService/GetWcfGenreatedCode/" +
                                                      wcfGuid).Replace("//", "/"),
                                                   (string)wcfData.Language));
        }
Esempio n. 21
0
 public static Task <TResult> CreateByMethodAndKeyAsync <TResult>(IRef <Method> methodRef,
                                                                  Guid accountId, IDictionary <string, string> parameters,
                                                                  Func <XIntegration, Authorization, TResult> onCreated,
                                                                  Func <string, TResult> onFailure)
 {
     return(CreateByMethodAndKeyAsync(
                Guid.NewGuid().AsRef <XIntegration>(),
                SecureGuid.Generate().AsRef <Authorization>(),
                methodRef,
                accountId,
                parameters,
                onCreated,
                () => throw new Exception("Guid not unique"),
                () => throw new Exception("Guid not unique"),
                onFailure));
 }
Esempio n. 22
0
        public IActionResult UpdatePost(Post post)
        {
            var user = _authHandler.UserFromClaimsPrincipal(User);

            if (string.IsNullOrWhiteSpace(post.Content) || string.IsNullOrWhiteSpace(post.Uuid))
            {
                _logger.LogInformation("Post content or uuid is null or empty.");
                _logger.LogInformation($"Terminating session. User: {user.Uuid}" +
                                       $", IP: {HttpContext?.Connection?.RemoteIpAddress?.ToString() ?? "Unknown IP"}");
                _authHandler.TerminateSession(user);
                return(BadRequest());
            }

            if (!SecureGuid.VerifyGuid(post.Uuid, out _))
            {
                _logger.LogInformation("Post UUID is invalid.");
                _logger.LogInformation($"Terminating session. User: {user.Uuid}" +
                                       $", IP: {HttpContext?.Connection?.RemoteIpAddress?.ToString() ?? "Unknown IP"}");
                _authHandler.TerminateSession(user);
                return(BadRequest());
            }


            if (!_database.VerifyPostUser(user, post))
            {
                _logger.LogInformation("Requester is not post creator.");
                _logger.LogInformation($"Terminating session. User: {user.Uuid}" +
                                       $", IP: {HttpContext?.Connection?.RemoteIpAddress?.ToString() ?? "Unknown IP"}");
                _authHandler.TerminateSession(user);

                return(BadRequest());
            }

            if (_database.UpdatePost(post, user))
            {
                _activityLogger.LogEditPost(Request.HttpContext.Connection.RemoteIpAddress, user, post);
                return(Ok());
            }

            _logger.LogInformation("DB failed to edit post.");
            _logger.LogInformation($"Terminating session. User: {user.Uuid}" +
                                   $", IP: {HttpContext?.Connection.RemoteIpAddress.ToString() ?? "Unknown IP"}");
            _authHandler.TerminateSession(user);

            return(BadRequest());
        }
Esempio n. 23
0
 public async Task <TResult> CreateLinkAsync <TResult>(Guid integrationId,
                                                       Uri callbackLocation,
                                                       string method, Uri redirectUrl,
                                                       Guid authenticationId, Guid actorId, System.Security.Claims.Claim[] claims,
                                                       Func <Type, Uri> typeToUrl,
                                                       Func <Session, TResult> onSuccess,
                                                       Func <TResult> onAlreadyExists,
                                                       Func <string, TResult> onUnauthorized,
                                                       Func <TResult> onCredentialSystemNotAvailable,
                                                       Func <string, TResult> onCredentialSystemNotInitialized,
                                                       Func <string, TResult> onFailure)
 {
     if (!await Library.configurationManager.CanAdministerCredentialAsync(authenticationId, actorId, claims))
     {
         return(onUnauthorized($"Provided token does not permit access to link {authenticationId} to a login"));
     }
     return(await Context.GetLoginProvider <Task <TResult> >(method,
                                                             async (provider) =>
     {
         var sessionId = SecureGuid.Generate();
         return await BlackBarLabs.Security.Tokens.JwtTools.CreateToken <Task <TResult> >(sessionId, callbackLocation, TimeSpan.FromMinutes(30),
                                                                                          async(token) => await await this.dataContext.AuthenticationRequests.CreateAsync <Task <TResult> >(integrationId,
                                                                                                                                                                                            method, AuthenticationActions.access, authenticationId, token, redirectUrl, redirectUrl,
                                                                                                                                                                                            () => dataContext.Integrations.CreateUnauthenticatedAsync(integrationId, authenticationId, method,
                                                                                                                                                                                                                                                      () => onSuccess(
                                                                                                                                                                                                                                                          new Session()
         {
             id = integrationId,
             //method = method,
             name = method.ToString(),
             action = AuthenticationActions.access,
             loginUrl = provider.GetLoginUrl(integrationId, callbackLocation, typeToUrl),
             logoutUrl = provider.GetLogoutUrl(integrationId, callbackLocation, typeToUrl),
             redirectUrl = redirectUrl,
             authorizationId = authenticationId,
             token = token,
         }),
                                                                                                                                                                                                                                                      onAlreadyExists),
                                                                                                                                                                                            onAlreadyExists.AsAsyncFunc()),
                                                                                          why => onFailure(why).ToTask(),
                                                                                          (param, why) => onFailure($"Invalid configuration for {param}:{why}").ToTask());
     },
                                                             onCredentialSystemNotAvailable.AsAsyncFunc(),
                                                             onCredentialSystemNotInitialized.AsAsyncFunc()));
 }
Esempio n. 24
0
        public IActionResult Put(Comment comment)
        {
            var user = _authHandler.UserFromClaimsPrincipal(User);

            if (string.IsNullOrWhiteSpace(comment.Uuid) || string.IsNullOrWhiteSpace(comment.Content))
            {
                _logger.LogInformation("Comment uuid or content is empty.");
                _logger.LogInformation($"Terminating session. User: {user.Uuid}" +
                                       $", IP: {HttpContext?.Connection?.RemoteIpAddress?.ToString() ?? "Unknown IP"}");
                _authHandler.TerminateSession(user);
                return(BadRequest());
            }

            if (!SecureGuid.VerifyGuid(comment.Uuid, out _))
            {
                _logger.LogInformation("Comment UUID is invalid.");
                _logger.LogInformation($"Terminating session. User: {user.Uuid}" +
                                       $", IP: {HttpContext?.Connection?.RemoteIpAddress?.ToString() ?? "Unknown IP"}");
                _authHandler.TerminateSession(user);

                return(BadRequest());
            }

            if (!_database.VerifyCommentUser(user, comment))
            {
                _logger.LogInformation("Requester is not comment creator.");
                _logger.LogInformation($"Terminating session. User: {user.Uuid}" +
                                       $", IP: {HttpContext?.Connection?.RemoteIpAddress?.ToString() ?? "Unknown IP"}");
                _authHandler.TerminateSession(user);
                return(BadRequest());
            }

            if (_database.UpdateComment(comment, user))
            {
                _activityLogger.LogEditComment(Request.HttpContext.Connection.RemoteIpAddress, user, comment);
                return(Ok());
            }

            _logger.LogInformation("Database failed to update comment.");
            _logger.LogInformation($"Terminating session. User: {user.Uuid}" +
                                   $", IP: {HttpContext?.Connection?.RemoteIpAddress?.ToString() ?? "Unknown IP"}");
            _authHandler.TerminateSession(user);
            return(BadRequest());
        }
Esempio n. 25
0
        public bool VerifyCommentUser(User user, Comment comment)
        {
            if (!SecureGuid.VerifyGuid(comment.Uuid, out var commentGuid))
            {
                return(false);
            }

            using var conn = new MySqlConnection(_connectionStringBuilder.ConnectionString);
            conn.Open();
            using var command = conn.CreateCommand();

            command.CommandText = "verifyCommentUser";
            command.CommandType = CommandType.StoredProcedure;
            command.Parameters.Add("@commentUUID", MySqlDbType.Binary, 16).Value = commentGuid.ToByteArray();
            command.Parameters.Add("@userUUID", MySqlDbType.Binary, 16).Value    = user.Uuid.ToByteArray();
            var result = command.ExecuteReader();

            return(result.HasRows);
        }
 public async Task <TResult> CreateLoginAsync <TResult>(Guid authenticationRequestId,
                                                        string method, Uri redirectUrl, Uri redirectLogoutUrl,
                                                        Func <Type, Uri> controllerToLocation,
                                                        Func <Session, TResult> onSuccess,
                                                        Func <TResult> onAlreadyExists,
                                                        Func <TResult> onCredentialSystemNotAvailable,
                                                        Func <string, TResult> onCredentialSystemNotInitialized,
                                                        Func <string, TResult> onFailure)
 {
     return(await Context.GetLoginProvider(method,
                                           async (provider) =>
     {
         var callbackLocation = controllerToLocation(provider.CallbackController);
         var sessionId = SecureGuid.Generate();
         var methodName = method;
         var result = await this.dataContext.AuthenticationRequests.CreateAsync(authenticationRequestId,
                                                                                methodName, AuthenticationActions.signin, redirectUrl, redirectLogoutUrl,
                                                                                () => BlackBarLabs.Security.Tokens.JwtTools.CreateToken(sessionId, callbackLocation, TimeSpan.FromMinutes(30),
                                                                                                                                        (token) =>
         {
             var session = new Session()
             {
                 id = authenticationRequestId,
                 method = methodName,
                 name = methodName,
                 action = AuthenticationActions.signin,
                 loginUrl = provider.GetLoginUrl(authenticationRequestId, callbackLocation, controllerToLocation),
                 logoutUrl = provider.GetLogoutUrl(authenticationRequestId, callbackLocation, controllerToLocation),
                 redirectUrl = redirectUrl,
                 redirectLogoutUrl = redirectLogoutUrl,
                 token = token,
             };
             return onSuccess(session);
         },
                                                                                                                                        why => onFailure(why),
                                                                                                                                        (param, why) => onFailure($"Invalid configuration for {param}:{why}")),
                                                                                onAlreadyExists);
         return result;
     },
                                           onCredentialSystemNotAvailable.AsAsyncFunc(),
                                           onCredentialSystemNotInitialized.AsAsyncFunc()));
 }
Esempio n. 27
0
        private async Task <JObject> ConvertToJsonAsync(MasterDataKeyValue masterData, int newId)
        {
            var lastModifieUser =
                await _securityContext.Users.SingleOrDefaultAsync(us => us.Id == masterData.CreateUserId);

            return(JObject.FromObject(new
            {
                masterData.Id,
                masterData.Guid,
                NewGuid = SecureGuid.NewGuid().ToString("N"),
                NewId = newId,
                masterData.PathOrUrl,
                masterData.SecondPathOrUrl,
                masterData.Name,
                masterData.Code,
                masterData.SecondCode,
                masterData.Key,
                masterData.Value,
                masterData.TypeId,
                masterData.ParentTypeId,
                masterData.Description,
                masterData.Data,
                masterData.EditMode,
                masterData.SlidingExpirationTimeInMinutes,
                masterData.IsLeaf,
                masterData.IsType,
                masterData.ParentId,
                masterData.Order,
                masterData.ForeignKey1,
                masterData.ForeignKey2,
                masterData.ForeignKey3,
                masterData.ViewRoleId,
                masterData.ModifyRoleId,
                masterData.AccessRoleId,
                masterData.Version,
                masterData.EnableCache,
                masterData.Status,
                LastModifieUser = lastModifieUser.UserName,
                LastModifieLocalDateTime = masterData.ModifieLocalDateTime,
                masterData.RowVersion
            }));
        }
Esempio n. 28
0
        public bool DeletePost(Post post, User user)
        {
            if (!SecureGuid.VerifyGuid(post.Uuid, out var postGuid))
            {
                return(false);
            }


            using var conn = new MySqlConnection(_connectionStringBuilder.ConnectionString);
            conn.Open();
            using var command = conn.CreateCommand();

            command.CommandText = "deletePost";
            command.CommandType = CommandType.StoredProcedure;
            command.Parameters.Add("@postUUID", MySqlDbType.Binary, 16).Value = postGuid.ToByteArray();
            command.Parameters.Add("@userUUID", MySqlDbType.Binary, 16).Value = user.Uuid.ToByteArray();
            var result = command.ExecuteNonQuery();

            return(result == 2);
        }
Esempio n. 29
0
        public bool UpdateComment(Comment comment, User user)
        {
            if (!SecureGuid.VerifyGuid(comment.Uuid, out var commentGuid))
            {
                return(false);
            }

            using var conn = new MySqlConnection(_connectionStringBuilder.ConnectionString);
            conn.Open();
            using var command = conn.CreateCommand();

            command.CommandText = "editComment";
            command.CommandType = CommandType.StoredProcedure;
            command.Parameters.Add("@commentUUID", MySqlDbType.Binary, 16).Value = commentGuid.ToByteArray();
            command.Parameters.Add("@userUUID", MySqlDbType.Binary, 16).Value    = user.Uuid.ToByteArray();
            command.Parameters.Add("@updatedContent", MySqlDbType.Text).Value    = comment.Content;
            var response = command.ExecuteNonQuery();

            return(response == 2);
        }
Esempio n. 30
0
        internal async Task <TResult> CreateSessionAsync <TResult>(Guid sessionId, Guid authenticationId,
                                                                   Func <string, string, TResult> onSuccess,
                                                                   Func <string, TResult> onConfigurationFailure)
        {
            Func <IDictionary <string, string>, TResult> authenticate =
                (claims) =>
            {
                var refreshToken = SecureGuid.Generate().ToString("N");
                var result       = GenerateToken(sessionId, authenticationId,
                                                 claims,
                                                 (jwtToken) => onSuccess(jwtToken, refreshToken),
                                                 (why) => onConfigurationFailure(why));
                return(result);
            };

            return(await this.context.Claims.FindByAccountIdAsync(authenticationId,
                                                                  (claims) => authenticate(claims
                                                                                           .Select(claim => new KeyValuePair <string, string>(claim.Type, claim.Value))
                                                                                           .ToDictionary()),
                                                                  () => authenticate(new Dictionary <string, string>())));
        }