QNUpToken.m 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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. NSError *tmp = nil;
  48. NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:&tmp];
  49. if (tmp != nil || dict[@"scope"] == nil || dict[@"deadline"] == nil) {
  50. return nil;
  51. }
  52. return [[QNUpToken alloc] init:dict token:token];
  53. }
  54. - (NSString *)index {
  55. return [NSString stringWithFormat:@"%@:%@", _access, _bucket];
  56. }
  57. @end