示例#1
0
def get_token(request, user, application_name):
    expire_seconds = oauth2_settings.user_settings['ACCESS_TOKEN_EXPIRE_SECONDS']
    scopes = oauth2_settings.user_settings['SCOPES']

    application = Application.objects.get(name=application_name)
    expires = datetime.now() + timedelta(seconds=expire_seconds)
    access_token = AccessToken.objects.create(
                    user=user,
                    application=application,
                    token=random_token_generator(request),
                    expires=expires,
                    scope=scopes)

    refresh_token = RefreshToken.objects.create(
                    user=user,
                    token=random_token_generator(request),
                    access_token=access_token,
                    application=application)

    token = {
        'access_token': access_token.token,
        'token_type': 'Bearer',
        'expires_in': expire_seconds,
        'refresh_token': refresh_token.token,
        'scope': scopes
    }

    return token
示例#2
0
    def create_access(user):
        """
			:param user: user object
			:return: json object
		"""
        expire_seconds = 36000
        scopes = 'read write'

        application = Application.objects.get(name="Application")
        expires = datetime.now() + timedelta(seconds=expire_seconds)
        access_token = AccessToken.objects.create(
            user=user,
            application=application,
            token=random_token_generator(req),
            expires=expires,
            scope=scopes)

        refresh_token = RefreshToken.objects.create(
            user=user,
            token=random_token_generator(req),
            access_token=access_token,
            application=application)
        token = {
            'access_token': access_token.token,
            'token_type': 'Bearer',
            'expires_in': expire_seconds,
            'refresh_token': refresh_token.token,
            'scope': scopes
        }
        return token
示例#3
0
    def create_token(self, request, app, user):
        """Create a BearerToken, by default without refresh token."""

        access_token = AccessToken.objects.get_or_create(
            user=user,
            application=app,
            expires=now() + timedelta(days=365),
            token=random_token_generator(request),
            scope="read write")[0]
        access_token.save()

        refresh_token = RefreshToken.objects.get_or_create(
            user=user,
            application=app,
            token=random_token_generator(request),
            access_token=access_token)[0]
        refresh_token.save()

        token = {
            "token_type": "Bearer",
            "refresh_token": refresh_token.token,
            "scope": access_token.scope,
            "access_token": access_token.token,
            "expires_in": 36000,
        }
        return token
示例#4
0
def generate_token(request, user):
    expire_seconds = oauth2_settings.user_settings[
        'ACCESS_TOKEN_EXPIRE_SECONDS']
    scopes = oauth2_settings.user_settings['SCOPES']

    application = Application.objects.first()
    expires = datetime.now() + timedelta(seconds=expire_seconds)
    access_token = AccessToken.objects.create(
        user=user,
        application=application,
        token=random_token_generator(request),
        expires=expires,
        scope=scopes)

    refresh_token = RefreshToken.objects.create(
        user=user,
        token=random_token_generator(request),
        access_token=access_token,
        application=application)

    token = {
        'access_token': access_token.token,
        'token_type': 'Bearer',
        'expires_in': expire_seconds,
        'refresh_token': refresh_token.token,
        'scope': scopes
    }
    return token
示例#5
0
def get_bearer_token(user, expires_in=3600):
    import hashlib
    import jwt
    import frappe.oauth
    from oauthlib.oauth2.rfc6749.tokens import random_token_generator, OAuth2Token

    client = get_oath_client()
    token = frappe._dict({
        'access_token': random_token_generator(None),
        'expires_in': expires_in,
        'token_type': 'Bearer',
        'scopes': client.scopes,
        'refresh_token': random_token_generator(None)
    })
    bearer_token = frappe.new_doc("OAuth Bearer Token")
    bearer_token.client = client.name
    bearer_token.scopes = token['scopes']
    bearer_token.access_token = token['access_token']
    bearer_token.refresh_token = token.get('refresh_token')
    bearer_token.expires_in = token['expires_in'] or 3600
    bearer_token.user = user
    bearer_token.save(ignore_permissions=True)
    frappe.db.commit()

    # ID Token
    id_token_header = {"typ": "jwt", "alg": "HS256"}
    id_token = {
        "aud":
        "token_client",
        "exp":
        int((frappe.db.get_value("OAuth Bearer Token", token.access_token,
                                 "expiration_time") -
             frappe.utils.datetime.datetime(1970, 1, 1)).total_seconds()),
        "sub":
        frappe.db.get_value("User Social Login", {
            "parent": bearer_token.user,
            "provider": "frappe"
        }, "userid"),
        "iss":
        "frappe_server_url",
        "at_hash":
        frappe.oauth.calculate_at_hash(token.access_token, hashlib.sha256)
    }
    id_token_encoded = jwt.encode(id_token,
                                  "client_secret",
                                  algorithm='HS256',
                                  headers=id_token_header)
    id_token_encoded = frappe.safe_decode(id_token_encoded)
    token.id_token = id_token_encoded
    frappe.flags.jwt = id_token_encoded
    return token
 def create_access_token(self, user, request, application_name):
     '''
     API for create access token funcion
     '''
     scopes = 'read write'
     application = Application.objects.get(name=application_name)
     expires = datetime.now() + timedelta(seconds=OAUTH_EXPIRY_SECONDS)
     access_token = AccessToken.objects.create(user=user,
                                               token=random_token_generator(
                                                   request),
                                               application=application,
                                               expires=expires, scope=scopes)
     RefreshToken.objects.create(user=user,
                                 token=random_token_generator(request),
                                 access_token=access_token,
                                 application=application)
     return access_token.token
