Exemple #1
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);
        }
Exemple #2
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);
            }
        }
Exemple #3
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());
        }
Exemple #4
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());
        }
Exemple #5
0
        public TokenInfo GenerateToken(User user)
        {
            if (!_memoryCache.TryGetValue(user.Uuid.ToString(), out Guid sessionGuid))
            {
                sessionGuid = SecureGuid.CreateSecureRfc4122Guid();
                var options = new MemoryCacheEntryOptions
                {
                    Priority = CacheItemPriority.NeverRemove
                };
                _memoryCache.Set(user.Uuid.ToString(), sessionGuid, options);
            }

            var claims = new[]
            {
                new Claim(JwtRegisteredClaimNames.Sub, user.Uuid.ToString()),
                new Claim(JwtRegisteredClaimNames.Jti,
                          SecureGuid.CreateSecureRfc4122Guid().ToString()),
                new Claim(JwtRegisteredClaimNames.Sid, sessionGuid.ToString()),
                new Claim(JwtRegisteredClaimNames.UniqueName, user.Username)
            };

            var key   = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["Tokens:Key"]));
            var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

            var token = new JwtSecurityToken(_configuration["Tokens:Issuer"],
                                             _configuration["Tokens:Issuer"],
                                             claims,
                                             expires: DateTime.Now.AddMinutes(30),
                                             signingCredentials: creds);

            var tokenInfo = new TokenInfo
            {
                Token    = new JwtSecurityTokenHandler().WriteToken(token),
                Username = user.Username,
                Expiry   = token.ValidTo
            };

            return(tokenInfo);
        }
Exemple #6
0
        public IActionResult VerifyAzureAdCode(TokenInput tokenInput)
        {
            if (string.IsNullOrWhiteSpace(tokenInput.Token))
            {
                _logger.LogInformation("Token is empty.");
                return(BadRequest());
            }

            var user = _authHandler.VerifyOauthForRegister(tokenInput.Token);

            if (user == null)
            {
                _logger.LogInformation("Auth handler rejected oauth token.");
                return(BadRequest());
            }

            if (_memoryCache.TryGetValue("R1" + user.Email, out string stringUuid))
            {
                _memoryCache.Remove("R1" + stringUuid);
            }

            var registerGuid      = SecureGuid.CreateSecureRfc4122Guid();
            var cacheEntryOptions = new MemoryCacheEntryOptions().SetAbsoluteExpiration(TimeSpan.FromMinutes(5));

            _memoryCache.Set("R1" + registerGuid, user, cacheEntryOptions);
            _memoryCache.Set("R1" + user.Email, registerGuid.ToString(), cacheEntryOptions);

            var response = new OauthSuccessResponse
            {
                Name         = user.Name,
                Email        = user.Email,
                RegisterCode = registerGuid.ToString()
            };

            return(Ok(response));
        }