#!/usr/bin/env python3  
# -*- coding: utf-8 -*-  
"""
@Copyright (C) ansjer cop Video Technology Co.,Ltd.All rights reserved.
@AUTHOR: ASJRD018
@NAME: AnsjerFormal
@software: PyCharm
@DATE: 2019/5/10 8:43
@Version: python3.6
@MODIFY DECORD:ansjer dev
@file: StsOssController.py
@Contact: chanjunkai@163.com
"""

from django.views.generic import View

from Object.ResponseObject import ResponseObject
from Object.TokenObject import TokenObject
from Ansjer.config import OSS_STS_ACCESS_SECRET, OSS_STS_ACCESS_KEY, OSS_ROLE_ARN
from aliyunsdkcore import client
from aliyunsdksts.request.v20150401 import AssumeRoleRequest
import json
from var_dump import var_dump


class StsOssView(View):

    def get(self, request, *args, **kwargs):
        request.encoding = 'utf-8'
        operation = kwargs.get('operation')

        return self.validation(request.GET, operation)

    def post(self, request, *args, **kwargs):
        request.encoding = 'utf-8'
        operation = kwargs.get('operation')

        return self.validation(request.POST, operation)

    def validation(self, request_dict, operation):
        response = ResponseObject()
        from var_dump import var_dump
        # var_dump(request_dict)
        token = request_dict.get('token', None)
        if operation == 'uidPreview':
            tko = TokenObject(token)
            if tko.code == 0:
                userID = tko.userID
                return self.uid_preview(userID, response)
            else:
                return response.json(tko.code)
        else:
            return response.json(444)

    def uid_preview(self, userID, response):
        storage = '{userID}/uid_preview/'.format(userID=userID)
        bucket_name = 'apg'
        endpoint = 'oss-cn-shenzhen.aliyuncs.com'
        region_id = 'cn-shenzhen'
        clt = client.AcsClient(OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET, region_id)
        req = AssumeRoleRequest.AssumeRoleRequest()
        req.set_accept_format('json')
        req.set_RoleArn(OSS_ROLE_ARN)
        req.set_RoleSessionName(userID)
        req.set_DurationSeconds(3600)
        Resource_access = "acs:oss:*:*:{bucket_name}/{userID}*".\
            format(bucket_name=bucket_name,userID=userID)
        policys = {
            "Version": "1",
            "Statement": [
                {
                    "Action": ["oss:PutObject", "oss:DeleteObject", "oss:GetObject",],
                    # "Action": ["*"],
                    # "Action": ["*"],
                    "Resource": [Resource_access],
                    # "Resource": ["*"],
                    "Effect": "Allow",
                    "Condition": {
                        # "IpAddress": {"acs:SourceIp": ip}
                        # "IpAddress": {"acs:SourceIp": "120.237.157.184"}
                        # "IpAddress": {"acs:SourceIp": "*"}
                    }
                },
                #######
                {
                    "Effect": "Allow",
                    "Action": [
                        "oss:ListObjects"
                    ],
                    "Resource": [
                        "*"
                    ]
                }
            ]
        }
        req.set_Policy(Policy=json.dumps(policys))
        body = clt.do_action(req)
        # 使用RAM账号的AccessKeyId和AccessKeySecret向STS申请临时token。
        token = json.loads(body.decode('utf-8'))
        print(token)
        res = {
            'AccessKeyId': token['Credentials']['AccessKeyId'],
            'AccessKeySecret': token['Credentials']['AccessKeySecret'],
            'SecurityToken': token['Credentials']['SecurityToken'],
            'Expiration': token['Credentials']['Expiration'],
            'expire': 3600,
            'endpoint': endpoint,
            'bucket_name': bucket_name,
            'arn': token['AssumedRoleUser']['Arn'],
            'code': 0,
            'storage': storage,
        }
        return response.json(0, res)