示例#7
0
 def create_access_token(self, user, request, application_name):
     '''
     API for create access token funcion
     '''
     scopes = 'read write'
     application = Application.objects.get(name=application_name)
     expires = datetime.now() + timedelta(seconds=OAUTH_EXPIRY_SECONDS)
     access_token = AccessToken.objects.create(
         user=user,
         token=random_token_generator(request),
         application=application,
         expires=expires,
         scope=scopes)
     RefreshToken.objects.create(user=user,
                                 token=random_token_generator(request),
                                 access_token=access_token,
                                 application=application)
     return access_token.token
示例#8
0
def refresh_auth_token(request, refresh_token, user, application_name):

    # Allow Auth Token Generation only if refresh_token found in RefreshToken

    expire_seconds = oauth2_settings.user_settings['ACCESS_TOKEN_EXPIRE_SECONDS']
    scopes = oauth2_settings.user_settings['SCOPES']

    application = Application.objects.get(name=application_name)
    expires = datetime.now() + timedelta(seconds=expire_seconds)
    try:
        r = RefreshToken.objects.get(token=refresh_token)

        # Remove refresh_token and it's access_token
        r.revoke()

        # Generate new refresh_token
        access_token = AccessToken.objects.create(
            user=user,
            application=application,
            token=random_token_generator(request, refresh_token=True),
            expires=expires,
            scope=scopes)

        refresh_token = RefreshToken.objects.create(
            user=user,
            token=random_token_generator(request),
            access_token=access_token,
            application=application)

        token = {
            'access_token': access_token.token,
            'token_type': 'Bearer',
            'expires_in': expire_seconds,
            'refresh_token': refresh_token.token,
            'scope': scopes
        }

        return token
    except RefreshToken.DoesNotExist as e:
        print("RefreshToken Not found")
        return None
    except Exception as e:
        print("Auth exception")
        return None
示例#9
0
    def create_oauth_token(self):
        '''
        Create Outh token by user_id and application name
        '''
        scopes = 'read write'
        application = Application.objects.get(name=self.app_name)
        expires = timezone.now() + timezone.timedelta(days=settings.USER_TOKEN_EXPIRES)
        access_token = AccessToken.objects.create(
            user=self.user,
            token=random_token_generator(self.request),
            application=application,
            expires=expires,
            scope=scopes)

        RefreshToken.objects.create(
            user=self.user,
            token=random_token_generator(self.request),
            access_token=access_token,
            application=application
        )
        return access_token

    # def get_device_keys_from_request(self):
    #     '''
    #     get device keys from request
    #     '''
    #     device_id = self.request.data.get('device_id', None)
    #     device_token = self.request.data.get('device_token', None)
    #     device_type = self.request.data.get('device_type', None)
    #     return device_id, device_token, device_type

    # @classmethod
    # def add_device_detail(cls, device_type, device_id, user, device_token=None):
    #     '''
    #     add device detail
    #     '''
    #     device_info = {'user': user, 'device_id': device_id,
    #                    'device_type': device_type,
    #                    'device_token': device_token}
    #     UserDevice.objects.filter(
    #         device_token=device_token, is_device_token_valid=True).update(
    #             is_device_token_valid=False)
    #     UserDevice.objects.create(**device_info)
示例#10
0
    def post(self, request, **kwargs):
        if not isinstance(request.auth, AccessToken):
            # need to use a oauth2 bearer token to authorize
            error_response = BaseSerializerV2.response_envelope(result=[], success=False, description="Invalid token")
            return Response(error_response, status=HTTP_403_FORBIDDEN)

        issuer_entityids = request.data.get('issuers', None)
        if not issuer_entityids:
            raise serializers.ValidationError({"issuers": "field is required"})

        issuers = []
        for issuer_entityid in issuer_entityids:
            try:
                issuer = Issuer.cached.get(entity_id=issuer_entityid)
                self.check_object_permissions(request, issuer)
            except Issuer.DoesNotExist as e:
                raise serializers.ValidationError({"issuers": "unknown issuer"})
            else:
                issuers.append(issuer)

        tokens = []
        expires = timezone.now() + datetime.timedelta(weeks=5200)
        for issuer in issuers:
            scope = "rw:issuer:{}".format(issuer.entity_id)

            # grant application user staff access to issuer if needed
            staff, staff_created = IssuerStaff.cached.get_or_create(
                issuer=issuer,
                user=request.auth.application.user,
                defaults=dict(
                    role=IssuerStaff.ROLE_STAFF
                )
            )

            accesstoken, created = AccessToken.objects.get_or_create(
                user=request.auth.application.user,
                application=request.auth.application,
                scope=scope,
                defaults=dict(
                    expires=expires,
                    token=random_token_generator(request)
                )
            )
            tokens.append({
                'issuer': issuer.entity_id,
                'token': accesstoken.token,
                'expires': accesstoken.expires,
            })

        serializer = IssuerAccessTokenSerializerV2(data=tokens, many=True, context=dict(
            request=request,
            kwargs=kwargs
        ))
        serializer.is_valid(raise_exception=True)
        return Response(serializer.data)
