QNUpToken.m 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. //
  2. // QNUpToken.m
  3. // QiniuSDK
  4. //
  5. // Created by bailong on 15/6/7.
  6. // Copyright (c) 2015年 Qiniu. All rights reserved.
  7. //
  8. #import "QNUrlSafeBase64.h"
  9. #import "QNUpToken.h"
  10. @interface QNUpToken ()
  11. - (instancetype)init:(NSDictionary *)policy token:(NSString *)token;
  12. @end
  13. @implementation QNUpToken
  14. - (instancetype)init:(NSDictionary *)policy token:(NSString *)token {
  15. if (self = [super init]) {
  16. _token = token;
  17. _access = [self getAccess];
  18. _bucket = [self getBucket:policy];
  19. _hasReturnUrl = (policy[@"returnUrl"] != nil);
  20. }
  21. return self;
  22. }
  23. - (NSString *)getAccess {
  24. NSRange range = [_token rangeOfString:@":" options:NSCaseInsensitiveSearch];
  25. return [_token substringToIndex:range.location];
  26. }
  27. - (NSString *)getBucket:(NSDictionary *)info {
  28. NSString *scope = [info objectForKey:@"scope"];
  29. if (!scope || [scope isKindOfClass:[NSNull class]]) {
  30. return @"";
  31. }
  32. NSRange range = [scope rangeOfString:@":"];
  33. if (range.location == NSNotFound) {
  34. return scope;
  35. }
  36. return [scope substringToIndex:range.location];
  37. }
  38. + (instancetype)parse:(NSString *)token {
  39. if (token == nil) {
  40. return nil;
  41. }
  42. NSArray *array = [token componentsSeparatedByString:@":"];
  43. if (array == nil || array.count != 3) {
  44. return nil;
  45. }
  46. NSData *data = [QNUrlSafeBase64 decodeString:array[2]];
  47. if (!data) {
  48. return nil;
  49. }
  50. NSError *tmp = nil;
  51. NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:&tmp];
  52. if (tmp != nil || dict[@"scope"] == nil || dict[@"deadline"] == nil) {
  53. return nil;
  54. }
  55. return [[QNUpToken alloc] init:dict token:token];
  56. }
  57. - (NSString *)index {
  58. return [NSString stringWithFormat:@"%@:%@", _access, _bucket];
  59. }
  60. - (BOOL)isValid {
  61. return _access && _access.length > 0 && _bucket && _bucket.length > 0;
  62. }
  63. @end