コード例 #1
0
ファイル: blueprint.py プロジェクト: qbx2/opencampus
def oauth2_token():
    grant_type = request.form.get('grant_type')

    if grant_type == 'authorization_code':
        """
        일반 사용자가 앱에서 토큰을 획득할 때 사용
        """
        client_id = request.form.get('client_id')
        client_secret = request.form.get('client_secret')
        redirect_uri = request.form.get('redirect_uri')     # TODO
        code = request.form.get('code')

        try:
            code = OAuth2AuthorizationCode.objects(code=code, client_id=client_id).get()
        except OAuth2AuthorizationCode.DoesNotExist:
            return jsonify({'error': 'invalid_request'}), 400

        try:
            client = ApplicationOAuth2Client.objects(id=code.client_id).get()
        except ApplicationOAuth2Client.DoesNotExist:
            return jsonify({'error': 'unauthorized_client'}), 400

        if client_secret != client.secret_key:
            return jsonify({'error': 'unauthorized_client'}), 400

        token = OAuth2AccessToken.create_token('account', code.account_id, scope=code.scope)
        token.client_id = client.id
        token.save()
        code.delete()

        expires_in = token.expires_at - datetime.utcnow()
        expires_in = expires_in.days * 86400 + expires_in.seconds
        return jsonify({
            'access_token': token.access_token,
            'expires_in': expires_in,
            'token_type': 'Bearer',
            'refresh_token': token.refresh_token
        })

    elif grant_type == 'client_credentials':
        """
        게이트웨이에서 토큰 획득 용으로 사용
        """
        client_id = request.form.get('client_id')
        client_secret = request.form.get('client_secret')
        try:
            gateway = CampusGateway.objects(id=client_id, secret_key=client_secret).get()
            token = OAuth2AccessToken.create_token('gateway', gateway.id)
            expires_in = token.expires_at - datetime.utcnow()
            expires_in = expires_in.days * 86400 + expires_in.seconds
            return jsonify({
                'access_token': token.access_token,
                'expires_in': expires_in,
                'token_type': 'Bearer',
                'refresh_token': token.refresh_token
            })
        except CampusGateway.DoesNotExist:
            pass
        return jsonify({'error': 'invalid_request'}), 400
    elif grant_type == 'refresh_token':
        return jsonify({'error': 'unsupported_response_type'}), 400
    else:
        return jsonify({'error': 'unsupported_grant_type'}), 400