示例#11
0
    def create_oauth_token(self):
        '''
        Create Outh token by user_id and application name
        '''
        scopes = 'read write'
        application = Application.objects.get(name=self.app_name)
        expires = timezone.now() + timezone.timedelta(
            days=settings.USER_TOKEN_EXPIRES)
        access_token = AccessToken.objects.create(user=self.user,
                                                  token=random_token_generator(
                                                      self.request),
                                                  application=application,
                                                  expires=expires,
                                                  scope=scopes)

        RefreshToken.objects.create(user=self.user,
                                    token=random_token_generator(self.request),
                                    access_token=access_token,
                                    application=application)
        return access_token
示例#12
0
    def create_oauth_token(user_id, request, application_name):
        '''
        Create Outh token by user_id and application name
        '''
        scopes = 'read write'
        application = Application.objects.get(name=application_name)

        expires = datetime.now() + \
            timedelta(seconds=settings.OAUTH_EXPIRY_SECONDS)
        access_token = AccessToken.objects.create(
            user=user_id,
            token=random_token_generator(request),
            application=application,
            expires=expires,
            scope=scopes)

        RefreshToken.objects.create(user=user_id,
                                    token=random_token_generator(request),
                                    access_token=access_token,
                                    application=application)
        return access_token
示例#13
0
def login(request):
    """
    url -> /auth/login/
    DataFormat -> {
        "username" : "",
        "password" : "",
    }
    """
    serializer = loginSerializer(data=request.data)
    if serializer.is_valid():
        user = serializer.validated_data
        if not user.is_active:
            return Response(status=401, data={'Msg': 'No longer access provided'})

        expire_seconds = OAUTH2_PROVIDER['ACCESS_TOKEN_EXPIRE_SECONDS']
        scopes = OAUTH2_PROVIDER['SCOPES']
        application = Application.objects.get(name="LIBRARY")
        expires = pytz.UTC.localize(datetime.now() + timedelta(seconds=expire_seconds))
        user=User.objects.get(username=request.data['username'])

        access_token = AccessToken.objects.create(
                user=user,
                application=application,
                token=random_token_generator(request),
                expires=expires,
                scope=scopes)

        refresh_token = RefreshToken.objects.create(
                user=user,
                token=random_token_generator(request),
                access_token=access_token,
                application=application)


        res={'access_token' : access_token.token}#response["access_token"]}
        return Response(res)
    else:
        res = serializer.errors
        return Response(res, status=status.HTTP_400_BAD_REQUEST)
示例#14
0
文件: views.py 项目: swmerko/skillask
def post_social_login(request):
    expire_seconds = oauth2_settings.user_settings["ACCESS_TOKEN_EXPIRE_SECONDS"]
    scopes = oauth2_settings.user_settings["SCOPES"]
    expires = datetime.now() + timedelta(seconds=expire_seconds)

    application = Application.objects.get(name="SkillaskFrontend")

    access_token = AccessToken.objects.create(
        user=request.user, application=application, token=random_token_generator(request), expires=expires, scope=scopes
    )

    token = access_token.token
    params = {"token": token}
    redirect_url = "%s?" % settings.FRONTEND_BASE_URL + urllib.urlencode(params)

    return redirect(redirect_url)
示例#15
0
def generate_access_token(user):
    try:
        app = Application.objects.get(name="breadcrumb")
    except Application.DoesNotExist:
        try:
            root_user = User.objects.get(username='******')
        except User.DoesNotExist:
            # todo: this is for testing purposes only, remove this when going live
            root_user = User.objects.create(username='******', email='*****@*****.**', password='******')
        app = Application.objects.create(client_id='breadcrumb', client_secret='secret', name='breadcrumb',
                                         user=root_user, authorization_grant_type='password')

    expires = datetime.datetime.now() + datetime.timedelta(seconds=31536000)
    access_token = AccessToken.objects.create(
        user=user,
        application=app,
        token=random_token_generator(None),
        expires=expires,
        scope=oauth2_settings.user_settings['SCOPES']
    )

    return access_token
示例#16
0
 def generate_access_token(self, request):
     return tokens.random_token_generator(request)