You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

TokenUtils.cs 2.1 kB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. namespace Discord
  7. {
  8. public static class TokenUtils
  9. {
  10. /// <summary>
  11. /// Checks the validity of the supplied token of a specific type.
  12. /// </summary>
  13. /// <param name="tokenType"> The type of token to validate. </param>
  14. /// <param name="token"> The token value to validate. </param>
  15. /// <exception cref="ArgumentNullException"> Thrown when the supplied token string is null, empty, or contains only whitespace.</exception>
  16. /// <exception cref="ArgumentException"> Thrown when the supplied TokenType or token value is invalid. </exception>
  17. public static void ValidateToken(TokenType tokenType, string token)
  18. {
  19. // A Null or WhiteSpace token of any type is invalid.
  20. if (string.IsNullOrWhiteSpace(token))
  21. throw new ArgumentNullException("A token cannot be null, empty, or contain only whitespace.", nameof(token));
  22. switch (tokenType)
  23. {
  24. case TokenType.Webhook:
  25. // no validation is performed on Webhook tokens
  26. break;
  27. case TokenType.Bearer:
  28. // no validation is performed on Bearer tokens
  29. break;
  30. case TokenType.Bot:
  31. // bot tokens are assumed to be at least 59 characters in length
  32. // this value was determined by referencing examples in the discord documentation, and by comparing with
  33. // pre-existing tokens
  34. if (token.Length < 59)
  35. throw new ArgumentException("A Bot token must be at least 59 characters in length.", nameof(token));
  36. break;
  37. default:
  38. // All unrecognized TokenTypes (including User tokens) are considered to be invalid.
  39. throw new ArgumentException("Unrecognized TokenType.", nameof(token));
  40. }
  41. }
  42. }
  43. }